on 155e306 help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1584 lines 62 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntaxTree where
6import Idris.Core.TT
7import Idris.Core.Evaluate
8import Idris.Core.Elaborate hiding (Tactic(..))
9import Idris.Core.Typecheck
10import Idris.Docstrings
11import IRTS.Lang
12import IRTS.CodegenCommon
13import Util.Pretty
14import Util.DynamicLinker
16import Idris.Colours
18import Paths_idris
20import System.Console.Haskeline
21import System.IO
23import Control.Monad.Trans.State.Strict
24import Control.Monad.Trans.Error
26import Data.List hiding (group)
27import Data.Char
28import qualified Data.Map as M
29import qualified Data.Text as T
30import qualified Data.Map as M
31import Data.Either
32import qualified Data.Set as S
33import Data.Word (Word)
35import Debug.Trace
37import Text.PrettyPrint.Annotated.Leijen
39data IOption = IOption { opt_logLevel :: Int,
40 opt_typecase :: Bool,
41 opt_typeintype :: Bool,
42 opt_coverage :: Bool,
43 opt_showimp :: Bool, -- ^^ show implicits
44 opt_errContext :: Bool,
45 opt_repl :: Bool,
46 opt_verbose :: Bool,
47 opt_nobanner :: Bool,
48 opt_quiet :: Bool,
49 opt_codegen :: Codegen,
50 opt_outputTy :: OutputType,
51 opt_ibcsubdir :: FilePath,
52 opt_importdirs :: [FilePath],
53 opt_triple :: String,
54 opt_cpu :: String,
55 opt_optLevel :: Word,
56 opt_cmdline :: [Opt], -- remember whole command line
57 opt_origerr :: Bool,
58 opt_autoSolve :: Bool -- ^ automatically apply "solve" tactic in prover
59 }
60 deriving (Show, Eq)
62defaultOpts = IOption { opt_logLevel = 0
63 , opt_typecase = False
64 , opt_typeintype = False
65 , opt_coverage = True
66 , opt_showimp = False
67 , opt_errContext = False
68 , opt_repl = True
69 , opt_verbose = True
70 , opt_nobanner = False
71 , opt_quiet = False
72 , opt_codegen = ViaC
73 , opt_outputTy = Executable
74 , opt_ibcsubdir = ""
75 , opt_importdirs = []
76 , opt_triple = ""
77 , opt_cpu = ""
78 , opt_optLevel = 2
79 , opt_cmdline = []
80 , opt_origerr = False
81 , opt_autoSolve = True
82 }
84data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
86-- | The output mode in use
87data OutputMode = RawOutput | IdeSlave Integer deriving Show
89-- | How wide is the console?
90data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
91 | ColsWide Int -- ^ Manually specified - must be positive
92 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
94-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
95-- without typechecking).
96-- This will include all the functions and data declarations, plus fixity declarations
97-- and syntax macros.
99-- | The global state used in the Idris monad
100data IState = IState {
101 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
102 idris_constraints :: [(UConstraint, FC)],
103 -- ^ A list of universe constraints and their corresponding source locations
104 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
105 idris_implicits :: Ctxt [PArg],
106 idris_statics :: Ctxt [Bool],
107 idris_classes :: Ctxt ClassInfo,
108 idris_dsls :: Ctxt DSL,
109 idris_optimisation :: Ctxt OptInfo,
110 idris_datatypes :: Ctxt TypeInfo,
111 idris_namehints :: Ctxt [Name],
112 idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
113 -- ^ list of lhs/rhs, and a list of missing clauses
114 idris_flags :: Ctxt [FnOpt],
115 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
116 idris_calledgraph :: Ctxt [Name],
117 idris_docstrings :: Ctxt (Docstring, [(Name, Docstring)]),
118 idris_tyinfodata :: Ctxt TIData,
119 idris_totcheck :: [(FC, Name)], -- names to check totality on
120 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
121 idris_options :: IOption,
122 idris_name :: Int,
123 idris_lineapps :: [((FilePath, Int), PTerm)],
124 -- ^ Full application LHS on source line
125 idris_metavars :: [(Name, (Maybe Name, Int, Bool))], -- ^ The currently defined but not proven metavariables
126 idris_coercions :: [Name],
127 idris_transforms :: [(Term, Term)],
128 idris_errRev :: [(Term, Term)],
129 syntax_rules :: [Syntax],
130 syntax_keywords :: [String],
131 imported :: [FilePath], -- ^ The imported modules
132 idris_scprims :: [(Name, (Int, PrimFn))],
133 idris_objs :: [(Codegen, FilePath)],
134 idris_libs :: [(Codegen, String)],
135 idris_cgflags :: [(Codegen, String)],
136 idris_hdrs :: [(Codegen, String)],
137 proof_list :: [(Name, [String])],
138 errSpan :: Maybe FC,
139 parserWarnings :: [(FC, Err)],
140 lastParse :: Maybe Name,
141 indent_stack :: [Int],
142 brace_stack :: [Maybe Int],
143 lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
144 hide_list :: [(Name, Maybe Accessibility)],
145 default_access :: Accessibility,
146 default_total :: Bool,
147 ibc_write :: [IBCWrite],
148 compiled_so :: Maybe String,
149 idris_dynamic_libs :: [DynamicLib],
150 idris_language_extensions :: [LanguageExt],
151 idris_outputmode :: OutputMode,
152 idris_colourRepl :: Bool,
153 idris_colourTheme :: ColourTheme,
154 idris_outh :: Handle,
155 idris_errorhandlers :: [Name], -- ^ Global error handlers
156 idris_nameIdx :: (Int, Ctxt (Int, Name)),
157 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
158 module_aliases :: M.Map [T.Text] [T.Text],
159 idris_consolewidth :: ConsoleWidth -- ^ How many chars wide is the console?
160 }
162data SizeChange = Smaller | Same | Bigger | Unknown
163 deriving (Show, Eq)
164{-!
165deriving instance Binary SizeChange
166deriving instance NFData SizeChange
167!-}
169type SCGEntry = (Name, [Maybe (Int, SizeChange)])
171data CGInfo = CGInfo { argsdef :: [Name],
172 calls :: [(Name, [[Name]])],
173 scg :: [SCGEntry],
174 argsused :: [Name],
175 unusedpos :: [Int] }
176 deriving Show
177{-!
178deriving instance Binary CGInfo
179deriving instance NFData CGInfo
180!-}
182primDefs = [sUN "unsafePerformPrimIO",
183 sUN "mkLazyForeignPrim",
184 sUN "mkForeignPrim",
185 sUN "FalseElim"]
187-- information that needs writing for the current module's .ibc file
188data IBCWrite = IBCFix FixDecl
189 | IBCImp Name
190 | IBCStatic Name
191 | IBCClass Name
192 | IBCInstance Bool Name Name
193 | IBCDSL Name
194 | IBCData Name
195 | IBCOpt Name
196 | IBCMetavar Name
197 | IBCSyntax Syntax
198 | IBCKeyword String
199 | IBCImport FilePath
200 | IBCObj Codegen FilePath
201 | IBCLib Codegen String
202 | IBCCGFlag Codegen String
203 | IBCDyLib String
204 | IBCHeader Codegen String
205 | IBCAccess Name Accessibility
206 | IBCMetaInformation Name MetaInformation
207 | IBCTotal Name Totality
208 | IBCFlags Name [FnOpt]
209 | IBCTrans (Term, Term)
210 | IBCErrRev (Term, Term)
211 | IBCCG Name
212 | IBCDoc Name
213 | IBCCoercion Name
214 | IBCDef Name -- i.e. main context
215 | IBCNameHint (Name, Name)
216 | IBCLineApp FilePath Int PTerm
217 | IBCErrorHandler Name
218 | IBCFunctionErrorHandler Name Name Name
219 deriving Show
221-- | The initial state for the compiler
222idrisInit :: IState
223idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
224 emptyContext emptyContext emptyContext emptyContext
225 emptyContext emptyContext emptyContext emptyContext
226 emptyContext emptyContext
227 [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
228 [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
229 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
230 AutomaticWidth
232-- | The monad for the main REPL - reading and processing files and updating
233-- global state (hence the IO inner monad).
234--type Idris = WriterT [Either String (IO ())] (State IState a))
235type Idris = StateT IState (ErrorT Err IO)
237-- Commands in the REPL
239data Codegen = ViaC
240 | ViaJava
241 | ViaNode
242 | ViaJavaScript
243 | ViaLLVM
244 | Bytecode
245 deriving (Show, Eq)
247-- | REPL commands
248data Command = Quit
249 | Help
250 | Eval PTerm
251 | Check PTerm
252 | DocStr Name
253 | TotCheck Name
254 | Reload
255 | Load FilePath
256 | ChangeDirectory FilePath
257 | ModImport String
258 | Edit
259 | Compile Codegen String
260 | Execute
261 | ExecVal PTerm
262 | Metavars
263 | Prove Name
264 | AddProof (Maybe Name)
265 | RmProof Name
266 | ShowProof Name
267 | Proofs
268 | Universes
269 | LogLvl Int
270 | Spec PTerm
271 | HNF PTerm
272 | TestInline PTerm
273 | Defn Name
274 | Info Name
275 | Missing Name
276 | DynamicLink FilePath
277 | ListDynamic
278 | Pattelab PTerm
279 | DebugInfo Name
280 | Search PTerm
281 | CaseSplitAt Bool Int Name
282 | AddClauseFrom Bool Int Name
283 | AddProofClauseFrom Bool Int Name
284 | AddMissing Bool Int Name
285 | MakeWith Bool Int Name
286 | DoProofSearch Bool Int Name [Name]
287 | SetOpt Opt
288 | UnsetOpt Opt
289 | NOP
290 | SetColour ColourType IdrisColour
291 | ColourOn
292 | ColourOff
293 | ListErrorHandlers
294 | SetConsoleWidth ConsoleWidth
295 | Apropos String
296 | MakeDoc String -- IdrisDoc
298data Opt = Filename String
299 | Ver
300 | Usage
301 | Quiet
302 | NoBanner
303 | ColourREPL Bool
304 | Ideslave
305 | ShowLibs
306 | ShowLibdir
307 | ShowIncs
308 | NoBasePkgs
309 | NoPrelude
310 | NoBuiltins -- only for the really primitive stuff!
311 | NoREPL
312 | OLogging Int
313 | Output String
314 | TypeCase
315 | TypeInType
316 | DefaultTotal
317 | DefaultPartial
318 | WarnPartial
319 | NoCoverage
320 | ErrContext
321 | ShowImpl
322 | Verbose
323 | IBCSubDir String
324 | ImportDir String
325 | PkgBuild String
326 | PkgInstall String
327 | PkgClean String
328 | PkgCheck String
329 | PkgREPL String
330 | WarnOnly
331 | Pkg String
332 | BCAsm String
333 | DumpDefun String
334 | DumpCases String
335 | UseCodegen Codegen
336 | OutputTy OutputType
337 | Extension LanguageExt
338 | InterpretScript String
339 | TargetTriple String
340 | TargetCPU String
341 | OptLevel Word
342 | Client String
343 | ShowOrigErr
344 | AutoWidth -- ^ Automatically adjust terminal width
345 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
346 deriving (Show, Eq)
348-- Parsed declarations
350data Fixity = Infixl { prec :: Int }
351 | Infixr { prec :: Int }
352 | InfixN { prec :: Int }
353 | PrefixN { prec :: Int }
354 deriving Eq
355{-!
356deriving instance Binary Fixity
357deriving instance NFData Fixity
358!-}
360instance Show Fixity where
361 show (Infixl i) = "infixl " ++ show i
362 show (Infixr i) = "infixr " ++ show i
363 show (InfixN i) = "infix " ++ show i
364 show (PrefixN i) = "prefix " ++ show i
366data FixDecl = Fix Fixity String
367 deriving Eq
369instance Show FixDecl where
370 show (Fix f s) = show f ++ " " ++ s
372{-!
373deriving instance Binary FixDecl
374deriving instance NFData FixDecl
375!-}
377instance Ord FixDecl where
378 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
381data Static = Static | Dynamic
382 deriving (Show, Eq)
383{-!
384deriving instance Binary Static
385deriving instance NFData Static
386!-}
388-- Mark bindings with their explicitness, and laziness
389data Plicity = Imp { pargopts :: [ArgOpt],
390 pstatic :: Static,
391 pparam :: Bool }
392 | Exp { pargopts :: [ArgOpt],
393 pstatic :: Static,
394 pparam :: Bool }
395 | Constraint { pargopts :: [ArgOpt],
396 pstatic :: Static }
397 | TacImp { pargopts :: [ArgOpt],
398 pstatic :: Static,
399 pscript :: PTerm }
400 deriving (Show, Eq)
402plazy :: Plicity -> Bool
403plazy tm = Lazy `elem` pargopts tm
405{-!
406deriving instance Binary Plicity
407deriving instance NFData Plicity
408!-}
410impl = Imp [Lazy] Dynamic False
411expl = Exp [] Dynamic False
412expl_param = Exp [] Dynamic True
413constraint = Constraint [] Dynamic
414tacimpl t = TacImp [] Dynamic t
416data FnOpt = Inlinable -- always evaluate when simplifying
417 | TotalFn | PartialFn | CoveringFn
418 | Coinductive | AssertTotal
419 | Dictionary -- type class dictionary, eval only when
420 -- a function argument, and further evaluation resutls
421 | Implicit -- implicit coercion
422 | CExport String -- export, with a C name
423 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
424 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
425 | Reflection -- a reflecting function, compile-time only
426 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
427 deriving (Show, Eq)
428{-!
429deriving instance Binary FnOpt
430deriving instance NFData FnOpt
431!-}
433type FnOpts = [FnOpt]
435inlinable :: FnOpts -> Bool
436inlinable = elem Inlinable
438dictionary :: FnOpts -> Bool
439dictionary = elem Dictionary
442-- | Data declaration options
443data DataOpt = Codata -- Set if the the data-type is coinductive
444 | DefaultEliminator -- Set if an eliminator should be generated for data type
445 | DataErrRev
446 deriving (Show, Eq)
448type DataOpts = [DataOpt]
450-- | Type provider - what to provide
451data ProvideWhat = ProvTerm -- ^ only allow providing terms
452 | ProvPostulate -- ^ only allow postulates
453 | ProvAny -- ^ either is ok
454 deriving (Show, Eq)
456-- | Top-level declarations such as compiler directives, definitions,
457-- datatypes and typeclasses.
458data PDecl' t
459 = PFix FC Fixity [String] -- ^ Fixity declaration
460 | PTy Docstring [(Name, Docstring)] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
461 | PPostulate Docstring SyntaxInfo FC FnOpts Name t -- ^ Postulate
462 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
463 | PCAF FC Name t -- ^ Top level constant
464 | PData Docstring [(Name, Docstring)] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
465 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
466 | PNamespace String [PDecl' t] -- ^ New namespace
467 | PRecord Docstring SyntaxInfo FC Name t Docstring Name t -- ^ Record declaration
468 | PClass Docstring SyntaxInfo FC
469 [t] -- constraints
470 Name
471 [(Name, t)] -- parameters
472 [PDecl' t] -- declarations
473 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
474 -- class name, parameters, method declarations
475 | PInstance SyntaxInfo FC [t] -- constraints
476 Name -- class
477 [t] -- parameters
478 t -- full instance type
479 (Maybe Name) -- explicit name
480 [PDecl' t]
481 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
482 -- class name, parameters, full instance type, optional explicit name, and definitions
483 | PDSL Name (DSL' t) -- ^ DSL declaration
484 | PSyntax FC Syntax -- ^ Syntax definition
485 | PMutual FC [PDecl' t] -- ^ Mutual block
486 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
487 | PProvider SyntaxInfo FC ProvideWhat Name t t -- ^ Type provider. The first t is the type, the second is the term
488 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
489 -- bool is True, lhs and rhs must be convertible
490 deriving Functor
491{-!
492deriving instance Binary PDecl'
493deriving instance NFData PDecl'
494!-}
496-- For elaborator state
497type ElabD a = Elab' [PDecl] a
499-- | One clause of a top-level definition. Term arguments to constructors are:
500--
501-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
502--
503-- 2. The list of extra 'with' patterns
504--
505-- 3. The right-hand side
506--
507-- 4. The where block (PDecl' t)
509data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
510 | PWith FC Name t [t] t [PDecl' t]
511 | PClauseR FC [t] t [PDecl' t]
512 | PWithR FC [t] t [PDecl' t]
513 deriving Functor
514{-!
515deriving instance Binary PClause'
516deriving instance NFData PClause'
517!-}
519-- | Data declaration
520data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
521 d_tcon :: t, -- ^ Type constructor
522 d_cons :: [(Docstring, [(Name, Docstring)], Name, t, FC, [Name])] -- ^ Constructors
523 }
524 -- ^ Data declaration
525 | PLaterdecl { d_name :: Name, d_tcon :: t }
526 -- ^ "Placeholder" for data whose constructors are defined later
527 deriving Functor
528{-!
529deriving instance Binary PData'
530deriving instance NFData PData'
531!-}
533-- Handy to get a free function for applying PTerm -> PTerm functions
534-- across a program, by deriving Functor
536type PDecl = PDecl' PTerm
537type PData = PData' PTerm
538type PClause = PClause' PTerm
540-- get all the names declared in a decl
542declared :: PDecl -> [Name]
543declared (PFix _ _ _) = []
544declared (PTy _ _ _ _ _ n t) = [n]
545declared (PPostulate _ _ _ _ n t) = [n]
546declared (PClauses _ _ n _) = [] -- not a declaration
547declared (PCAF _ n _) = [n]
548declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
549 where fstt (_, _, a, _, _, _) = a
550declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
551declared (PParams _ _ ds) = concatMap declared ds
552declared (PNamespace _ ds) = concatMap declared ds
553declared (PRecord _ _ _ n _ _ c _) = [n, c]
554declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
555declared (PInstance _ _ _ _ _ _ _ _) = []
556declared (PDSL n _) = [n]
557declared (PSyntax _ _) = []
558declared (PMutual _ ds) = concatMap declared ds
559declared (PDirective _) = []
561-- get the names declared, not counting nested parameter blocks
562tldeclared :: PDecl -> [Name]
563tldeclared (PFix _ _ _) = []
564tldeclared (PTy _ _ _ _ _ n t) = [n]
565tldeclared (PPostulate _ _ _ _ n t) = [n]
566tldeclared (PClauses _ _ n _) = [] -- not a declaration
567tldeclared (PRecord _ _ _ n _ _ c _) = [n, c]
568tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
569 where fstt (_, _, a, _, _, _) = a
570tldeclared (PParams _ _ ds) = []
571tldeclared (PMutual _ ds) = concatMap tldeclared ds
572tldeclared (PNamespace _ ds) = concatMap tldeclared ds
573tldeclared (PClass _ _ _ _ n _ ms) = concatMap tldeclared ms
574tldeclared (PInstance _ _ _ _ _ _ _ _) = []
575tldeclared _ = []
577defined :: PDecl -> [Name]
578defined (PFix _ _ _) = []
579defined (PTy _ _ _ _ _ n t) = []
580defined (PPostulate _ _ _ _ n t) = []
581defined (PClauses _ _ n _) = [n] -- not a declaration
582defined (PCAF _ n _) = [n]
583defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
584 where fstt (_, _, a, _, _, _) = a
585defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
586defined (PParams _ _ ds) = concatMap defined ds
587defined (PNamespace _ ds) = concatMap defined ds
588defined (PRecord _ _ _ n _ _ c _) = [n, c]
589defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
590defined (PInstance _ _ _ _ _ _ _ _) = []
591defined (PDSL n _) = [n]
592defined (PSyntax _ _) = []
593defined (PMutual _ ds) = concatMap defined ds
594defined (PDirective _) = []
595--defined _ = []
597updateN :: [(Name, Name)] -> Name -> Name
598updateN ns n | Just n' <- lookup n ns = n'
599updateN _ n = n
601updateNs :: [(Name, Name)] -> PTerm -> PTerm
602updateNs [] t = t
603updateNs ns t = mapPT updateRef t
604 where updateRef (PRef fc f) = PRef fc (updateN ns f)
605 updateRef t = t
607-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
608-- updateDNs [] t = t
609-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
610-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
611-- where updateCNs ns (PClause n l ts r ds)
612-- = PClause (updateN ns n) (fmap (updateNs ns) l)
613-- (map (fmap (updateNs ns)) ts)
614-- (fmap (updateNs ns) r)
615-- (map (updateDNs ns) ds)
616-- updateDNs ns c = c
618data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
620-- | High level language terms
621data PTerm = PQuote Raw
622 | PRef FC Name
623 | PInferRef FC Name -- ^ A name to be defined later
624 | PPatvar FC Name
625 | PLam Name PTerm PTerm
626 | PPi Plicity Name PTerm PTerm
627 | PLet Name PTerm PTerm PTerm
628 | PTyped PTerm PTerm -- ^ Term with explicit type
629 | PApp FC PTerm [PArg]
630 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
631 | PMatchApp FC Name -- ^ Make an application by type matching
632 | PCase FC PTerm [(PTerm, PTerm)]
633 | PTrue FC PunInfo
634 | PFalse FC
635 | PRefl FC PTerm
636 | PResolveTC FC
637 | PEq FC PTerm PTerm
638 | PRewrite FC PTerm PTerm (Maybe PTerm)
639 | PPair FC PunInfo PTerm PTerm
640 | PDPair FC PunInfo PTerm PTerm PTerm
641 | PAlternative Bool [PTerm] -- True if only one may work
642 | PHidden PTerm -- ^ Irrelevant or hidden pattern
643 | PType
644 | PGoal FC PTerm Name PTerm
645 | PConstant Const
646 | Placeholder
647 | PDoBlock [PDo]
648 | PIdiom FC PTerm
649 | PReturn FC
650 | PMetavar Name
651 | PProof [PTactic] -- ^ Proof script
652 | PTactics [PTactic] -- ^ As PProof, but no auto solving
653 | PElabError Err -- ^ Error to report on elaboration
654 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
655 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
656 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
657 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
658 | PNoImplicits PTerm -- ^ never run implicit converions on the term
659 deriving Eq
662{-!
663deriving instance Binary PTerm
664deriving instance NFData PTerm
665!-}
667mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
668mapPT f t = f (mpt t) where
669 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
670 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
671 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
672 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
673 (fmap (mapPT f) g)
674 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
675 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
676 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
677 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
678 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
679 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
680 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
681 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
682 mpt (PHidden t) = PHidden (mapPT f t)
683 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
684 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
685 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
686 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
687 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
688 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
689 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
690 mpt x = x
693data PTactic' t = Intro [Name] | Intros | Focus Name
694 | Refine Name [Bool] | Rewrite t
695 | Induction Name
696 | Equiv t
697 | MatchRefine Name
698 | LetTac Name t | LetTacTy Name t t
699 | Exact t | Compute | Trivial | TCInstance
700 | ProofSearch (Maybe Name) [Name]
701 | Solve
702 | Attack
703 | ProofState | ProofTerm | Undo
704 | Try (PTactic' t) (PTactic' t)
705 | TSeq (PTactic' t) (PTactic' t)
706 | ApplyTactic t -- see Language.Reflection module
707 | ByReflection t
708 | Reflect t
709 | Fill t
710 | GoalType String (PTactic' t)
711 | TCheck t
712 | TEval t
713 | Qed | Abandon
714 deriving (Show, Eq, Functor)
715{-!
716deriving instance Binary PTactic'
717deriving instance NFData PTactic'
718!-}
719instance Sized a => Sized (PTactic' a) where
720 size (Intro nms) = 1 + size nms
721 size Intros = 1
722 size (Focus nm) = 1 + size nm
723 size (Refine nm bs) = 1 + size nm + length bs
724 size (Rewrite t) = 1 + size t
725 size (Induction t) = 1 + size t
726 size (LetTac nm t) = 1 + size nm + size t
727 size (Exact t) = 1 + size t
728 size Compute = 1
729 size Trivial = 1
730 size Solve = 1
731 size Attack = 1
732 size ProofState = 1
733 size ProofTerm = 1
734 size Undo = 1
735 size (Try l r) = 1 + size l + size r
736 size (TSeq l r) = 1 + size l + size r
737 size (ApplyTactic t) = 1 + size t
738 size (Reflect t) = 1 + size t
739 size (Fill t) = 1 + size t
740 size Qed = 1
741 size Abandon = 1
743type PTactic = PTactic' PTerm
745data PDo' t = DoExp FC t
746 | DoBind FC Name t
747 | DoBindP FC t t [(t,t)]
748 | DoLet FC Name t t
749 | DoLetP FC t t
750 deriving (Eq, Functor)
751{-!
752deriving instance Binary PDo'
753deriving instance NFData PDo'
754!-}
756instance Sized a => Sized (PDo' a) where
757 size (DoExp fc t) = 1 + size fc + size t
758 size (DoBind fc nm t) = 1 + size fc + size nm + size t
759 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
760 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
761 size (DoLetP fc l r) = 1 + size fc + size l + size r
763type PDo = PDo' PTerm
765-- The priority gives a hint as to elaboration order. Best to elaborate
766-- things early which will help give a more concrete type to other
767-- variables, e.g. a before (interpTy a).
769data PArg' t = PImp { priority :: Int,
770 machine_inf :: Bool, -- true if the machine inferred it
771 argopts :: [ArgOpt],
772 pname :: Name, getTm :: t }
773 | PExp { priority :: Int,
774 argopts :: [ArgOpt],
775 getTm :: t }
776 | PConstraint { priority :: Int,
777 argopts :: [ArgOpt],
778 getTm :: t }
779 | PTacImplicit { priority :: Int,
780 argopts :: [ArgOpt],
781 pname :: Name,
782 getScript :: t,
783 getTm :: t }
784 deriving (Show, Eq, Functor)
786data ArgOpt = Lazy | HideDisplay
787 deriving (Show, Eq)
789lazyarg :: PArg' t -> Bool
790lazyarg tm = Lazy `elem` argopts tm
792instance Sized a => Sized (PArg' a) where
793 size (PImp p _ l nm trm) = 1 + size nm + size trm
794 size (PExp p l trm) = 1 + size trm
795 size (PConstraint p l trm) = 1 + size trm
796 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
798{-!
799deriving instance Binary PArg'
800deriving instance NFData PArg'
801!-}
803pimp n t mach = PImp 1 mach [Lazy] n t
804pexp t = PExp 1 [] t
805pconst t = PConstraint 1 [] t
806ptacimp n s t = PTacImplicit 2 [Lazy] n s t
808type PArg = PArg' PTerm
810-- Type class data
812data ClassInfo = CI { instanceName :: Name,
813 class_methods :: [(Name, (FnOpts, PTerm))],
814 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
815 class_default_superclasses :: [PDecl],
816 class_params :: [Name],
817 class_instances :: [Name] }
818 deriving Show
819{-!
820deriving instance Binary ClassInfo
821deriving instance NFData ClassInfo
822!-}
824-- Type inference data
826data TIData = TIPartial -- ^ a function with a partially defined type
827 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
828 deriving Show
830-- An argument is conditionally forceable iff its forceability
831-- depends on the collapsibility of the whole type.
832data Forceability = Conditional | Unconditional deriving (Show, Enum, Bounded, Eq, Ord)
834{-!
835deriving instance Binary Forceability
836deriving instance NFData Forceability
837!-}
839data OptInfo = Optimise { collapsible :: Bool,
840 isnewtype :: Bool,
841 -- The following should actually be (IntMap Forceability)
842 -- but the corresponding Binary instance seems to be broken.
843 -- Let's store a list and convert it to IntMap whenever needed.
844 forceable :: [(Int, Forceability)],
845 recursive :: [Int] }
846 deriving Show
847{-!
848deriving instance Binary OptInfo
849deriving instance NFData OptInfo
850!-}
853data TypeInfo = TI { con_names :: [Name],
854 codata :: Bool,
855 data_opts :: DataOpts,
856 param_pos :: [Int] }
857 deriving Show
858{-!
859deriving instance Binary TypeInfo
860deriving instance NFData TypeInfo
861!-}
863-- Syntactic sugar info
865data DSL' t = DSL { dsl_bind :: t,
866 dsl_return :: t,
867 dsl_apply :: t,
868 dsl_pure :: t,
869 dsl_var :: Maybe t,
870 index_first :: Maybe t,
871 index_next :: Maybe t,
872 dsl_lambda :: Maybe t,
873 dsl_let :: Maybe t
874 }
875 deriving (Show, Functor)
876{-!
877deriving instance Binary DSL'
878deriving instance NFData DSL'
879!-}
881type DSL = DSL' PTerm
883data SynContext = PatternSyntax | TermSyntax | AnySyntax
884 deriving Show
885{-!
886deriving instance Binary SynContext
887deriving instance NFData SynContext
888!-}
890data Syntax = Rule [SSymbol] PTerm SynContext
891 deriving Show
892{-!
893deriving instance Binary Syntax
894deriving instance NFData Syntax
895!-}
897data SSymbol = Keyword Name
898 | Symbol String
899 | Binding Name
900 | Expr Name
901 | SimpleExpr Name
902 deriving Show
903{-!
904deriving instance Binary SSymbol
905deriving instance NFData SSymbol
906!-}
908initDSL = DSL (PRef f (sUN ">>="))
909 (PRef f (sUN "return"))
910 (PRef f (sUN "<$>"))
911 (PRef f (sUN "pure"))
912 Nothing
913 Nothing
914 Nothing
915 Nothing
916 Nothing
917 where f = fileFC "(builtin)"
919data Using = UImplicit Name PTerm
920 | UConstraint Name [Name]
921 deriving (Show, Eq)
922{-!
923deriving instance Binary Using
924deriving instance NFData Using
925!-}
927data SyntaxInfo = Syn { using :: [Using],
928 syn_params :: [(Name, PTerm)],
929 syn_namespace :: [String],
930 no_imp :: [Name],
931 decoration :: Name -> Name,
932 inPattern :: Bool,
933 implicitAllowed :: Bool,
934 dsl_info :: DSL }
935 deriving Show
936{-!
937deriving instance NFData SyntaxInfo
938deriving instance Binary SyntaxInfo
939!-}
941defaultSyntax = Syn [] [] [] [] id False False initDSL
943expandNS :: SyntaxInfo -> Name -> Name
944expandNS syn n@(NS _ _) = n
945expandNS syn n = case syn_namespace syn of
946 [] -> n
947 xs -> sNS n xs
950-- For inferring types of things
952bi = fileFC "builtin"
954inferTy = sMN 0 "__Infer"
955inferCon = sMN 0 "__infer"
956inferDecl = PDatadecl inferTy
957 PType
958 [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType (
959 PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType"))
960 (PRef bi inferTy)), bi, [])]
961inferOpts = []
963infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
964infP = P (TCon 6 0) inferTy (TType (UVal 0))
966getInferTerm, getInferType :: Term -> Term
967getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
968getInferTerm (App (App _ _) tm) = tm
969getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
971getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
972 where toTy (Lam t) = Pi t
973 toTy (PVar t) = PVTy t
974 toTy b = b
975getInferType (App (App _ ty) _) = ty
979-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign, Elim type class
981primNames = [unitTy, unitCon,
982 falseTy, pairTy, pairCon,
983 eqTy, eqCon, inferTy, inferCon]
985unitTy = sMN 0 "__Unit"
986unitCon = sMN 0 "__II"
987unitDecl = PDatadecl unitTy PType
988 [(emptyDocstring, [], unitCon, PRef bi unitTy, bi, [])]
989unitOpts = [DefaultEliminator]
991falseTy = sMN 0 "__False"
992falseDecl = PDatadecl falseTy PType []
993falseOpts = []
995pairTy = sMN 0 "__Pair"
996pairCon = sMN 0 "__MkPair"
997pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
998 [(emptyDocstring, [], pairCon, PPi impl (n "A") PType (
999 PPi impl (n "B") PType (
1000 PPi expl (n "a") (PRef bi (n "A")) (
1001 PPi expl (n "b") (PRef bi (n "B"))
1002 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
1003 pexp (PRef bi (n "B"))])))), bi, [])]
1004 where n a = sMN 0 a
1005pairOpts = []
1007eqTy = sUN "="
1008eqCon = sUN "refl"
1009eqDecl = PDatadecl eqTy (piBind [(n "A", PType), (n "B", PType),
1010 (n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))]
1011 PType)
1012 [(emptyDocstring, [], eqCon, PPi impl (n "A") PType (
1013 PPi impl (n "x") (PRef bi (n "A"))
1014 (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False,
1015 pimp (n "B") Placeholder False,
1016 pexp (PRef bi (n "x")),
1017 pexp (PRef bi (n "x"))])), bi, [])]
1018 where n a = sMN 0 a
1019eqOpts = []
1021elimName = sUN "__Elim"
1022elimMethElimTy = sUN "__elimTy"
1023elimMethElim = sUN "elim"
1024elimDecl = PClass (parseDocstring . T.pack $ "Type class for eliminators") defaultSyntax bi [] elimName [(sUN "scrutineeType", PType)]
1025 [PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElimTy PType,
1026 PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElim (PRef bi elimMethElimTy)]
1028-- Defined in builtins.idr
1029sigmaTy = sUN "Exists"
1030existsCon = sUN "Ex_intro"
1032piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1033piBind = piBindp expl
1035piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1036piBindp p [] t = t
1037piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t)
1040-- Pretty-printing declarations and terms
1042-- These "show" instances render to an absurdly wide screen because inserted line breaks
1043-- could interfere with interactive editing, which calls "show".
1045instance Show PTerm where
1046 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp False) tm
1048instance Show PDecl where
1049 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp False) d
1051instance Show PClause where
1052 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp True) c
1054instance Show PData where
1055 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp False) d
1057instance Pretty PTerm OutputAnnotation where
1058 pretty = prettyImp False
1060-- | Colourise annotations according to an Idris state. It ignores the names
1061-- in the annotation, as there's no good way to show extended information on a
1062-- terminal.
1063consoleDecorate :: IState -> OutputAnnotation -> String -> String
1064consoleDecorate ist _ | not (idris_colourRepl ist) = id
1065consoleDecorate ist AnnConstData = let theme = idris_colourTheme ist
1066 in colouriseData theme
1067consoleDecorate ist AnnConstType = let theme = idris_colourTheme ist
1068 in colouriseType theme
1069consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
1070consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
1071consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1072consoleDecorate ist (AnnName n _ _) = let ctxt = tt_ctxt ist
1073 theme = idris_colourTheme ist
1074 in case () of
1075 _ | isDConName n ctxt -> colouriseData theme
1076 _ | isFnName n ctxt -> colouriseFun theme
1077 _ | isTConName n ctxt -> colouriseType theme
1078 _ | otherwise -> id -- don't colourise unknown names
1079consoleDecorate ist (AnnFC _) = id
1080consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
1081 where colour BoldText = IdrisColour Nothing True False True False
1082 colour UnderlineText = IdrisColour Nothing True True False False
1083 colour ItalicText = IdrisColour Nothing True False False True
1085-- | Pretty-print a high-level closed Idris term
1086prettyImp :: Bool -- ^^ whether to show implicits
1087 -> PTerm -- ^^ the term to pretty-print
1088 -> Doc OutputAnnotation
1089prettyImp impl = pprintPTerm impl []
1091-- | Pretty-print a high-level Idris term in some bindings context
1092pprintPTerm :: Bool -- ^^ whether to show implicits
1093 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1094 -> PTerm -- ^^ the term to pretty-print
1095 -> Doc OutputAnnotation
1096pprintPTerm impl bnd = prettySe 10 bnd
1097 where
1098 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1099 prettySe p bnd (PQuote r) =
1100 text "![" <> pretty r <> text "]"
1101 prettySe p bnd (PPatvar fc n) = pretty n
1102 prettySe p bnd e
1103 | Just str <- slist p bnd e = str
1104 | Just n <- snat p e = annotate AnnConstData (text (show n))
1105 prettySe p bnd (PRef fc n) = prettyName impl bnd n
1106 prettySe p bnd (PLam n ty sc) =
1107 bracket p 2 . group . align . hang 2 $
1108 text "\\" <> bindingOf n False <+> text "=>" <$>
1109 prettySe 10 ((n, False):bnd) sc
1110 prettySe p bnd (PLet n ty v sc) =
1111 bracket p 2 $
1112 kwd "let" <+> bindingOf n False <+> text "=" </>
1113 prettySe 10 bnd v <+> kwd "in" </>
1114 prettySe 10 ((n, False):bnd) sc
1115 prettySe p bnd (PPi (Exp l s _) n ty sc)
1116 | n `elem` allNamesIn sc || impl =
1117 let open = if Lazy `elem` l then text "|" <> lparen else lparen in
1118 bracket p 2 . group $
1119 enclose open rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1120 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1121 | otherwise =
1122 bracket p 2 . group $
1123 group (prettySe 0 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1124 where
1125 st =
1126 case s of
1127 Static -> text "[static]" <> space
1128 _ -> empty
1129 prettySe p bnd (PPi (Imp l s _) n ty sc)
1130 | impl =
1131 let open = if Lazy `elem` l then text "|" <> lbrace else lbrace in
1132 bracket p 2 $
1133 open <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1134 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1135 | otherwise = prettySe 10 ((n, True):bnd) sc
1136 where
1137 st =
1138 case s of
1139 Static -> text "[static]" <> space
1140 _ -> empty
1141 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1142 bracket p 2 $
1143 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1144 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1145 bracket p 2 $
1146 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1147 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1148 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1149 | UN nm <- basename f
1150 , not impl && null (getExps args) = if isAlpha (thead nm)
1151 then prettyName impl bnd f
1152 else enclose lparen rparen $
1153 prettyName impl bnd f
1154 prettySe p bnd (PAppBind _ (PRef _ f) [])
1155 | not impl = text "!" <> prettyName impl bnd f
1156 prettySe p bnd (PApp _ (PRef _ op) args)
1157 | UN nm <- basename op
1158 , not (tnull nm) &&
1159 (not impl) && (not $ isAlpha (thead nm)) =
1160 case getExps args of
1161 [] -> enclose lparen rparen opName
1162 [x] -> group (enclose lparen rparen opName <$> group (prettySe 0 bnd x))
1163 [l,r] -> bracket p 1 $ inFix l r
1164 (l:r:rest) -> bracket p 1 $
1165 enclose lparen rparen (inFix l r) <+>
1166 align (group (vsep (map (prettyArgSe bnd) rest)))
1167 where opName = prettyName impl bnd op
1168 inFix l r = align . group $
1169 (prettySe 1 bnd l <+> opName) <$> group (prettySe 0 bnd r)
1170 prettySe p bnd (PApp _ hd@(PRef fc f) [tm])
1171 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1172 f == sUN "Symbol_" = char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1173 prettySe p bnd (PApp _ f as) =
1174 let args = getExps as
1175 fp = prettySe 1 bnd f
1176 in
1177 bracket p 1 . group $
1178 if impl
1179 then if null as
1180 then fp
1181 else fp <+> align (vsep (map (prettyArgS bnd) as))
1182 else if null args
1183 then fp
1184 else fp <+> align (vsep (map (prettyArgSe bnd) args))
1185 prettySe p bnd (PCase _ scr opts) =
1186 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1187 where
1188 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1190 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1191 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1192 prettySe p bnd (PRefl _ _) = annotate (AnnName eqCon Nothing Nothing) $ text "refl"
1193 prettySe p bnd (PResolveTC _) = text "resolvetc"
1194 prettySe p bnd (PTrue _ IsType) = annotate (AnnName unitTy Nothing Nothing) $ text "()"
1195 prettySe p bnd (PTrue _ IsTerm) = annotate (AnnName unitCon Nothing Nothing) $ text "()"
1196 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1197 prettySe p bnd (PFalse _) = annotate (AnnName falseTy Nothing Nothing) $ text "_|_"
1198 prettySe p bnd (PEq _ l r) =
1199 bracket p 2 . align . group $
1200 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1201 where eq = annotate (AnnName eqTy Nothing Nothing) (text "=")
1202 prettySe p bnd (PRewrite _ l r _) =
1203 bracket p 2 $
1204 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1205 prettySe p bnd (PTyped l r) =
1206 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1207 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1208 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1209 align . group . vsep . punctuate (ann comma) $
1210 map (prettySe 10 bnd) elts
1211 where ann = case pun of
1212 TypeOrTerm -> id
1213 IsType -> annotate (AnnName pairTy Nothing Nothing)
1214 IsTerm -> annotate (AnnName pairCon Nothing Nothing)
1215 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1216 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1217 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1218 annotate (AnnName sigmaTy Nothing Nothing) lparen <>
1219 bindingOf n False <+>
1220 annotate (AnnName sigmaTy Nothing Nothing) (text "**") <+>
1221 prettySe 10 ((n, False):bnd) r <>
1222 annotate (AnnName sigmaTy Nothing Nothing) rparen
1223 prettySe p bnd (PDPair _ IsType l t r) =
1224 annotate (AnnName sigmaTy Nothing Nothing) lparen <>
1225 prettySe 10 bnd l <+>
1226 annotate (AnnName sigmaTy Nothing Nothing) (text "**") <+>
1227 prettySe 10 bnd r <>
1228 annotate (AnnName sigmaTy Nothing Nothing) rparen
1229 prettySe p bnd (PDPair _ IsTerm l t r) =
1230 annotate (AnnName existsCon Nothing Nothing) lparen <>
1231 prettySe 10 bnd l <+>
1232 annotate (AnnName existsCon Nothing Nothing) (text "**") <+>
1233 prettySe 10 bnd r <>
1234 annotate (AnnName existsCon Nothing Nothing) rparen
1235 prettySe p bnd (PAlternative a as) =
1236 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1237 where
1238 prettyAs =
1239 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1240 prettySe p bnd PType = annotate AnnConstType $ text "Type"
1241 prettySe p bnd (PConstant c) = annotate (annot c) (text (show c))
1242 where annot (AType _) = AnnConstType
1243 annot StrType = AnnConstType
1244 annot PtrType = AnnConstType
1245 annot VoidType = AnnConstType
1246 annot _ = AnnConstData
1247 -- XXX: add pretty for tactics
1248 prettySe p bnd (PProof ts) =
1249 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1250 prettySe p bnd (PTactics ts) =
1251 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1252 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1253 prettySe p bnd (PReturn f) = kwd "return"
1254 prettySe p bnd PImpossible = kwd "impossible"
1255 prettySe p bnd Placeholder = text "_"
1256 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1257 prettySe p bnd (PElabError s) = pretty s
1259 prettySe p bnd _ = text "test"
1261 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1262 prettyArgS bnd (PExp _ _ tm) = prettyArgSe bnd tm
1263 prettyArgS bnd (PConstraint _ _ tm) = prettyArgSc bnd tm
1264 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1266 prettyArgSe bnd arg = prettySe 0 bnd arg
1267 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1268 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1269 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1271 basename :: Name -> Name
1272 basename (NS n _) = basename n
1273 basename n = n
1275 slist' p bnd (PApp _ (PRef _ nil) _)
1276 | not impl && nsroot nil == sUN "Nil" = Just []
1277 slist' p bnd (PRef _ nil)
1278 | not impl && nsroot nil == sUN "Nil" = Just []
1279 slist' p bnd (PApp _ (PRef _ cons) args)
1280 | nsroot cons == sUN "::",
1281 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1282 all isImp imps,
1283 Just tl' <- slist' p bnd tl
1284 = Just (hd:tl')
1285 where
1286 isImp (PImp {}) = True
1287 isImp _ = False
1288 slist' _ _ tm = Nothing
1290 slist p bnd e | Just es <- slist' p bnd e = Just $
1291 case es of [] -> annotate AnnConstData $ text "[]"
1292 [x] -> enclose left right . group $
1293 prettySe p bnd x
1294 xs -> (enclose left right .
1295 align . group . vsep .
1296 punctuate comma .
1297 map (prettySe p bnd)) xs
1298 where left = (annotate AnnConstData (text "["))
1299 right = (annotate AnnConstData (text "]"))
1300 comma = (annotate AnnConstData (text ","))
1301 slist _ _ _ = Nothing
1303 pairElts :: PTerm -> Maybe [PTerm]
1304 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1305 | otherwise = Just [x, y]
1306 pairElts _ = Nothing
1308 natns = "Prelude.Nat."
1310 snat p (PRef _ z)
1311 | show z == (natns++"Z") || show z == "Z" = Just 0
1312 snat p (PApp _ s [PExp {getTm=n}])
1313 | show s == (natns++"S") || show s == "S",
1314 Just n' <- snat p n
1315 = Just $ 1 + n'
1316 snat _ _ = Nothing
1318 bracket outer inner doc
1319 | inner > outer = lparen <> doc <> rparen
1320 | otherwise = doc
1322 kwd = annotate AnnKeyword . text
1324-- | Pretty-printer helper for the binding site of a name
1325bindingOf :: Name -- ^^ the bound name
1326 -> Bool -- ^^ whether the name is implicit
1327 -> Doc OutputAnnotation
1328bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1330-- | Pretty-printer helper for names that attaches the correct annotations
1331prettyName :: Bool -- ^^ whether to show namespaces
1332 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1333 -> Name -- ^^ the name to pprint
1334 -> Doc OutputAnnotation
1335prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1336 | otherwise = annotate (AnnName n Nothing Nothing) (text (strName n))
1337 where strName (UN n) = T.unpack n
1338 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1339 | otherwise = strName n
1340 strName (MN i s) = T.unpack s
1341 strName other = show other
1344showCImp :: Bool -> PClause -> Doc OutputAnnotation
1345showCImp impl (PClause _ n l ws r w)
1346 = prettyImp impl l <+> showWs ws <+> text "=" <+> prettyImp impl r
1347 <+> text "where" <+> text (show w)
1348 where
1349 showWs [] = empty
1350 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1351showCImp impl (PWith _ n l ws r w)
1352 = prettyImp impl l <+> showWs ws <+> text "with" <+> prettyImp impl r
1353 <+> braces (text (show w))
1354 where
1355 showWs [] = empty
1356 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1359showDImp :: Bool -> PData -> Doc OutputAnnotation
1360showDImp impl (PDatadecl n ty cons)
1361 = text "data" <+> text (show n) <+> colon <+> prettyImp impl ty <+> text "where" <$>
1362 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp impl t) cons))
1364showDecls :: Bool -> [PDecl] -> Doc OutputAnnotation
1365showDecls i ds = vsep (map (showDeclImp i) ds)
1367showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1368showDeclImp i (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp i t
1369showDeclImp i (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1370 indent 2 (vsep (map (showCImp i) cs))
1371showDeclImp _ (PData _ _ _ _ _ d) = showDImp True d
1372showDeclImp i (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls i ps <> line)
1373showDeclImp i (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls i ps <> line)
1374showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1375showDeclImp i (PClass _ _ _ cs n ps ds)
1376 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls i ds
1377showDeclImp i (PInstance _ _ cs n _ t _ ds)
1378 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp i t <> line <> showDecls i ds
1379showDeclImp _ _ = text "..."
1380-- showDeclImp (PImport i) = "import " ++ i
1382instance Show (Doc OutputAnnotation) where
1383 show = flip (displayS . renderCompact) ""
1385getImps :: [PArg] -> [(Name, PTerm)]
1386getImps [] = []
1387getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1388getImps (_ : xs) = getImps xs
1390getExps :: [PArg] -> [PTerm]
1391getExps [] = []
1392getExps (PExp _ _ tm : xs) = tm : getExps xs
1393getExps (_ : xs) = getExps xs
1395getConsts :: [PArg] -> [PTerm]
1396getConsts [] = []
1397getConsts (PConstraint _ _ tm : xs) = tm : getConsts xs
1398getConsts (_ : xs) = getConsts xs
1400getAll :: [PArg] -> [PTerm]
1401getAll = map getTm
1404-- | Show Idris name
1405showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1406 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1407 -> Bool -- ^^ whether to show implicits
1408 -> Bool -- ^^ whether to colourise
1409 -> Name -- ^^ the term to show
1410 -> String
1411showName ist bnd impl colour n = case ist of
1412 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1413 Nothing -> showbasic n
1414 where name = if impl then show n else showbasic n
1415 showbasic n@(UN _) = showCG n
1416 showbasic (MN _ s) = str s
1417 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1418 showbasic (SN s) = show s
1419 fst3 (x, _, _) = x
1420 colourise n t = let ctxt' = fmap tt_ctxt ist in
1421 case ctxt' of
1422 Nothing -> name
1423 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1424 else colouriseBound t name
1425 | isDConName n ctxt -> colouriseData t name
1426 | isFnName n ctxt -> colouriseFun t name
1427 | isTConName n ctxt -> colouriseType t name
1428 -- The assumption is that if a name is not bound and does not exist in the
1429 -- global context, then we're somewhere in which implicit info has been lost
1430 -- (like error messages). Thus, unknown vars are colourised as implicits.
1431 | otherwise -> colouriseImplicit t name
1433showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1434 -> PTerm -- ^^ the term to show
1435 -> String
1436showTm ist = displayDecorated (consoleDecorate ist) . renderCompact . prettyImp (opt_showimp (idris_options ist))
1438-- | Show a term with implicits, no colours
1439showTmImpls :: PTerm -> String
1440showTmImpls = flip (displayS . renderCompact . prettyImp True) ""
1443instance Sized PTerm where
1444 size (PQuote rawTerm) = size rawTerm
1445 size (PRef fc name) = size name
1446 size (PLam name ty bdy) = 1 + size ty + size bdy
1447 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1448 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1449 size (PTyped trm ty) = 1 + size trm + size ty
1450 size (PApp fc name args) = 1 + size args
1451 size (PAppBind fc name args) = 1 + size args
1452 size (PCase fc trm bdy) = 1 + size trm + size bdy
1453 size (PTrue fc _) = 1
1454 size (PFalse fc) = 1
1455 size (PRefl fc _) = 1
1456 size (PResolveTC fc) = 1
1457 size (PEq fc left right) = 1 + size left + size right
1458 size (PRewrite fc left right _) = 1 + size left + size right
1459 size (PPair fc _ left right) = 1 + size left + size right
1460 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1461 size (PAlternative a alts) = 1 + size alts
1462 size (PHidden hidden) = size hidden
1463 size (PUnifyLog tm) = size tm
1464 size (PDisamb _ tm) = size tm
1465 size (PNoImplicits tm) = size tm
1466 size PType = 1
1467 size (PConstant const) = 1 + size const
1468 size Placeholder = 1
1469 size (PDoBlock dos) = 1 + size dos
1470 size (PIdiom fc term) = 1 + size term
1471 size (PReturn fc) = 1
1472 size (PMetavar name) = 1
1473 size (PProof tactics) = size tactics
1474 size (PElabError err) = size err
1475 size PImpossible = 1
1477getPArity :: PTerm -> Int
1478getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1479getPArity _ = 0
1481-- Return all names, free or globally bound, in the given term.
1483allNamesIn :: PTerm -> [Name]
1484allNamesIn tm = nub $ ni [] tm
1485 where
1486 ni env (PRef _ n)
1487 | not (n `elem` env) = [n]
1488 ni env (PPatvar _ n) = [n]
1489 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1490 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1491 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1492 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1493 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1494 ni env (PHidden tm) = ni env tm
1495 ni env (PEq _ l r) = ni env l ++ ni env r
1496 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1497 ni env (PTyped l r) = ni env l ++ ni env r
1498 ni env (PPair _ _ l r) = ni env l ++ ni env r
1499 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1500 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1501 ni env (PAlternative a ls) = concatMap (ni env) ls
1502 ni env (PUnifyLog tm) = ni env tm
1503 ni env (PDisamb _ tm) = ni env tm
1504 ni env (PNoImplicits tm) = ni env tm
1505 ni env _ = []
1507-- Return all names defined in binders in the given term
1508boundNamesIn :: PTerm -> [Name]
1509boundNamesIn tm = nub $ ni tm
1510 where
1511 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1512 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1513 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1514 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1515 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1516 ni (PPi _ n ty sc) = n : (ni ty ++ ni sc)
1517 ni (PEq _ l r) = ni l ++ ni r
1518 ni (PRewrite _ l r _) = ni l ++ ni r
1519 ni (PTyped l r) = ni l ++ ni r
1520 ni (PPair _ _ l r) = ni l ++ ni r
1521 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1522 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1523 ni (PAlternative a as) = concatMap (ni) as
1524 ni (PHidden tm) = ni tm
1525 ni (PUnifyLog tm) = ni tm
1526 ni (PDisamb _ tm) = ni tm
1527 ni (PNoImplicits tm) = ni tm
1528 ni _ = []
1530-- Return names which are free in the given term.
1531namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1532namesIn uvars ist tm = nub $ ni [] tm
1533 where
1534 ni env (PRef _ n)
1535 | not (n `elem` env)
1536 = case lookupTy n (tt_ctxt ist) of
1537 [] -> [n]
1538 _ -> if n `elem` (map fst uvars) then [n] else []
1539 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1540 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1541 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1542 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1543 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1544 ni env (PEq _ l r) = ni env l ++ ni env r
1545 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1546 ni env (PTyped l r) = ni env l ++ ni env r
1547 ni env (PPair _ _ l r) = ni env l ++ ni env r
1548 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1549 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1550 ni env (PAlternative a as) = concatMap (ni env) as
1551 ni env (PHidden tm) = ni env tm
1552 ni env (PUnifyLog tm) = ni env tm
1553 ni env (PDisamb _ tm) = ni env tm
1554 ni env (PNoImplicits tm) = ni env tm
1555 ni env _ = []
1557-- Return which of the given names are used in the given term.
1559usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1560usedNamesIn vars ist tm = nub $ ni [] tm
1561 where
1562 ni env (PRef _ n)
1563 | n `elem` vars && not (n `elem` env)
1564 = case lookupTy n (tt_ctxt ist) of
1565 [] -> [n]
1566 _ -> []
1567 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1568 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1569 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1570 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1571 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1572 ni env (PEq _ l r) = ni env l ++ ni env r
1573 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1574 ni env (PTyped l r) = ni env l ++ ni env r
1575 ni env (PPair _ _ l r) = ni env l ++ ni env r
1576 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1577 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1578 ni env (PAlternative a as) = concatMap (ni env) as
1579 ni env (PHidden tm) = ni env tm
1580 ni env (PUnifyLog tm) = ni env tm
1581 ni env (PDisamb _ tm) = ni env tm
1582 ni env (PNoImplicits tm) = ni env tm
1583 ni env _ = []