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