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