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