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