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