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