on 53376fc help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1333 lines 50 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntaxTree where
6import Core.TT
7import Core.Evaluate
8import Core.Elaborate hiding (Tactic(..))
9import Core.Typecheck
10import IRTS.Lang
11import IRTS.CodegenCommon
12import Util.Pretty
13import Util.DynamicLinker
15import Idris.Colours
17import Paths_idris
19import System.Console.Haskeline
22import Control.Monad.Trans.State.Strict
24import Data.List
25import Data.Char
26import Data.Either
27import Data.Word (Word)
29import Debug.Trace
31data IOption = IOption { opt_logLevel :: Int,
32 opt_typecase :: Bool,
33 opt_typeintype :: Bool,
34 opt_coverage :: Bool,
35 opt_showimp :: Bool, -- ^^ show implicits
36 opt_errContext :: Bool,
37 opt_repl :: Bool,
38 opt_verbose :: Bool,
39 opt_quiet :: Bool,
40 opt_codegen :: Codegen,
41 opt_outputTy :: OutputType,
42 opt_ibcsubdir :: FilePath,
43 opt_importdirs :: [FilePath],
44 opt_triple :: String,
45 opt_cpu :: String,
46 opt_optLevel :: Word,
47 opt_cmdline :: [Opt] -- remember whole command line
48 }
49 deriving (Show, Eq)
51defaultOpts = IOption { opt_logLevel = 0
52 , opt_typecase = False
53 , opt_typeintype = False
54 , opt_coverage = True
55 , opt_showimp = False
56 , opt_errContext = False
57 , opt_repl = True
58 , opt_verbose = True
59 , opt_quiet = False
60 , opt_codegen = ViaC
61 , opt_outputTy = Executable
62 , opt_ibcsubdir = ""
63 , opt_importdirs = []
64 , opt_triple = ""
65 , opt_cpu = ""
66 , opt_optLevel = 2
67 , opt_cmdline = []
68 }
70data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
72-- | The output mode in use
73data OutputMode = RawOutput | IdeSlave Integer deriving Show
75-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
76-- without typechecking).
77-- This will include all the functions and data declarations, plus fixity declarations
78-- and syntax macros.
80-- | The global state used in the Idris monad
81data IState = IState {
82 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
83 idris_constraints :: [(UConstraint, FC)],
84 -- ^ A list of universe constraints and their corresponding source locations
85 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
86 idris_implicits :: Ctxt [PArg],
87 idris_statics :: Ctxt [Bool],
88 idris_classes :: Ctxt ClassInfo,
89 idris_dsls :: Ctxt DSL,
90 idris_optimisation :: Ctxt OptInfo,
91 idris_datatypes :: Ctxt TypeInfo,
92 idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
93 -- ^ list of lhs/rhs, and a list of missing clauses
94 idris_flags :: Ctxt [FnOpt],
95 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
96 idris_calledgraph :: Ctxt [Name],
97 idris_docstrings :: Ctxt String,
98 idris_totcheck :: [(FC, Name)],
99 idris_log :: String,
100 idris_options :: IOption,
101 idris_name :: Int,
102 idris_metavars :: [Name], -- ^ The currently defined but not proven metavariables
103 idris_coercions :: [Name],
104 idris_transforms :: [(Term, Term)],
105 syntax_rules :: [Syntax],
106 syntax_keywords :: [String],
107 imported :: [FilePath], -- ^ The imported modules
108 idris_scprims :: [(Name, (Int, PrimFn))],
109 idris_objs :: [(Codegen, FilePath)],
110 idris_libs :: [(Codegen, String)],
111 idris_cgflags :: [(Codegen, String)],
112 idris_hdrs :: [(Codegen, String)],
113 proof_list :: [(Name, [String])],
114 errLine :: Maybe Int,
115 lastParse :: Maybe Name,
116 indent_stack :: [Int],
117 brace_stack :: [Maybe Int],
118 hide_list :: [(Name, Maybe Accessibility)],
119 default_access :: Accessibility,
120 default_total :: Bool,
121 ibc_write :: [IBCWrite],
122 compiled_so :: Maybe String,
123 idris_dynamic_libs :: [DynamicLib],
124 idris_language_extensions :: [LanguageExt],
125 idris_outputmode :: OutputMode,
126 idris_colourRepl :: Bool,
127 idris_colourTheme :: ColourTheme
128 }
130data SizeChange = Smaller | Same | Bigger | Unknown
131 deriving (Show, Eq)
132{-!
133deriving instance Binary SizeChange
134!-}
136type SCGEntry = (Name, [Maybe (Int, SizeChange)])
138data CGInfo = CGInfo { argsdef :: [Name],
139 calls :: [(Name, [[Name]])],
140 scg :: [SCGEntry],
141 argsused :: [Name],
142 unusedpos :: [Int] }
143 deriving Show
144{-!
145deriving instance Binary CGInfo
146!-}
148primDefs = [UN "unsafePerformPrimIO",
149 UN "mkLazyForeignPrim",
150 UN "mkForeignPrim",
151 UN "FalseElim"]
153-- information that needs writing for the current module's .ibc file
154data IBCWrite = IBCFix FixDecl
155 | IBCImp Name
156 | IBCStatic Name
157 | IBCClass Name
158 | IBCInstance Bool Name Name
159 | IBCDSL Name
160 | IBCData Name
161 | IBCOpt Name
162 | IBCSyntax Syntax
163 | IBCKeyword String
164 | IBCImport FilePath
165 | IBCObj Codegen FilePath
166 | IBCLib Codegen String
167 | IBCCGFlag Codegen String
168 | IBCDyLib String
169 | IBCHeader Codegen String
170 | IBCAccess Name Accessibility
171 | IBCTotal Name Totality
172 | IBCFlags Name [FnOpt]
173 | IBCTrans (Term, Term)
174 | IBCCG Name
175 | IBCDoc Name
176 | IBCCoercion Name
177 | IBCDef Name -- i.e. main context
178 deriving Show
180idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
181 emptyContext emptyContext emptyContext emptyContext
182 emptyContext emptyContext emptyContext emptyContext
183 [] "" defaultOpts 6 [] [] [] [] [] [] [] [] [] [] []
184 [] Nothing Nothing [] [] [] Hidden False [] Nothing [] [] RawOutput
185 True defaultTheme
187-- | The monad for the main REPL - reading and processing files and updating
188-- global state (hence the IO inner monad).
189--type Idris = WriterT [Either String (IO ())] (State IState a))
190type Idris = StateT IState IO
192-- Commands in the REPL
194data Codegen = ViaC
195 | ViaJava
196 | ViaNode
197 | ViaJavaScript
198 | ViaLLVM
199 | Bytecode
200 deriving (Show, Eq)
202-- | REPL commands
203data Command = Quit
204 | Help
205 | Eval PTerm
206 | Check PTerm
207 | DocStr Name
208 | TotCheck Name
209 | Reload
210 | Load FilePath
211 | ChangeDirectory FilePath
212 | ModImport String
213 | Edit
214 | Compile Codegen String
215 | Execute
216 | ExecVal PTerm
217 | Metavars
218 | Prove Name
219 | AddProof (Maybe Name)
220 | RmProof Name
221 | ShowProof Name
222 | Proofs
223 | Universes
224 | TTShell
225 | LogLvl Int
226 | Spec PTerm
227 | HNF PTerm
228 | TestInline PTerm
229 | Defn Name
230 | Info Name
231 | Missing Name
232 | DynamicLink FilePath
233 | ListDynamic
234 | Pattelab PTerm
235 | DebugInfo Name
236 | Search PTerm
237 | SetOpt Opt
238 | UnsetOpt Opt
239 | NOP
240 | SetColour ColourType IdrisColour
241 | ColourOn
242 | ColourOff
244data Opt = Filename String
245 | Ver
246 | Usage
247 | Quiet
248 | ColourREPL Bool
249 | Ideslave
250 | ShowLibs
251 | ShowLibdir
252 | ShowIncs
253 | NoPrelude
254 | NoREPL
255 | OLogging Int
256 | Output String
257 | TypeCase
258 | TypeInType
259 | DefaultTotal
260 | DefaultPartial
261 | WarnPartial
262 | NoCoverage
263 | ErrContext
264 | ShowImpl
265 | Verbose
266 | IBCSubDir String
267 | ImportDir String
268 | PkgBuild String
269 | PkgInstall String
270 | PkgClean String
271 | WarnOnly
272 | Pkg String
273 | BCAsm String
274 | DumpDefun String
275 | DumpCases String
276 | FOVM String
277 | UseCodegen Codegen
278 | OutputTy OutputType
279 | Extension LanguageExt
280 | InterpretScript String
281 | TargetTriple String
282 | TargetCPU String
283 | OptLevel Word
284 deriving (Show, Eq)
286-- Parsed declarations
288data Fixity = Infixl { prec :: Int }
289 | Infixr { prec :: Int }
290 | InfixN { prec :: Int }
291 | PrefixN { prec :: Int }
292 deriving Eq
293{-!
294deriving instance Binary Fixity
295!-}
297instance Show Fixity where
298 show (Infixl i) = "infixl " ++ show i
299 show (Infixr i) = "infixr " ++ show i
300 show (InfixN i) = "infix " ++ show i
301 show (PrefixN i) = "prefix " ++ show i
303data FixDecl = Fix Fixity String
304 deriving Eq
306instance Show FixDecl where
307 show (Fix f s) = show f ++ " " ++ s
309{-!
310deriving instance Binary FixDecl
311!-}
313instance Ord FixDecl where
314 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
317data Static = Static | Dynamic
318 deriving (Show, Eq)
319{-!
320deriving instance Binary Static
321!-}
323-- Mark bindings with their explicitness, and laziness
324data Plicity = Imp { plazy :: Bool,
325 pstatic :: Static,
326 pdocstr :: String }
327 | Exp { plazy :: Bool,
328 pstatic :: Static,
329 pdocstr :: String }
330 | Constraint { plazy :: Bool,
331 pstatic :: Static,
332 pdocstr :: String }
333 | TacImp { plazy :: Bool,
334 pstatic :: Static,
335 pscript :: PTerm,
336 pdocstr :: String }
337 deriving (Show, Eq)
339{-!
340deriving instance Binary Plicity
341!-}
343impl = Imp False Dynamic ""
344expl = Exp False Dynamic ""
345constraint = Constraint False Dynamic ""
346tacimpl t = TacImp False Dynamic t ""
348data FnOpt = Inlinable -- always evaluate when simplifying
349 | TotalFn | PartialFn
350 | Coinductive | AssertTotal
351 | Dictionary -- type class dictionary, eval only when
352 -- a function argument, and further evaluation resutls
353 | Implicit -- implicit coercion
354 | CExport String -- export, with a C name
355 | Reflection -- a reflecting function, compile-time only
356 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
357 deriving (Show, Eq)
358{-!
359deriving instance Binary FnOpt
360!-}
362type FnOpts = [FnOpt]
364inlinable :: FnOpts -> Bool
365inlinable = elem Inlinable
367dictionary :: FnOpts -> Bool
368dictionary = elem Dictionary
370-- | Top-level declarations such as compiler directives, definitions,
371-- datatypes and typeclasses.
372data PDecl' t
373 = PFix FC Fixity [String] -- ^ Fixity declaration
374 | PTy String SyntaxInfo FC FnOpts Name t -- ^ Type declaration
375 | PPostulate String SyntaxInfo FC FnOpts Name t -- ^ Postulate
376 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
377 | PCAF FC Name t -- ^ Top level constant
378 | PData String SyntaxInfo FC Bool (PData' t) -- ^ Data declaration. The Bool argument is True for codata.
379 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
380 | PNamespace String [PDecl' t] -- ^ New namespace
381 | PRecord String SyntaxInfo FC Name t String Name t -- ^ Record declaration
382 | PClass String SyntaxInfo FC
383 [t] -- constraints
384 Name
385 [(Name, t)] -- parameters
386 [PDecl' t] -- declarations
387 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
388 -- class name, parameters, method declarations
389 | PInstance SyntaxInfo FC [t] -- constraints
390 Name -- class
391 [t] -- parameters
392 t -- full instance type
393 (Maybe Name) -- explicit name
394 [PDecl' t]
395 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
396 -- class name, parameters, full instance type, optional explicit name, and definitions
397 | PDSL Name (DSL' t) -- ^ DSL declaration
398 | PSyntax FC Syntax -- ^ Syntax definition
399 | PMutual FC [PDecl' t] -- ^ Mutual block
400 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
401 | PProvider SyntaxInfo FC Name t t -- ^ Type provider. The first t is the type, the second is the term
402 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
403 -- bool is True, lhs and rhs must be convertible
404 deriving Functor
405{-!
406deriving instance Binary PDecl'
407!-}
409-- | One clause of a top-level definition. Term arguments to constructors are:
410--
411-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
412--
413-- 2. The list of patterns
414--
415-- 3. The right-hand side
416--
417-- 4. The where block (PDecl' t)
418data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
419 | PWith FC Name t [t] t [PDecl' t]
420 | PClauseR FC [t] t [PDecl' t]
421 | PWithR FC [t] t [PDecl' t]
422 deriving Functor
423{-!
424deriving instance Binary PClause'
425!-}
427-- | Data declaration
428data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
429 d_tcon :: t, -- ^ Type constructor
430 d_cons :: [(String, Name, t, FC)] -- ^ Constructors
431 }
432 -- ^ Data declaration
433 | PLaterdecl { d_name :: Name, d_tcon :: t }
434 -- ^ "Placeholder" for data whose constructors are defined later
435 deriving Functor
436{-!
437deriving instance Binary PData'
438!-}
440-- Handy to get a free function for applying PTerm -> PTerm functions
441-- across a program, by deriving Functor
443type PDecl = PDecl' PTerm
444type PData = PData' PTerm
445type PClause = PClause' PTerm
447-- get all the names declared in a decl
449declared :: PDecl -> [Name]
450declared (PFix _ _ _) = []
451declared (PTy _ _ _ _ n t) = [n]
452declared (PPostulate _ _ _ _ n t) = [n]
453declared (PClauses _ _ n _) = [] -- not a declaration
454declared (PCAF _ n _) = [n]
455declared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
456 where fstt (_, a, _, _) = a
457declared (PData _ _ _ _ (PLaterdecl n _)) = [n]
458declared (PParams _ _ ds) = concatMap declared ds
459declared (PNamespace _ ds) = concatMap declared ds
460declared (PRecord _ _ _ n _ _ c _) = [n, c]
461declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
462declared (PInstance _ _ _ _ _ _ _ _) = []
463declared (PDSL n _) = [n]
464declared (PSyntax _ _) = []
465declared (PMutual _ ds) = concatMap declared ds
466declared (PDirective _) = []
468-- get the names declared, not counting nested parameter blocks
469tldeclared :: PDecl -> [Name]
470tldeclared (PFix _ _ _) = []
471tldeclared (PTy _ _ _ _ n t) = [n]
472tldeclared (PPostulate _ _ _ _ n t) = [n]
473tldeclared (PClauses _ _ n _) = [] -- not a declaration
474tldeclared (PRecord _ _ _ n _ _ c _) = [n, c]
475tldeclared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
476 where fstt (_, a, _, _) = a
477tldeclared (PParams _ _ ds) = []
478tldeclared (PMutual _ ds) = concatMap tldeclared ds
479tldeclared (PNamespace _ ds) = concatMap tldeclared ds
480tldeclared (PClass _ _ _ _ n _ ms) = concatMap tldeclared ms
481tldeclared (PInstance _ _ _ _ _ _ _ _) = []
482tldeclared _ = []
484defined :: PDecl -> [Name]
485defined (PFix _ _ _) = []
486defined (PTy _ _ _ _ n t) = []
487defined (PPostulate _ _ _ _ n t) = []
488defined (PClauses _ _ n _) = [n] -- not a declaration
489defined (PCAF _ n _) = [n]
490defined (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
491 where fstt (_, a, _, _) = a
492defined (PData _ _ _ _ (PLaterdecl n _)) = []
493defined (PParams _ _ ds) = concatMap defined ds
494defined (PNamespace _ ds) = concatMap defined ds
495defined (PRecord _ _ _ n _ _ c _) = [n, c]
496defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
497defined (PInstance _ _ _ _ _ _ _ _) = []
498defined (PDSL n _) = [n]
499defined (PSyntax _ _) = []
500defined (PMutual _ ds) = concatMap defined ds
501defined (PDirective _) = []
502--defined _ = []
504updateN :: [(Name, Name)] -> Name -> Name
505updateN ns n | Just n' <- lookup n ns = n'
506updateN _ n = n
508updateNs :: [(Name, Name)] -> PTerm -> PTerm
509updateNs [] t = t
510updateNs ns t = mapPT updateRef t
511 where updateRef (PRef fc f) = PRef fc (updateN ns f)
512 updateRef t = t
514-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
515-- updateDNs [] t = t
516-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
517-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
518-- where updateCNs ns (PClause n l ts r ds)
519-- = PClause (updateN ns n) (fmap (updateNs ns) l)
520-- (map (fmap (updateNs ns)) ts)
521-- (fmap (updateNs ns) r)
522-- (map (updateDNs ns) ds)
523-- updateDNs ns c = c
525-- | High level language terms
526data PTerm = PQuote Raw
527 | PRef FC Name
528 | PInferRef FC Name -- ^ A name to be defined later
529 | PPatvar FC Name
530 | PLam Name PTerm PTerm
531 | PPi Plicity Name PTerm PTerm
532 | PLet Name PTerm PTerm PTerm
533 | PTyped PTerm PTerm -- ^ Term with explicit type
534 | PApp FC PTerm [PArg]
535 | PMatchApp FC Name -- ^ Make an application by type matching
536 | PCase FC PTerm [(PTerm, PTerm)]
537 | PTrue FC
538 | PFalse FC
539 | PRefl FC PTerm
540 | PResolveTC FC
541 | PEq FC PTerm PTerm
542 | PRewrite FC PTerm PTerm (Maybe PTerm)
543 | PPair FC PTerm PTerm
544 | PDPair FC PTerm PTerm PTerm
545 | PAlternative Bool [PTerm] -- True if only one may work
546 | PHidden PTerm -- ^ Irrelevant or hidden pattern
547 | PType
548 | PGoal FC PTerm Name PTerm
549 | PConstant Const
550 | Placeholder
551 | PDoBlock [PDo]
552 | PIdiom FC PTerm
553 | PReturn FC
554 | PMetavar Name
555 | PProof [PTactic] -- ^ Proof script
556 | PTactics [PTactic] -- ^ As PProof, but no auto solving
557 | PElabError Err -- ^ Error to report on elaboration
558 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
559 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
560 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
561 deriving Eq
562{-!
563deriving instance Binary PTerm
564!-}
566mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
567mapPT f t = f (mpt t) where
568 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
569 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
570 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
571 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
572 (fmap (mapPT f) g)
573 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
574 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
575 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
576 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
577 mpt (PPair fc l r) = PPair fc (mapPT f l) (mapPT f r)
578 mpt (PDPair fc l t r) = PDPair fc (mapPT f l) (mapPT f t) (mapPT f r)
579 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
580 mpt (PHidden t) = PHidden (mapPT f t)
581 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
582 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
583 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
584 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
585 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
586 mpt x = x
589data PTactic' t = Intro [Name] | Intros | Focus Name
590 | Refine Name [Bool] | Rewrite t
591 | Equiv t
592 | MatchRefine Name
593 | LetTac Name t | LetTacTy Name t t
594 | Exact t | Compute | Trivial
595 | Solve
596 | Attack
597 | ProofState | ProofTerm | Undo
598 | Try (PTactic' t) (PTactic' t)
599 | TSeq (PTactic' t) (PTactic' t)
600 | ApplyTactic t -- see Language.Reflection module
601 | Reflect t
602 | Fill t
603 | GoalType String (PTactic' t)
604 | Qed | Abandon
605 deriving (Show, Eq, Functor)
606{-!
607deriving instance Binary PTactic'
608!-}
610instance Sized a => Sized (PTactic' a) where
611 size (Intro nms) = 1 + size nms
612 size Intros = 1
613 size (Focus nm) = 1 + size nm
614 size (Refine nm bs) = 1 + size nm + length bs
615 size (Rewrite t) = 1 + size t
616 size (LetTac nm t) = 1 + size nm + size t
617 size (Exact t) = 1 + size t
618 size Compute = 1
619 size Trivial = 1
620 size Solve = 1
621 size Attack = 1
622 size ProofState = 1
623 size ProofTerm = 1
624 size Undo = 1
625 size (Try l r) = 1 + size l + size r
626 size (TSeq l r) = 1 + size l + size r
627 size (ApplyTactic t) = 1 + size t
628 size (Reflect t) = 1 + size t
629 size (Fill t) = 1 + size t
630 size Qed = 1
631 size Abandon = 1
633type PTactic = PTactic' PTerm
635data PDo' t = DoExp FC t
636 | DoBind FC Name t
637 | DoBindP FC t t
638 | DoLet FC Name t t
639 | DoLetP FC t t
640 deriving (Eq, Functor)
641{-!
642deriving instance Binary PDo'
643!-}
645instance Sized a => Sized (PDo' a) where
646 size (DoExp fc t) = 1 + size fc + size t
647 size (DoBind fc nm t) = 1 + size fc + size nm + size t
648 size (DoBindP fc l r) = 1 + size fc + size l + size r
649 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
650 size (DoLetP fc l r) = 1 + size fc + size l + size r
652type PDo = PDo' PTerm
654-- The priority gives a hint as to elaboration order. Best to elaborate
655-- things early which will help give a more concrete type to other
656-- variables, e.g. a before (interpTy a).
657-- TODO: priority no longer serves any purpose, drop it!
659data PArg' t = PImp { priority :: Int,
660 lazyarg :: Bool, pname :: Name, getTm :: t,
661 pargdoc :: String }
662 | PExp { priority :: Int,
663 lazyarg :: Bool, getTm :: t,
664 pargdoc :: String }
665 | PConstraint { priority :: Int,
666 lazyarg :: Bool, getTm :: t,
667 pargdoc :: String }
668 | PTacImplicit { priority :: Int,
669 lazyarg :: Bool, pname :: Name,
670 getScript :: t,
671 getTm :: t,
672 pargdoc :: String }
673 deriving (Show, Eq, Functor)
675instance Sized a => Sized (PArg' a) where
676 size (PImp p l nm trm _) = 1 + size nm + size trm
677 size (PExp p l trm _) = 1 + size trm
678 size (PConstraint p l trm _) = 1 + size trm
679 size (PTacImplicit p l nm scr trm _) = 1 + size nm + size scr + size trm
681{-!
682deriving instance Binary PArg'
683!-}
685pimp n t = PImp 0 True n t ""
686pexp t = PExp 0 False t ""
687pconst t = PConstraint 0 False t ""
688ptacimp n s t = PTacImplicit 0 True n s t ""
690type PArg = PArg' PTerm
692-- Type class data
694data ClassInfo = CI { instanceName :: Name,
695 class_methods :: [(Name, (FnOpts, PTerm))],
696 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
697 class_params :: [Name],
698 class_instances :: [Name] }
699 deriving Show
700{-!
701deriving instance Binary ClassInfo
702!-}
704data OptInfo = Optimise { collapsible :: Bool,
705 isnewtype :: Bool,
706 forceable :: [Int], -- argument positions
707 recursive :: [Int] }
708 deriving Show
709{-!
710deriving instance Binary OptInfo
711!-}
714data TypeInfo = TI { con_names :: [Name],
715 codata :: Bool,
716 param_pos :: [Int] }
717 deriving Show
718{-!
719deriving instance Binary TypeInfo
720!-}
722-- Syntactic sugar info
724data DSL' t = DSL { dsl_bind :: t,
725 dsl_return :: t,
726 dsl_apply :: t,
727 dsl_pure :: t,
728 dsl_var :: Maybe t,
729 index_first :: Maybe t,
730 index_next :: Maybe t,
731 dsl_lambda :: Maybe t,
732 dsl_let :: Maybe t
733 }
734 deriving (Show, Functor)
735{-!
736deriving instance Binary DSL'
737!-}
739type DSL = DSL' PTerm
741data SynContext = PatternSyntax | TermSyntax | AnySyntax
742 deriving Show
743{-!
744deriving instance Binary SynContext
745!-}
747data Syntax = Rule [SSymbol] PTerm SynContext
748 deriving Show
749{-!
750deriving instance Binary Syntax
751!-}
753data SSymbol = Keyword Name
754 | Symbol String
755 | Binding Name
756 | Expr Name
757 | SimpleExpr Name
758 deriving Show
759{-!
760deriving instance Binary SSymbol
761!-}
763initDSL = DSL (PRef f (UN ">>="))
764 (PRef f (UN "return"))
765 (PRef f (UN "<$>"))
766 (PRef f (UN "pure"))
767 Nothing
768 Nothing
769 Nothing
770 Nothing
771 Nothing
772 where f = FC "(builtin)" 0
774data Using = UImplicit Name PTerm
775 | UConstraint Name [Name]
776 deriving (Show, Eq)
777{-!
778deriving instance Binary Using
779!-}
781data SyntaxInfo = Syn { using :: [Using],
782 syn_params :: [(Name, PTerm)],
783 syn_namespace :: [String],
784 no_imp :: [Name],
785 decoration :: Name -> Name,
786 inPattern :: Bool,
787 implicitAllowed :: Bool,
788 dsl_info :: DSL }
789 deriving Show
790{-!
791deriving instance Binary SyntaxInfo
792!-}
794defaultSyntax = Syn [] [] [] [] id False False initDSL
796expandNS :: SyntaxInfo -> Name -> Name
797expandNS syn n@(NS _ _) = n
798expandNS syn n = case syn_namespace syn of
799 [] -> n
800 xs -> NS n xs
803--- Pretty printing declarations and terms
805instance Show PTerm where
806 show tm = showImp Nothing False False tm
808instance Pretty PTerm where
809 pretty = prettyImp False
811instance Show PDecl where
812 show d = showDeclImp False d
814instance Show PClause where
815 show c = showCImp True c
817instance Show PData where
818 show d = showDImp False d
820showDeclImp _ (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
821showDeclImp t (PTy _ _ _ _ n ty) = show n ++ " : " ++ showImp Nothing t False ty
822showDeclImp t (PPostulate _ _ _ _ n ty) = show n ++ " : " ++ showImp Nothing t False ty
823showDeclImp _ (PClauses _ _ n c) = showSep "\n" (map show c)
824showDeclImp _ (PData _ _ _ _ d) = show d
825showDeclImp _ (PParams f ns ps) = "parameters " ++ show ns ++ "\n" ++
826 showSep "\n" (map show ps)
829showCImp :: Bool -> PClause -> String
830showCImp impl (PClause _ n l ws r w)
831 = showImp Nothing impl False l ++ showWs ws ++ " = " ++ showImp Nothing impl False r
832 ++ " where " ++ show w
833 where
834 showWs [] = ""
835 showWs (x : xs) = " | " ++ showImp Nothing impl False x ++ showWs xs
836showCImp impl (PWith _ n l ws r w)
837 = showImp Nothing impl False l ++ showWs ws ++ " with " ++ showImp Nothing impl False r
838 ++ " { " ++ show w ++ " } "
839 where
840 showWs [] = ""
841 showWs (x : xs) = " | " ++ showImp Nothing impl False x ++ showWs xs
844showDImp :: Bool -> PData -> String
845showDImp impl (PDatadecl n ty cons)
846 = "data " ++ show n ++ " : " ++ showImp Nothing impl False ty ++ " where\n\t"
847 ++ showSep "\n\t| "
848 (map (\ (_, n, t, _) -> show n ++ " : " ++ showImp Nothing impl False t) cons)
850getImps :: [PArg] -> [(Name, PTerm)]
851getImps [] = []
852getImps (PImp _ _ n tm _ : xs) = (n, tm) : getImps xs
853getImps (_ : xs) = getImps xs
855getExps :: [PArg] -> [PTerm]
856getExps [] = []
857getExps (PExp _ _ tm _ : xs) = tm : getExps xs
858getExps (_ : xs) = getExps xs
860getConsts :: [PArg] -> [PTerm]
861getConsts [] = []
862getConsts (PConstraint _ _ tm _ : xs) = tm : getConsts xs
863getConsts (_ : xs) = getConsts xs
865getAll :: [PArg] -> [PTerm]
866getAll = map getTm
868-- | Pretty-print a high-level Idris term
869prettyImp :: Bool -- ^^ whether to show implicits
870 -> PTerm -- ^^ the term to pretty-print
871 -> Doc
872prettyImp impl = prettySe 10
873 where
874 prettySe p (PQuote r) =
875 if size r > breakingSize then
876 text "![" $$ pretty r <> text "]"
877 else
878 text "![" <> pretty r <> text "]"
879 prettySe p (PPatvar fc n) = pretty n
880 prettySe p (PRef fc n) =
881 if impl then
882 pretty n
883 else
884 prettyBasic n
885 where
886 prettyBasic n@(UN _) = pretty n
887 prettyBasic (MN _ s) = text s
888 prettyBasic (NS n s) = (foldr (<>) empty (intersperse (text ".") (map text $ reverse s))) <> prettyBasic n
889 prettySe p (PLam n ty sc) =
890 bracket p 2 $
891 if size sc > breakingSize then
892 text "λ" <> pretty n <+> text "=>" $+$ pretty sc
893 else
894 text "λ" <> pretty n <+> text "=>" <+> pretty sc
895 prettySe p (PLet n ty v sc) =
896 bracket p 2 $
897 if size sc > breakingSize then
898 text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" $+$
899 nest nestingSize (prettySe 10 sc)
900 else
901 text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" <+>
902 prettySe 10 sc
903 prettySe p (PPi (Exp l s _) n ty sc)
904 | n `elem` allNamesIn sc || impl =
905 let open = if l then text "|" <> lparen else lparen in
906 bracket p 2 $
907 if size sc > breakingSize then
908 open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+>
909 st <+> text "->" $+$ prettySe 10 sc
910 else
911 open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+>
912 st <+> text "->" <+> prettySe 10 sc
913 | otherwise =
914 bracket p 2 $
915 if size sc > breakingSize then
916 prettySe 0 ty <+> st <+> text "->" $+$ prettySe 10 sc
917 else
918 prettySe 0 ty <+> st <+> text "->" <+> prettySe 10 sc
919 where
920 st =
921 case s of
922 Static -> text "[static]"
923 _ -> empty
924 prettySe p (PPi (Imp l s _) n ty sc)
925 | impl =
926 let open = if l then text "|" <> lbrace else lbrace in
927 bracket p 2 $
928 if size sc > breakingSize then
929 open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+>
930 st <+> text "->" <+> prettySe 10 sc
931 else
932 open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+>
933 st <+> text "->" <+> prettySe 10 sc
934 | otherwise = prettySe 10 sc
935 where
936 st =
937 case s of
938 Static -> text $ "[static]"
939 _ -> empty
940 prettySe p (PPi (Constraint _ _ _) n ty sc) =
941 bracket p 2 $
942 if size sc > breakingSize then
943 prettySe 10 ty <+> text "=>" <+> prettySe 10 sc
944 else
945 prettySe 10 ty <+> text "=>" $+$ prettySe 10 sc
946 prettySe p (PPi (TacImp _ _ s _) n ty sc) =
947 bracket p 2 $
948 if size sc > breakingSize then
949 lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <>
950 rbrace <+> text "->" $+$ prettySe 10 sc
951 else
952 lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <>
953 rbrace <+> text "->" <+> prettySe 10 sc
954 prettySe p (PApp _ (PRef _ f) [])
955 | not impl = pretty f
956 prettySe p (PApp _ (PRef _ op@(UN (f:_))) args)
957 | length (getExps args) == 2 && (not impl) && (not $ isAlpha f) =
958 let [l, r] = getExps args in
959 bracket p 1 $
960 if size r > breakingSize then
961 prettySe 1 l <+> pretty op $+$ prettySe 0 r
962 else
963 prettySe 1 l <+> pretty op <+> prettySe 0 r
964 prettySe p (PApp _ f as) =
965 let args = getExps as in
966 bracket p 1 $
967 prettySe 1 f <+>
968 if impl then
969 foldl' fS empty as
970 -- foldr (<+>) empty $ map prettyArgS as
971 else
972 foldl' fSe empty args
973 -- foldr (<+>) empty $ map prettyArgSe args
974 where
975 fS l r =
976 if size r > breakingSize then
977 l $+$ nest nestingSize (prettyArgS r)
978 else
979 l <+> prettyArgS r
981 fSe l r =
982 if size r > breakingSize then
983 l $+$ nest nestingSize (prettyArgSe r)
984 else
985 l <+> prettyArgSe r
986 prettySe p (PCase _ scr opts) =
987 text "case" <+> prettySe 10 scr <+> text "of" $+$ nest nestingSize prettyBody
988 where
989 prettyBody = foldr ($$) empty $ intersperse (text "|") $ map sc opts
991 sc (l, r) = prettySe 10 l <+> text "=>" <+> prettySe 10 r
992 prettySe p (PHidden tm) = text "." <> prettySe 0 tm
993 prettySe p (PRefl _ _) = text "refl"
994 prettySe p (PResolveTC _) = text "resolvetc"
995 prettySe p (PTrue _) = text "()"
996 prettySe p (PFalse _) = text "_|_"
997 prettySe p (PEq _ l r) =
998 bracket p 2 $
999 if size r > breakingSize then
1000 prettySe 10 l <+> text "=" $$ nest nestingSize (prettySe 10 r)
1001 else
1002 prettySe 10 l <+> text "=" <+> prettySe 10 r
1003 prettySe p (PRewrite _ l r _) =
1004 bracket p 2 $
1005 if size r > breakingSize then
1006 text "rewrite" <+> prettySe 10 l <+> text "in" $$ nest nestingSize (prettySe 10 r)
1007 else
1008 text "rewrite" <+> prettySe 10 l <+> text "in" <+> prettySe 10 r
1009 prettySe p (PTyped l r) =
1010 lparen <> prettySe 10 l <+> colon <+> prettySe 10 r <> rparen
1011 prettySe p (PPair _ l r) =
1012 if size r > breakingSize then
1013 lparen <> prettySe 10 l <> text "," $+$
1014 prettySe 10 r <> rparen
1015 else
1016 lparen <> prettySe 10 l <> text "," <+> prettySe 10 r <> rparen
1017 prettySe p (PDPair _ l t r) =
1018 if size r > breakingSize then
1019 lparen <> prettySe 10 l <+> text "**" $+$
1020 prettySe 10 r <> rparen
1021 else
1022 lparen <> prettySe 10 l <+> text "**" <+> prettySe 10 r <> rparen
1023 prettySe p (PAlternative a as) =
1024 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1025 where
1026 prettyAs =
1027 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10) as
1028 prettySe p PType = text "Type"
1029 prettySe p (PConstant c) = pretty c
1030 -- XXX: add pretty for tactics
1031 prettySe p (PProof ts) =
1032 text "proof" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace
1033 prettySe p (PTactics ts) =
1034 text "tactics" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace
1035 prettySe p (PMetavar n) = text "?" <> pretty n
1036 prettySe p (PReturn f) = text "return"
1037 prettySe p PImpossible = text "impossible"
1038 prettySe p Placeholder = text "_"
1039 prettySe p (PDoBlock _) = text "do block pretty not implemented"
1040 prettySe p (PElabError s) = pretty s
1042 prettySe p _ = text "test"
1044 prettyArgS (PImp _ _ n tm _) = prettyArgSi (n, tm)
1045 prettyArgS (PExp _ _ tm _) = prettyArgSe tm
1046 prettyArgS (PConstraint _ _ tm _) = prettyArgSc tm
1047 prettyArgS (PTacImplicit _ _ n _ tm _) = prettyArgSti (n, tm)
1049 prettyArgSe arg = prettySe 0 arg
1050 prettyArgSi (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 val <> rbrace
1051 prettyArgSc val = lbrace <> lbrace <> prettySe 10 val <> rbrace <> rbrace
1052 prettyArgSti (n, val) = lbrace <> text "auto" <+> pretty n <+> text "=" <+> prettySe 10 val <> rbrace
1054 bracket outer inner doc
1055 | inner > outer = lparen <> doc <> rparen
1056 | otherwise = doc
1058-- | Show Idris name
1059showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1060 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1061 -> Bool -- ^^ whether to show implicits
1062 -> Bool -- ^^ whether to colourise
1063 -> Name -- ^^ the term to show
1064 -> String
1065showName ist bnd impl colour n = case ist of
1066 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1067 Nothing -> showbasic n
1068 where name = if impl then show n else showbasic n
1069 showbasic n@(UN _) = show n
1070 showbasic (MN _ s) = s
1071 showbasic (NS n s) = showSep "." (reverse s) ++ "." ++ showbasic n
1072 showbasic (SN s) = show s
1073 fst3 (x, _, _) = x
1074 colourise n t = let ctxt' = fmap tt_ctxt ist in
1075 case ctxt' of
1076 Nothing -> name
1077 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1078 else colouriseBound t name
1079 | isDConName n ctxt -> colouriseData t name
1080 | isFnName n ctxt -> colouriseFun t name
1081 | isTConName n ctxt -> colouriseType t name
1082 -- The assumption is that if a name is not bound and does not exist in the
1083 -- global context, then we're somewhere in which implicit info has been lost
1084 -- (like error messages). Thus, unknown vars are colourised as implicits.
1085 | otherwise -> colouriseImplicit t name
1087-- | Show Idris term
1088showImp :: Maybe IState -- ^^ the Idris state, for information about identifiers and colours
1089 -> Bool -- ^^ whether to show implicits
1090 -> Bool -- ^^ whether to colourise
1091 -> PTerm -- ^^ the term to show
1092 -> String
1093showImp ist impl colour tm = se 10 [] tm where
1094 perhapsColourise :: (ColourTheme -> String -> String) -> String -> String
1095 perhapsColourise col str = case ist of
1096 Just i -> if colour then col (idris_colourTheme i) str else str
1097 Nothing -> str
1099 se :: Int -> [(Name, Bool)] -> PTerm -> String
1100 se p bnd (PQuote r) = "![" ++ show r ++ "]"
1101 se p bnd (PPatvar fc n) = if impl then show n ++ "[p]" else show n
1102 se p bnd (PInferRef fc n) = "!" ++ show n -- ++ "[" ++ show fc ++ "]"
1103 se p bnd e
1104 | Just str <- slist p bnd e = str
1105 | Just num <- snat p e = perhapsColourise colouriseData (show num)
1106 se p bnd (PRef fc n) = showName ist bnd impl colour n
1107 se p bnd (PLam n ty sc) = bracket p 2 $ "\\ " ++ perhapsColourise colouriseBound (show n) ++
1108 (if impl then " : " ++ se 10 bnd ty else "") ++ " => "
1109 ++ se 10 ((n, False):bnd) sc
1110 se p bnd (PLet n ty v sc) = bracket p 2 $ "let " ++ perhapsColourise colouriseBound (show n) ++
1111 " = " ++ se 10 bnd v ++
1112 " in " ++ se 10 ((n, False):bnd) sc
1113 se p bnd (PPi (Exp l s _) n ty sc)
1114 | n `elem` allNamesIn sc || impl
1115 = bracket p 2 $
1116 (if l then "|(" else "(") ++
1117 perhapsColourise colouriseBound (show n) ++ " : " ++ se 10 bnd ty ++
1118 ") " ++ st ++
1119 "-> " ++ se 10 ((n, False):bnd) sc
1120 | otherwise = bracket p 2 $ se 0 bnd ty ++ " " ++ st ++ "-> " ++ se 10 bnd sc
1121 where st = case s of
1122 Static -> "[static] "
1123 _ -> ""
1124 se p bnd (PPi (Imp l s _) n ty sc)
1125 | impl = bracket p 2 $ (if l then "|{" else "{") ++
1126 perhapsColourise colouriseBound (show n) ++ " : " ++ se 10 bnd ty ++
1127 "} " ++ st ++ "-> " ++ se 10 ((n, True):bnd) sc
1128 | otherwise = se 10 ((n, True):bnd) sc
1129 where st = case s of
1130 Static -> "[static] "
1131 _ -> ""
1132 se p bnd (PPi (Constraint _ _ _) n ty sc)
1133 = bracket p 2 $ se 10 bnd ty ++ " => " ++ se 10 bnd sc
1134 se p bnd (PPi (TacImp _ _ s _) n ty sc)
1135 = bracket p 2 $
1136 "{tacimp " ++ (perhapsColourise colouriseBound (show n)) ++ " : " ++ se 10 bnd ty ++ "} -> " ++
1137 se 10 ((n, False):bnd) sc
1138 se p bnd (PMatchApp _ f) = "match " ++ show f
1139 se p bnd (PApp _ hd@(PRef _ f) [])
1140 | not impl = se p bnd hd
1141 se p bnd (PApp _ op@(PRef _ (UN (f:_))) args)
1142 | length (getExps args) == 2 && not impl && not (isAlpha f)
1143 = let [l, r] = getExps args in
1144 bracket p 1 $ se 1 bnd l ++ " " ++ se p bnd op ++ " " ++ se 0 bnd r
1145 se p bnd (PApp _ f as)
1146 = let args = getExps as in
1147 bracket p 1 $ se 1 bnd f ++ if impl then concatMap (sArg bnd) as
1148 else concatMap (seArg bnd) args
1149 se p bnd (PCase _ scr opts) = "case " ++ se 10 bnd scr ++ " of " ++ showSep " | " (map sc opts)
1150 where sc (l, r) = se 10 bnd l ++ " => " ++ se 10 bnd r
1151 se p bnd (PHidden tm) = "." ++ se 0 bnd tm
1152 se p bnd (PRefl _ t)
1153 | not impl = perhapsColourise colouriseData "refl"
1154 | otherwise = perhapsColourise colouriseData $ "refl {" ++ se 10 bnd t ++ "}"
1155 se p bnd (PResolveTC _) = "resolvetc"
1156 se p bnd (PTrue _) = perhapsColourise colouriseType "()"
1157 se p bnd (PFalse _) = perhapsColourise colouriseType "_|_"
1158 se p bnd (PEq _ l r) = bracket p 2 $ se 10 bnd l ++ perhapsColourise colouriseType " = " ++ se 10 bnd r
1159 se p bnd (PRewrite _ l r _) = bracket p 2 $ "rewrite " ++ se 10 bnd l ++ " in " ++ se 10 bnd r
1160 se p bnd (PTyped l r) = "(" ++ se 10 bnd l ++ " : " ++ se 10 bnd r ++ ")"
1161 se p bnd (PPair _ l r) = "(" ++ se 10 bnd l ++ ", " ++ se 10 bnd r ++ ")"
1162 se p bnd (PDPair _ l t r) = "(" ++ se 10 bnd l ++ " ** " ++ se 10 bnd r ++ ")"
1163 se p bnd (PAlternative a as) = "(|" ++ showSep " , " (map (se 10 bnd) as) ++ "|)"
1164 se p bnd PType = perhapsColourise colouriseType "Type"
1165 se p bnd (PConstant c) = perhapsColourise (cfun c) (show c)
1166 where cfun (AType _) = colouriseType
1167 cfun StrType = colouriseType
1168 cfun PtrType = colouriseType
1169 cfun VoidType = colouriseType
1170 cfun _ = colouriseData
1171 se p bnd (PProof ts) = "proof { " ++ show ts ++ "}"
1172 se p bnd (PTactics ts) = "tactics { " ++ show ts ++ "}"
1173 se p bnd (PMetavar n) = "?" ++ show n
1174 se p bnd (PReturn f) = "return"
1175 se p bnd PImpossible = "impossible"
1176 se p bnd Placeholder = "_"
1177 se p bnd (PDoBlock _) = "do block show not implemented"
1178 se p bnd (PElabError s) = show s
1179 se p bnd (PCoerced t) = se p bnd t
1180 se p bnd (PUnifyLog t) = "%unifyLog " ++ se p bnd t
1181-- se p bnd x = "Not implemented"
1183 slist' p bnd (PApp _ (PRef _ nil) _)
1184 | nsroot nil == UN "Nil" = Just []
1185 slist' p bnd (PApp _ (PRef _ cons) args)
1186 | nsroot cons == UN "::",
1187 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1188 all isImp imps,
1189 Just tl' <- slist' p bnd tl
1190 = Just (hd:tl')
1191 where
1192 isImp (PImp {}) = True
1193 isImp _ = False
1194 slist' _ _ _ = Nothing
1196 slist p bnd e | Just es <- slist' p bnd e = Just $
1197 case es of [] -> "[]"
1198 [x] -> "[" ++ se p bnd x ++ "]"
1199 xs -> "[" ++ intercalate "," (map (se p bnd ) xs) ++ "]"
1200 slist _ _ _ = Nothing
1202 -- since Prelude is always imported, S & Z are unqualified iff they're the
1203 -- Nat ones.
1204 snat p (PRef _ o)
1205 | show o == (natns++"Z") || show o == "Z" = Just 0
1206 snat p (PApp _ s [PExp {getTm=n}])
1207 | show s == (natns++"S") || show s == "S",
1208 Just n' <- snat p n
1209 = Just $ 1 + n'
1210 snat _ _ = Nothing
1212 natns = "Prelude.Nat."
1214 sArg bnd (PImp _ _ n tm _) = siArg bnd (n, tm)
1215 sArg bnd (PExp _ _ tm _) = seArg bnd tm
1216 sArg bnd (PConstraint _ _ tm _) = scArg bnd tm
1217 sArg bnd (PTacImplicit _ _ n _ tm _) = stiArg bnd (n, tm)
1219 seArg bnd arg = " " ++ se 0 bnd arg
1220 siArg bnd (n, val) = " {" ++ show n ++ " = " ++ se 10 bnd val ++ "}"
1221 scArg bnd val = " {{" ++ se 10 bnd val ++ "}}"
1222 stiArg bnd (n, val) = " {auto " ++ show n ++ " = " ++ se 10 bnd val ++ "}"
1224 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
1225 | otherwise = str
1228instance Sized PTerm where
1229 size (PQuote rawTerm) = size rawTerm
1230 size (PRef fc name) = size name
1231 size (PLam name ty bdy) = 1 + size ty + size bdy
1232 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1233 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1234 size (PTyped trm ty) = 1 + size trm + size ty
1235 size (PApp fc name args) = 1 + size args
1236 size (PCase fc trm bdy) = 1 + size trm + size bdy
1237 size (PTrue fc) = 1
1238 size (PFalse fc) = 1
1239 size (PRefl fc _) = 1
1240 size (PResolveTC fc) = 1
1241 size (PEq fc left right) = 1 + size left + size right
1242 size (PRewrite fc left right _) = 1 + size left + size right
1243 size (PPair fc left right) = 1 + size left + size right
1244 size (PDPair fs left ty right) = 1 + size left + size ty + size right
1245 size (PAlternative a alts) = 1 + size alts
1246 size (PHidden hidden) = size hidden
1247 size (PUnifyLog tm) = size tm
1248 size PType = 1
1249 size (PConstant const) = 1 + size const
1250 size Placeholder = 1
1251 size (PDoBlock dos) = 1 + size dos
1252 size (PIdiom fc term) = 1 + size term
1253 size (PReturn fc) = 1
1254 size (PMetavar name) = 1
1255 size (PProof tactics) = size tactics
1256 size (PElabError err) = size err
1257 size PImpossible = 1
1259getPArity :: PTerm -> Int
1260getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1261getPArity _ = 0
1263-- Return all names, free or globally bound, in the given term.
1265allNamesIn :: PTerm -> [Name]
1266allNamesIn tm = nub $ ni [] tm
1267 where
1268 ni env (PRef _ n)
1269 | not (n `elem` env) = [n]
1270 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1271 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1272 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1273 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1274 ni env (PHidden tm) = ni env tm
1275 ni env (PEq _ l r) = ni env l ++ ni env r
1276 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1277 ni env (PTyped l r) = ni env l ++ ni env r
1278 ni env (PPair _ l r) = ni env l ++ ni env r
1279 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1280 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1281 ni env (PAlternative a ls) = concatMap (ni env) ls
1282 ni env (PUnifyLog tm) = ni env tm
1283 ni env _ = []
1285-- Return names which are free in the given term.
1287namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1288namesIn uvars ist tm = nub $ ni [] tm
1289 where
1290 ni env (PRef _ n)
1291 | not (n `elem` env)
1292 = case lookupTy n (tt_ctxt ist) of
1293 [] -> [n]
1294 _ -> if n `elem` (map fst uvars) then [n] else []
1295 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1296 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1297 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1298 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1299 ni env (PEq _ l r) = ni env l ++ ni env r
1300 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1301 ni env (PTyped l r) = ni env l ++ ni env r
1302 ni env (PPair _ l r) = ni env l ++ ni env r
1303 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1304 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1305 ni env (PAlternative a as) = concatMap (ni env) as
1306 ni env (PHidden tm) = ni env tm
1307 ni env (PUnifyLog tm) = ni env tm
1308 ni env _ = []
1310-- Return which of the given names are used in the given term.
1312usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1313usedNamesIn vars ist tm = nub $ ni [] tm
1314 where
1315 ni env (PRef _ n)
1316 | n `elem` vars && not (n `elem` env)
1317 = case lookupTy n (tt_ctxt ist) of
1318 [] -> [n]
1319 _ -> []
1320 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1321 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1322 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1323 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1324 ni env (PEq _ l r) = ni env l ++ ni env r
1325 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1326 ni env (PTyped l r) = ni env l ++ ni env r
1327 ni env (PPair _ l r) = ni env l ++ ni env r
1328 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1329 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1330 ni env (PAlternative a as) = concatMap (ni env) as
1331 ni env (PHidden tm) = ni env tm
1332 ni env (PUnifyLog tm) = ni env tm
1333 ni env _ = []