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