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