on a85d407 help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1863 lines 76 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 System.Console.Haskeline
19import System.IO
21import Control.Monad.Trans.State.Strict
22import Control.Monad.Trans.Error
24import Data.Function (on)
25import Data.List hiding (group)
26import Data.Char
27import qualified Data.Map as M
28import qualified Data.Text as T
29import qualified Data.Map as M
30import Data.Either
31import qualified Data.Set as S
32import Data.Word (Word)
33import Data.Maybe (fromMaybe, mapMaybe)
34import Data.Traversable (Traversable)
35import Data.Foldable (Foldable)
37import Debug.Trace
39import Text.PrettyPrint.Annotated.Leijen
41data ElabWhat = ETypes | EDefns | EAll
42 deriving (Show, Eq)
44-- Data to pass to recursively called elaborators; e.g. for where blocks,
45-- paramaterised declarations, etc.
47-- rec_elabDecl is used to pass the top level elaborator into other elaborators,
48-- so that we can have mutually recursive elaborators in separate modules without
49-- having to muck about with cyclic modules.
50data ElabInfo = EInfo { params :: [(Name, PTerm)],
51 inblock :: Ctxt [Name], -- names in the block, and their params
52 liftname :: Name -> Name,
53 namespace :: Maybe [String],
54 elabFC :: Maybe FC,
55 rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl ->
56 Idris () }
58toplevel :: ElabInfo
59toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented")
61eInfoNames :: ElabInfo -> [Name]
62eInfoNames info = map fst (params info) ++ M.keys (inblock info)
64data IOption = IOption { opt_logLevel :: Int,
65 opt_typecase :: Bool,
66 opt_typeintype :: Bool,
67 opt_coverage :: Bool,
68 opt_showimp :: Bool, -- ^^ show implicits
69 opt_errContext :: Bool,
70 opt_repl :: Bool,
71 opt_verbose :: Bool,
72 opt_nobanner :: Bool,
73 opt_quiet :: Bool,
74 opt_codegen :: Codegen,
75 opt_outputTy :: OutputType,
76 opt_ibcsubdir :: FilePath,
77 opt_importdirs :: [FilePath],
78 opt_triple :: String,
79 opt_cpu :: String,
80 opt_cmdline :: [Opt], -- remember whole command line
81 opt_origerr :: Bool,
82 opt_autoSolve :: Bool, -- ^ automatically apply "solve" tactic in prover
83 opt_autoImport :: [FilePath], -- ^ e.g. Builtins+Prelude
84 opt_optimise :: [Optimisation]
85 }
86 deriving (Show, Eq)
88defaultOpts = IOption { opt_logLevel = 0
89 , opt_typecase = False
90 , opt_typeintype = False
91 , opt_coverage = True
92 , opt_showimp = False
93 , opt_errContext = False
94 , opt_repl = True
95 , opt_verbose = True
96 , opt_nobanner = False
97 , opt_quiet = False
98 , opt_codegen = Via "c"
99 , opt_outputTy = Executable
100 , opt_ibcsubdir = ""
101 , opt_importdirs = []
102 , opt_triple = ""
103 , opt_cpu = ""
104 , opt_cmdline = []
105 , opt_origerr = False
106 , opt_autoSolve = True
107 , opt_autoImport = []
108 , opt_optimise = defaultOptimise
109 }
111data PPOption = PPOption {
112 ppopt_impl :: Bool -- ^^ whether to show implicits
113} deriving (Show)
115data Optimisation = PETransform -- partial eval and associated transforms
116 deriving (Show, Eq)
118defaultOptimise = [PETransform]
120-- | Pretty printing options with default verbosity.
121defaultPPOption :: PPOption
122defaultPPOption = PPOption { ppopt_impl = False }
124-- | Pretty printing options with the most verbosity.
125verbosePPOption :: PPOption
126verbosePPOption = PPOption { ppopt_impl = True }
128-- | Get pretty printing options from the big options record.
129ppOption :: IOption -> PPOption
130ppOption opt = PPOption {
131 ppopt_impl = opt_showimp opt
134-- | Get pretty printing options from an idris state record.
135ppOptionIst :: IState -> PPOption
136ppOptionIst = ppOption . idris_options
138data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
140-- | The output mode in use
141data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle
142 | IdeSlave Integer Handle -- ^ Send IDE output for some request ID to the handle
143 deriving Show
145-- | How wide is the console?
146data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
147 | ColsWide Int -- ^ Manually specified - must be positive
148 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
150-- | The global state used in the Idris monad
151data IState = IState {
152 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
153 idris_constraints :: [(UConstraint, FC)],
154 -- ^ A list of universe constraints and their corresponding source locations
155 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
156 idris_implicits :: Ctxt [PArg],
157 idris_statics :: Ctxt [Bool],
158 idris_classes :: Ctxt ClassInfo,
159 idris_dsls :: Ctxt DSL,
160 idris_optimisation :: Ctxt OptInfo,
161 idris_datatypes :: Ctxt TypeInfo,
162 idris_namehints :: Ctxt [Name],
163 idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
164 -- ^ list of lhs/rhs, and a list of missing clauses
165 idris_flags :: Ctxt [FnOpt],
166 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
167 idris_calledgraph :: Ctxt [Name],
168 idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]),
169 idris_tyinfodata :: Ctxt TIData,
170 idris_fninfo :: Ctxt FnInfo,
171 idris_transforms :: Ctxt [(Term, Term)],
172 idris_totcheck :: [(FC, Name)], -- names to check totality on
173 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
174 idris_totcheckfail :: [(FC, String)],
175 idris_options :: IOption,
176 idris_name :: Int,
177 idris_lineapps :: [((FilePath, Int), PTerm)],
178 -- ^ Full application LHS on source line
179 idris_metavars :: [(Name, (Maybe Name, Int, Bool))], -- ^ The currently defined but not proven metavariables
180 idris_coercions :: [Name],
181 idris_errRev :: [(Term, Term)],
182 syntax_rules :: SyntaxRules,
183 syntax_keywords :: [String],
184 imported :: [FilePath], -- ^ The imported modules
185 idris_scprims :: [(Name, (Int, PrimFn))],
186 idris_objs :: [(Codegen, FilePath)],
187 idris_libs :: [(Codegen, String)],
188 idris_cgflags :: [(Codegen, String)],
189 idris_hdrs :: [(Codegen, String)],
190 idris_imported :: [FilePath], -- ^ Imported ibc file names
191 proof_list :: [(Name, [String])],
192 errSpan :: Maybe FC,
193 parserWarnings :: [(FC, Err)],
194 lastParse :: Maybe Name,
195 indent_stack :: [Int],
196 brace_stack :: [Maybe Int],
197 lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
198 idris_parsedSpan :: Maybe FC,
199 hide_list :: [(Name, Maybe Accessibility)],
200 default_access :: Accessibility,
201 default_total :: Bool,
202 ibc_write :: [IBCWrite],
203 compiled_so :: Maybe String,
204 idris_dynamic_libs :: [DynamicLib],
205 idris_language_extensions :: [LanguageExt],
206 idris_outputmode :: OutputMode,
207 idris_colourRepl :: Bool,
208 idris_colourTheme :: ColourTheme,
209 idris_errorhandlers :: [Name], -- ^ Global error handlers
210 idris_nameIdx :: (Int, Ctxt (Int, Name)),
211 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
212 module_aliases :: M.Map [T.Text] [T.Text],
213 idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
214 idris_postulates :: S.Set Name,
215 idris_whocalls :: Maybe (M.Map Name [Name]),
216 idris_callswho :: Maybe (M.Map Name [Name]),
217 idris_repl_defs :: [Name] -- ^ List of names that were defined in the repl, and can be re-/un-defined
218 }
220-- Required for parsers library, and therefore trifecta
221instance Show IState where
222 show = const "{internal state}"
224data SizeChange = Smaller | Same | Bigger | Unknown
225 deriving (Show, Eq)
226{-!
227deriving instance Binary SizeChange
228deriving instance NFData SizeChange
229!-}
231type SCGEntry = (Name, [Maybe (Int, SizeChange)])
232type UsageReason = (Name, Int) -- fn_name, its_arg_number
234data CGInfo = CGInfo { argsdef :: [Name],
235 calls :: [(Name, [[Name]])],
236 scg :: [SCGEntry],
237 argsused :: [Name],
238 usedpos :: [(Int, [UsageReason])] }
239 deriving Show
240{-!
241deriving instance Binary CGInfo
242deriving instance NFData CGInfo
243!-}
245primDefs = [sUN "unsafePerformPrimIO",
246 sUN "mkLazyForeignPrim",
247 sUN "mkForeignPrim",
248 sUN "void"]
250-- information that needs writing for the current module's .ibc file
251data IBCWrite = IBCFix FixDecl
252 | IBCImp Name
253 | IBCStatic Name
254 | IBCClass Name
255 | IBCInstance Bool Name Name
256 | IBCDSL Name
257 | IBCData Name
258 | IBCOpt Name
259 | IBCMetavar Name
260 | IBCSyntax Syntax
261 | IBCKeyword String
262 | IBCImport FilePath
263 | IBCImportDir FilePath
264 | IBCObj Codegen FilePath
265 | IBCLib Codegen String
266 | IBCCGFlag Codegen String
267 | IBCDyLib String
268 | IBCHeader Codegen String
269 | IBCAccess Name Accessibility
270 | IBCMetaInformation Name MetaInformation
271 | IBCTotal Name Totality
272 | IBCFlags Name [FnOpt]
273 | IBCFnInfo Name FnInfo
274 | IBCTrans Name (Term, Term)
275 | IBCErrRev (Term, Term)
276 | IBCCG Name
277 | IBCDoc Name
278 | IBCCoercion Name
279 | IBCDef Name -- i.e. main context
280 | IBCNameHint (Name, Name)
281 | IBCLineApp FilePath Int PTerm
282 | IBCErrorHandler Name
283 | IBCFunctionErrorHandler Name Name Name
284 | IBCPostulate Name
285 | IBCTotCheckErr FC String
286 | IBCParsedRegion FC
287 deriving Show
289-- | The initial state for the compiler
290idrisInit :: IState
291idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
292 emptyContext emptyContext emptyContext emptyContext
293 emptyContext emptyContext emptyContext emptyContext
294 emptyContext emptyContext emptyContext emptyContext
295 [] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []
296 [] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] []
297 (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty
298 AutomaticWidth S.empty Nothing Nothing []
300-- | The monad for the main REPL - reading and processing files and updating
301-- global state (hence the IO inner monad).
302--type Idris = WriterT [Either String (IO ())] (State IState a))
303type Idris = StateT IState (ErrorT Err IO)
305-- Commands in the REPL
307data Codegen = Via String
308-- | ViaC
309-- | ViaJava
310-- | ViaNode
311-- | ViaJavaScript
312-- | ViaLLVM
313 | Bytecode
314 deriving (Show, Eq)
316-- | REPL commands
317data Command = Quit
318 | Help
319 | Eval PTerm
320 | NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
321 | Undefine [Name]
322 | Check PTerm
323 | DocStr (Either Name Const)
324 | TotCheck Name
325 | Reload
326 | Load FilePath (Maybe Int) -- up to maximum line number
327 | ChangeDirectory FilePath
328 | ModImport String
329 | Edit
330 | Compile Codegen String
331 | Execute
332 | ExecVal PTerm
333 | Metavars
334 | Prove Name
335 | AddProof (Maybe Name)
336 | RmProof Name
337 | ShowProof Name
338 | Proofs
339 | Universes
340 | LogLvl Int
341 | Spec PTerm
342 | HNF PTerm
343 | TestInline PTerm
344 | Defn Name
345 | Missing Name
346 | DynamicLink FilePath
347 | ListDynamic
348 | Pattelab PTerm
349 | Search PTerm
350 | CaseSplitAt Bool Int Name
351 | AddClauseFrom Bool Int Name
352 | AddProofClauseFrom Bool Int Name
353 | AddMissing Bool Int Name
354 | MakeWith Bool Int Name
355 | MakeLemma Bool Int Name
356 | DoProofSearch Bool Bool Int Name [Name]
357 -- ^ the first bool is whether to update,
358 -- the second is whether to search recursively (i.e. for the arguments)
359 | SetOpt Opt
360 | UnsetOpt Opt
361 | NOP
362 | SetColour ColourType IdrisColour
363 | ColourOn
364 | ColourOff
365 | ListErrorHandlers
366 | SetConsoleWidth ConsoleWidth
367 | Apropos String
368 | WhoCalls Name
369 | CallsWho Name
370 | MakeDoc String -- IdrisDoc
371 | Warranty
372 | PrintDef Name
373 | PPrint OutputFmt Int PTerm
374 | TransformInfo Name
375 -- Debugging commands
376 | DebugInfo Name
377 | DebugUnify PTerm PTerm
379data OutputFmt = HTMLOutput | LaTeXOutput
381data Opt = Filename String
382 | Quiet
383 | NoBanner
384 | ColourREPL Bool
385 | Ideslave
386 | IdeslaveSocket
387 | ShowLibs
388 | ShowLibdir
389 | ShowIncs
390 | NoBasePkgs
391 | NoPrelude
392 | NoBuiltins -- only for the really primitive stuff!
393 | NoREPL
394 | OLogging Int
395 | Output String
396 | TypeCase
397 | TypeInType
398 | DefaultTotal
399 | DefaultPartial
400 | WarnPartial
401 | WarnReach
402 | NoCoverage
403 | ErrContext
404 | ShowImpl
405 | Verbose
406 | Port String -- REPL TCP port
407 | IBCSubDir String
408 | ImportDir String
409 | PkgBuild String
410 | PkgInstall String
411 | PkgClean String
412 | PkgCheck String
413 | PkgREPL String
414 | PkgMkDoc String -- IdrisDoc
415 | PkgTest String
416 | WarnOnly
417 | Pkg String
418 | BCAsm String
419 | DumpDefun String
420 | DumpCases String
421 | UseCodegen Codegen
422 | OutputTy OutputType
423 | Extension LanguageExt
424 | InterpretScript String
425 | EvalExpr String
426 | TargetTriple String
427 | TargetCPU String
428 | OptLevel Int
429 | AddOpt Optimisation
430 | RemoveOpt Optimisation
431 | Client String
432 | ShowOrigErr
433 | AutoWidth -- ^ Automatically adjust terminal width
434 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
435 deriving (Show, Eq)
437-- Parsed declarations
439data Fixity = Infixl { prec :: Int }
440 | Infixr { prec :: Int }
441 | InfixN { prec :: Int }
442 | PrefixN { prec :: Int }
443 deriving Eq
444{-!
445deriving instance Binary Fixity
446deriving instance NFData Fixity
447!-}
449instance Show Fixity where
450 show (Infixl i) = "infixl " ++ show i
451 show (Infixr i) = "infixr " ++ show i
452 show (InfixN i) = "infix " ++ show i
453 show (PrefixN i) = "prefix " ++ show i
455data FixDecl = Fix Fixity String
456 deriving Eq
458instance Show FixDecl where
459 show (Fix f s) = show f ++ " " ++ s
461{-!
462deriving instance Binary FixDecl
463deriving instance NFData FixDecl
464!-}
466instance Ord FixDecl where
467 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
470data Static = Static | Dynamic
471 deriving (Show, Eq)
472{-!
473deriving instance Binary Static
474deriving instance NFData Static
475!-}
477-- Mark bindings with their explicitness, and laziness
478data Plicity = Imp { pargopts :: [ArgOpt],
479 pstatic :: Static,
480 pparam :: Bool }
481 | Exp { pargopts :: [ArgOpt],
482 pstatic :: Static,
483 pparam :: Bool } -- this is a param (rather than index)
484 | Constraint { pargopts :: [ArgOpt],
485 pstatic :: Static }
486 | TacImp { pargopts :: [ArgOpt],
487 pstatic :: Static,
488 pscript :: PTerm }
489 deriving (Show, Eq)
491{-!
492deriving instance Binary Plicity
493deriving instance NFData Plicity
494!-}
496impl = Imp [] Dynamic False
497expl = Exp [] Dynamic False
498expl_param = Exp [] Dynamic True
499constraint = Constraint [] Static
500tacimpl t = TacImp [] Dynamic t
502data FnOpt = Inlinable -- always evaluate when simplifying
503 | TotalFn | PartialFn | CoveringFn
504 | Coinductive | AssertTotal
505 | Dictionary -- type class dictionary, eval only when
506 -- a function argument, and further evaluation resutls
507 | Implicit -- implicit coercion
508 | NoImplicit -- do not apply implicit coercions
509 | CExport String -- export, with a C name
510 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
511 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
512 | Reflection -- a reflecting function, compile-time only
513 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
514 | Constructor -- Data constructor type
515 deriving (Show, Eq)
516{-!
517deriving instance Binary FnOpt
518deriving instance NFData FnOpt
519!-}
521type FnOpts = [FnOpt]
523inlinable :: FnOpts -> Bool
524inlinable = elem Inlinable
526dictionary :: FnOpts -> Bool
527dictionary = elem Dictionary
530-- | Data declaration options
531data DataOpt = Codata -- ^ Set if the the data-type is coinductive
532 | DefaultEliminator -- ^ Set if an eliminator should be generated for data type
533 | DefaultCaseFun -- ^ Set if a case function should be generated for data type
534 | DataErrRev
535 deriving (Show, Eq)
537type DataOpts = [DataOpt]
539-- | Type provider - what to provide
540data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
541 | ProvPostulate t -- ^ goal type must be Type, so only term
542 deriving (Show, Eq, Functor)
544type ProvideWhat = ProvideWhat' PTerm
546-- | Top-level declarations such as compiler directives, definitions,
547-- datatypes and typeclasses.
548data PDecl' t
549 = PFix FC Fixity [String] -- ^ Fixity declaration
550 | PTy (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
551 | PPostulate (Docstring (Either Err PTerm)) SyntaxInfo FC FnOpts Name t -- ^ Postulate
552 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
553 | PCAF FC Name t -- ^ Top level constant
554 | PData (Docstring (Either Err PTerm)) [(Name, Docstring (Either Err PTerm))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
555 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
556 | PNamespace String [PDecl' t] -- ^ New namespace
557 | PRecord (Docstring (Either Err PTerm)) SyntaxInfo FC Name t DataOpts (Docstring (Either Err PTerm)) Name t -- ^ Record declaration
558 | PClass (Docstring (Either Err PTerm)) SyntaxInfo FC
559 [t] -- constraints
560 Name
561 [(Name, t)] -- parameters
562 [(Name, Docstring (Either Err PTerm))] -- parameter docstrings
563 [PDecl' t] -- declarations
564 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
565 -- class name, parameters, method declarations
566 | PInstance SyntaxInfo FC [t] -- constraints
567 Name -- class
568 [t] -- parameters
569 t -- full instance type
570 (Maybe Name) -- explicit name
571 [PDecl' t]
572 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
573 -- class name, parameters, full instance type, optional explicit name, and definitions
574 | PDSL Name (DSL' t) -- ^ DSL declaration
575 | PSyntax FC Syntax -- ^ Syntax definition
576 | PMutual FC [PDecl' t] -- ^ Mutual block
577 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
578 | PProvider SyntaxInfo FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term
579 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
580 -- bool is True, lhs and rhs must be convertible
581 deriving Functor
582{-!
583deriving instance Binary PDecl'
584deriving instance NFData PDecl'
585!-}
587-- For elaborator state
588type ElabD a = Elab' [PDecl] a
590-- | One clause of a top-level definition. Term arguments to constructors are:
591--
592-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
593--
594-- 2. The list of extra 'with' patterns
595--
596-- 3. The right-hand side
597--
598-- 4. The where block (PDecl' t)
600data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
601 | PWith FC Name t [t] t [PDecl' t]
602 | PClauseR FC [t] t [PDecl' t]
603 | PWithR FC [t] t [PDecl' t]
604 deriving Functor
605{-!
606deriving instance Binary PClause'
607deriving instance NFData PClause'
608!-}
610-- | Data declaration
611data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
612 d_tcon :: t, -- ^ Type constructor
613 d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, t, FC, [Name])] -- ^ Constructors
614 }
615 -- ^ Data declaration
616 | PLaterdecl { d_name :: Name, d_tcon :: t }
617 -- ^ "Placeholder" for data whose constructors are defined later
618 deriving Functor
619{-!
620deriving instance Binary PData'
621deriving instance NFData PData'
622!-}
624-- Handy to get a free function for applying PTerm -> PTerm functions
625-- across a program, by deriving Functor
627type PDecl = PDecl' PTerm
628type PData = PData' PTerm
629type PClause = PClause' PTerm
631-- get all the names declared in a decl
633declared :: PDecl -> [Name]
634declared (PFix _ _ _) = []
635declared (PTy _ _ _ _ _ n t) = [n]
636declared (PPostulate _ _ _ _ n t) = [n]
637declared (PClauses _ _ n _) = [] -- not a declaration
638declared (PCAF _ n _) = [n]
639declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
640 where fstt (_, _, a, _, _, _) = a
641declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
642declared (PParams _ _ ds) = concatMap declared ds
643declared (PNamespace _ ds) = concatMap declared ds
644declared (PRecord _ _ _ n _ _ _ c _) = [n, c]
645declared (PClass _ _ _ _ n _ _ ms) = n : concatMap declared ms
646declared (PInstance _ _ _ _ _ _ _ _) = []
647declared (PDSL n _) = [n]
648declared (PSyntax _ _) = []
649declared (PMutual _ ds) = concatMap declared ds
650declared (PDirective _) = []
652-- get the names declared, not counting nested parameter blocks
653tldeclared :: PDecl -> [Name]
654tldeclared (PFix _ _ _) = []
655tldeclared (PTy _ _ _ _ _ n t) = [n]
656tldeclared (PPostulate _ _ _ _ n t) = [n]
657tldeclared (PClauses _ _ n _) = [] -- not a declaration
658tldeclared (PRecord _ _ _ n _ _ _ c _) = [n, c]
659tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
660 where fstt (_, _, a, _, _, _) = a
661tldeclared (PParams _ _ ds) = []
662tldeclared (PMutual _ ds) = concatMap tldeclared ds
663tldeclared (PNamespace _ ds) = concatMap tldeclared ds
664tldeclared (PClass _ _ _ _ n _ _ ms) = concatMap tldeclared ms
665tldeclared (PInstance _ _ _ _ _ _ _ _) = []
666tldeclared _ = []
668defined :: PDecl -> [Name]
669defined (PFix _ _ _) = []
670defined (PTy _ _ _ _ _ n t) = []
671defined (PPostulate _ _ _ _ n t) = []
672defined (PClauses _ _ n _) = [n] -- not a declaration
673defined (PCAF _ n _) = [n]
674defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
675 where fstt (_, _, a, _, _, _) = a
676defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
677defined (PParams _ _ ds) = concatMap defined ds
678defined (PNamespace _ ds) = concatMap defined ds
679defined (PRecord _ _ _ n _ _ _ c _) = [n, c]
680defined (PClass _ _ _ _ n _ _ ms) = n : concatMap defined ms
681defined (PInstance _ _ _ _ _ _ _ _) = []
682defined (PDSL n _) = [n]
683defined (PSyntax _ _) = []
684defined (PMutual _ ds) = concatMap defined ds
685defined (PDirective _) = []
686--defined _ = []
688updateN :: [(Name, Name)] -> Name -> Name
689updateN ns n | Just n' <- lookup n ns = n'
690updateN _ n = n
692updateNs :: [(Name, Name)] -> PTerm -> PTerm
693updateNs [] t = t
694updateNs ns t = mapPT updateRef t
695 where updateRef (PRef fc f) = PRef fc (updateN ns f)
696 updateRef t = t
698-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
699-- updateDNs [] t = t
700-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
701-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
702-- where updateCNs ns (PClause n l ts r ds)
703-- = PClause (updateN ns n) (fmap (updateNs ns) l)
704-- (map (fmap (updateNs ns)) ts)
705-- (fmap (updateNs ns) r)
706-- (map (updateDNs ns) ds)
707-- updateDNs ns c = c
709data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
711-- | High level language terms
712data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language
713 | PRef FC Name -- ^ A reference to a variable
714 | PInferRef FC Name -- ^ A name to be defined later
715 | PPatvar FC Name -- ^ A pattern variable
716 | PLam Name PTerm PTerm -- ^ A lambda abstraction
717 | PPi Plicity Name PTerm PTerm -- ^ (n : t1) -> t2
718 | PLet Name PTerm PTerm PTerm -- ^ A let binding
719 | PTyped PTerm PTerm -- ^ Term with explicit type
720 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
721 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
722 | PMatchApp FC Name -- ^ Make an application by type matching
723 | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
724 | PTrue FC PunInfo -- ^ Unit type..?
725 | PRefl FC PTerm -- ^ The canonical proof of the equality type
726 | PResolveTC FC -- ^ Solve this dictionary by type class resolution
727 | PEq FC PTerm PTerm PTerm PTerm -- ^ Heterogeneous equality type: A = B
728 | PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type
729 | PPair FC PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration)
730 | PDPair FC PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration)
731 | PAlternative Bool [PTerm] -- ^ True if only one may work. (| A, B, C|)
732 | PHidden PTerm -- ^ Irrelevant or hidden pattern
733 | PType -- ^ 'Type' type
734 | PUniverse Universe -- ^ Some universe
735 | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
736 | PConstant Const -- ^ Builtin types
737 | Placeholder -- ^ Underscore
738 | PDoBlock [PDo] -- ^ Do notation
739 | PIdiom FC PTerm -- ^ Idiom brackets
740 | PReturn FC
741 | PMetavar Name -- ^ A metavariable, ?name
742 | PProof [PTactic] -- ^ Proof script
743 | PTactics [PTactic] -- ^ As PProof, but no auto solving
744 | PElabError Err -- ^ Error to report on elaboration
745 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
746 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
747 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
748 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
749 | PNoImplicits PTerm -- ^ never run implicit converions on the term
750 | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
751 | PUnquote PTerm -- ^ ,Term
752 deriving Eq
755{-!
756deriving instance Binary PTerm
757deriving instance NFData PTerm
758!-}
760mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
761mapPT f t = f (mpt t) where
762 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
763 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
764 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
765 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
766 (fmap (mapPT f) g)
767 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
768 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
769 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
770 mpt (PEq fc lt rt l r) = PEq fc (mapPT f lt) (mapPT f rt) (mapPT f l) (mapPT f r)
771 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
772 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
773 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
774 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
775 mpt (PHidden t) = PHidden (mapPT f t)
776 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
777 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
778 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
779 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
780 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
781 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
782 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
783 mpt x = x
786data PTactic' t = Intro [Name] | Intros | Focus Name
787 | Refine Name [Bool] | Rewrite t | DoUnify
788 | Induction t
789 | CaseTac t
790 | Equiv t
791 | MatchRefine Name
792 | LetTac Name t | LetTacTy Name t t
793 | Exact t | Compute | Trivial | TCInstance
794 | ProofSearch Bool Bool Int (Maybe Name) [Name]
795 -- ^ the bool is whether to search recursively
796 | Solve
797 | Attack
798 | ProofState | ProofTerm | Undo
799 | Try (PTactic' t) (PTactic' t)
800 | TSeq (PTactic' t) (PTactic' t)
801 | ApplyTactic t -- see Language.Reflection module
802 | ByReflection t
803 | Reflect t
804 | Fill t
805 | GoalType String (PTactic' t)
806 | TCheck t
807 | TEval t
808 | TDocStr (Either Name Const)
809 | TSearch t
810 | Skip
811 | TFail [ErrorReportPart]
812 | Qed | Abandon
813 | SourceFC
814 deriving (Show, Eq, Functor, Foldable, Traversable)
815{-!
816deriving instance Binary PTactic'
817deriving instance NFData PTactic'
818!-}
819instance Sized a => Sized (PTactic' a) where
820 size (Intro nms) = 1 + size nms
821 size Intros = 1
822 size (Focus nm) = 1 + size nm
823 size (Refine nm bs) = 1 + size nm + length bs
824 size (Rewrite t) = 1 + size t
825 size (Induction t) = 1 + size t
826 size (LetTac nm t) = 1 + size nm + size t
827 size (Exact t) = 1 + size t
828 size Compute = 1
829 size Trivial = 1
830 size Solve = 1
831 size Attack = 1
832 size ProofState = 1
833 size ProofTerm = 1
834 size Undo = 1
835 size (Try l r) = 1 + size l + size r
836 size (TSeq l r) = 1 + size l + size r
837 size (ApplyTactic t) = 1 + size t
838 size (Reflect t) = 1 + size t
839 size (Fill t) = 1 + size t
840 size Qed = 1
841 size Abandon = 1
842 size Skip = 1
843 size (TFail ts) = 1 + size ts
844 size SourceFC = 1
846type PTactic = PTactic' PTerm
848data PDo' t = DoExp FC t
849 | DoBind FC Name t
850 | DoBindP FC t t [(t,t)]
851 | DoLet FC Name t t
852 | DoLetP FC t t
853 deriving (Eq, Functor)
854{-!
855deriving instance Binary PDo'
856deriving instance NFData PDo'
857!-}
859instance Sized a => Sized (PDo' a) where
860 size (DoExp fc t) = 1 + size fc + size t
861 size (DoBind fc nm t) = 1 + size fc + size nm + size t
862 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
863 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
864 size (DoLetP fc l r) = 1 + size fc + size l + size r
866type PDo = PDo' PTerm
868-- The priority gives a hint as to elaboration order. Best to elaborate
869-- things early which will help give a more concrete type to other
870-- variables, e.g. a before (interpTy a).
872data PArg' t = PImp { priority :: Int,
873 machine_inf :: Bool, -- true if the machine inferred it
874 argopts :: [ArgOpt],
875 pname :: Name, getTm :: t }
876 | PExp { priority :: Int,
877 argopts :: [ArgOpt],
878 pname :: Name,
879 getTm :: t }
880 | PConstraint { priority :: Int,
881 argopts :: [ArgOpt],
882 pname :: Name,
883 getTm :: t }
884 | PTacImplicit { priority :: Int,
885 argopts :: [ArgOpt],
886 pname :: Name,
887 getScript :: t,
888 getTm :: t }
889 deriving (Show, Eq, Functor)
891data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg
892 deriving (Show, Eq)
894instance Sized a => Sized (PArg' a) where
895 size (PImp p _ l nm trm) = 1 + size nm + size trm
896 size (PExp p l nm trm) = 1 + size nm + size trm
897 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
898 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
900{-!
901deriving instance Binary PArg'
902deriving instance NFData PArg'
903!-}
905pimp n t mach = PImp 1 mach [] n t
906pexp t = PExp 1 [] (sMN 0 "arg") t
907pconst t = PConstraint 1 [] (sMN 0 "carg") t
908ptacimp n s t = PTacImplicit 2 [] n s t
910type PArg = PArg' PTerm
912-- Type class data
914data ClassInfo = CI { instanceName :: Name,
915 class_methods :: [(Name, (FnOpts, PTerm))],
916 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
917 class_default_superclasses :: [PDecl],
918 class_params :: [Name],
919 class_instances :: [Name] }
920 deriving Show
921{-!
922deriving instance Binary ClassInfo
923deriving instance NFData ClassInfo
924!-}
926-- Type inference data
928data TIData = TIPartial -- ^ a function with a partially defined type
929 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
930 deriving Show
932-- | Miscellaneous information about functions
933data FnInfo = FnInfo { fn_params :: [Int] }
934 deriving Show
935{-!
936deriving instance Binary FnInfo
937!-}
939data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
940 detaggable :: Bool }
941 deriving Show
942{-!
943deriving instance Binary OptInfo
944deriving instance NFData OptInfo
945!-}
948data TypeInfo = TI { con_names :: [Name],
949 codata :: Bool,
950 data_opts :: DataOpts,
951 param_pos :: [Int],
952 mutual_types :: [Name] }
953 deriving Show
954{-!
955deriving instance Binary TypeInfo
956deriving instance NFData TypeInfo
957!-}
959-- Syntactic sugar info
961data DSL' t = DSL { dsl_bind :: t,
962 dsl_return :: t,
963 dsl_apply :: t,
964 dsl_pure :: t,
965 dsl_var :: Maybe t,
966 index_first :: Maybe t,
967 index_next :: Maybe t,
968 dsl_lambda :: Maybe t,
969 dsl_let :: Maybe t,
970 dsl_pi :: Maybe t
971 }
972 deriving (Show, Functor)
973{-!
974deriving instance Binary DSL'
975deriving instance NFData DSL'
976!-}
978type DSL = DSL' PTerm
980data SynContext = PatternSyntax | TermSyntax | AnySyntax
981 deriving Show
982{-!
983deriving instance Binary SynContext
984deriving instance NFData SynContext
985!-}
987data Syntax = Rule [SSymbol] PTerm SynContext
988 deriving Show
990syntaxNames :: Syntax -> [Name]
991syntaxNames (Rule syms _ _) = mapMaybe ename syms
992 where ename (Keyword n) = Just n
993 ename _ = Nothing
995syntaxSymbols :: Syntax -> [SSymbol]
996syntaxSymbols (Rule ss _ _) = ss
997{-!
998deriving instance Binary Syntax
999deriving instance NFData Syntax
1000!-}
1002data SSymbol = Keyword Name
1003 | Symbol String
1004 | Binding Name
1005 | Expr Name
1006 | SimpleExpr Name
1007 deriving (Show, Eq)
1010{-!
1011deriving instance Binary SSymbol
1012deriving instance NFData SSymbol
1013!-}
1015newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
1017emptySyntaxRules :: SyntaxRules
1018emptySyntaxRules = SyntaxRules []
1020updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
1021updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
1022 where
1023 newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
1025 ruleSort [] [] = EQ
1026 ruleSort [] _ = LT
1027 ruleSort _ [] = GT
1028 ruleSort (s1:ss1) (s2:ss2) =
1029 case symCompare s1 s2 of
1030 EQ -> ruleSort ss1 ss2
1031 r -> r
1033 -- Better than creating Ord instance for SSymbol since
1034 -- in general this ordering does not really make sense.
1035 symCompare (Keyword n1) (Keyword n2) = compare n1 n2
1036 symCompare (Keyword _) _ = LT
1037 symCompare (Symbol _) (Keyword _) = GT
1038 symCompare (Symbol s1) (Symbol s2) = compare s1 s2
1039 symCompare (Symbol _) _ = LT
1040 symCompare (Binding _) (Keyword _) = GT
1041 symCompare (Binding _) (Symbol _) = GT
1042 symCompare (Binding b1) (Binding b2) = compare b1 b2
1043 symCompare (Binding _) _ = LT
1044 symCompare (Expr _) (Keyword _) = GT
1045 symCompare (Expr _) (Symbol _) = GT
1046 symCompare (Expr _) (Binding _) = GT
1047 symCompare (Expr e1) (Expr e2) = compare e1 e2
1048 symCompare (Expr _) _ = LT
1049 symCompare (SimpleExpr _) (Keyword _) = GT
1050 symCompare (SimpleExpr _) (Symbol _) = GT
1051 symCompare (SimpleExpr _) (Binding _) = GT
1052 symCompare (SimpleExpr _) (Expr _) = GT
1053 symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
1055initDSL = DSL (PRef f (sUN ">>="))
1056 (PRef f (sUN "return"))
1057 (PRef f (sUN "<$>"))
1058 (PRef f (sUN "pure"))
1059 Nothing
1060 Nothing
1061 Nothing
1062 Nothing
1063 Nothing
1064 Nothing
1065 where f = fileFC "(builtin)"
1067data Using = UImplicit Name PTerm
1068 | UConstraint Name [Name]
1069 deriving (Show, Eq)
1070{-!
1071deriving instance Binary Using
1072deriving instance NFData Using
1073!-}
1075data SyntaxInfo = Syn { using :: [Using],
1076 syn_params :: [(Name, PTerm)],
1077 syn_namespace :: [String],
1078 no_imp :: [Name],
1079 decoration :: Name -> Name,
1080 inPattern :: Bool,
1081 implicitAllowed :: Bool,
1082 maxline :: Maybe Int,
1083 mut_nesting :: Int,
1084 dsl_info :: DSL,
1085 syn_in_quasiquote :: Int }
1086 deriving Show
1087{-!
1088deriving instance NFData SyntaxInfo
1089deriving instance Binary SyntaxInfo
1090!-}
1092defaultSyntax = Syn [] [] [] [] id False False Nothing 0 initDSL 0
1094expandNS :: SyntaxInfo -> Name -> Name
1095expandNS syn n@(NS _ _) = n
1096expandNS syn n = case syn_namespace syn of
1097 [] -> n
1098 xs -> sNS n xs
1101-- For inferring types of things
1103bi = fileFC "builtin"
1105inferTy = sMN 0 "__Infer"
1106inferCon = sMN 0 "__infer"
1107inferDecl = PDatadecl inferTy
1108 PType
1109 [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType (
1110 PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType"))
1111 (PRef bi inferTy)), bi, [])]
1112inferOpts = []
1114infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
1115infP = P (TCon 6 0) inferTy (TType (UVal 0))
1117getInferTerm, getInferType :: Term -> Term
1118getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
1119getInferTerm (App (App _ _) tm) = tm
1120getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1122getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1123 where toTy (Lam t) = Pi t (TType (UVar 0))
1124 toTy (PVar t) = PVTy t
1125 toTy b = b
1126getInferType (App (App _ ty) _) = ty
1130-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
1132primNames = [eqTy, eqCon, inferTy, inferCon]
1134unitTy = sUN "Unit"
1135unitCon = sUN "MkUnit"
1137falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
1138 "The empty type, also known as the trivially false proposition." ++
1139 "\n\n" ++
1140 "Use `void` or `absurd` to prove anything if you have a variable " ++
1141 "of type `Void` in scope."
1142falseTy = sUN "Void"
1144pairTy = sUN "Pair"
1145pairCon = sUN "MkPair"
1147eqTy = sUN "="
1148eqCon = sUN "Refl"
1149eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
1150 "The propositional equality type. A proof that `x` = `y`." ++
1151 "\n\n" ++
1152 "To use such a proof, pattern-match on it, and the two equal things will " ++
1153 "then need to be the _same_ pattern." ++
1154 "\n\n" ++
1155 "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
1156 "is possible to state equalities between values of potentially different " ++
1157 "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
1158 "\n\n" ++
1159 "You may need to use `(~=~)` to explicitly request heterogeneous equality."
1161eqDecl = PDatadecl eqTy (piBindp impl [(n "A", PType), (n "B", PType)]
1162 (piBind [(n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))]
1163 PType))
1164 [(reflDoc, reflParamDoc,
1165 eqCon, PPi impl (n "A") PType (
1166 PPi impl (n "x") (PRef bi (n "A"))
1167 (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False,
1168 pimp (n "B") Placeholder False,
1169 pexp (PRef bi (n "x")),
1170 pexp (PRef bi (n "x"))])), bi, [])]
1171 where n a = sUN a
1172 reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
1173 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1174 "shown that both sides are in fact equal."
1175 reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
1176 (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1178eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
1179 (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
1181 where n a = sUN a
1183eqOpts = []
1185-- Defined in builtins.idr
1186sigmaTy = sUN "Sigma"
1187existsCon = sUN "MkSigma"
1189piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1190piBind = piBindp expl
1192piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1193piBindp p [] t = t
1194piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t)
1197-- Pretty-printing declarations and terms
1199-- These "show" instances render to an absurdly wide screen because inserted line breaks
1200-- could interfere with interactive editing, which calls "show".
1202instance Show PTerm where
1203 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1205instance Show PDecl where
1206 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
1208instance Show PClause where
1209 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1211instance Show PData where
1212 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1214instance Pretty PTerm OutputAnnotation where
1215 pretty = prettyImp defaultPPOption
1217-- | Colourise annotations according to an Idris state. It ignores the names
1218-- in the annotation, as there's no good way to show extended information on a
1219-- terminal.
1220consoleDecorate :: IState -> OutputAnnotation -> String -> String
1221consoleDecorate ist _ | not (idris_colourRepl ist) = id
1222consoleDecorate ist (AnnConst c) = let theme = idris_colourTheme ist
1223 in if constIsType c
1224 then colouriseType theme
1225 else colouriseData theme
1226consoleDecorate ist (AnnData _ _) = colouriseData (idris_colourTheme ist)
1227consoleDecorate ist (AnnType _ _) = colouriseType (idris_colourTheme ist)
1228consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
1229consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
1230consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1231consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1232 theme = idris_colourTheme ist
1233 in case () of
1234 _ | isDConName n ctxt -> colouriseData theme
1235 _ | isFnName n ctxt -> colouriseFun theme
1236 _ | isTConName n ctxt -> colouriseType theme
1237 _ | isPostulateName n ist -> colourisePostulate theme
1238 _ | otherwise -> id -- don't colourise unknown names
1239consoleDecorate ist (AnnFC _) = id
1240consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
1241 where colour BoldText = IdrisColour Nothing True False True False
1242 colour UnderlineText = IdrisColour Nothing True True False False
1243 colour ItalicText = IdrisColour Nothing True False False True
1244consoleDecorate ist (AnnTerm _ _) = id
1245consoleDecorate ist (AnnSearchResult _) = id
1246consoleDecorate ist (AnnErr _) = id
1248isPostulateName :: Name -> IState -> Bool
1249isPostulateName n ist = S.member n (idris_postulates ist)
1251-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1252prettyImp :: PPOption -- ^^ pretty printing options
1253 -> PTerm -- ^^ the term to pretty-print
1254 -> Doc OutputAnnotation
1255prettyImp impl = pprintPTerm impl [] [] []
1257-- | Serialise something to base64 using its Binary instance.
1259-- | Do the right thing for rendering a term in an IState
1260prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1261prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1263-- | Pretty-print a high-level Idris term in some bindings context with infix info
1264pprintPTerm :: PPOption -- ^^ pretty printing options
1265 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1266 -> [Name] -- ^^ names to always show in pi, even if not used
1267 -> [FixDecl] -- ^^ Fixity declarations
1268 -> PTerm -- ^^ the term to pretty-print
1269 -> Doc OutputAnnotation
1270pprintPTerm ppo bnd docArgs infixes = prettySe 10 bnd
1271 where
1272 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1273 prettySe p bnd (PQuote r) =
1274 text "![" <> pretty r <> text "]"
1275 prettySe p bnd (PPatvar fc n) = pretty n
1276 prettySe p bnd e
1277 | Just str <- slist p bnd e = str
1278 | Just n <- snat p e = annotate (AnnData "Nat" "") (text (show n))
1279 prettySe p bnd (PRef fc n) = prettyName True (ppopt_impl ppo) bnd n
1280 prettySe p bnd (PLam n ty sc) =
1281 bracket p 2 . group . align . hang 2 $
1282 text "\\" <> bindingOf n False <+> text "=>" <$>
1283 prettySe 10 ((n, False):bnd) sc
1284 prettySe p bnd (PLet n ty v sc) =
1285 bracket p 2 . group . align $
1286 kwd "let" <+> (group . align . hang 2 $ bindingOf n False <+> text "=" <$> prettySe 10 bnd v) </>
1287 kwd "in" <+> (group . align . hang 2 $ prettySe 10 ((n, False):bnd) sc)
1288 prettySe p bnd (PPi (Exp l s _) n ty sc)
1289 | n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs =
1290 bracket p 2 . group $
1291 enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1292 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1293 | otherwise =
1294 bracket p 2 . group $
1295 group (prettySe 1 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1296 where
1297 st =
1298 case s of
1299 Static -> text "[static]" <> space
1300 _ -> empty
1301 prettySe p bnd (PPi (Imp l s _) n ty sc)
1302 | ppopt_impl ppo =
1303 bracket p 2 $
1304 lbrace <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1305 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1306 | otherwise = prettySe 10 ((n, True):bnd) sc
1307 where
1308 st =
1309 case s of
1310 Static -> text "[static]" <> space
1311 _ -> empty
1312 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1313 bracket p 2 $
1314 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1315 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1316 bracket p 2 $
1317 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1318 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1319 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1320 | UN nm <- basename f
1321 , not (ppopt_impl ppo) && null (getShowArgs args) =
1322 prettyName True (ppopt_impl ppo) bnd f
1323 prettySe p bnd (PAppBind _ (PRef _ f) [])
1324 | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
1325 prettySe p bnd (PApp _ (PRef _ op) args) -- infix operators
1326 | UN nm <- basename op
1327 , not (tnull nm) &&
1328 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1329 case getShowArgs args of
1330 [] -> opName True
1331 [x] -> group (opName True <$> group (prettySe 0 bnd (getTm x)))
1332 [l,r] -> let precedence = fromMaybe 20 (fmap prec f)
1333 in bracket p precedence $ inFix (getTm l) (getTm r)
1334 (l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) ->
1335 bracket p 1 $
1336 enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
1337 align (group (vsep (map (prettyArgS bnd) rest)))
1338 as -> opName True <+> align (vsep (map (prettyArgS bnd) as))
1339 where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
1340 f = getFixity (opStr op)
1341 left l = case f of
1342 Nothing -> prettySe (-1) bnd l
1343 Just (Infixl p') -> prettySe p' bnd l
1344 Just f' -> prettySe (prec f'-1) bnd l
1345 right r = case f of
1346 Nothing -> prettySe (-1) bnd r
1347 Just (Infixr p') -> prettySe p' bnd r
1348 Just f' -> prettySe (prec f'-1) bnd r
1349 inFix l r = align . group $
1350 (left l <+> opName False) <$> group (right r)
1351 prettySe p bnd (PApp _ hd@(PRef fc f) [tm]) -- symbols, like 'foo
1352 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1353 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1354 char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1355 prettySe p bnd (PApp _ f as) = -- Normal prefix applications
1356 let args = getShowArgs as
1357 fp = prettySe 1 bnd f
1358 in
1359 bracket p 1 . group $
1360 if ppopt_impl ppo
1361 then if null as
1362 then fp
1363 else fp <+> align (vsep (map (prettyArgS bnd) as))
1364 else if null args
1365 then fp
1366 else fp <+> align (vsep (map (prettyArgS bnd) args))
1367 prettySe p bnd (PCase _ scr opts) =
1368 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1369 where
1370 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1372 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1373 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1374 prettySe p bnd (PRefl _ _) = annName eqCon $ text "Refl"
1375 prettySe p bnd (PResolveTC _) = text "resolvetc"
1376 prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1377 prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1378 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1379 prettySe p bnd (PEq _ lt rt l r)
1380 | ppopt_impl ppo =
1381 bracket p 1 $
1382 enclose lparen rparen eq <+>
1383 align (group (vsep (map (prettyArgS bnd)
1384 [PImp 0 False [] (sUN "A") lt,
1385 PImp 0 False [] (sUN "B") rt,
1386 PExp 0 [] (sUN "x") l,
1387 PExp 0 [] (sUN "y") r])))
1388 | otherwise =
1389 bracket p 2 . align . group $
1390 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1391 where eq = annName eqTy (text "=")
1392 prettySe p bnd (PRewrite _ l r _) =
1393 bracket p 2 $
1394 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1395 prettySe p bnd (PTyped l r) =
1396 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1397 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1398 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1399 align . group . vsep . punctuate (ann comma) $
1400 map (prettySe 10 bnd) elts
1401 where ann = case pun of
1402 TypeOrTerm -> id
1403 IsType -> annName pairTy
1404 IsTerm -> annName pairCon
1405 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1406 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1407 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1408 annName sigmaTy lparen <>
1409 bindingOf n False <+>
1410 annName sigmaTy (text "**") <+>
1411 prettySe 10 ((n, False):bnd) r <>
1412 annName sigmaTy rparen
1413 prettySe p bnd (PDPair _ IsType l t r) =
1414 annName sigmaTy lparen <>
1415 prettySe 10 bnd l <+>
1416 annName sigmaTy (text "**") <+>
1417 prettySe 10 bnd r <>
1418 annName sigmaTy rparen
1419 prettySe p bnd (PDPair _ IsTerm l t r) =
1420 annName existsCon lparen <>
1421 prettySe 10 bnd l <+>
1422 annName existsCon (text "**") <+>
1423 prettySe 10 bnd r <>
1424 annName existsCon rparen
1425 prettySe p bnd (PAlternative a as) =
1426 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1427 where
1428 prettyAs =
1429 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1430 prettySe p bnd PType = annotate (AnnType "Type" "The type of types") $ text "Type"
1431 prettySe p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
1432 prettySe p bnd (PConstant c) = annotate (AnnConst c) (text (show c))
1433 -- XXX: add pretty for tactics
1434 prettySe p bnd (PProof ts) =
1435 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1436 prettySe p bnd (PTactics ts) =
1437 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1438 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1439 prettySe p bnd (PReturn f) = kwd "return"
1440 prettySe p bnd PImpossible = kwd "impossible"
1441 prettySe p bnd Placeholder = text "_"
1442 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1443 prettySe p bnd (PCoerced t) = prettySe p bnd t
1444 prettySe p bnd (PElabError s) = pretty s
1445 -- Quasiquote pprinting ignores bound vars
1446 prettySe p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe p [] t <> text ")"
1447 prettySe p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe p [] t <+> colon <+> prettySe p [] g <> text ")"
1448 prettySe p bnd (PUnquote t) = text "~" <> prettySe p bnd t
1450 prettySe p bnd _ = text "missing pretty-printer for term"
1452 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1453 prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm
1454 prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm
1455 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1457 prettyArgSe bnd arg = prettySe 0 bnd arg
1458 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1459 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1460 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1462 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1463 annName n = annotate (AnnName n Nothing Nothing Nothing)
1465 opStr :: Name -> String
1466 opStr (NS n _) = opStr n
1467 opStr (UN n) = T.unpack n
1469 basename :: Name -> Name
1470 basename (NS n _) = basename n
1471 basename n = n
1473 slist' p bnd (PApp _ (PRef _ nil) _)
1474 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1475 slist' p bnd (PRef _ nil)
1476 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1477 slist' p bnd (PApp _ (PRef _ cons) args)
1478 | nsroot cons == sUN "::",
1479 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1480 all isImp imps,
1481 Just tl' <- slist' p bnd tl
1482 = Just (hd:tl')
1483 where
1484 isImp (PImp {}) = True
1485 isImp _ = False
1486 slist' _ _ tm = Nothing
1488 slist p bnd e | Just es <- slist' p bnd e = Just $
1489 case es of [] -> annotate (AnnData "" "") $ text "[]"
1490 [x] -> enclose left right . group $
1491 prettySe p bnd x
1492 xs -> (enclose left right .
1493 align . group . vsep .
1494 punctuate comma .
1495 map (prettySe p bnd)) xs
1496 where left = (annotate (AnnData "" "") (text "["))
1497 right = (annotate (AnnData "" "") (text "]"))
1498 comma = (annotate (AnnData "" "") (text ","))
1499 slist _ _ _ = Nothing
1501 pairElts :: PTerm -> Maybe [PTerm]
1502 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1503 | otherwise = Just [x, y]
1504 pairElts _ = Nothing
1506 natns = "Prelude.Nat."
1508 snat p (PRef _ z)
1509 | show z == (natns++"Z") || show z == "Z" = Just 0
1510 snat p (PApp _ s [PExp {getTm=n}])
1511 | show s == (natns++"S") || show s == "S",
1512 Just n' <- snat p n
1513 = Just $ 1 + n'
1514 snat _ _ = Nothing
1516 bracket outer inner doc
1517 | inner > outer = lparen <> doc <> rparen
1518 | otherwise = doc
1520 kwd = annotate AnnKeyword . text
1522 fixities :: M.Map String Fixity
1523 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
1525 getFixity :: String -> Maybe Fixity
1526 getFixity = flip M.lookup fixities
1528-- | Pretty-printer helper for the binding site of a name
1529bindingOf :: Name -- ^^ the bound name
1530 -> Bool -- ^^ whether the name is implicit
1531 -> Doc OutputAnnotation
1532bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1534-- | Pretty-printer helper for names that attaches the correct annotations
1535prettyName
1536 :: Bool -- ^^ whether the name should be parenthesised if it is an infix operator
1537 -> Bool -- ^^ whether to show namespaces
1538 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1539 -> Name -- ^^ the name to pprint
1540 -> Doc OutputAnnotation
1541prettyName infixParen showNS bnd n
1542 | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
1543 | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
1544 where fullName = text nameSpace <> parenthesise (text (baseName n))
1545 baseName (UN n) = T.unpack n
1546 baseName (NS n ns) = baseName n
1547 baseName (MN i s) = T.unpack s
1548 baseName other = show other
1549 nameSpace = case n of
1550 (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
1551 _ -> ""
1552 isInfix = case baseName n of
1553 "" -> False
1554 (c : _) -> not (isAlpha c)
1555 parenthesise = if isInfix && infixParen then enclose lparen rparen else id
1558showCImp :: PPOption -> PClause -> Doc OutputAnnotation
1559showCImp ppo (PClause _ n l ws r w)
1560 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
1561 <+> text "where" <+> text (show w)
1562 where
1563 showWs [] = empty
1564 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
1565showCImp ppo (PWith _ n l ws r w)
1566 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
1567 <+> braces (text (show w))
1568 where
1569 showWs [] = empty
1570 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
1573showDImp :: PPOption -> PData -> Doc OutputAnnotation
1574showDImp ppo (PDatadecl n ty cons)
1575 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
1576 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
1578showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
1579showDecls o ds = vsep (map (showDeclImp o) ds)
1581showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1582showDeclImp o (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
1583showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1584 indent 2 (vsep (map (showCImp o) cs))
1585showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
1586showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
1587showDeclImp o (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
1588showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1589showDeclImp o (PClass _ _ _ cs n ps _ ds)
1590 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
1591showDeclImp o (PInstance _ _ cs n _ t _ ds)
1592 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
1593showDeclImp _ _ = text "..."
1594-- showDeclImp (PImport o) = "import " ++ o
1596instance Show (Doc OutputAnnotation) where
1597 show = flip (displayS . renderCompact) ""
1599getImps :: [PArg] -> [(Name, PTerm)]
1600getImps [] = []
1601getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1602getImps (_ : xs) = getImps xs
1604getExps :: [PArg] -> [PTerm]
1605getExps [] = []
1606getExps (PExp _ _ _ tm : xs) = tm : getExps xs
1607getExps (_ : xs) = getExps xs
1609getShowArgs :: [PArg] -> [PArg]
1610getShowArgs [] = []
1611getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
1612getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
1613getShowArgs (_ : xs) = getShowArgs xs
1615getConsts :: [PArg] -> [PTerm]
1616getConsts [] = []
1617getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
1618getConsts (_ : xs) = getConsts xs
1620getAll :: [PArg] -> [PTerm]
1621getAll = map getTm
1624-- | Show Idris name
1625showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1626 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1627 -> PPOption -- ^^ pretty printing options
1628 -> Bool -- ^^ whether to colourise
1629 -> Name -- ^^ the term to show
1630 -> String
1631showName ist bnd ppo colour n = case ist of
1632 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1633 Nothing -> showbasic n
1634 where name = if ppopt_impl ppo then show n else showbasic n
1635 showbasic n@(UN _) = showCG n
1636 showbasic (MN i s) = str s
1637 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1638 showbasic (SN s) = show s
1639 fst3 (x, _, _) = x
1640 colourise n t = let ctxt' = fmap tt_ctxt ist in
1641 case ctxt' of
1642 Nothing -> name
1643 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1644 else colouriseBound t name
1645 | isDConName n ctxt -> colouriseData t name
1646 | isFnName n ctxt -> colouriseFun t name
1647 | isTConName n ctxt -> colouriseType t name
1648 -- The assumption is that if a name is not bound and does not exist in the
1649 -- global context, then we're somewhere in which implicit info has been lost
1650 -- (like error messages). Thus, unknown vars are colourised as implicits.
1651 | otherwise -> colouriseImplicit t name
1653showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1654 -> PTerm -- ^^ the term to show
1655 -> String
1656showTm ist = displayDecorated (consoleDecorate ist) .
1657 renderPretty 0.8 100000 .
1658 prettyImp (ppOptionIst ist)
1660-- | Show a term with implicits, no colours
1661showTmImpls :: PTerm -> String
1662showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
1666instance Sized PTerm where
1667 size (PQuote rawTerm) = size rawTerm
1668 size (PRef fc name) = size name
1669 size (PLam name ty bdy) = 1 + size ty + size bdy
1670 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1671 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1672 size (PTyped trm ty) = 1 + size trm + size ty
1673 size (PApp fc name args) = 1 + size args
1674 size (PAppBind fc name args) = 1 + size args
1675 size (PCase fc trm bdy) = 1 + size trm + size bdy
1676 size (PTrue fc _) = 1
1677 size (PRefl fc _) = 1
1678 size (PResolveTC fc) = 1
1679 size (PEq fc _ _ left right) = 1 + size left + size right
1680 size (PRewrite fc left right _) = 1 + size left + size right
1681 size (PPair fc _ left right) = 1 + size left + size right
1682 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1683 size (PAlternative a alts) = 1 + size alts
1684 size (PHidden hidden) = size hidden
1685 size (PUnifyLog tm) = size tm
1686 size (PDisamb _ tm) = size tm
1687 size (PNoImplicits tm) = size tm
1688 size PType = 1
1689 size (PUniverse _) = 1
1690 size (PConstant const) = 1 + size const
1691 size Placeholder = 1
1692 size (PDoBlock dos) = 1 + size dos
1693 size (PIdiom fc term) = 1 + size term
1694 size (PReturn fc) = 1
1695 size (PMetavar name) = 1
1696 size (PProof tactics) = size tactics
1697 size (PElabError err) = size err
1698 size PImpossible = 1
1699 size _ = 0
1701getPArity :: PTerm -> Int
1702getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1703getPArity _ = 0
1705-- Return all names, free or globally bound, in the given term.
1707allNamesIn :: PTerm -> [Name]
1708allNamesIn tm = nub $ ni [] tm
1709 where -- TODO THINK added niTacImp, but is it right?
1710 ni env (PRef _ n)
1711 | not (n `elem` env) = [n]
1712 ni env (PPatvar _ n) = [n]
1713 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1714 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1715 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1716 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1717 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1718 ni env (PHidden tm) = ni env tm
1719 ni env (PEq _ _ _ l r) = ni env l ++ ni env r
1720 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1721 ni env (PTyped l r) = ni env l ++ ni env r
1722 ni env (PPair _ _ l r) = ni env l ++ ni env r
1723 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1724 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1725 ni env (PAlternative a ls) = concatMap (ni env) ls
1726 ni env (PUnifyLog tm) = ni env tm
1727 ni env (PDisamb _ tm) = ni env tm
1728 ni env (PNoImplicits tm) = ni env tm
1729 ni env _ = []
1731 niTacImp env (TacImp _ _ scr) = ni env scr
1732 niTacImp _ _ = []
1734-- Return all names defined in binders in the given term
1735boundNamesIn :: PTerm -> [Name]
1736boundNamesIn tm = nub $ ni tm
1737 where -- TODO THINK Added niTacImp, but is it right?
1738 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1739 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1740 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1741 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1742 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1743 ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc))
1744 ni (PEq _ _ _ l r) = ni l ++ ni r
1745 ni (PRewrite _ l r _) = ni l ++ ni r
1746 ni (PTyped l r) = ni l ++ ni r
1747 ni (PPair _ _ l r) = ni l ++ ni r
1748 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1749 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1750 ni (PAlternative a as) = concatMap (ni) as
1751 ni (PHidden tm) = ni tm
1752 ni (PUnifyLog tm) = ni tm
1753 ni (PDisamb _ tm) = ni tm
1754 ni (PNoImplicits tm) = ni tm
1755 ni _ = []
1757 niTacImp (TacImp _ _ scr) = ni scr
1758 niTacImp _ = []
1760-- Return names which are valid implicits in the given term (type).
1761implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
1762implicitNamesIn uvars ist tm = nub $ ni [] tm
1763 where
1764 ni env (PRef _ n)
1765 | not (n `elem` env)
1766 = case lookupTy n (tt_ctxt ist) of
1767 [] -> [n]
1768 _ -> if n `elem` uvars then [n] else []
1769 ni env (PApp _ f@(PRef _ n) as)
1770 | n `elem` uvars = ni env f ++ concatMap (ni env) (map getTm as)
1771 | otherwise = concatMap (ni env) (map getTm as)
1772 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1773 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1774 ni env (PCase _ c os) = ni env c ++
1775 -- names in 'os', not counting the names bound in the cases
1776 (nub (concatMap (ni env) (map snd os))
1777 \\ nub (concatMap (ni env) (map fst os)))
1778 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1779 ni env (PPi p n ty sc) = ni env ty ++ ni (n:env) sc
1780 ni env (PEq _ _ _ l r) = ni env l ++ ni env r
1781 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1782 ni env (PTyped l r) = ni env l ++ ni env r
1783 ni env (PPair _ _ l r) = ni env l ++ ni env r
1784 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1785 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1786 ni env (PAlternative a as) = concatMap (ni env) as
1787 ni env (PHidden tm) = ni env tm
1788 ni env (PUnifyLog tm) = ni env tm
1789 ni env (PDisamb _ tm) = ni env tm
1790 ni env (PNoImplicits tm) = ni env tm
1791 ni env _ = []
1793-- Return names which are free in the given term.
1794namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1795namesIn uvars ist tm = nub $ ni [] tm
1796 where
1797 ni env (PRef _ n)
1798 | not (n `elem` env)
1799 = case lookupTy n (tt_ctxt ist) of
1800 [] -> [n]
1801 _ -> if n `elem` (map fst uvars) then [n] else []
1802 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1803 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1804 ni env (PCase _ c os) = ni env c ++
1805 -- names in 'os', not counting the names bound in the cases
1806 (nub (concatMap (ni env) (map snd os))
1807 \\ nub (concatMap (ni env) (map fst os)))
1808 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1809 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1810 ni env (PEq _ _ _ l r) = ni env l ++ ni env r
1811 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1812 ni env (PTyped l r) = ni env l ++ ni env r
1813 ni env (PPair _ _ l r) = ni env l ++ ni env r
1814 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1815 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1816 ni env (PAlternative a as) = concatMap (ni env) as
1817 ni env (PHidden tm) = ni env tm
1818 ni env (PUnifyLog tm) = ni env tm
1819 ni env (PDisamb _ tm) = ni env tm
1820 ni env (PNoImplicits tm) = ni env tm
1821 ni env _ = []
1823 niTacImp env (TacImp _ _ scr) = ni env scr
1824 niTacImp _ _ = []
1826-- Return which of the given names are used in the given term.
1828usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1829usedNamesIn vars ist tm = nub $ ni [] tm
1830 where -- TODO THINK added niTacImp, but is it right?
1831 ni env (PRef _ n)
1832 | n `elem` vars && not (n `elem` env)
1833 = case lookupDefExact n (tt_ctxt ist) of
1834 Nothing -> [n]
1835 _ -> []
1836 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1837 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1838 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1839 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1840 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1841 ni env (PEq _ _ _ l r) = ni env l ++ ni env r
1842 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1843 ni env (PTyped l r) = ni env l ++ ni env r
1844 ni env (PPair _ _ l r) = ni env l ++ ni env r
1845 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1846 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1847 ni env (PAlternative a as) = concatMap (ni env) as
1848 ni env (PHidden tm) = ni env tm
1849 ni env (PUnifyLog tm) = ni env tm
1850 ni env (PDisamb _ tm) = ni env tm
1851 ni env (PNoImplicits tm) = ni env tm
1852 ni env _ = []
1854 niTacImp env (TacImp _ _ scr) = ni env scr
1855 niTacImp _ _ = []
1857-- Return the list of inaccessible (= dotted) positions for a name.
1858getErasureInfo :: IState -> Name -> [Int]
1859getErasureInfo ist n =
1860 case lookupCtxtExact n (idris_optimisation ist) of
1861 Just (Optimise inacc detagg) -> map fst inacc
1862 Nothing -> []