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