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