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