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