on 88f88eb help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1574 lines 61 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-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
95-- without typechecking).
96-- This will include all the functions and data declarations, plus fixity declarations
97-- and syntax macros.
99-- | The global state used in the Idris monad
100data IState = IState {
101 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
102 idris_constraints :: [(UConstraint, FC)],
103 -- ^ A list of universe constraints and their corresponding source locations
104 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
105 idris_implicits :: Ctxt [PArg],
106 idris_statics :: Ctxt [Bool],
107 idris_classes :: Ctxt ClassInfo,
108 idris_dsls :: Ctxt DSL,
109 idris_optimisation :: Ctxt OptInfo,
110 idris_datatypes :: Ctxt TypeInfo,
111 idris_namehints :: Ctxt [Name],
112 idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
113 -- ^ list of lhs/rhs, and a list of missing clauses
114 idris_flags :: Ctxt [FnOpt],
115 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
116 idris_calledgraph :: Ctxt [Name],
117 idris_docstrings :: Ctxt (Docstring, [(Name, Docstring)]),
118 idris_tyinfodata :: Ctxt TIData,
119 idris_totcheck :: [(FC, Name)], -- names to check totality on
120 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
121 idris_options :: IOption,
122 idris_name :: Int,
123 idris_lineapps :: [((FilePath, Int), PTerm)],
124 -- ^ Full application LHS on source line
125 idris_metavars :: [(Name, (Maybe Name, Int, Bool))], -- ^ The currently defined but not proven metavariables
126 idris_coercions :: [Name],
127 idris_transforms :: [(Term, Term)],
128 idris_errRev :: [(Term, Term)],
129 syntax_rules :: [Syntax],
130 syntax_keywords :: [String],
131 imported :: [FilePath], -- ^ The imported modules
132 idris_scprims :: [(Name, (Int, PrimFn))],
133 idris_objs :: [(Codegen, FilePath)],
134 idris_libs :: [(Codegen, String)],
135 idris_cgflags :: [(Codegen, String)],
136 idris_hdrs :: [(Codegen, String)],
137 proof_list :: [(Name, [String])],
138 errLine :: Maybe Int,
139 parserWarnings :: [(FC, Err)],
140 lastParse :: Maybe Name,
141 indent_stack :: [Int],
142 brace_stack :: [Maybe Int],
143 hide_list :: [(Name, Maybe Accessibility)],
144 default_access :: Accessibility,
145 default_total :: Bool,
146 ibc_write :: [IBCWrite],
147 compiled_so :: Maybe String,
148 idris_dynamic_libs :: [DynamicLib],
149 idris_language_extensions :: [LanguageExt],
150 idris_outputmode :: OutputMode,
151 idris_colourRepl :: Bool,
152 idris_colourTheme :: ColourTheme,
153 idris_outh :: Handle,
154 idris_errorhandlers :: [Name], -- ^ Global error handlers
155 idris_nameIdx :: (Int, Ctxt (Int, Name)),
156 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
157 module_aliases :: M.Map [T.Text] [T.Text],
158 idris_consolewidth :: ConsoleWidth -- ^ How many chars wide is the console?
159 }
161data SizeChange = Smaller | Same | Bigger | Unknown
162 deriving (Show, Eq)
163{-!
164deriving instance Binary SizeChange
165deriving instance NFData SizeChange
166!-}
168type SCGEntry = (Name, [Maybe (Int, SizeChange)])
170data CGInfo = CGInfo { argsdef :: [Name],
171 calls :: [(Name, [[Name]])],
172 scg :: [SCGEntry],
173 argsused :: [Name],
174 unusedpos :: [Int] }
175 deriving Show
176{-!
177deriving instance Binary CGInfo
178deriving instance NFData CGInfo
179!-}
181primDefs = [sUN "unsafePerformPrimIO",
182 sUN "mkLazyForeignPrim",
183 sUN "mkForeignPrim",
184 sUN "FalseElim"]
186-- information that needs writing for the current module's .ibc file
187data IBCWrite = IBCFix FixDecl
188 | IBCImp Name
189 | IBCStatic Name
190 | IBCClass Name
191 | IBCInstance Bool Name Name
192 | IBCDSL Name
193 | IBCData Name
194 | IBCOpt Name
195 | IBCMetavar Name
196 | IBCSyntax Syntax
197 | IBCKeyword String
198 | IBCImport FilePath
199 | IBCObj Codegen FilePath
200 | IBCLib Codegen String
201 | IBCCGFlag Codegen String
202 | IBCDyLib String
203 | IBCHeader Codegen String
204 | IBCAccess Name Accessibility
205 | IBCMetaInformation Name MetaInformation
206 | IBCTotal Name Totality
207 | IBCFlags Name [FnOpt]
208 | IBCTrans (Term, Term)
209 | IBCErrRev (Term, Term)
210 | IBCCG Name
211 | IBCDoc Name
212 | IBCCoercion Name
213 | IBCDef Name -- i.e. main context
214 | IBCNameHint (Name, Name)
215 | IBCLineApp FilePath Int PTerm
216 | IBCErrorHandler Name
217 | IBCFunctionErrorHandler Name Name Name
218 deriving Show
220-- | The initial state for the compiler
221idrisInit :: IState
222idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
223 emptyContext emptyContext emptyContext emptyContext
224 emptyContext emptyContext emptyContext emptyContext
225 emptyContext emptyContext
226 [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
227 [] Nothing [] Nothing [] [] [] Hidden False [] Nothing [] [] RawOutput
228 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
229 AutomaticWidth
231-- | The monad for the main REPL - reading and processing files and updating
232-- global state (hence the IO inner monad).
233--type Idris = WriterT [Either String (IO ())] (State IState a))
234type Idris = StateT IState (ErrorT Err IO)
236-- Commands in the REPL
238data Codegen = ViaC
239 | ViaJava
240 | ViaNode
241 | ViaJavaScript
242 | ViaLLVM
243 | Bytecode
244 deriving (Show, Eq)
246-- | REPL commands
247data Command = Quit
248 | Help
249 | Eval PTerm
250 | Check PTerm
251 | DocStr Name
252 | TotCheck Name
253 | Reload
254 | Load FilePath
255 | ChangeDirectory FilePath
256 | ModImport String
257 | Edit
258 | Compile Codegen String
259 | Execute
260 | ExecVal PTerm
261 | Metavars
262 | Prove Name
263 | AddProof (Maybe Name)
264 | RmProof Name
265 | ShowProof Name
266 | Proofs
267 | Universes
268 | LogLvl Int
269 | Spec PTerm
270 | HNF PTerm
271 | TestInline PTerm
272 | Defn Name
273 | Info Name
274 | Missing Name
275 | DynamicLink FilePath
276 | ListDynamic
277 | Pattelab PTerm
278 | DebugInfo Name
279 | Search PTerm
280 | CaseSplitAt Bool Int Name
281 | AddClauseFrom Bool Int Name
282 | AddProofClauseFrom Bool Int Name
283 | AddMissing Bool Int Name
284 | MakeWith Bool Int Name
285 | DoProofSearch Bool Int Name [Name]
286 | SetOpt Opt
287 | UnsetOpt Opt
288 | NOP
289 | SetColour ColourType IdrisColour
290 | ColourOn
291 | ColourOff
292 | ListErrorHandlers
293 | SetConsoleWidth ConsoleWidth
295data Opt = Filename String
296 | Ver
297 | Usage
298 | Quiet
299 | NoBanner
300 | ColourREPL Bool
301 | Ideslave
302 | ShowLibs
303 | ShowLibdir
304 | ShowIncs
305 | NoBasePkgs
306 | NoPrelude
307 | NoBuiltins -- only for the really primitive stuff!
308 | NoREPL
309 | OLogging Int
310 | Output String
311 | TypeCase
312 | TypeInType
313 | DefaultTotal
314 | DefaultPartial
315 | WarnPartial
316 | NoCoverage
317 | ErrContext
318 | ShowImpl
319 | Verbose
320 | IBCSubDir String
321 | ImportDir String
322 | PkgBuild String
323 | PkgInstall String
324 | PkgClean String
325 | PkgCheck String
326 | PkgREPL String
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
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 (AnnName n _ _) = let ctxt = tt_ctxt ist
1069 theme = idris_colourTheme ist
1070 in case () of
1071 _ | isDConName n ctxt -> colouriseData theme
1072 _ | isFnName n ctxt -> colouriseFun theme
1073 _ | isTConName n ctxt -> colouriseType theme
1074 _ | otherwise -> id -- don't colourise unknown names
1075consoleDecorate ist (AnnFC _) = id
1077-- | Pretty-print a high-level closed Idris term
1078prettyImp :: Bool -- ^^ whether to show implicits
1079 -> PTerm -- ^^ the term to pretty-print
1080 -> Doc OutputAnnotation
1081prettyImp impl = pprintPTerm impl []
1083-- | Pretty-print a high-level Idris term in some bindings context
1084pprintPTerm :: Bool -- ^^ whether to show implicits
1085 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1086 -> PTerm -- ^^ the term to pretty-print
1087 -> Doc OutputAnnotation
1088pprintPTerm impl bnd = prettySe 10 bnd
1089 where
1090 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1091 prettySe p bnd (PQuote r) =
1092 text "![" <> pretty r <> text "]"
1093 prettySe p bnd (PPatvar fc n) = pretty n
1094 prettySe p bnd e
1095 | Just str <- slist p bnd e = str
1096 | Just n <- snat p e = annotate AnnConstData (text (show n))
1097 prettySe p bnd (PRef fc n) = prettyName impl bnd n
1098 prettySe p bnd (PLam n ty sc) =
1099 bracket p 2 . group . align . hang 2 $
1100 text "\\" <> bindingOf n False <+> text "=>" <$>
1101 prettySe 10 ((n, False):bnd) sc
1102 prettySe p bnd (PLet n ty v sc) =
1103 bracket p 2 $
1104 text "let" <+> bindingOf n False <+> text "=" </>
1105 prettySe 10 bnd v <+> text "in" </>
1106 prettySe 10 ((n, False):bnd) sc
1107 prettySe p bnd (PPi (Exp l s _) n ty sc)
1108 | n `elem` allNamesIn sc || impl =
1109 let open = if Lazy `elem` l then text "|" <> lparen else lparen in
1110 bracket p 2 . group $
1111 enclose open rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1112 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1113 | otherwise =
1114 bracket p 2 . group $
1115 group (prettySe 0 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1116 where
1117 st =
1118 case s of
1119 Static -> text "[static]" <> space
1120 _ -> empty
1121 prettySe p bnd (PPi (Imp l s _) n ty sc)
1122 | impl =
1123 let open = if Lazy `elem` l then text "|" <> lbrace else lbrace in
1124 bracket p 2 $
1125 open <> 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 <> text "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 text "case" <+> prettySe 10 bnd scr <+> text "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 _ _) = annotate (AnnName eqCon Nothing Nothing) $ text "refl"
1185 prettySe p bnd (PResolveTC _) = text "resolvetc"
1186 prettySe p bnd (PTrue _ IsType) = annotate (AnnName unitTy Nothing Nothing) $ text "()"
1187 prettySe p bnd (PTrue _ IsTerm) = annotate (AnnName unitCon Nothing Nothing) $ text "()"
1188 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1189 prettySe p bnd (PFalse _) = annotate (AnnName falseTy Nothing Nothing) $ 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 = annotate (AnnName eqTy Nothing Nothing) (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 -> annotate (AnnName pairTy Nothing Nothing)
1206 IsTerm -> annotate (AnnName pairCon Nothing Nothing)
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 annotate (AnnName sigmaTy Nothing Nothing) lparen <>
1211 bindingOf n False <+>
1212 annotate (AnnName sigmaTy Nothing Nothing) (text "**") <+>
1213 prettySe 10 ((n, False):bnd) r <>
1214 annotate (AnnName sigmaTy Nothing Nothing) rparen
1215 prettySe p bnd (PDPair _ IsType l t r) =
1216 annotate (AnnName sigmaTy Nothing Nothing) lparen <>
1217 prettySe 10 bnd l <+>
1218 annotate (AnnName sigmaTy Nothing Nothing) (text "**") <+>
1219 prettySe 10 bnd r <>
1220 annotate (AnnName sigmaTy Nothing Nothing) rparen
1221 prettySe p bnd (PDPair _ IsTerm l t r) =
1222 annotate (AnnName existsCon Nothing Nothing) lparen <>
1223 prettySe 10 bnd l <+>
1224 annotate (AnnName existsCon Nothing Nothing) (text "**") <+>
1225 prettySe 10 bnd r <>
1226 annotate (AnnName existsCon Nothing Nothing) 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) = text "return"
1246 prettySe p bnd PImpossible = text "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 <> text "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1263 basename :: Name -> Name
1264 basename (NS n _) = basename n
1265 basename n = n
1267 slist' p bnd (PApp _ (PRef _ nil) _)
1268 | not impl && nsroot nil == sUN "Nil" = Just []
1269 slist' p bnd (PRef _ nil)
1270 | not impl && nsroot nil == sUN "Nil" = Just []
1271 slist' p bnd (PApp _ (PRef _ cons) args)
1272 | nsroot cons == sUN "::",
1273 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1274 all isImp imps,
1275 Just tl' <- slist' p bnd tl
1276 = Just (hd:tl')
1277 where
1278 isImp (PImp {}) = True
1279 isImp _ = False
1280 slist' _ _ tm = Nothing
1282 slist p bnd e | Just es <- slist' p bnd e = Just $
1283 case es of [] -> annotate AnnConstData $ text "[]"
1284 [x] -> enclose left right . group $
1285 prettySe p bnd x
1286 xs -> (enclose left right .
1287 align . group . vsep .
1288 punctuate comma .
1289 map (prettySe p bnd)) xs
1290 where left = (annotate AnnConstData (text "["))
1291 right = (annotate AnnConstData (text "]"))
1292 comma = (annotate AnnConstData (text ","))
1293 slist _ _ _ = Nothing
1295 pairElts :: PTerm -> Maybe [PTerm]
1296 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1297 | otherwise = Just [x, y]
1298 pairElts _ = Nothing
1300 natns = "Prelude.Nat."
1302 snat p (PRef _ z)
1303 | show z == (natns++"Z") || show z == "Z" = Just 0
1304 snat p (PApp _ s [PExp {getTm=n}])
1305 | show s == (natns++"S") || show s == "S",
1306 Just n' <- snat p n
1307 = Just $ 1 + n'
1308 snat _ _ = Nothing
1310 bracket outer inner doc
1311 | inner > outer = lparen <> doc <> rparen
1312 | otherwise = doc
1314-- | Pretty-printer helper for the binding site of a name
1315bindingOf :: Name -- ^^ the bound name
1316 -> Bool -- ^^ whether the name is implicit
1317 -> Doc OutputAnnotation
1318bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1320-- | Pretty-printer helper for names that attaches the correct annotations
1321prettyName :: Bool -- ^^ whether to show namespaces
1322 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1323 -> Name -- ^^ the name to pprint
1324 -> Doc OutputAnnotation
1325prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1326 | otherwise = annotate (AnnName n Nothing Nothing) (text (strName n))
1327 where strName (UN n) = T.unpack n
1328 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1329 | otherwise = strName n
1330 strName (MN i s) = T.unpack s
1331 strName other = show other
1334showCImp :: Bool -> PClause -> Doc OutputAnnotation
1335showCImp impl (PClause _ n l ws r w)
1336 = prettyImp impl l <+> showWs ws <+> text "=" <+> prettyImp impl r
1337 <+> text "where" <+> text (show w)
1338 where
1339 showWs [] = empty
1340 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1341showCImp impl (PWith _ n l ws r w)
1342 = prettyImp impl l <+> showWs ws <+> text "with" <+> prettyImp impl r
1343 <+> braces (text (show w))
1344 where
1345 showWs [] = empty
1346 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1349showDImp :: Bool -> PData -> Doc OutputAnnotation
1350showDImp impl (PDatadecl n ty cons)
1351 = text "data" <+> text (show n) <+> colon <+> prettyImp impl ty <+> text "where" <$>
1352 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp impl t) cons))
1354showDecls :: Bool -> [PDecl] -> Doc OutputAnnotation
1355showDecls i ds = vsep (map (showDeclImp i) ds)
1357showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1358showDeclImp i (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp i t
1359showDeclImp i (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1360 indent 2 (vsep (map (showCImp i) cs))
1361showDeclImp _ (PData _ _ _ _ _ d) = showDImp True d
1362showDeclImp i (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls i ps <> line)
1363showDeclImp i (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls i ps <> line)
1364showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1365showDeclImp i (PClass _ _ _ cs n ps ds)
1366 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls i ds
1367showDeclImp i (PInstance _ _ cs n _ t _ ds)
1368 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp i t <> line <> showDecls i ds
1369showDeclImp _ _ = text "..."
1370-- showDeclImp (PImport i) = "import " ++ i
1372instance Show (Doc OutputAnnotation) where
1373 show = flip (displayS . renderCompact) ""
1375getImps :: [PArg] -> [(Name, PTerm)]
1376getImps [] = []
1377getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1378getImps (_ : xs) = getImps xs
1380getExps :: [PArg] -> [PTerm]
1381getExps [] = []
1382getExps (PExp _ _ tm : xs) = tm : getExps xs
1383getExps (_ : xs) = getExps xs
1385getConsts :: [PArg] -> [PTerm]
1386getConsts [] = []
1387getConsts (PConstraint _ _ tm : xs) = tm : getConsts xs
1388getConsts (_ : xs) = getConsts xs
1390getAll :: [PArg] -> [PTerm]
1391getAll = map getTm
1394-- | Show Idris name
1395showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1396 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1397 -> Bool -- ^^ whether to show implicits
1398 -> Bool -- ^^ whether to colourise
1399 -> Name -- ^^ the term to show
1400 -> String
1401showName ist bnd impl colour n = case ist of
1402 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1403 Nothing -> showbasic n
1404 where name = if impl then show n else showbasic n
1405 showbasic n@(UN _) = showCG n
1406 showbasic (MN _ s) = str s
1407 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1408 showbasic (SN s) = show s
1409 fst3 (x, _, _) = x
1410 colourise n t = let ctxt' = fmap tt_ctxt ist in
1411 case ctxt' of
1412 Nothing -> name
1413 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1414 else colouriseBound t name
1415 | isDConName n ctxt -> colouriseData t name
1416 | isFnName n ctxt -> colouriseFun t name
1417 | isTConName n ctxt -> colouriseType t name
1418 -- The assumption is that if a name is not bound and does not exist in the
1419 -- global context, then we're somewhere in which implicit info has been lost
1420 -- (like error messages). Thus, unknown vars are colourised as implicits.
1421 | otherwise -> colouriseImplicit t name
1423showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1424 -> PTerm -- ^^ the term to show
1425 -> String
1426showTm ist = displayDecorated (consoleDecorate ist) . renderCompact . prettyImp (opt_showimp (idris_options ist))
1428-- | Show a term with implicits, no colours
1429showTmImpls :: PTerm -> String
1430showTmImpls = flip (displayS . renderCompact . prettyImp True) ""
1433instance Sized PTerm where
1434 size (PQuote rawTerm) = size rawTerm
1435 size (PRef fc name) = size name
1436 size (PLam name ty bdy) = 1 + size ty + size bdy
1437 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1438 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1439 size (PTyped trm ty) = 1 + size trm + size ty
1440 size (PApp fc name args) = 1 + size args
1441 size (PAppBind fc name args) = 1 + size args
1442 size (PCase fc trm bdy) = 1 + size trm + size bdy
1443 size (PTrue fc _) = 1
1444 size (PFalse fc) = 1
1445 size (PRefl fc _) = 1
1446 size (PResolveTC fc) = 1
1447 size (PEq fc left right) = 1 + size left + size right
1448 size (PRewrite fc left right _) = 1 + size left + size right
1449 size (PPair fc _ left right) = 1 + size left + size right
1450 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1451 size (PAlternative a alts) = 1 + size alts
1452 size (PHidden hidden) = size hidden
1453 size (PUnifyLog tm) = size tm
1454 size (PDisamb _ tm) = size tm
1455 size (PNoImplicits tm) = size tm
1456 size PType = 1
1457 size (PConstant const) = 1 + size const
1458 size Placeholder = 1
1459 size (PDoBlock dos) = 1 + size dos
1460 size (PIdiom fc term) = 1 + size term
1461 size (PReturn fc) = 1
1462 size (PMetavar name) = 1
1463 size (PProof tactics) = size tactics
1464 size (PElabError err) = size err
1465 size PImpossible = 1
1467getPArity :: PTerm -> Int
1468getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1469getPArity _ = 0
1471-- Return all names, free or globally bound, in the given term.
1473allNamesIn :: PTerm -> [Name]
1474allNamesIn tm = nub $ ni [] tm
1475 where
1476 ni env (PRef _ n)
1477 | not (n `elem` env) = [n]
1478 ni env (PPatvar _ n) = [n]
1479 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1480 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1481 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1482 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1483 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1484 ni env (PHidden tm) = ni env tm
1485 ni env (PEq _ l r) = ni env l ++ ni env r
1486 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1487 ni env (PTyped l r) = ni env l ++ ni env r
1488 ni env (PPair _ _ l r) = ni env l ++ ni env r
1489 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1490 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1491 ni env (PAlternative a ls) = concatMap (ni env) ls
1492 ni env (PUnifyLog tm) = ni env tm
1493 ni env (PDisamb _ tm) = ni env tm
1494 ni env (PNoImplicits tm) = ni env tm
1495 ni env _ = []
1497-- Return all names defined in binders in the given term
1498boundNamesIn :: PTerm -> [Name]
1499boundNamesIn tm = nub $ ni tm
1500 where
1501 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1502 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1503 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1504 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1505 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1506 ni (PPi _ n ty sc) = n : (ni ty ++ ni sc)
1507 ni (PEq _ l r) = ni l ++ ni r
1508 ni (PRewrite _ l r _) = ni l ++ ni r
1509 ni (PTyped l r) = ni l ++ ni r
1510 ni (PPair _ _ l r) = ni l ++ ni r
1511 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1512 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1513 ni (PAlternative a as) = concatMap (ni) as
1514 ni (PHidden tm) = ni tm
1515 ni (PUnifyLog tm) = ni tm
1516 ni (PDisamb _ tm) = ni tm
1517 ni (PNoImplicits tm) = ni tm
1518 ni _ = []
1520-- Return names which are free in the given term.
1521namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1522namesIn uvars ist tm = nub $ ni [] tm
1523 where
1524 ni env (PRef _ n)
1525 | not (n `elem` env)
1526 = case lookupTy n (tt_ctxt ist) of
1527 [] -> [n]
1528 _ -> if n `elem` (map fst uvars) then [n] else []
1529 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1530 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1531 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1532 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1533 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1534 ni env (PEq _ l r) = ni env l ++ ni env r
1535 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1536 ni env (PTyped l r) = ni env l ++ ni env r
1537 ni env (PPair _ _ l r) = ni env l ++ ni env r
1538 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1539 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1540 ni env (PAlternative a as) = concatMap (ni env) as
1541 ni env (PHidden tm) = ni env tm
1542 ni env (PUnifyLog tm) = ni env tm
1543 ni env (PDisamb _ tm) = ni env tm
1544 ni env (PNoImplicits tm) = ni env tm
1545 ni env _ = []
1547-- Return which of the given names are used in the given term.
1549usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1550usedNamesIn vars ist tm = nub $ ni [] tm
1551 where
1552 ni env (PRef _ n)
1553 | n `elem` vars && not (n `elem` env)
1554 = case lookupTy n (tt_ctxt ist) of
1555 [] -> [n]
1556 _ -> []
1557 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1558 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1559 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1560 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1561 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1562 ni env (PEq _ l r) = ni env l ++ ni env r
1563 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1564 ni env (PTyped l r) = ni env l ++ ni env r
1565 ni env (PPair _ _ l r) = ni env l ++ ni env r
1566 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1567 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1568 ni env (PAlternative a as) = concatMap (ni env) as
1569 ni env (PHidden tm) = ni env tm
1570 ni env (PUnifyLog tm) = ni env tm
1571 ni env (PDisamb _ tm) = ni env tm
1572 ni env (PNoImplicits tm) = ni env tm
1573 ni env _ = []