on bab6c7b help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1501 lines 57 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 Data.Either
30import qualified Data.Set as S
31import Data.Word (Word)
33import Debug.Trace
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 syntax_rules :: [Syntax],
115 syntax_keywords :: [String],
116 imported :: [FilePath], -- ^ The imported modules
117 idris_scprims :: [(Name, (Int, PrimFn))],
118 idris_objs :: [(Codegen, FilePath)],
119 idris_libs :: [(Codegen, String)],
120 idris_cgflags :: [(Codegen, String)],
121 idris_hdrs :: [(Codegen, String)],
122 proof_list :: [(Name, [String])],
123 errLine :: Maybe Int,
124 lastParse :: Maybe Name,
125 indent_stack :: [Int],
126 brace_stack :: [Maybe Int],
127 hide_list :: [(Name, Maybe Accessibility)],
128 default_access :: Accessibility,
129 default_total :: Bool,
130 ibc_write :: [IBCWrite],
131 compiled_so :: Maybe String,
132 idris_dynamic_libs :: [DynamicLib],
133 idris_language_extensions :: [LanguageExt],
134 idris_outputmode :: OutputMode,
135 idris_colourRepl :: Bool,
136 idris_colourTheme :: ColourTheme,
137 idris_outh :: Handle,
138 idris_errorhandlers :: [Name], -- ^ Global error handlers
139 idris_nameIdx :: (Int, Ctxt (Int, Name)),
140 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)) -- ^ Specific error handlers
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 | IBCCG Name
191 | IBCDoc Name
192 | IBCCoercion Name
193 | IBCDef Name -- i.e. main context
194 | IBCNameHint (Name, Name)
195 | IBCLineApp FilePath Int PTerm
196 | IBCErrorHandler Name
197 | IBCFunctionErrorHandler Name Name Name
198 deriving Show
200-- | The initial state for the compiler
201idrisInit :: IState
202idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
203 emptyContext emptyContext emptyContext emptyContext
204 emptyContext emptyContext emptyContext emptyContext
205 emptyContext
206 [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] []
207 [] Nothing Nothing [] [] [] Hidden False [] Nothing [] [] RawOutput
208 True defaultTheme stdout [] (0, emptyContext) emptyContext
210-- | The monad for the main REPL - reading and processing files and updating
211-- global state (hence the IO inner monad).
212--type Idris = WriterT [Either String (IO ())] (State IState a))
213type Idris = StateT IState (ErrorT Err IO)
215-- Commands in the REPL
217data Codegen = ViaC
218 | ViaJava
219 | ViaNode
220 | ViaJavaScript
221 | ViaLLVM
222 | Bytecode
223 deriving (Show, Eq)
225-- | REPL commands
226data Command = Quit
227 | Help
228 | Eval PTerm
229 | Check PTerm
230 | DocStr Name
231 | TotCheck Name
232 | Reload
233 | Load FilePath
234 | ChangeDirectory FilePath
235 | ModImport String
236 | Edit
237 | Compile Codegen String
238 | Execute
239 | ExecVal PTerm
240 | Metavars
241 | Prove Name
242 | AddProof (Maybe Name)
243 | RmProof Name
244 | ShowProof Name
245 | Proofs
246 | Universes
247 | LogLvl Int
248 | Spec PTerm
249 | HNF PTerm
250 | TestInline PTerm
251 | Defn Name
252 | Info Name
253 | Missing Name
254 | DynamicLink FilePath
255 | ListDynamic
256 | Pattelab PTerm
257 | DebugInfo Name
258 | Search PTerm
259 | CaseSplitAt Bool Int Name
260 | AddClauseFrom Bool Int Name
261 | AddProofClauseFrom Bool Int Name
262 | AddMissing Bool Int Name
263 | MakeWith Bool Int Name
264 | DoProofSearch Bool Int Name [Name]
265 | SetOpt Opt
266 | UnsetOpt Opt
267 | NOP
268 | SetColour ColourType IdrisColour
269 | ColourOn
270 | ColourOff
271 | ListErrorHandlers
273data Opt = Filename String
274 | Ver
275 | Usage
276 | Quiet
277 | NoBanner
278 | ColourREPL Bool
279 | Ideslave
280 | ShowLibs
281 | ShowLibdir
282 | ShowIncs
283 | NoBasePkgs
284 | NoPrelude
285 | NoBuiltins -- only for the really primitive stuff!
286 | NoREPL
287 | OLogging Int
288 | Output String
289 | TypeCase
290 | TypeInType
291 | DefaultTotal
292 | DefaultPartial
293 | WarnPartial
294 | NoCoverage
295 | ErrContext
296 | ShowImpl
297 | Verbose
298 | IBCSubDir String
299 | ImportDir String
300 | PkgBuild String
301 | PkgInstall String
302 | PkgClean String
303 | PkgCheck String
304 | WarnOnly
305 | Pkg String
306 | BCAsm String
307 | DumpDefun String
308 | DumpCases String
309 | UseCodegen Codegen
310 | OutputTy OutputType
311 | Extension LanguageExt
312 | InterpretScript String
313 | TargetTriple String
314 | TargetCPU String
315 | OptLevel Word
316 | Client String
317 deriving (Show, Eq)
319-- Parsed declarations
321data Fixity = Infixl { prec :: Int }
322 | Infixr { prec :: Int }
323 | InfixN { prec :: Int }
324 | PrefixN { prec :: Int }
325 deriving Eq
326{-!
327deriving instance Binary Fixity
328deriving instance NFData Fixity
329!-}
331instance Show Fixity where
332 show (Infixl i) = "infixl " ++ show i
333 show (Infixr i) = "infixr " ++ show i
334 show (InfixN i) = "infix " ++ show i
335 show (PrefixN i) = "prefix " ++ show i
337data FixDecl = Fix Fixity String
338 deriving Eq
340instance Show FixDecl where
341 show (Fix f s) = show f ++ " " ++ s
343{-!
344deriving instance Binary FixDecl
345deriving instance NFData FixDecl
346!-}
348instance Ord FixDecl where
349 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
352data Static = Static | Dynamic
353 deriving (Show, Eq)
354{-!
355deriving instance Binary Static
356deriving instance NFData Static
357!-}
359-- Mark bindings with their explicitness, and laziness
360data Plicity = Imp { plazy :: Bool,
361 pstatic :: Static,
362 pdocstr :: String,
363 pparam :: Bool }
364 | Exp { plazy :: Bool,
365 pstatic :: Static,
366 pdocstr :: String,
367 pparam :: Bool }
368 | Constraint { plazy :: Bool,
369 pstatic :: Static,
370 pdocstr :: String }
371 | TacImp { plazy :: Bool,
372 pstatic :: Static,
373 pscript :: PTerm,
374 pdocstr :: String }
375 deriving (Show, Eq)
377{-!
378deriving instance Binary Plicity
379deriving instance NFData Plicity
380!-}
382impl = Imp False Dynamic "" False
383expl = Exp False Dynamic "" False
384expl_param = Exp False Dynamic "" True
385constraint = Constraint False Dynamic ""
386tacimpl t = TacImp False Dynamic t ""
388data FnOpt = Inlinable -- always evaluate when simplifying
389 | TotalFn | PartialFn
390 | Coinductive | AssertTotal
391 | Dictionary -- type class dictionary, eval only when
392 -- a function argument, and further evaluation resutls
393 | Implicit -- implicit coercion
394 | CExport String -- export, with a C name
395 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
396 | Reflection -- a reflecting function, compile-time only
397 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
398 deriving (Show, Eq)
399{-!
400deriving instance Binary FnOpt
401deriving instance NFData FnOpt
402!-}
404type FnOpts = [FnOpt]
406inlinable :: FnOpts -> Bool
407inlinable = elem Inlinable
409dictionary :: FnOpts -> Bool
410dictionary = elem Dictionary
413-- | Data declaration options
414data DataOpt = Codata -- Set if the the data-type is coinductive
415 | DefaultEliminator -- Set if an eliminator should be generated for data type
416 deriving (Show, Eq)
418type DataOpts = [DataOpt]
420-- | Top-level declarations such as compiler directives, definitions,
421-- datatypes and typeclasses.
422data PDecl' t
423 = PFix FC Fixity [String] -- ^ Fixity declaration
424 | PTy String SyntaxInfo FC FnOpts Name t -- ^ Type declaration
425 | PPostulate String SyntaxInfo FC FnOpts Name t -- ^ Postulate
426 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
427 | PCAF FC Name t -- ^ Top level constant
428 | PData String SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
429 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
430 | PNamespace String [PDecl' t] -- ^ New namespace
431 | PRecord String SyntaxInfo FC Name t String Name t -- ^ Record declaration
432 | PClass String SyntaxInfo FC
433 [t] -- constraints
434 Name
435 [(Name, t)] -- parameters
436 [PDecl' t] -- declarations
437 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
438 -- class name, parameters, method declarations
439 | PInstance SyntaxInfo FC [t] -- constraints
440 Name -- class
441 [t] -- parameters
442 t -- full instance type
443 (Maybe Name) -- explicit name
444 [PDecl' t]
445 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
446 -- class name, parameters, full instance type, optional explicit name, and definitions
447 | PDSL Name (DSL' t) -- ^ DSL declaration
448 | PSyntax FC Syntax -- ^ Syntax definition
449 | PMutual FC [PDecl' t] -- ^ Mutual block
450 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
451 | PProvider SyntaxInfo FC Name t t -- ^ Type provider. The first t is the type, the second is the term
452 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
453 -- bool is True, lhs and rhs must be convertible
454 deriving Functor
455{-!
456deriving instance Binary PDecl'
457deriving instance NFData PDecl'
458!-}
460-- For elaborator state
461type ElabD a = Elab' [PDecl] a
463-- | One clause of a top-level definition. Term arguments to constructors are:
464--
465-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
466--
467-- 2. The list of extra 'with' patterns
468--
469-- 3. The right-hand side
470--
471-- 4. The where block (PDecl' t)
473data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
474 | PWith FC Name t [t] t [PDecl' t]
475 | PClauseR FC [t] t [PDecl' t]
476 | PWithR FC [t] t [PDecl' t]
477 deriving Functor
478{-!
479deriving instance Binary PClause'
480deriving instance NFData PClause'
481!-}
483-- | Data declaration
484data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
485 d_tcon :: t, -- ^ Type constructor
486 d_cons :: [(String, Name, t, FC, [Name])] -- ^ Constructors
487 }
488 -- ^ Data declaration
489 | PLaterdecl { d_name :: Name, d_tcon :: t }
490 -- ^ "Placeholder" for data whose constructors are defined later
491 deriving Functor
492{-!
493deriving instance Binary PData'
494deriving instance NFData PData'
495!-}
497-- Handy to get a free function for applying PTerm -> PTerm functions
498-- across a program, by deriving Functor
500type PDecl = PDecl' PTerm
501type PData = PData' PTerm
502type PClause = PClause' PTerm
504-- get all the names declared in a decl
506declared :: PDecl -> [Name]
507declared (PFix _ _ _) = []
508declared (PTy _ _ _ _ n t) = [n]
509declared (PPostulate _ _ _ _ n t) = [n]
510declared (PClauses _ _ n _) = [] -- not a declaration
511declared (PCAF _ n _) = [n]
512declared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
513 where fstt (_, a, _, _, _) = a
514declared (PData _ _ _ _ (PLaterdecl n _)) = [n]
515declared (PParams _ _ ds) = concatMap declared ds
516declared (PNamespace _ ds) = concatMap declared ds
517declared (PRecord _ _ _ n _ _ c _) = [n, c]
518declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
519declared (PInstance _ _ _ _ _ _ _ _) = []
520declared (PDSL n _) = [n]
521declared (PSyntax _ _) = []
522declared (PMutual _ ds) = concatMap declared ds
523declared (PDirective _) = []
525-- get the names declared, not counting nested parameter blocks
526tldeclared :: PDecl -> [Name]
527tldeclared (PFix _ _ _) = []
528tldeclared (PTy _ _ _ _ n t) = [n]
529tldeclared (PPostulate _ _ _ _ n t) = [n]
530tldeclared (PClauses _ _ n _) = [] -- not a declaration
531tldeclared (PRecord _ _ _ n _ _ c _) = [n, c]
532tldeclared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
533 where fstt (_, a, _, _, _) = a
534tldeclared (PParams _ _ ds) = []
535tldeclared (PMutual _ ds) = concatMap tldeclared ds
536tldeclared (PNamespace _ ds) = concatMap tldeclared ds
537tldeclared (PClass _ _ _ _ n _ ms) = concatMap tldeclared ms
538tldeclared (PInstance _ _ _ _ _ _ _ _) = []
539tldeclared _ = []
541defined :: PDecl -> [Name]
542defined (PFix _ _ _) = []
543defined (PTy _ _ _ _ n t) = []
544defined (PPostulate _ _ _ _ n t) = []
545defined (PClauses _ _ n _) = [n] -- not a declaration
546defined (PCAF _ n _) = [n]
547defined (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
548 where fstt (_, a, _, _, _) = a
549defined (PData _ _ _ _ (PLaterdecl n _)) = []
550defined (PParams _ _ ds) = concatMap defined ds
551defined (PNamespace _ ds) = concatMap defined ds
552defined (PRecord _ _ _ n _ _ c _) = [n, c]
553defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
554defined (PInstance _ _ _ _ _ _ _ _) = []
555defined (PDSL n _) = [n]
556defined (PSyntax _ _) = []
557defined (PMutual _ ds) = concatMap defined ds
558defined (PDirective _) = []
559--defined _ = []
561updateN :: [(Name, Name)] -> Name -> Name
562updateN ns n | Just n' <- lookup n ns = n'
563updateN _ n = n
565updateNs :: [(Name, Name)] -> PTerm -> PTerm
566updateNs [] t = t
567updateNs ns t = mapPT updateRef t
568 where updateRef (PRef fc f) = PRef fc (updateN ns f)
569 updateRef t = t
571-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
572-- updateDNs [] t = t
573-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
574-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
575-- where updateCNs ns (PClause n l ts r ds)
576-- = PClause (updateN ns n) (fmap (updateNs ns) l)
577-- (map (fmap (updateNs ns)) ts)
578-- (fmap (updateNs ns) r)
579-- (map (updateDNs ns) ds)
580-- updateDNs ns c = c
582-- | High level language terms
583data PTerm = PQuote Raw
584 | PRef FC Name
585 | PInferRef FC Name -- ^ A name to be defined later
586 | PPatvar FC Name
587 | PLam Name PTerm PTerm
588 | PPi Plicity Name PTerm PTerm
589 | PLet Name PTerm PTerm PTerm
590 | PTyped PTerm PTerm -- ^ Term with explicit type
591 | PApp FC PTerm [PArg]
592 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
593 | PMatchApp FC Name -- ^ Make an application by type matching
594 | PCase FC PTerm [(PTerm, PTerm)]
595 | PTrue FC
596 | PFalse FC
597 | PRefl FC PTerm
598 | PResolveTC FC
599 | PEq FC PTerm PTerm
600 | PRewrite FC PTerm PTerm (Maybe PTerm)
601 | PPair FC PTerm PTerm
602 | PDPair FC PTerm PTerm PTerm
603 | PAlternative Bool [PTerm] -- True if only one may work
604 | PHidden PTerm -- ^ Irrelevant or hidden pattern
605 | PType
606 | PGoal FC PTerm Name PTerm
607 | PConstant Const
608 | Placeholder
609 | PDoBlock [PDo]
610 | PIdiom FC PTerm
611 | PReturn FC
612 | PMetavar Name
613 | PProof [PTactic] -- ^ Proof script
614 | PTactics [PTactic] -- ^ As PProof, but no auto solving
615 | PElabError Err -- ^ Error to report on elaboration
616 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
617 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
618 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
619 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
620 | PNoImplicits PTerm -- ^ never run implicit converions on the term
621 deriving Eq
624{-!
625deriving instance Binary PTerm
626deriving instance NFData PTerm
627!-}
629mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
630mapPT f t = f (mpt t) where
631 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
632 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
633 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
634 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
635 (fmap (mapPT f) g)
636 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
637 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
638 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
639 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
640 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
641 mpt (PPair fc l r) = PPair fc (mapPT f l) (mapPT f r)
642 mpt (PDPair fc l t r) = PDPair fc (mapPT f l) (mapPT f t) (mapPT f r)
643 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
644 mpt (PHidden t) = PHidden (mapPT f t)
645 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
646 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
647 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
648 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
649 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
650 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
651 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
652 mpt x = x
655data PTactic' t = Intro [Name] | Intros | Focus Name
656 | Refine Name [Bool] | Rewrite t
657 | Induction Name
658 | Equiv t
659 | MatchRefine Name
660 | LetTac Name t | LetTacTy Name t t
661 | Exact t | Compute | Trivial
662 | ProofSearch (Maybe Name) Name [Name]
663 | Solve
664 | Attack
665 | ProofState | ProofTerm | Undo
666 | Try (PTactic' t) (PTactic' t)
667 | TSeq (PTactic' t) (PTactic' t)
668 | ApplyTactic t -- see Language.Reflection module
669 | ByReflection t
670 | Reflect t
671 | Fill t
672 | GoalType String (PTactic' t)
673 | Qed | Abandon
674 deriving (Show, Eq, Functor)
675{-!
676deriving instance Binary PTactic'
677deriving instance NFData PTactic'
678!-}
680instance Sized a => Sized (PTactic' a) where
681 size (Intro nms) = 1 + size nms
682 size Intros = 1
683 size (Focus nm) = 1 + size nm
684 size (Refine nm bs) = 1 + size nm + length bs
685 size (Rewrite t) = 1 + size t
686 size (Induction t) = 1 + size t
687 size (LetTac nm t) = 1 + size nm + size t
688 size (Exact t) = 1 + size t
689 size Compute = 1
690 size Trivial = 1
691 size Solve = 1
692 size Attack = 1
693 size ProofState = 1
694 size ProofTerm = 1
695 size Undo = 1
696 size (Try l r) = 1 + size l + size r
697 size (TSeq l r) = 1 + size l + size r
698 size (ApplyTactic t) = 1 + size t
699 size (Reflect t) = 1 + size t
700 size (Fill t) = 1 + size t
701 size Qed = 1
702 size Abandon = 1
704type PTactic = PTactic' PTerm
706data PDo' t = DoExp FC t
707 | DoBind FC Name t
708 | DoBindP FC t t
709 | DoLet FC Name t t
710 | DoLetP FC t t
711 deriving (Eq, Functor)
712{-!
713deriving instance Binary PDo'
714deriving instance NFData PDo'
715!-}
717instance Sized a => Sized (PDo' a) where
718 size (DoExp fc t) = 1 + size fc + size t
719 size (DoBind fc nm t) = 1 + size fc + size nm + size t
720 size (DoBindP fc l r) = 1 + size fc + size l + size r
721 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
722 size (DoLetP fc l r) = 1 + size fc + size l + size r
724type PDo = PDo' PTerm
726-- The priority gives a hint as to elaboration order. Best to elaborate
727-- things early which will help give a more concrete type to other
728-- variables, e.g. a before (interpTy a).
730data PArg' t = PImp { priority :: Int,
731 machine_inf :: Bool, -- true if the machine inferred it
732 lazyarg :: Bool, pname :: Name, getTm :: t,
733 pargdoc :: String }
734 | PExp { priority :: Int,
735 lazyarg :: Bool, getTm :: t,
736 pargdoc :: String }
737 | PConstraint { priority :: Int,
738 lazyarg :: Bool, getTm :: t,
739 pargdoc :: String }
740 | PTacImplicit { priority :: Int,
741 lazyarg :: Bool, pname :: Name,
742 getScript :: t,
743 getTm :: t,
744 pargdoc :: String }
745 deriving (Show, Eq, Functor)
747instance Sized a => Sized (PArg' a) where
748 size (PImp p _ l nm trm _) = 1 + size nm + size trm
749 size (PExp p l trm _) = 1 + size trm
750 size (PConstraint p l trm _) = 1 + size trm
751 size (PTacImplicit p l nm scr trm _) = 1 + size nm + size scr + size trm
753{-!
754deriving instance Binary PArg'
755deriving instance NFData PArg'
756!-}
758pimp n t mach = PImp 1 mach True n t ""
759pexp t = PExp 1 False t ""
760pconst t = PConstraint 1 False t ""
761ptacimp n s t = PTacImplicit 2 True n s t ""
763type PArg = PArg' PTerm
765-- Type class data
767data ClassInfo = CI { instanceName :: Name,
768 class_methods :: [(Name, (FnOpts, PTerm))],
769 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
770 class_default_superclasses :: [PDecl],
771 class_params :: [Name],
772 class_instances :: [Name] }
773 deriving Show
774{-!
775deriving instance Binary ClassInfo
776deriving instance NFData ClassInfo
777!-}
779-- An argument is conditionally forceable iff its forceability
780-- depends on the collapsibility of the whole type.
781data Forceability = Conditional | Unconditional deriving (Show, Enum, Bounded, Eq, Ord)
783{-!
784deriving instance Binary Forceability
785deriving instance NFData Forceability
786!-}
788data OptInfo = Optimise { collapsible :: Bool,
789 isnewtype :: Bool,
790 -- The following should actually be (IntMap Forceability)
791 -- but the corresponding Binary instance seems to be broken.
792 -- Let's store a list and convert it to IntMap whenever needed.
793 forceable :: [(Int, Forceability)],
794 recursive :: [Int] }
795 deriving Show
796{-!
797deriving instance Binary OptInfo
798deriving instance NFData OptInfo
799!-}
802data TypeInfo = TI { con_names :: [Name],
803 codata :: Bool,
804 param_pos :: [Int] }
805 deriving Show
806{-!
807deriving instance Binary TypeInfo
808deriving instance NFData TypeInfo
809!-}
811-- Syntactic sugar info
813data DSL' t = DSL { dsl_bind :: t,
814 dsl_return :: t,
815 dsl_apply :: t,
816 dsl_pure :: t,
817 dsl_var :: Maybe t,
818 index_first :: Maybe t,
819 index_next :: Maybe t,
820 dsl_lambda :: Maybe t,
821 dsl_let :: Maybe t
822 }
823 deriving (Show, Functor)
824{-!
825deriving instance Binary DSL'
826deriving instance NFData DSL'
827!-}
829type DSL = DSL' PTerm
831data SynContext = PatternSyntax | TermSyntax | AnySyntax
832 deriving Show
833{-!
834deriving instance Binary SynContext
835deriving instance NFData SynContext
836!-}
838data Syntax = Rule [SSymbol] PTerm SynContext
839 deriving Show
840{-!
841deriving instance Binary Syntax
842deriving instance NFData Syntax
843!-}
845data SSymbol = Keyword Name
846 | Symbol String
847 | Binding Name
848 | Expr Name
849 | SimpleExpr Name
850 deriving Show
851{-!
852deriving instance Binary SSymbol
853deriving instance NFData SSymbol
854!-}
856initDSL = DSL (PRef f (sUN ">>="))
857 (PRef f (sUN "return"))
858 (PRef f (sUN "<$>"))
859 (PRef f (sUN "pure"))
860 Nothing
861 Nothing
862 Nothing
863 Nothing
864 Nothing
865 where f = fileFC "(builtin)"
867data Using = UImplicit Name PTerm
868 | UConstraint Name [Name]
869 deriving (Show, Eq)
870{-!
871deriving instance Binary Using
872deriving instance NFData Using
873!-}
875data SyntaxInfo = Syn { using :: [Using],
876 syn_params :: [(Name, PTerm)],
877 syn_namespace :: [String],
878 no_imp :: [Name],
879 decoration :: Name -> Name,
880 inPattern :: Bool,
881 implicitAllowed :: Bool,
882 dsl_info :: DSL }
883 deriving Show
884{-!
885deriving instance NFData SyntaxInfo
886deriving instance Binary SyntaxInfo
887!-}
889defaultSyntax = Syn [] [] [] [] id False False initDSL
891expandNS :: SyntaxInfo -> Name -> Name
892expandNS syn n@(NS _ _) = n
893expandNS syn n = case syn_namespace syn of
894 [] -> n
895 xs -> sNS n xs
898--- Pretty printing declarations and terms
900instance Show PTerm where
901 show tm = showImp Nothing False False tm
903instance Pretty PTerm where
904 pretty = prettyImp False
906instance Show PDecl where
907 show d = showDeclImp False d
909instance Show PClause where
910 show c = showCImp True c
912instance Show PData where
913 show d = showDImp False d
915showDecls :: Bool -> [PDecl] -> String
916showDecls _ [] = ""
917showDecls i (d:ds) = showDeclImp i d ++ "\n" ++ showDecls i ds
919showDeclImp _ (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
920showDeclImp i (PTy _ _ _ _ n t) = "tydecl " ++ showCG n ++ " : " ++ showImp Nothing i False t
921showDeclImp i (PClauses _ _ n cs) = "pat " ++ showCG n ++ "\t" ++ showSep "\n\t" (map (showCImp i) cs)
922showDeclImp _ (PData _ _ _ _ d) = showDImp True d
923showDeclImp i (PParams _ ns ps) = "params {" ++ show ns ++ "\n" ++ showDecls i ps ++ "}\n"
924showDeclImp i (PNamespace n ps) = "namespace {" ++ n ++ "\n" ++ showDecls i ps ++ "}\n"
925showDeclImp _ (PSyntax _ syn) = "syntax " ++ show syn
926showDeclImp i (PClass _ _ _ cs n ps ds)
927 = "class " ++ show cs ++ " " ++ show n ++ " " ++ show ps ++ "\n" ++ showDecls i ds
928showDeclImp i (PInstance _ _ cs n _ t _ ds)
929 = "instance " ++ show cs ++ " " ++ show n ++ " " ++ show t ++ "\n" ++ showDecls i ds
930showDeclImp _ _ = "..."
931-- showDeclImp (PImport i) = "import " ++ i
934showCImp :: Bool -> PClause -> String
935showCImp impl (PClause _ n l ws r w)
936 = showImp Nothing impl False l ++ showWs ws ++ " = " ++ showImp Nothing impl False r
937 ++ " where " ++ show w
938 where
939 showWs [] = ""
940 showWs (x : xs) = " | " ++ showImp Nothing impl False x ++ showWs xs
941showCImp impl (PWith _ n l ws r w)
942 = showImp Nothing impl False l ++ showWs ws ++ " with " ++ showImp Nothing impl False r
943 ++ " { " ++ show w ++ " } "
944 where
945 showWs [] = ""
946 showWs (x : xs) = " | " ++ showImp Nothing impl False x ++ showWs xs
949showDImp :: Bool -> PData -> String
950showDImp impl (PDatadecl n ty cons)
951 = "data " ++ show n ++ " : " ++ showImp Nothing impl False ty ++ " where\n\t"
952 ++ showSep "\n\t| "
953 (map (\ (_, n, t, _, _) -> show n ++ " : " ++ showImp Nothing impl False t) cons)
955getImps :: [PArg] -> [(Name, PTerm)]
956getImps [] = []
957getImps (PImp _ _ _ n tm _ : xs) = (n, tm) : getImps xs
958getImps (_ : xs) = getImps xs
960getExps :: [PArg] -> [PTerm]
961getExps [] = []
962getExps (PExp _ _ tm _ : xs) = tm : getExps xs
963getExps (_ : xs) = getExps xs
965getConsts :: [PArg] -> [PTerm]
966getConsts [] = []
967getConsts (PConstraint _ _ tm _ : xs) = tm : getConsts xs
968getConsts (_ : xs) = getConsts xs
970getAll :: [PArg] -> [PTerm]
971getAll = map getTm
973-- | Pretty-print a high-level Idris term
974prettyImp :: Bool -- ^^ whether to show implicits
975 -> PTerm -- ^^ the term to pretty-print
976 -> Doc
977prettyImp impl = prettySe 10
978 where
979 prettySe p (PQuote r) =
980 if size r > breakingSize then
981 text "![" $$ pretty r <> text "]"
982 else
983 text "![" <> pretty r <> text "]"
984 prettySe p (PPatvar fc n) = pretty n
985 prettySe p (PRef fc n) =
986 if impl then
987 pretty n
988 else
989 prettyBasic n
990 where
991 prettyBasic n@(UN _) = pretty n
992 prettyBasic (MN _ s) = text (str s)
993 prettyBasic (NS n s) = (foldr (<>) empty (intersperse (text ".") (map (text.str) $ reverse s))) <> prettyBasic n
994 prettyBasic (SN sn) = text (show sn)
995 prettySe p (PLam n ty sc) =
996 bracket p 2 $
997 if size sc > breakingSize then
998 text "λ" <> pretty n <+> text "=>" $+$ pretty sc
999 else
1000 text "λ" <> pretty n <+> text "=>" <+> pretty sc
1001 prettySe p (PLet n ty v sc) =
1002 bracket p 2 $
1003 if size sc > breakingSize then
1004 text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" $+$
1005 nest nestingSize (prettySe 10 sc)
1006 else
1007 text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" <+>
1008 prettySe 10 sc
1009 prettySe p (PPi (Exp l s _ _) n ty sc)
1010 | n `elem` allNamesIn sc || impl =
1011 let open = if l then text "|" <> lparen else lparen in
1012 bracket p 2 $
1013 if size sc > breakingSize then
1014 open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+>
1015 st <+> text "->" $+$ prettySe 10 sc
1016 else
1017 open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+>
1018 st <+> text "->" <+> prettySe 10 sc
1019 | otherwise =
1020 bracket p 2 $
1021 if size sc > breakingSize then
1022 prettySe 0 ty <+> st <+> text "->" $+$ prettySe 10 sc
1023 else
1024 prettySe 0 ty <+> st <+> text "->" <+> prettySe 10 sc
1025 where
1026 st =
1027 case s of
1028 Static -> text "[static]"
1029 _ -> empty
1030 prettySe p (PPi (Imp l s _ _) n ty sc)
1031 | impl =
1032 let open = if l then text "|" <> lbrace else lbrace in
1033 bracket p 2 $
1034 if size sc > breakingSize then
1035 open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+>
1036 st <+> text "->" <+> prettySe 10 sc
1037 else
1038 open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+>
1039 st <+> text "->" <+> prettySe 10 sc
1040 | otherwise = prettySe 10 sc
1041 where
1042 st =
1043 case s of
1044 Static -> text $ "[static]"
1045 _ -> empty
1046 prettySe p (PPi (Constraint _ _ _) n ty sc) =
1047 bracket p 2 $
1048 if size sc > breakingSize then
1049 prettySe 10 ty <+> text "=>" <+> prettySe 10 sc
1050 else
1051 prettySe 10 ty <+> text "=>" $+$ prettySe 10 sc
1052 prettySe p (PPi (TacImp _ _ s _) n ty sc) =
1053 bracket p 2 $
1054 if size sc > breakingSize then
1055 lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <>
1056 rbrace <+> text "->" $+$ prettySe 10 sc
1057 else
1058 lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <>
1059 rbrace <+> text "->" <+> prettySe 10 sc
1060 prettySe p (PApp _ (PRef _ f) [])
1061 | not impl = pretty f
1062 prettySe p (PAppBind _ (PRef _ f) [])
1063 | not impl = text "!" <+> pretty f
1064 prettySe p (PApp _ (PRef _ op@(UN nm)) args)
1065 | not (tnull nm) &&
1066 length (getExps args) == 2 && (not impl) && (not $ isAlpha (thead nm)) =
1067 let [l, r] = getExps args in
1068 bracket p 1 $
1069 if size r > breakingSize then
1070 prettySe 1 l <+> pretty op $+$ prettySe 0 r
1071 else
1072 prettySe 1 l <+> pretty op <+> prettySe 0 r
1073 prettySe p (PApp _ f as) =
1074 let args = getExps as in
1075 bracket p 1 $
1076 prettySe 1 f <+>
1077 if impl then
1078 foldl' fS empty as
1079 -- foldr (<+>) empty $ map prettyArgS as
1080 else
1081 foldl' fSe empty args
1082 -- foldr (<+>) empty $ map prettyArgSe args
1083 where
1084 fS l r =
1085 if size r > breakingSize then
1086 l $+$ nest nestingSize (prettyArgS r)
1087 else
1088 l <+> prettyArgS r
1090 fSe l r =
1091 if size r > breakingSize then
1092 l $+$ nest nestingSize (prettyArgSe r)
1093 else
1094 l <+> prettyArgSe r
1095 prettySe p (PCase _ scr opts) =
1096 text "case" <+> prettySe 10 scr <+> text "of" $+$ nest nestingSize prettyBody
1097 where
1098 prettyBody = foldr ($$) empty $ intersperse (text "|") $ map sc opts
1100 sc (l, r) = prettySe 10 l <+> text "=>" <+> prettySe 10 r
1101 prettySe p (PHidden tm) = text "." <> prettySe 0 tm
1102 prettySe p (PRefl _ _) = text "refl"
1103 prettySe p (PResolveTC _) = text "resolvetc"
1104 prettySe p (PTrue _) = text "()"
1105 prettySe p (PFalse _) = text "_|_"
1106 prettySe p (PEq _ l r) =
1107 bracket p 2 $
1108 if size r > breakingSize then
1109 prettySe 10 l <+> text "=" $$ nest nestingSize (prettySe 10 r)
1110 else
1111 prettySe 10 l <+> text "=" <+> prettySe 10 r
1112 prettySe p (PRewrite _ l r _) =
1113 bracket p 2 $
1114 if size r > breakingSize then
1115 text "rewrite" <+> prettySe 10 l <+> text "in" $$ nest nestingSize (prettySe 10 r)
1116 else
1117 text "rewrite" <+> prettySe 10 l <+> text "in" <+> prettySe 10 r
1118 prettySe p (PTyped l r) =
1119 lparen <> prettySe 10 l <+> colon <+> prettySe 10 r <> rparen
1120 prettySe p (PPair _ l r) =
1121 if size r > breakingSize then
1122 lparen <> prettySe 10 l <> text "," $+$
1123 prettySe 10 r <> rparen
1124 else
1125 lparen <> prettySe 10 l <> text "," <+> prettySe 10 r <> rparen
1126 prettySe p (PDPair _ l t r) =
1127 if size r > breakingSize then
1128 lparen <> prettySe 10 l <+> text "**" $+$
1129 prettySe 10 r <> rparen
1130 else
1131 lparen <> prettySe 10 l <+> text "**" <+> prettySe 10 r <> rparen
1132 prettySe p (PAlternative a as) =
1133 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1134 where
1135 prettyAs =
1136 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10) as
1137 prettySe p PType = text "Type"
1138 prettySe p (PConstant c) = pretty c
1139 -- XXX: add pretty for tactics
1140 prettySe p (PProof ts) =
1141 text "proof" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace
1142 prettySe p (PTactics ts) =
1143 text "tactics" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace
1144 prettySe p (PMetavar n) = text "?" <> pretty n
1145 prettySe p (PReturn f) = text "return"
1146 prettySe p PImpossible = text "impossible"
1147 prettySe p Placeholder = text "_"
1148 prettySe p (PDoBlock _) = text "do block pretty not implemented"
1149 prettySe p (PElabError s) = pretty s
1151 prettySe p _ = text "test"
1153 prettyArgS (PImp _ _ _ n tm _) = prettyArgSi (n, tm)
1154 prettyArgS (PExp _ _ tm _) = prettyArgSe tm
1155 prettyArgS (PConstraint _ _ tm _) = prettyArgSc tm
1156 prettyArgS (PTacImplicit _ _ n _ tm _) = prettyArgSti (n, tm)
1158 prettyArgSe arg = prettySe 0 arg
1159 prettyArgSi (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 val <> rbrace
1160 prettyArgSc val = lbrace <> lbrace <> prettySe 10 val <> rbrace <> rbrace
1161 prettyArgSti (n, val) = lbrace <> text "auto" <+> pretty n <+> text "=" <+> prettySe 10 val <> rbrace
1163 bracket outer inner doc
1164 | inner > outer = lparen <> doc <> rparen
1165 | otherwise = doc
1167-- | Show Idris name
1168showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1169 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1170 -> Bool -- ^^ whether to show implicits
1171 -> Bool -- ^^ whether to colourise
1172 -> Name -- ^^ the term to show
1173 -> String
1174showName ist bnd impl colour n = case ist of
1175 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1176 Nothing -> showbasic n
1177 where name = if impl then show n else showbasic n
1178 showbasic n@(UN _) = showCG n
1179 showbasic (MN _ s) = str s
1180 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1181 showbasic (SN s) = show s
1182 fst3 (x, _, _) = x
1183 colourise n t = let ctxt' = fmap tt_ctxt ist in
1184 case ctxt' of
1185 Nothing -> name
1186 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1187 else colouriseBound t name
1188 | isDConName n ctxt -> colouriseData t name
1189 | isFnName n ctxt -> colouriseFun t name
1190 | isTConName n ctxt -> colouriseType t name
1191 -- The assumption is that if a name is not bound and does not exist in the
1192 -- global context, then we're somewhere in which implicit info has been lost
1193 -- (like error messages). Thus, unknown vars are colourised as implicits.
1194 | otherwise -> colouriseImplicit t name
1196-- | Show Idris term
1197showImp :: Maybe IState -- ^^ the Idris state, for information about identifiers and colours
1198 -> Bool -- ^^ whether to show implicits
1199 -> Bool -- ^^ whether to colourise
1200 -> PTerm -- ^^ the term to show
1201 -> String
1202showImp ist impl colour tm = se 10 [] tm where
1203 perhapsColourise :: (ColourTheme -> String -> String) -> String -> String
1204 perhapsColourise col str = case ist of
1205 Just i -> if colour then col (idris_colourTheme i) str else str
1206 Nothing -> str
1208 se :: Int -> [(Name, Bool)] -> PTerm -> String
1209 se p bnd (PQuote r) = "![" ++ show r ++ "]"
1210 se p bnd (PPatvar fc n) = if impl then show n ++ "[p]" else show n
1211 se p bnd (PInferRef fc n) = "!" ++ show n -- ++ "[" ++ show fc ++ "]"
1212 se p bnd e
1213 | Just str <- slist p bnd e = str
1214 | Just num <- snat p e = perhapsColourise colouriseData (show num)
1215 se p bnd (PRef fc n) = showName ist bnd impl colour n
1216 se p bnd (PLam n ty sc) = bracket p 2 $ "\\ " ++ perhapsColourise colouriseBound (show n) ++
1217 (if impl then " : " ++ se 10 bnd ty else "") ++ " => "
1218 ++ se 10 ((n, False):bnd) sc
1219 se p bnd (PLet n ty v sc) = bracket p 2 $ "let " ++ perhapsColourise colouriseBound (show n) ++
1220 " = " ++ se 10 bnd v ++
1221 " in " ++ se 10 ((n, False):bnd) sc
1222 se p bnd (PPi (Exp l s _ param) n ty sc)
1223 | n `elem` allNamesIn sc || impl
1224 = bracket p 2 $
1225 (if l then "|(" else "(") ++
1226 perhapsColourise colouriseBound (show n) ++ " : " ++ se 10 bnd ty ++
1227 ") " ++
1228 (if (impl && param) then "P" else "") ++
1229 st ++
1230 "-> " ++ se 10 ((n, False):bnd) sc
1231 | otherwise = bracket p 2 $ se 0 bnd ty ++ " " ++ st ++ "-> " ++ se 10 bnd sc
1232 where st = case s of
1233 Static -> "[static] "
1234 _ -> ""
1235 se p bnd (PPi (Imp l s _ _) n ty sc)
1236 | impl = bracket p 2 $ (if l then "|{" else "{") ++
1237 perhapsColourise colouriseBound (show n) ++ " : " ++ se 10 bnd ty ++
1238 "} " ++ st ++ "-> " ++ se 10 ((n, True):bnd) sc
1239 | otherwise = se 10 ((n, True):bnd) sc
1240 where st = case s of
1241 Static -> "[static] "
1242 _ -> ""
1243 se p bnd (PPi (Constraint _ _ _) n ty sc)
1244 = bracket p 2 $ se 10 bnd ty ++ " => " ++ se 10 bnd sc
1245 se p bnd (PPi (TacImp _ _ s _) n ty sc)
1246 = bracket p 2 $
1247 "{tacimp " ++ (perhapsColourise colouriseBound (show n)) ++ " : " ++ se 10 bnd ty ++ "} -> " ++
1248 se 10 ((n, False):bnd) sc
1249 se p bnd (PMatchApp _ f) = "match " ++ show f
1250 se p bnd (PApp _ hd@(PRef _ f) [])
1251 | not impl = se p bnd hd
1252 se p bnd (PAppBind _ hd@(PRef _ f) [])
1253 | not impl = "!" ++ se p bnd hd
1254 se p bnd (PApp _ op@(PRef _ (UN nm)) args)
1255 | not (tnull nm) &&
1256 length (getExps args) == 2 && not impl && not (isAlpha (thead nm))
1257 = let [l, r] = getExps args in
1258 bracket p 1 $ se 1 bnd l ++ " " ++ se p bnd op ++ " " ++ se 0 bnd r
1259 se p bnd (PApp _ f as)
1260 = -- let args = getExps as in
1261 bracket p 1 $ se 1 bnd f ++
1262 if impl then concatMap (sArg bnd) as
1263 else concatMap (suiArg impl bnd) as
1264 se p bnd (PAppBind _ f as)
1265 = let args = getExps as in
1266 "!" ++ (bracket p 1 $ se 1 bnd f ++ if impl then concatMap (sArg bnd) as
1267 else concatMap (seArg bnd) args)
1268 se p bnd (PCase _ scr opts) = "case " ++ se 10 bnd scr ++ " of " ++ showSep " | " (map sc opts)
1269 where sc (l, r) = se 10 bnd l ++ " => " ++ se 10 bnd r
1270 se p bnd (PHidden tm) = "." ++ se 0 bnd tm
1271 se p bnd (PRefl _ t)
1272 | not impl = perhapsColourise colouriseData "refl"
1273 | otherwise = perhapsColourise colouriseData $ "refl {" ++ se 10 bnd t ++ "}"
1274 se p bnd (PResolveTC _) = "resolvetc"
1275 se p bnd (PTrue _) = perhapsColourise colouriseType "()"
1276 se p bnd (PFalse _) = perhapsColourise colouriseType "_|_"
1277 se p bnd (PEq _ l r) = bracket p 2 $ se 10 bnd l ++ perhapsColourise colouriseType " = " ++ se 10 bnd r
1278 se p bnd (PRewrite _ l r _) = bracket p 2 $ "rewrite " ++ se 10 bnd l ++ " in " ++ se 10 bnd r
1279 se p bnd (PTyped l r) = "(" ++ se 10 bnd l ++ " : " ++ se 10 bnd r ++ ")"
1280 se p bnd (PPair _ l r) = "(" ++ se 10 bnd l ++ ", " ++ se 10 bnd r ++ ")"
1281 se p bnd (PDPair _ l t r) = "(" ++ se 10 bnd l ++ " ** " ++ se 10 bnd r ++ ")"
1282 se p bnd (PAlternative a as) = "(|" ++ showSep " , " (map (se 10 bnd) as) ++ "|)"
1283 se p bnd PType = perhapsColourise colouriseType "Type"
1284 se p bnd (PConstant c) = perhapsColourise (cfun c) (show c)
1285 where cfun (AType _) = colouriseType
1286 cfun StrType = colouriseType
1287 cfun PtrType = colouriseType
1288 cfun VoidType = colouriseType
1289 cfun _ = colouriseData
1290 se p bnd (PProof ts) = "proof { " ++ show ts ++ "}"
1291 se p bnd (PTactics ts) = "tactics { " ++ show ts ++ "}"
1292 se p bnd (PMetavar n) = "?" ++ show n
1293 se p bnd (PReturn f) = "return"
1294 se p bnd PImpossible = "impossible"
1295 se p bnd Placeholder = "_"
1296 se p bnd (PDoBlock _) = "do block show not implemented"
1297 se p bnd (PElabError s) = show s
1298 se p bnd (PCoerced t) = se p bnd t
1299 se p bnd (PUnifyLog t) = "%unifyLog " ++ se p bnd t
1300 se p bnd (PDisamb ns t) = "%disamb " ++ show ns ++ se p bnd t
1301 se p bnd (PNoImplicits t) = "%noimplicit " ++ se p bnd t
1302-- se p bnd x = "Not implemented"
1304 slist' p bnd (PApp _ (PRef _ nil) _)
1305 | not impl && nsroot nil == sUN "Nil" = Just []
1306 slist' p bnd (PApp _ (PRef _ cons) args)
1307 | nsroot cons == sUN "::",
1308 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1309 all isImp imps,
1310 Just tl' <- slist' p bnd tl
1311 = Just (hd:tl')
1312 where
1313 isImp (PImp {}) = True
1314 isImp _ = False
1315 slist' _ _ _ = Nothing
1317 slist p bnd e | Just es <- slist' p bnd e = Just $
1318 case es of [] -> "[]"
1319 [x] -> "[" ++ se p bnd x ++ "]"
1320 xs -> "[" ++ intercalate "," (map (se p bnd ) xs) ++ "]"
1321 slist _ _ _ = Nothing
1323 -- since Prelude is always imported, S & Z are unqualified iff they're the
1324 -- Nat ones.
1325 snat p (PRef _ o)
1326 | show o == (natns++"Z") || show o == "Z" = Just 0
1327 snat p (PApp _ s [PExp {getTm=n}])
1328 | show s == (natns++"S") || show s == "S",
1329 Just n' <- snat p n
1330 = Just $ 1 + n'
1331 snat _ _ = Nothing
1333 natns = "Prelude.Nat."
1335 sArg bnd (PImp _ _ _ n tm _) = siArg bnd (n, tm)
1336 sArg bnd (PExp _ _ tm _) = seArg bnd tm
1337 sArg bnd (PConstraint _ _ tm _) = scArg bnd tm
1338 sArg bnd (PTacImplicit _ _ n _ tm _) = stiArg bnd (n, tm)
1340 -- show argument, implicits given by the user also shown
1341 suiArg impl bnd (PImp _ mi _ n tm _)
1342 | impl || not mi = siArg bnd (n, tm)
1343 suiArg impl bnd (PExp _ _ tm _) = seArg bnd tm
1344 suiArg impl bnd _ = ""
1346 seArg bnd arg = " " ++ se 0 bnd arg
1347 siArg bnd (n, val) =
1348 let n' = show n
1349 val' = se 10 bnd val in
1350 if (n' == val')
1351 then " {" ++ n' ++ "}"
1352 else " {" ++ n' ++ " = " ++ val' ++ "}"
1353 scArg bnd val = " {{" ++ se 10 bnd val ++ "}}"
1354 stiArg bnd (n, val) = " {auto " ++ show n ++ " = " ++ se 10 bnd val ++ "}"
1356 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
1357 | otherwise = str
1360instance Sized PTerm where
1361 size (PQuote rawTerm) = size rawTerm
1362 size (PRef fc name) = size name
1363 size (PLam name ty bdy) = 1 + size ty + size bdy
1364 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1365 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1366 size (PTyped trm ty) = 1 + size trm + size ty
1367 size (PApp fc name args) = 1 + size args
1368 size (PAppBind fc name args) = 1 + size args
1369 size (PCase fc trm bdy) = 1 + size trm + size bdy
1370 size (PTrue fc) = 1
1371 size (PFalse fc) = 1
1372 size (PRefl fc _) = 1
1373 size (PResolveTC fc) = 1
1374 size (PEq fc left right) = 1 + size left + size right
1375 size (PRewrite fc left right _) = 1 + size left + size right
1376 size (PPair fc left right) = 1 + size left + size right
1377 size (PDPair fs left ty right) = 1 + size left + size ty + size right
1378 size (PAlternative a alts) = 1 + size alts
1379 size (PHidden hidden) = size hidden
1380 size (PUnifyLog tm) = size tm
1381 size (PDisamb _ tm) = size tm
1382 size (PNoImplicits tm) = size tm
1383 size PType = 1
1384 size (PConstant const) = 1 + size const
1385 size Placeholder = 1
1386 size (PDoBlock dos) = 1 + size dos
1387 size (PIdiom fc term) = 1 + size term
1388 size (PReturn fc) = 1
1389 size (PMetavar name) = 1
1390 size (PProof tactics) = size tactics
1391 size (PElabError err) = size err
1392 size PImpossible = 1
1394getPArity :: PTerm -> Int
1395getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1396getPArity _ = 0
1398-- Return all names, free or globally bound, in the given term.
1400allNamesIn :: PTerm -> [Name]
1401allNamesIn tm = nub $ ni [] tm
1402 where
1403 ni env (PRef _ n)
1404 | not (n `elem` env) = [n]
1405 ni env (PPatvar _ n) = [n]
1406 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1407 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1408 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1409 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1410 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1411 ni env (PHidden tm) = ni env tm
1412 ni env (PEq _ l r) = ni env l ++ ni env r
1413 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1414 ni env (PTyped l r) = ni env l ++ ni env r
1415 ni env (PPair _ l r) = ni env l ++ ni env r
1416 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1417 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1418 ni env (PAlternative a ls) = concatMap (ni env) ls
1419 ni env (PUnifyLog tm) = ni env tm
1420 ni env (PDisamb _ tm) = ni env tm
1421 ni env (PNoImplicits tm) = ni env tm
1422 ni env _ = []
1424-- Return all names defined in binders in the given term
1425boundNamesIn :: PTerm -> [Name]
1426boundNamesIn tm = nub $ ni tm
1427 where
1428 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1429 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1430 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1431 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1432 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1433 ni (PPi _ n ty sc) = n : (ni ty ++ ni sc)
1434 ni (PEq _ l r) = ni l ++ ni r
1435 ni (PRewrite _ l r _) = ni l ++ ni r
1436 ni (PTyped l r) = ni l ++ ni r
1437 ni (PPair _ l r) = ni l ++ ni r
1438 ni (PDPair _ (PRef _ n) t r) = ni t ++ ni r
1439 ni (PDPair _ l t r) = ni l ++ ni t ++ ni r
1440 ni (PAlternative a as) = concatMap (ni) as
1441 ni (PHidden tm) = ni tm
1442 ni (PUnifyLog tm) = ni tm
1443 ni (PDisamb _ tm) = ni tm
1444 ni (PNoImplicits tm) = ni tm
1445 ni _ = []
1447-- Return names which are free in the given term.
1448namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1449namesIn uvars ist tm = nub $ ni [] tm
1450 where
1451 ni env (PRef _ n)
1452 | not (n `elem` env)
1453 = case lookupTy n (tt_ctxt ist) of
1454 [] -> [n]
1455 _ -> if n `elem` (map fst uvars) then [n] else []
1456 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1457 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1458 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1459 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1460 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1461 ni env (PEq _ l r) = ni env l ++ ni env r
1462 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1463 ni env (PTyped l r) = ni env l ++ ni env r
1464 ni env (PPair _ l r) = ni env l ++ ni env r
1465 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1466 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1467 ni env (PAlternative a as) = concatMap (ni env) as
1468 ni env (PHidden tm) = ni env tm
1469 ni env (PUnifyLog tm) = ni env tm
1470 ni env (PDisamb _ tm) = ni env tm
1471 ni env (PNoImplicits tm) = ni env tm
1472 ni env _ = []
1474-- Return which of the given names are used in the given term.
1476usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1477usedNamesIn vars ist tm = nub $ ni [] tm
1478 where
1479 ni env (PRef _ n)
1480 | n `elem` vars && not (n `elem` env)
1481 = case lookupTy n (tt_ctxt ist) of
1482 [] -> [n]
1483 _ -> []
1484 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1485 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1486 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1487 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1488 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1489 ni env (PEq _ l r) = ni env l ++ ni env r
1490 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1491 ni env (PTyped l r) = ni env l ++ ni env r
1492 ni env (PPair _ l r) = ni env l ++ ni env r
1493 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1494 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1495 ni env (PAlternative a as) = concatMap (ni env) as
1496 ni env (PHidden tm) = ni env tm
1497 ni env (PUnifyLog tm) = ni env tm
1498 ni env (PDisamb _ tm) = ni env tm
1499 ni env (PNoImplicits tm) = ni env tm
1500 ni env _ = []