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