on bb6873c help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1593 lines 62 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 | IBCPostulate Name
230 deriving Show
232-- | The initial state for the compiler
233idrisInit :: IState
234idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
235 emptyContext emptyContext emptyContext emptyContext
236 emptyContext emptyContext emptyContext emptyContext
237 emptyContext emptyContext
238 [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
239 [] [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
240 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
241 AutomaticWidth S.empty
243-- | The monad for the main REPL - reading and processing files and updating
244-- global state (hence the IO inner monad).
245--type Idris = WriterT [Either String (IO ())] (State IState a))
246type Idris = StateT IState (ErrorT Err IO)
248-- Commands in the REPL
250data Codegen = ViaC
251 | ViaJava
252 | ViaNode
253 | ViaJavaScript
254 | ViaLLVM
255 | Bytecode
256 deriving (Show, Eq)
258-- | REPL commands
259data Command = Quit
260 | Help
261 | Eval PTerm
262 | Check PTerm
263 | DocStr Name
264 | TotCheck Name
265 | Reload
266 | Load FilePath
267 | ChangeDirectory FilePath
268 | ModImport String
269 | Edit
270 | Compile Codegen String
271 | Execute
272 | ExecVal PTerm
273 | Metavars
274 | Prove Name
275 | AddProof (Maybe Name)
276 | RmProof Name
277 | ShowProof Name
278 | Proofs
279 | Universes
280 | LogLvl Int
281 | Spec PTerm
282 | HNF PTerm
283 | TestInline PTerm
284 | Defn Name
285 | Info Name
286 | Missing Name
287 | DynamicLink FilePath
288 | ListDynamic
289 | Pattelab PTerm
290 | DebugInfo Name
291 | Search PTerm
292 | CaseSplitAt Bool Int Name
293 | AddClauseFrom Bool Int Name
294 | AddProofClauseFrom Bool Int Name
295 | AddMissing Bool Int Name
296 | MakeWith Bool Int Name
297 | DoProofSearch Bool Int Name [Name]
298 | SetOpt Opt
299 | UnsetOpt Opt
300 | NOP
301 | SetColour ColourType IdrisColour
302 | ColourOn
303 | ColourOff
304 | ListErrorHandlers
305 | SetConsoleWidth ConsoleWidth
306 | Apropos String
308data Opt = Filename String
309 | Ver
310 | Usage
311 | Quiet
312 | NoBanner
313 | ColourREPL Bool
314 | Ideslave
315 | ShowLibs
316 | ShowLibdir
317 | ShowIncs
318 | NoBasePkgs
319 | NoPrelude
320 | NoBuiltins -- only for the really primitive stuff!
321 | NoREPL
322 | OLogging Int
323 | Output String
324 | TypeCase
325 | TypeInType
326 | DefaultTotal
327 | DefaultPartial
328 | WarnPartial
329 | WarnReach
330 | NoCoverage
331 | ErrContext
332 | ShowImpl
333 | Verbose
334 | IBCSubDir String
335 | ImportDir String
336 | PkgBuild String
337 | PkgInstall String
338 | PkgClean String
339 | PkgCheck String
340 | PkgREPL String
341 | WarnOnly
342 | Pkg String
343 | BCAsm String
344 | DumpDefun String
345 | DumpCases String
346 | UseCodegen Codegen
347 | OutputTy OutputType
348 | Extension LanguageExt
349 | InterpretScript String
350 | TargetTriple String
351 | TargetCPU String
352 | OptLevel Word
353 | Client String
354 | ShowOrigErr
355 | AutoWidth -- ^ Automatically adjust terminal width
356 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
357 deriving (Show, Eq)
359-- Parsed declarations
361data Fixity = Infixl { prec :: Int }
362 | Infixr { prec :: Int }
363 | InfixN { prec :: Int }
364 | PrefixN { prec :: Int }
365 deriving Eq
366{-!
367deriving instance Binary Fixity
368deriving instance NFData Fixity
369!-}
371instance Show Fixity where
372 show (Infixl i) = "infixl " ++ show i
373 show (Infixr i) = "infixr " ++ show i
374 show (InfixN i) = "infix " ++ show i
375 show (PrefixN i) = "prefix " ++ show i
377data FixDecl = Fix Fixity String
378 deriving Eq
380instance Show FixDecl where
381 show (Fix f s) = show f ++ " " ++ s
383{-!
384deriving instance Binary FixDecl
385deriving instance NFData FixDecl
386!-}
388instance Ord FixDecl where
389 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
392data Static = Static | Dynamic
393 deriving (Show, Eq)
394{-!
395deriving instance Binary Static
396deriving instance NFData Static
397!-}
399-- Mark bindings with their explicitness, and laziness
400data Plicity = Imp { pargopts :: [ArgOpt],
401 pstatic :: Static,
402 pparam :: Bool }
403 | Exp { pargopts :: [ArgOpt],
404 pstatic :: Static,
405 pparam :: Bool } -- this is a param (rather than index)
406 | Constraint { pargopts :: [ArgOpt],
407 pstatic :: Static }
408 | TacImp { pargopts :: [ArgOpt],
409 pstatic :: Static,
410 pscript :: PTerm }
411 deriving (Show, Eq)
413{-!
414deriving instance Binary Plicity
415deriving instance NFData Plicity
416!-}
418impl = Imp [] Dynamic False
419expl = Exp [] Dynamic False
420expl_param = Exp [] Dynamic True
421constraint = Constraint [] Dynamic
422tacimpl t = TacImp [] Dynamic t
424data FnOpt = Inlinable -- always evaluate when simplifying
425 | TotalFn | PartialFn | CoveringFn
426 | Coinductive | AssertTotal
427 | Dictionary -- type class dictionary, eval only when
428 -- a function argument, and further evaluation resutls
429 | Implicit -- implicit coercion
430 | CExport String -- export, with a C name
431 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
432 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
433 | Reflection -- a reflecting function, compile-time only
434 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
435 deriving (Show, Eq)
436{-!
437deriving instance Binary FnOpt
438deriving instance NFData FnOpt
439!-}
441type FnOpts = [FnOpt]
443inlinable :: FnOpts -> Bool
444inlinable = elem Inlinable
446dictionary :: FnOpts -> Bool
447dictionary = elem Dictionary
450-- | Data declaration options
451data DataOpt = Codata -- Set if the the data-type is coinductive
452 | DefaultEliminator -- Set if an eliminator should be generated for data type
453 | DataErrRev
454 deriving (Show, Eq)
456type DataOpts = [DataOpt]
458-- | Type provider - what to provide
459data ProvideWhat = ProvTerm -- ^ only allow providing terms
460 | ProvPostulate -- ^ only allow postulates
461 | ProvAny -- ^ either is ok
462 deriving (Show, Eq)
464-- | Top-level declarations such as compiler directives, definitions,
465-- datatypes and typeclasses.
466data PDecl' t
467 = PFix FC Fixity [String] -- ^ Fixity declaration
468 | PTy Docstring [(Name, Docstring)] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
469 | PPostulate Docstring SyntaxInfo FC FnOpts Name t -- ^ Postulate
470 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
471 | PCAF FC Name t -- ^ Top level constant
472 | PData Docstring [(Name, Docstring)] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
473 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
474 | PNamespace String [PDecl' t] -- ^ New namespace
475 | PRecord Docstring SyntaxInfo FC Name t Docstring Name t -- ^ Record declaration
476 | PClass Docstring SyntaxInfo FC
477 [t] -- constraints
478 Name
479 [(Name, t)] -- parameters
480 [PDecl' t] -- declarations
481 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
482 -- class name, parameters, method declarations
483 | PInstance SyntaxInfo FC [t] -- constraints
484 Name -- class
485 [t] -- parameters
486 t -- full instance type
487 (Maybe Name) -- explicit name
488 [PDecl' t]
489 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
490 -- class name, parameters, full instance type, optional explicit name, and definitions
491 | PDSL Name (DSL' t) -- ^ DSL declaration
492 | PSyntax FC Syntax -- ^ Syntax definition
493 | PMutual FC [PDecl' t] -- ^ Mutual block
494 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
495 | PProvider SyntaxInfo FC ProvideWhat Name t t -- ^ Type provider. The first t is the type, the second is the term
496 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
497 -- bool is True, lhs and rhs must be convertible
498 deriving Functor
499{-!
500deriving instance Binary PDecl'
501deriving instance NFData PDecl'
502!-}
504-- For elaborator state
505type ElabD a = Elab' [PDecl] a
507-- | One clause of a top-level definition. Term arguments to constructors are:
508--
509-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
510--
511-- 2. The list of extra 'with' patterns
512--
513-- 3. The right-hand side
514--
515-- 4. The where block (PDecl' t)
517data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
518 | PWith FC Name t [t] t [PDecl' t]
519 | PClauseR FC [t] t [PDecl' t]
520 | PWithR FC [t] t [PDecl' t]
521 deriving Functor
522{-!
523deriving instance Binary PClause'
524deriving instance NFData PClause'
525!-}
527-- | Data declaration
528data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
529 d_tcon :: t, -- ^ Type constructor
530 d_cons :: [(Docstring, [(Name, Docstring)], Name, t, FC, [Name])] -- ^ Constructors
531 }
532 -- ^ Data declaration
533 | PLaterdecl { d_name :: Name, d_tcon :: t }
534 -- ^ "Placeholder" for data whose constructors are defined later
535 deriving Functor
536{-!
537deriving instance Binary PData'
538deriving instance NFData PData'
539!-}
541-- Handy to get a free function for applying PTerm -> PTerm functions
542-- across a program, by deriving Functor
544type PDecl = PDecl' PTerm
545type PData = PData' PTerm
546type PClause = PClause' PTerm
548-- get all the names declared in a decl
550declared :: PDecl -> [Name]
551declared (PFix _ _ _) = []
552declared (PTy _ _ _ _ _ n t) = [n]
553declared (PPostulate _ _ _ _ n t) = [n]
554declared (PClauses _ _ n _) = [] -- not a declaration
555declared (PCAF _ n _) = [n]
556declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
557 where fstt (_, _, a, _, _, _) = a
558declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
559declared (PParams _ _ ds) = concatMap declared ds
560declared (PNamespace _ ds) = concatMap declared ds
561declared (PRecord _ _ _ n _ _ c _) = [n, c]
562declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
563declared (PInstance _ _ _ _ _ _ _ _) = []
564declared (PDSL n _) = [n]
565declared (PSyntax _ _) = []
566declared (PMutual _ ds) = concatMap declared ds
567declared (PDirective _) = []
569-- get the names declared, not counting nested parameter blocks
570tldeclared :: PDecl -> [Name]
571tldeclared (PFix _ _ _) = []
572tldeclared (PTy _ _ _ _ _ n t) = [n]
573tldeclared (PPostulate _ _ _ _ n t) = [n]
574tldeclared (PClauses _ _ n _) = [] -- not a declaration
575tldeclared (PRecord _ _ _ n _ _ c _) = [n, c]
576tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
577 where fstt (_, _, a, _, _, _) = a
578tldeclared (PParams _ _ ds) = []
579tldeclared (PMutual _ ds) = concatMap tldeclared ds
580tldeclared (PNamespace _ ds) = concatMap tldeclared ds
581tldeclared (PClass _ _ _ _ n _ ms) = concatMap tldeclared ms
582tldeclared (PInstance _ _ _ _ _ _ _ _) = []
583tldeclared _ = []
585defined :: PDecl -> [Name]
586defined (PFix _ _ _) = []
587defined (PTy _ _ _ _ _ n t) = []
588defined (PPostulate _ _ _ _ n t) = []
589defined (PClauses _ _ n _) = [n] -- not a declaration
590defined (PCAF _ n _) = [n]
591defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
592 where fstt (_, _, a, _, _, _) = a
593defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
594defined (PParams _ _ ds) = concatMap defined ds
595defined (PNamespace _ ds) = concatMap defined ds
596defined (PRecord _ _ _ n _ _ c _) = [n, c]
597defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
598defined (PInstance _ _ _ _ _ _ _ _) = []
599defined (PDSL n _) = [n]
600defined (PSyntax _ _) = []
601defined (PMutual _ ds) = concatMap defined ds
602defined (PDirective _) = []
603--defined _ = []
605updateN :: [(Name, Name)] -> Name -> Name
606updateN ns n | Just n' <- lookup n ns = n'
607updateN _ n = n
609updateNs :: [(Name, Name)] -> PTerm -> PTerm
610updateNs [] t = t
611updateNs ns t = mapPT updateRef t
612 where updateRef (PRef fc f) = PRef fc (updateN ns f)
613 updateRef t = t
615-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
616-- updateDNs [] t = t
617-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
618-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
619-- where updateCNs ns (PClause n l ts r ds)
620-- = PClause (updateN ns n) (fmap (updateNs ns) l)
621-- (map (fmap (updateNs ns)) ts)
622-- (fmap (updateNs ns) r)
623-- (map (updateDNs ns) ds)
624-- updateDNs ns c = c
626data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
628-- | High level language terms
629data PTerm = PQuote Raw
630 | PRef FC Name
631 | PInferRef FC Name -- ^ A name to be defined later
632 | PPatvar FC Name
633 | PLam Name PTerm PTerm
634 | PPi Plicity Name PTerm PTerm
635 | PLet Name PTerm PTerm PTerm
636 | PTyped PTerm PTerm -- ^ Term with explicit type
637 | PApp FC PTerm [PArg]
638 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
639 | PMatchApp FC Name -- ^ Make an application by type matching
640 | PCase FC PTerm [(PTerm, PTerm)]
641 | PTrue FC PunInfo
642 | PFalse FC
643 | PRefl FC PTerm
644 | PResolveTC FC
645 | PEq FC PTerm PTerm
646 | PRewrite FC PTerm PTerm (Maybe PTerm)
647 | PPair FC PunInfo PTerm PTerm
648 | PDPair FC PunInfo PTerm PTerm PTerm
649 | PAlternative Bool [PTerm] -- True if only one may work
650 | PHidden PTerm -- ^ Irrelevant or hidden pattern
651 | PType
652 | PGoal FC PTerm Name PTerm
653 | PConstant Const
654 | Placeholder
655 | PDoBlock [PDo]
656 | PIdiom FC PTerm
657 | PReturn FC
658 | PMetavar Name
659 | PProof [PTactic] -- ^ Proof script
660 | PTactics [PTactic] -- ^ As PProof, but no auto solving
661 | PElabError Err -- ^ Error to report on elaboration
662 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
663 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
664 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
665 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
666 | PNoImplicits PTerm -- ^ never run implicit converions on the term
667 deriving Eq
670{-!
671deriving instance Binary PTerm
672deriving instance NFData PTerm
673!-}
675mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
676mapPT f t = f (mpt t) where
677 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
678 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
679 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
680 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
681 (fmap (mapPT f) g)
682 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
683 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
684 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
685 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
686 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
687 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
688 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
689 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
690 mpt (PHidden t) = PHidden (mapPT f t)
691 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
692 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
693 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
694 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
695 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
696 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
697 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
698 mpt x = x
701data PTactic' t = Intro [Name] | Intros | Focus Name
702 | Refine Name [Bool] | Rewrite t
703 | Induction Name
704 | Equiv t
705 | MatchRefine Name
706 | LetTac Name t | LetTacTy Name t t
707 | Exact t | Compute | Trivial | TCInstance
708 | ProofSearch (Maybe Name) [Name]
709 | Solve
710 | Attack
711 | ProofState | ProofTerm | Undo
712 | Try (PTactic' t) (PTactic' t)
713 | TSeq (PTactic' t) (PTactic' t)
714 | ApplyTactic t -- see Language.Reflection module
715 | ByReflection t
716 | Reflect t
717 | Fill t
718 | GoalType String (PTactic' t)
719 | TCheck t
720 | TEval t
721 | Qed | Abandon
722 deriving (Show, Eq, Functor)
723{-!
724deriving instance Binary PTactic'
725deriving instance NFData PTactic'
726!-}
727instance Sized a => Sized (PTactic' a) where
728 size (Intro nms) = 1 + size nms
729 size Intros = 1
730 size (Focus nm) = 1 + size nm
731 size (Refine nm bs) = 1 + size nm + length bs
732 size (Rewrite t) = 1 + size t
733 size (Induction t) = 1 + size t
734 size (LetTac nm t) = 1 + size nm + size t
735 size (Exact t) = 1 + size t
736 size Compute = 1
737 size Trivial = 1
738 size Solve = 1
739 size Attack = 1
740 size ProofState = 1
741 size ProofTerm = 1
742 size Undo = 1
743 size (Try l r) = 1 + size l + size r
744 size (TSeq l r) = 1 + size l + size r
745 size (ApplyTactic t) = 1 + size t
746 size (Reflect t) = 1 + size t
747 size (Fill t) = 1 + size t
748 size Qed = 1
749 size Abandon = 1
751type PTactic = PTactic' PTerm
753data PDo' t = DoExp FC t
754 | DoBind FC Name t
755 | DoBindP FC t t [(t,t)]
756 | DoLet FC Name t t
757 | DoLetP FC t t
758 deriving (Eq, Functor)
759{-!
760deriving instance Binary PDo'
761deriving instance NFData PDo'
762!-}
764instance Sized a => Sized (PDo' a) where
765 size (DoExp fc t) = 1 + size fc + size t
766 size (DoBind fc nm t) = 1 + size fc + size nm + size t
767 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
768 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
769 size (DoLetP fc l r) = 1 + size fc + size l + size r
771type PDo = PDo' PTerm
773-- The priority gives a hint as to elaboration order. Best to elaborate
774-- things early which will help give a more concrete type to other
775-- variables, e.g. a before (interpTy a).
777data PArg' t = PImp { priority :: Int,
778 machine_inf :: Bool, -- true if the machine inferred it
779 argopts :: [ArgOpt],
780 pname :: Name, getTm :: t }
781 | PExp { priority :: Int,
782 argopts :: [ArgOpt],
783 pname :: Name,
784 getTm :: t }
785 | PConstraint { priority :: Int,
786 argopts :: [ArgOpt],
787 pname :: Name,
788 getTm :: t }
789 | PTacImplicit { priority :: Int,
790 argopts :: [ArgOpt],
791 pname :: Name,
792 getScript :: t,
793 getTm :: t }
794 deriving (Show, Eq, Functor)
796data ArgOpt = HideDisplay | InaccessibleArg
797 deriving (Show, Eq)
799instance Sized a => Sized (PArg' a) where
800 size (PImp p _ l nm trm) = 1 + size nm + size trm
801 size (PExp p l nm trm) = 1 + size nm + size trm
802 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
803 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
805{-!
806deriving instance Binary PArg'
807deriving instance NFData PArg'
808!-}
810pimp n t mach = PImp 1 mach [] n t
811pexp t = PExp 1 [] (sMN 0 "arg") t
812pconst t = PConstraint 1 [] (sMN 0 "carg") t
813ptacimp n s t = PTacImplicit 2 [] n s t
815type PArg = PArg' PTerm
817-- Type class data
819data ClassInfo = CI { instanceName :: Name,
820 class_methods :: [(Name, (FnOpts, PTerm))],
821 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
822 class_default_superclasses :: [PDecl],
823 class_params :: [Name],
824 class_instances :: [Name] }
825 deriving Show
826{-!
827deriving instance Binary ClassInfo
828deriving instance NFData ClassInfo
829!-}
831-- Type inference data
833data TIData = TIPartial -- ^ a function with a partially defined type
834 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
835 deriving Show
837data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
838 detaggable :: Bool }
839 deriving Show
840{-!
841deriving instance Binary OptInfo
842deriving instance NFData OptInfo
843!-}
846data TypeInfo = TI { con_names :: [Name],
847 codata :: Bool,
848 data_opts :: DataOpts,
849 param_pos :: [Int] }
850 deriving Show
851{-!
852deriving instance Binary TypeInfo
853deriving instance NFData TypeInfo
854!-}
856-- Syntactic sugar info
858data DSL' t = DSL { dsl_bind :: t,
859 dsl_return :: t,
860 dsl_apply :: t,
861 dsl_pure :: t,
862 dsl_var :: Maybe t,
863 index_first :: Maybe t,
864 index_next :: Maybe t,
865 dsl_lambda :: Maybe t,
866 dsl_let :: Maybe t
867 }
868 deriving (Show, Functor)
869{-!
870deriving instance Binary DSL'
871deriving instance NFData DSL'
872!-}
874type DSL = DSL' PTerm
876data SynContext = PatternSyntax | TermSyntax | AnySyntax
877 deriving Show
878{-!
879deriving instance Binary SynContext
880deriving instance NFData SynContext
881!-}
883data Syntax = Rule [SSymbol] PTerm SynContext
884 deriving Show
885{-!
886deriving instance Binary Syntax
887deriving instance NFData Syntax
888!-}
890data SSymbol = Keyword Name
891 | Symbol String
892 | Binding Name
893 | Expr Name
894 | SimpleExpr Name
895 deriving Show
896{-!
897deriving instance Binary SSymbol
898deriving instance NFData SSymbol
899!-}
901initDSL = DSL (PRef f (sUN ">>="))
902 (PRef f (sUN "return"))
903 (PRef f (sUN "<$>"))
904 (PRef f (sUN "pure"))
905 Nothing
906 Nothing
907 Nothing
908 Nothing
909 Nothing
910 where f = fileFC "(builtin)"
912data Using = UImplicit Name PTerm
913 | UConstraint Name [Name]
914 deriving (Show, Eq)
915{-!
916deriving instance Binary Using
917deriving instance NFData Using
918!-}
920data SyntaxInfo = Syn { using :: [Using],
921 syn_params :: [(Name, PTerm)],
922 syn_namespace :: [String],
923 no_imp :: [Name],
924 decoration :: Name -> Name,
925 inPattern :: Bool,
926 implicitAllowed :: Bool,
927 dsl_info :: DSL }
928 deriving Show
929{-!
930deriving instance NFData SyntaxInfo
931deriving instance Binary SyntaxInfo
932!-}
934defaultSyntax = Syn [] [] [] [] id False False initDSL
936expandNS :: SyntaxInfo -> Name -> Name
937expandNS syn n@(NS _ _) = n
938expandNS syn n = case syn_namespace syn of
939 [] -> n
940 xs -> sNS n xs
943-- For inferring types of things
945bi = fileFC "builtin"
947inferTy = sMN 0 "__Infer"
948inferCon = sMN 0 "__infer"
949inferDecl = PDatadecl inferTy
950 PType
951 [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType (
952 PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType"))
953 (PRef bi inferTy)), bi, [])]
954inferOpts = []
956infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
957infP = P (TCon 6 0) inferTy (TType (UVal 0))
959getInferTerm, getInferType :: Term -> Term
960getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
961getInferTerm (App (App _ _) tm) = tm
962getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
964getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
965 where toTy (Lam t) = Pi t
966 toTy (PVar t) = PVTy t
967 toTy b = b
968getInferType (App (App _ ty) _) = ty
972-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign, Elim type class
974primNames = [unitTy, unitCon,
975 falseTy, pairTy, pairCon,
976 eqTy, eqCon, inferTy, inferCon]
978unitTy = sMN 0 "__Unit"
979unitCon = sMN 0 "__II"
980unitDecl = PDatadecl unitTy PType
981 [(emptyDocstring, [], unitCon, PRef bi unitTy, bi, [])]
982unitOpts = [DefaultEliminator]
984falseTy = sMN 0 "__False"
985falseDecl = PDatadecl falseTy PType []
986falseOpts = []
988pairTy = sMN 0 "__Pair"
989pairCon = sMN 0 "__MkPair"
990pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
991 [(emptyDocstring, [], pairCon, PPi impl (n "A") PType (
992 PPi impl (n "B") PType (
993 PPi expl (n "a") (PRef bi (n "A")) (
994 PPi expl (n "b") (PRef bi (n "B"))
995 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
996 pexp (PRef bi (n "B"))])))), bi, [])]
997 where n a = sMN 0 a
998pairOpts = []
1000eqTy = sUN "="
1001eqCon = sUN "refl"
1002eqDecl = PDatadecl eqTy (piBind [(n "A", PType), (n "B", PType),
1003 (n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))]
1004 PType)
1005 [(emptyDocstring, [], eqCon, PPi impl (n "A") PType (
1006 PPi impl (n "x") (PRef bi (n "A"))
1007 (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False,
1008 pimp (n "B") Placeholder False,
1009 pexp (PRef bi (n "x")),
1010 pexp (PRef bi (n "x"))])), bi, [])]
1011 where n a = sMN 0 a
1012eqOpts = []
1014elimName = sUN "__Elim"
1015elimMethElimTy = sUN "__elimTy"
1016elimMethElim = sUN "elim"
1017elimDecl = PClass (parseDocstring . T.pack $ "Type class for eliminators") defaultSyntax bi [] elimName [(sUN "scrutineeType", PType)]
1018 [PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElimTy PType,
1019 PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElim (PRef bi elimMethElimTy)]
1021-- Defined in builtins.idr
1022sigmaTy = sUN "Exists"
1023existsCon = sUN "Ex_intro"
1025piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1026piBind = piBindp expl
1028piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1029piBindp p [] t = t
1030piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t)
1033-- Pretty-printing declarations and terms
1035-- These "show" instances render to an absurdly wide screen because inserted line breaks
1036-- could interfere with interactive editing, which calls "show".
1038instance Show PTerm where
1039 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp False) tm
1041instance Show PDecl where
1042 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp False) d
1044instance Show PClause where
1045 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp True) c
1047instance Show PData where
1048 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp False) d
1050instance Pretty PTerm OutputAnnotation where
1051 pretty = prettyImp False
1053-- | Colourise annotations according to an Idris state. It ignores the names
1054-- in the annotation, as there's no good way to show extended information on a
1055-- terminal.
1056consoleDecorate :: IState -> OutputAnnotation -> String -> String
1057consoleDecorate ist _ | not (idris_colourRepl ist) = id
1058consoleDecorate ist AnnConstData = let theme = idris_colourTheme ist
1059 in colouriseData theme
1060consoleDecorate ist AnnConstType = let theme = idris_colourTheme ist
1061 in colouriseType theme
1062consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
1063consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
1064consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1065consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1066 theme = idris_colourTheme ist
1067 in case () of
1068 _ | isDConName n ctxt -> colouriseData theme
1069 _ | isFnName n ctxt -> colouriseFun theme
1070 _ | isTConName n ctxt -> colouriseType theme
1071 _ | otherwise -> id -- don't colourise unknown names
1072consoleDecorate ist (AnnFC _) = id
1073consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
1074 where colour BoldText = IdrisColour Nothing True False True False
1075 colour UnderlineText = IdrisColour Nothing True True False False
1076 colour ItalicText = IdrisColour Nothing True False False True
1078-- | Pretty-print a high-level closed Idris term
1079prettyImp :: Bool -- ^^ whether to show implicits
1080 -> PTerm -- ^^ the term to pretty-print
1081 -> Doc OutputAnnotation
1082prettyImp impl = pprintPTerm impl [] []
1084-- | Pretty-print a high-level Idris term in some bindings context
1085pprintPTerm :: Bool -- ^^ whether to show implicits
1086 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1087 -> [Name] -- ^^ names to always show in pi, even if not used
1088 -> PTerm -- ^^ the term to pretty-print
1089 -> Doc OutputAnnotation
1090pprintPTerm impl bnd docArgs = prettySe 10 bnd
1091 where
1092 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1093 prettySe p bnd (PQuote r) =
1094 text "![" <> pretty r <> text "]"
1095 prettySe p bnd (PPatvar fc n) = pretty n
1096 prettySe p bnd e
1097 | Just str <- slist p bnd e = str
1098 | Just n <- snat p e = annotate AnnConstData (text (show n))
1099 prettySe p bnd (PRef fc n) = prettyName impl bnd n
1100 prettySe p bnd (PLam n ty sc) =
1101 bracket p 2 . group . align . hang 2 $
1102 text "\\" <> bindingOf n False <+> text "=>" <$>
1103 prettySe 10 ((n, False):bnd) sc
1104 prettySe p bnd (PLet n ty v sc) =
1105 bracket p 2 $
1106 kwd "let" <+> bindingOf n False <+> text "=" </>
1107 prettySe 10 bnd v <+> kwd "in" </>
1108 prettySe 10 ((n, False):bnd) sc
1109 prettySe p bnd (PPi (Exp l s _) n ty sc)
1110 | n `elem` allNamesIn sc || impl || n `elem` docArgs =
1111 bracket p 2 . group $
1112 enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1113 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1114 | otherwise =
1115 bracket p 2 . group $
1116 group (prettySe 0 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1117 where
1118 st =
1119 case s of
1120 Static -> text "[static]" <> space
1121 _ -> empty
1122 prettySe p bnd (PPi (Imp l s _) n ty sc)
1123 | impl =
1124 bracket p 2 $
1125 lparen <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1126 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1127 | otherwise = prettySe 10 ((n, True):bnd) sc
1128 where
1129 st =
1130 case s of
1131 Static -> text "[static]" <> space
1132 _ -> empty
1133 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1134 bracket p 2 $
1135 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1136 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1137 bracket p 2 $
1138 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1139 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1140 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1141 | UN nm <- basename f
1142 , not impl && null (getExps args) = if isAlpha (thead nm)
1143 then prettyName impl bnd f
1144 else enclose lparen rparen $
1145 prettyName impl bnd f
1146 prettySe p bnd (PAppBind _ (PRef _ f) [])
1147 | not impl = text "!" <> prettyName impl bnd f
1148 prettySe p bnd (PApp _ (PRef _ op) args)
1149 | UN nm <- basename op
1150 , not (tnull nm) &&
1151 (not impl) && (not $ isAlpha (thead nm)) =
1152 case getExps args of
1153 [] -> enclose lparen rparen opName
1154 [x] -> group (enclose lparen rparen opName <$> group (prettySe 0 bnd x))
1155 [l,r] -> bracket p 1 $ inFix l r
1156 (l:r:rest) -> bracket p 1 $
1157 enclose lparen rparen (inFix l r) <+>
1158 align (group (vsep (map (prettyArgSe bnd) rest)))
1159 where opName = prettyName impl bnd op
1160 inFix l r = align . group $
1161 (prettySe 1 bnd l <+> opName) <$> group (prettySe 0 bnd r)
1162 prettySe p bnd (PApp _ hd@(PRef fc f) [tm])
1163 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1164 f == sUN "Symbol_" = char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1165 prettySe p bnd (PApp _ f as) =
1166 let args = getExps as
1167 fp = prettySe 1 bnd f
1168 in
1169 bracket p 1 . group $
1170 if impl
1171 then if null as
1172 then fp
1173 else fp <+> align (vsep (map (prettyArgS bnd) as))
1174 else if null args
1175 then fp
1176 else fp <+> align (vsep (map (prettyArgSe bnd) args))
1177 prettySe p bnd (PCase _ scr opts) =
1178 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1179 where
1180 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1182 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1183 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1184 prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
1185 prettySe p bnd (PResolveTC _) = text "resolvetc"
1186 prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1187 prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1188 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1189 prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
1190 prettySe p bnd (PEq _ l r) =
1191 bracket p 2 . align . group $
1192 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1193 where eq = annName eqTy (text "=")
1194 prettySe p bnd (PRewrite _ l r _) =
1195 bracket p 2 $
1196 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1197 prettySe p bnd (PTyped l r) =
1198 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1199 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1200 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1201 align . group . vsep . punctuate (ann comma) $
1202 map (prettySe 10 bnd) elts
1203 where ann = case pun of
1204 TypeOrTerm -> id
1205 IsType -> annName pairTy
1206 IsTerm -> annName pairCon
1207 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1208 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1209 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1210 annName sigmaTy lparen <>
1211 bindingOf n False <+>
1212 annName sigmaTy (text "**") <+>
1213 prettySe 10 ((n, False):bnd) r <>
1214 annName sigmaTy rparen
1215 prettySe p bnd (PDPair _ IsType l t r) =
1216 annName sigmaTy lparen <>
1217 prettySe 10 bnd l <+>
1218 annName sigmaTy (text "**") <+>
1219 prettySe 10 bnd r <>
1220 annName sigmaTy rparen
1221 prettySe p bnd (PDPair _ IsTerm l t r) =
1222 annName existsCon lparen <>
1223 prettySe 10 bnd l <+>
1224 annName existsCon (text "**") <+>
1225 prettySe 10 bnd r <>
1226 annName existsCon rparen
1227 prettySe p bnd (PAlternative a as) =
1228 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1229 where
1230 prettyAs =
1231 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1232 prettySe p bnd PType = annotate AnnConstType $ text "Type"
1233 prettySe p bnd (PConstant c) = annotate (annot c) (text (show c))
1234 where annot (AType _) = AnnConstType
1235 annot StrType = AnnConstType
1236 annot PtrType = AnnConstType
1237 annot VoidType = AnnConstType
1238 annot _ = AnnConstData
1239 -- XXX: add pretty for tactics
1240 prettySe p bnd (PProof ts) =
1241 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1242 prettySe p bnd (PTactics ts) =
1243 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1244 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1245 prettySe p bnd (PReturn f) = kwd "return"
1246 prettySe p bnd PImpossible = kwd "impossible"
1247 prettySe p bnd Placeholder = text "_"
1248 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1249 prettySe p bnd (PElabError s) = pretty s
1251 prettySe p bnd _ = text "test"
1253 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1254 prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm
1255 prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm
1256 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1258 prettyArgSe bnd arg = prettySe 0 bnd arg
1259 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1260 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1261 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1263 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1264 annName n = annotate (AnnName n Nothing Nothing Nothing)
1266 basename :: Name -> Name
1267 basename (NS n _) = basename n
1268 basename n = n
1270 slist' p bnd (PApp _ (PRef _ nil) _)
1271 | not impl && nsroot nil == sUN "Nil" = Just []
1272 slist' p bnd (PRef _ nil)
1273 | not impl && nsroot nil == sUN "Nil" = Just []
1274 slist' p bnd (PApp _ (PRef _ cons) args)
1275 | nsroot cons == sUN "::",
1276 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1277 all isImp imps,
1278 Just tl' <- slist' p bnd tl
1279 = Just (hd:tl')
1280 where
1281 isImp (PImp {}) = True
1282 isImp _ = False
1283 slist' _ _ tm = Nothing
1285 slist p bnd e | Just es <- slist' p bnd e = Just $
1286 case es of [] -> annotate AnnConstData $ text "[]"
1287 [x] -> enclose left right . group $
1288 prettySe p bnd x
1289 xs -> (enclose left right .
1290 align . group . vsep .
1291 punctuate comma .
1292 map (prettySe p bnd)) xs
1293 where left = (annotate AnnConstData (text "["))
1294 right = (annotate AnnConstData (text "]"))
1295 comma = (annotate AnnConstData (text ","))
1296 slist _ _ _ = Nothing
1298 pairElts :: PTerm -> Maybe [PTerm]
1299 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1300 | otherwise = Just [x, y]
1301 pairElts _ = Nothing
1303 natns = "Prelude.Nat."
1305 snat p (PRef _ z)
1306 | show z == (natns++"Z") || show z == "Z" = Just 0
1307 snat p (PApp _ s [PExp {getTm=n}])
1308 | show s == (natns++"S") || show s == "S",
1309 Just n' <- snat p n
1310 = Just $ 1 + n'
1311 snat _ _ = Nothing
1313 bracket outer inner doc
1314 | inner > outer = lparen <> doc <> rparen
1315 | otherwise = doc
1317 kwd = annotate AnnKeyword . text
1319-- | Pretty-printer helper for the binding site of a name
1320bindingOf :: Name -- ^^ the bound name
1321 -> Bool -- ^^ whether the name is implicit
1322 -> Doc OutputAnnotation
1323bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1325-- | Pretty-printer helper for names that attaches the correct annotations
1326prettyName :: Bool -- ^^ whether to show namespaces
1327 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1328 -> Name -- ^^ the name to pprint
1329 -> Doc OutputAnnotation
1330prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1331 | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
1332 where strName (UN n) = T.unpack n
1333 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1334 | otherwise = strName n
1335 strName (MN i s) = T.unpack s
1336 strName other = show other
1339showCImp :: Bool -> PClause -> Doc OutputAnnotation
1340showCImp impl (PClause _ n l ws r w)
1341 = prettyImp impl l <+> showWs ws <+> text "=" <+> prettyImp impl r
1342 <+> text "where" <+> text (show w)
1343 where
1344 showWs [] = empty
1345 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1346showCImp impl (PWith _ n l ws r w)
1347 = prettyImp impl l <+> showWs ws <+> text "with" <+> prettyImp impl r
1348 <+> braces (text (show w))
1349 where
1350 showWs [] = empty
1351 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1354showDImp :: Bool -> PData -> Doc OutputAnnotation
1355showDImp impl (PDatadecl n ty cons)
1356 = text "data" <+> text (show n) <+> colon <+> prettyImp impl ty <+> text "where" <$>
1357 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp impl t) cons))
1359showDecls :: Bool -> [PDecl] -> Doc OutputAnnotation
1360showDecls i ds = vsep (map (showDeclImp i) ds)
1362showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1363showDeclImp i (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp i t
1364showDeclImp i (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1365 indent 2 (vsep (map (showCImp i) cs))
1366showDeclImp _ (PData _ _ _ _ _ d) = showDImp True d
1367showDeclImp i (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls i ps <> line)
1368showDeclImp i (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls i ps <> line)
1369showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1370showDeclImp i (PClass _ _ _ cs n ps ds)
1371 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls i ds
1372showDeclImp i (PInstance _ _ cs n _ t _ ds)
1373 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp i t <> line <> showDecls i ds
1374showDeclImp _ _ = text "..."
1375-- showDeclImp (PImport i) = "import " ++ i
1377instance Show (Doc OutputAnnotation) where
1378 show = flip (displayS . renderCompact) ""
1380getImps :: [PArg] -> [(Name, PTerm)]
1381getImps [] = []
1382getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1383getImps (_ : xs) = getImps xs
1385getExps :: [PArg] -> [PTerm]
1386getExps [] = []
1387getExps (PExp _ _ _ tm : xs) = tm : getExps xs
1388getExps (_ : xs) = getExps xs
1390getConsts :: [PArg] -> [PTerm]
1391getConsts [] = []
1392getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
1393getConsts (_ : xs) = getConsts xs
1395getAll :: [PArg] -> [PTerm]
1396getAll = map getTm
1399-- | Show Idris name
1400showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1401 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1402 -> Bool -- ^^ whether to show implicits
1403 -> Bool -- ^^ whether to colourise
1404 -> Name -- ^^ the term to show
1405 -> String
1406showName ist bnd impl colour n = case ist of
1407 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1408 Nothing -> showbasic n
1409 where name = if impl then show n else showbasic n
1410 showbasic n@(UN _) = showCG n
1411 showbasic (MN _ s) = str s
1412 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1413 showbasic (SN s) = show s
1414 fst3 (x, _, _) = x
1415 colourise n t = let ctxt' = fmap tt_ctxt ist in
1416 case ctxt' of
1417 Nothing -> name
1418 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1419 else colouriseBound t name
1420 | isDConName n ctxt -> colouriseData t name
1421 | isFnName n ctxt -> colouriseFun t name
1422 | isTConName n ctxt -> colouriseType t name
1423 -- The assumption is that if a name is not bound and does not exist in the
1424 -- global context, then we're somewhere in which implicit info has been lost
1425 -- (like error messages). Thus, unknown vars are colourised as implicits.
1426 | otherwise -> colouriseImplicit t name
1428showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1429 -> PTerm -- ^^ the term to show
1430 -> String
1431showTm ist = displayDecorated (consoleDecorate ist) .
1432 renderPretty 0.8 100000 .
1433 prettyImp (opt_showimp (idris_options ist))
1435-- | Show a term with implicits, no colours
1436showTmImpls :: PTerm -> String
1437showTmImpls = flip (displayS . renderCompact . prettyImp True) ""
1440instance Sized PTerm where
1441 size (PQuote rawTerm) = size rawTerm
1442 size (PRef fc name) = size name
1443 size (PLam name ty bdy) = 1 + size ty + size bdy
1444 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1445 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1446 size (PTyped trm ty) = 1 + size trm + size ty
1447 size (PApp fc name args) = 1 + size args
1448 size (PAppBind fc name args) = 1 + size args
1449 size (PCase fc trm bdy) = 1 + size trm + size bdy
1450 size (PTrue fc _) = 1
1451 size (PFalse fc) = 1
1452 size (PRefl fc _) = 1
1453 size (PResolveTC fc) = 1
1454 size (PEq fc left right) = 1 + size left + size right
1455 size (PRewrite fc left right _) = 1 + size left + size right
1456 size (PPair fc _ left right) = 1 + size left + size right
1457 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1458 size (PAlternative a alts) = 1 + size alts
1459 size (PHidden hidden) = size hidden
1460 size (PUnifyLog tm) = size tm
1461 size (PDisamb _ tm) = size tm
1462 size (PNoImplicits tm) = size tm
1463 size PType = 1
1464 size (PConstant const) = 1 + size const
1465 size Placeholder = 1
1466 size (PDoBlock dos) = 1 + size dos
1467 size (PIdiom fc term) = 1 + size term
1468 size (PReturn fc) = 1
1469 size (PMetavar name) = 1
1470 size (PProof tactics) = size tactics
1471 size (PElabError err) = size err
1472 size PImpossible = 1
1474getPArity :: PTerm -> Int
1475getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1476getPArity _ = 0
1478-- Return all names, free or globally bound, in the given term.
1480allNamesIn :: PTerm -> [Name]
1481allNamesIn tm = nub $ ni [] tm
1482 where -- TODO THINK added niTacImp, but is it right?
1483 ni env (PRef _ n)
1484 | not (n `elem` env) = [n]
1485 ni env (PPatvar _ n) = [n]
1486 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1487 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1488 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1489 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1490 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1491 ni env (PHidden tm) = ni env tm
1492 ni env (PEq _ l r) = ni env l ++ ni env r
1493 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1494 ni env (PTyped l r) = ni env l ++ ni env r
1495 ni env (PPair _ _ l r) = ni env l ++ ni env r
1496 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1497 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1498 ni env (PAlternative a ls) = concatMap (ni env) ls
1499 ni env (PUnifyLog tm) = ni env tm
1500 ni env (PDisamb _ tm) = ni env tm
1501 ni env (PNoImplicits tm) = ni env tm
1502 ni env _ = []
1504 niTacImp env (TacImp _ _ scr) = ni env scr
1505 niTacImp _ _ = []
1507-- Return all names defined in binders in the given term
1508boundNamesIn :: PTerm -> [Name]
1509boundNamesIn tm = nub $ ni tm
1510 where -- TODO THINK Added niTacImp, but is it right?
1511 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1512 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1513 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1514 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1515 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1516 ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc))
1517 ni (PEq _ l r) = ni l ++ ni r
1518 ni (PRewrite _ l r _) = ni l ++ ni r
1519 ni (PTyped l r) = ni l ++ ni r
1520 ni (PPair _ _ l r) = ni l ++ ni r
1521 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1522 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1523 ni (PAlternative a as) = concatMap (ni) as
1524 ni (PHidden tm) = ni tm
1525 ni (PUnifyLog tm) = ni tm
1526 ni (PDisamb _ tm) = ni tm
1527 ni (PNoImplicits tm) = ni tm
1528 ni _ = []
1530 niTacImp (TacImp _ _ scr) = ni scr
1531 niTacImp _ = []
1533-- Return names which are free in the given term.
1534namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1535namesIn uvars ist tm = nub $ ni [] tm
1536 where
1537 ni env (PRef _ n)
1538 | not (n `elem` env)
1539 = case lookupTy n (tt_ctxt ist) of
1540 [] -> [n]
1541 _ -> if n `elem` (map fst uvars) then [n] else []
1542 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1543 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1544 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1545 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1546 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1547 ni env (PEq _ l r) = ni env l ++ ni env r
1548 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1549 ni env (PTyped l r) = ni env l ++ ni env r
1550 ni env (PPair _ _ l r) = ni env l ++ ni env r
1551 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1552 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1553 ni env (PAlternative a as) = concatMap (ni env) as
1554 ni env (PHidden tm) = ni env tm
1555 ni env (PUnifyLog tm) = ni env tm
1556 ni env (PDisamb _ tm) = ni env tm
1557 ni env (PNoImplicits tm) = ni env tm
1558 ni env _ = []
1560 niTacImp env (TacImp _ _ scr) = ni env scr
1561 niTacImp _ _ = []
1563-- Return which of the given names are used in the given term.
1565usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1566usedNamesIn vars ist tm = nub $ ni [] tm
1567 where -- TODO THINK added niTacImp, but is it right?
1568 ni env (PRef _ n)
1569 | n `elem` vars && not (n `elem` env)
1570 = case lookupTy n (tt_ctxt ist) of
1571 [] -> [n]
1572 _ -> []
1573 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1574 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1575 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1576 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1577 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1578 ni env (PEq _ l r) = ni env l ++ ni env r
1579 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1580 ni env (PTyped l r) = ni env l ++ ni env r
1581 ni env (PPair _ _ l r) = ni env l ++ ni env r
1582 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1583 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1584 ni env (PAlternative a as) = concatMap (ni env) as
1585 ni env (PHidden tm) = ni env tm
1586 ni env (PUnifyLog tm) = ni env tm
1587 ni env (PDisamb _ tm) = ni env tm
1588 ni env (PNoImplicits tm) = ni env tm
1589 ni env _ = []
1591 niTacImp env (TacImp _ _ scr) = ni env scr
1592 niTacImp _ _ = []