on aa39233 help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1583 lines 61 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntaxTree where
6import Idris.Core.TT
7import Idris.Core.Evaluate
8import Idris.Core.Elaborate hiding (Tactic(..))
9import Idris.Core.Typecheck
10import Idris.Docstrings
11import IRTS.Lang
12import IRTS.CodegenCommon
13import Util.Pretty
14import Util.DynamicLinker
16import Idris.Colours
18import Paths_idris
20import System.Console.Haskeline
21import System.IO
23import Control.Monad.Trans.State.Strict
24import Control.Monad.Trans.Error
26import Data.List hiding (group)
27import Data.Char
28import qualified Data.Map as M
29import qualified Data.Text as T
30import qualified Data.Map as M
31import Data.Either
32import qualified Data.Set as S
33import Data.Word (Word)
35import Debug.Trace
37import Text.PrettyPrint.Annotated.Leijen
39data IOption = IOption { opt_logLevel :: Int,
40 opt_typecase :: Bool,
41 opt_typeintype :: Bool,
42 opt_coverage :: Bool,
43 opt_showimp :: Bool, -- ^^ show implicits
44 opt_errContext :: Bool,
45 opt_repl :: Bool,
46 opt_verbose :: Bool,
47 opt_nobanner :: Bool,
48 opt_quiet :: Bool,
49 opt_codegen :: Codegen,
50 opt_outputTy :: OutputType,
51 opt_ibcsubdir :: FilePath,
52 opt_importdirs :: [FilePath],
53 opt_triple :: String,
54 opt_cpu :: String,
55 opt_optLevel :: Word,
56 opt_cmdline :: [Opt], -- remember whole command line
57 opt_origerr :: Bool,
58 opt_autoSolve :: Bool -- ^ automatically apply "solve" tactic in prover
59 }
60 deriving (Show, Eq)
62defaultOpts = IOption { opt_logLevel = 0
63 , opt_typecase = False
64 , opt_typeintype = False
65 , opt_coverage = True
66 , opt_showimp = False
67 , opt_errContext = False
68 , opt_repl = True
69 , opt_verbose = True
70 , opt_nobanner = False
71 , opt_quiet = False
72 , opt_codegen = ViaC
73 , opt_outputTy = Executable
74 , opt_ibcsubdir = ""
75 , opt_importdirs = []
76 , opt_triple = ""
77 , opt_cpu = ""
78 , opt_optLevel = 2
79 , opt_cmdline = []
80 , opt_origerr = False
81 , opt_autoSolve = True
82 }
84data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
86-- | The output mode in use
87data OutputMode = RawOutput | IdeSlave Integer deriving Show
89-- | How wide is the console?
90data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
91 | ColsWide Int -- ^ Manually specified - must be positive
92 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
94-- | The global state used in the Idris monad
95data IState = IState {
96 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
97 idris_constraints :: [(UConstraint, FC)],
98 -- ^ A list of universe constraints and their corresponding source locations
99 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
100 idris_implicits :: Ctxt [PArg],
101 idris_statics :: Ctxt [Bool],
102 idris_classes :: Ctxt ClassInfo,
103 idris_dsls :: Ctxt DSL,
104 idris_optimisation :: Ctxt OptInfo,
105 idris_datatypes :: Ctxt TypeInfo,
106 idris_namehints :: Ctxt [Name],
107 idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
108 -- ^ list of lhs/rhs, and a list of missing clauses
109 idris_flags :: Ctxt [FnOpt],
110 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
111 idris_calledgraph :: Ctxt [Name],
112 idris_docstrings :: Ctxt (Docstring, [(Name, Docstring)]),
113 idris_tyinfodata :: Ctxt TIData,
114 idris_totcheck :: [(FC, Name)], -- names to check totality on
115 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
116 idris_options :: IOption,
117 idris_name :: Int,
118 idris_lineapps :: [((FilePath, Int), PTerm)],
119 -- ^ Full application LHS on source line
120 idris_metavars :: [(Name, (Maybe Name, Int, Bool))], -- ^ The currently defined but not proven metavariables
121 idris_coercions :: [Name],
122 idris_transforms :: [(Term, Term)],
123 idris_errRev :: [(Term, Term)],
124 syntax_rules :: [Syntax],
125 syntax_keywords :: [String],
126 imported :: [FilePath], -- ^ The imported modules
127 idris_scprims :: [(Name, (Int, PrimFn))],
128 idris_objs :: [(Codegen, FilePath)],
129 idris_libs :: [(Codegen, String)],
130 idris_cgflags :: [(Codegen, String)],
131 idris_hdrs :: [(Codegen, String)],
132 idris_imported :: [FilePath], -- ^ Imported ibc file names
133 proof_list :: [(Name, [String])],
134 errSpan :: Maybe FC,
135 parserWarnings :: [(FC, Err)],
136 lastParse :: Maybe Name,
137 indent_stack :: [Int],
138 brace_stack :: [Maybe Int],
139 lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
140 hide_list :: [(Name, Maybe Accessibility)],
141 default_access :: Accessibility,
142 default_total :: Bool,
143 ibc_write :: [IBCWrite],
144 compiled_so :: Maybe String,
145 idris_dynamic_libs :: [DynamicLib],
146 idris_language_extensions :: [LanguageExt],
147 idris_outputmode :: OutputMode,
148 idris_colourRepl :: Bool,
149 idris_colourTheme :: ColourTheme,
150 idris_outh :: Handle,
151 idris_errorhandlers :: [Name], -- ^ Global error handlers
152 idris_nameIdx :: (Int, Ctxt (Int, Name)),
153 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
154 module_aliases :: M.Map [T.Text] [T.Text],
155 idris_consolewidth :: ConsoleWidth -- ^ How many chars wide is the console?
156 }
158data SizeChange = Smaller | Same | Bigger | Unknown
159 deriving (Show, Eq)
160{-!
161deriving instance Binary SizeChange
162deriving instance NFData SizeChange
163!-}
165type SCGEntry = (Name, [Maybe (Int, SizeChange)])
167data CGInfo = CGInfo { argsdef :: [Name],
168 calls :: [(Name, [[Name]])],
169 scg :: [SCGEntry],
170 argsused :: [Name],
171 unusedpos :: [Int] }
172 deriving Show
173{-!
174deriving instance Binary CGInfo
175deriving instance NFData CGInfo
176!-}
178primDefs = [sUN "unsafePerformPrimIO",
179 sUN "mkLazyForeignPrim",
180 sUN "mkForeignPrim",
181 sUN "FalseElim"]
183-- information that needs writing for the current module's .ibc file
184data IBCWrite = IBCFix FixDecl
185 | IBCImp Name
186 | IBCStatic Name
187 | IBCClass Name
188 | IBCInstance Bool Name Name
189 | IBCDSL Name
190 | IBCData Name
191 | IBCOpt Name
192 | IBCMetavar Name
193 | IBCSyntax Syntax
194 | IBCKeyword String
195 | IBCImport FilePath
196 | IBCObj Codegen FilePath
197 | IBCLib Codegen String
198 | IBCCGFlag Codegen String
199 | IBCDyLib String
200 | IBCHeader Codegen String
201 | IBCAccess Name Accessibility
202 | IBCMetaInformation Name MetaInformation
203 | IBCTotal Name Totality
204 | IBCFlags Name [FnOpt]
205 | IBCTrans (Term, Term)
206 | IBCErrRev (Term, Term)
207 | IBCCG Name
208 | IBCDoc Name
209 | IBCCoercion Name
210 | IBCDef Name -- i.e. main context
211 | IBCNameHint (Name, Name)
212 | IBCLineApp FilePath Int PTerm
213 | IBCErrorHandler Name
214 | IBCFunctionErrorHandler Name Name Name
215 deriving Show
217-- | The initial state for the compiler
218idrisInit :: IState
219idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
220 emptyContext emptyContext emptyContext emptyContext
221 emptyContext emptyContext emptyContext emptyContext
222 emptyContext emptyContext
223 [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
224 [] [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
225 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
226 AutomaticWidth
228-- | The monad for the main REPL - reading and processing files and updating
229-- global state (hence the IO inner monad).
230--type Idris = WriterT [Either String (IO ())] (State IState a))
231type Idris = StateT IState (ErrorT Err IO)
233-- Commands in the REPL
235data Codegen = ViaC
236 | ViaJava
237 | ViaNode
238 | ViaJavaScript
239 | ViaLLVM
240 | Bytecode
241 deriving (Show, Eq)
243-- | REPL commands
244data Command = Quit
245 | Help
246 | Eval PTerm
247 | Check PTerm
248 | DocStr Name
249 | TotCheck Name
250 | Reload
251 | Load FilePath
252 | ChangeDirectory FilePath
253 | ModImport String
254 | Edit
255 | Compile Codegen String
256 | Execute
257 | ExecVal PTerm
258 | Metavars
259 | Prove Name
260 | AddProof (Maybe Name)
261 | RmProof Name
262 | ShowProof Name
263 | Proofs
264 | Universes
265 | LogLvl Int
266 | Spec PTerm
267 | HNF PTerm
268 | TestInline PTerm
269 | Defn Name
270 | Info Name
271 | Missing Name
272 | DynamicLink FilePath
273 | ListDynamic
274 | Pattelab PTerm
275 | DebugInfo Name
276 | Search PTerm
277 | CaseSplitAt Bool Int Name
278 | AddClauseFrom Bool Int Name
279 | AddProofClauseFrom Bool Int Name
280 | AddMissing Bool Int Name
281 | MakeWith Bool Int Name
282 | DoProofSearch Bool Int Name [Name]
283 | SetOpt Opt
284 | UnsetOpt Opt
285 | NOP
286 | SetColour ColourType IdrisColour
287 | ColourOn
288 | ColourOff
289 | ListErrorHandlers
290 | SetConsoleWidth ConsoleWidth
291 | Apropos String
293data Opt = Filename String
294 | Ver
295 | Usage
296 | Quiet
297 | NoBanner
298 | ColourREPL Bool
299 | Ideslave
300 | ShowLibs
301 | ShowLibdir
302 | ShowIncs
303 | NoBasePkgs
304 | NoPrelude
305 | NoBuiltins -- only for the really primitive stuff!
306 | NoREPL
307 | OLogging Int
308 | Output String
309 | TypeCase
310 | TypeInType
311 | DefaultTotal
312 | DefaultPartial
313 | WarnPartial
314 | NoCoverage
315 | ErrContext
316 | ShowImpl
317 | Verbose
318 | IBCSubDir String
319 | ImportDir String
320 | PkgBuild String
321 | PkgInstall String
322 | PkgClean String
323 | PkgCheck String
324 | PkgREPL String
325 | WarnOnly
326 | Pkg String
327 | BCAsm String
328 | DumpDefun String
329 | DumpCases String
330 | UseCodegen Codegen
331 | OutputTy OutputType
332 | Extension LanguageExt
333 | InterpretScript String
334 | TargetTriple String
335 | TargetCPU String
336 | OptLevel Word
337 | Client String
338 | ShowOrigErr
339 | AutoWidth -- ^ Automatically adjust terminal width
340 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
341 deriving (Show, Eq)
343-- Parsed declarations
345data Fixity = Infixl { prec :: Int }
346 | Infixr { prec :: Int }
347 | InfixN { prec :: Int }
348 | PrefixN { prec :: Int }
349 deriving Eq
350{-!
351deriving instance Binary Fixity
352deriving instance NFData Fixity
353!-}
355instance Show Fixity where
356 show (Infixl i) = "infixl " ++ show i
357 show (Infixr i) = "infixr " ++ show i
358 show (InfixN i) = "infix " ++ show i
359 show (PrefixN i) = "prefix " ++ show i
361data FixDecl = Fix Fixity String
362 deriving Eq
364instance Show FixDecl where
365 show (Fix f s) = show f ++ " " ++ s
367{-!
368deriving instance Binary FixDecl
369deriving instance NFData FixDecl
370!-}
372instance Ord FixDecl where
373 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
376data Static = Static | Dynamic
377 deriving (Show, Eq)
378{-!
379deriving instance Binary Static
380deriving instance NFData Static
381!-}
383-- Mark bindings with their explicitness, and laziness
384data Plicity = Imp { pargopts :: [ArgOpt],
385 pstatic :: Static,
386 pparam :: Bool }
387 | Exp { pargopts :: [ArgOpt],
388 pstatic :: Static,
389 pparam :: Bool }
390 | Constraint { pargopts :: [ArgOpt],
391 pstatic :: Static }
392 | TacImp { pargopts :: [ArgOpt],
393 pstatic :: Static,
394 pscript :: PTerm }
395 deriving (Show, Eq)
397plazy :: Plicity -> Bool
398plazy tm = Lazy `elem` pargopts tm
400{-!
401deriving instance Binary Plicity
402deriving instance NFData Plicity
403!-}
405impl = Imp [Lazy] Dynamic False
406expl = Exp [] Dynamic False
407expl_param = Exp [] Dynamic True
408constraint = Constraint [] Dynamic
409tacimpl t = TacImp [] Dynamic t
411data FnOpt = Inlinable -- always evaluate when simplifying
412 | TotalFn | PartialFn | CoveringFn
413 | Coinductive | AssertTotal
414 | Dictionary -- type class dictionary, eval only when
415 -- a function argument, and further evaluation resutls
416 | Implicit -- implicit coercion
417 | CExport String -- export, with a C name
418 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
419 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
420 | Reflection -- a reflecting function, compile-time only
421 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
422 deriving (Show, Eq)
423{-!
424deriving instance Binary FnOpt
425deriving instance NFData FnOpt
426!-}
428type FnOpts = [FnOpt]
430inlinable :: FnOpts -> Bool
431inlinable = elem Inlinable
433dictionary :: FnOpts -> Bool
434dictionary = elem Dictionary
437-- | Data declaration options
438data DataOpt = Codata -- Set if the the data-type is coinductive
439 | DefaultEliminator -- Set if an eliminator should be generated for data type
440 | DataErrRev
441 deriving (Show, Eq)
443type DataOpts = [DataOpt]
445-- | Type provider - what to provide
446data ProvideWhat = ProvTerm -- ^ only allow providing terms
447 | ProvPostulate -- ^ only allow postulates
448 | ProvAny -- ^ either is ok
449 deriving (Show, Eq)
451-- | Top-level declarations such as compiler directives, definitions,
452-- datatypes and typeclasses.
453data PDecl' t
454 = PFix FC Fixity [String] -- ^ Fixity declaration
455 | PTy Docstring [(Name, Docstring)] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
456 | PPostulate Docstring SyntaxInfo FC FnOpts Name t -- ^ Postulate
457 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
458 | PCAF FC Name t -- ^ Top level constant
459 | PData Docstring [(Name, Docstring)] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
460 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
461 | PNamespace String [PDecl' t] -- ^ New namespace
462 | PRecord Docstring SyntaxInfo FC Name t Docstring Name t -- ^ Record declaration
463 | PClass Docstring SyntaxInfo FC
464 [t] -- constraints
465 Name
466 [(Name, t)] -- parameters
467 [PDecl' t] -- declarations
468 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
469 -- class name, parameters, method declarations
470 | PInstance SyntaxInfo FC [t] -- constraints
471 Name -- class
472 [t] -- parameters
473 t -- full instance type
474 (Maybe Name) -- explicit name
475 [PDecl' t]
476 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
477 -- class name, parameters, full instance type, optional explicit name, and definitions
478 | PDSL Name (DSL' t) -- ^ DSL declaration
479 | PSyntax FC Syntax -- ^ Syntax definition
480 | PMutual FC [PDecl' t] -- ^ Mutual block
481 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
482 | PProvider SyntaxInfo FC ProvideWhat Name t t -- ^ Type provider. The first t is the type, the second is the term
483 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
484 -- bool is True, lhs and rhs must be convertible
485 deriving Functor
486{-!
487deriving instance Binary PDecl'
488deriving instance NFData PDecl'
489!-}
491-- For elaborator state
492type ElabD a = Elab' [PDecl] a
494-- | One clause of a top-level definition. Term arguments to constructors are:
495--
496-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
497--
498-- 2. The list of extra 'with' patterns
499--
500-- 3. The right-hand side
501--
502-- 4. The where block (PDecl' t)
504data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
505 | PWith FC Name t [t] t [PDecl' t]
506 | PClauseR FC [t] t [PDecl' t]
507 | PWithR FC [t] t [PDecl' t]
508 deriving Functor
509{-!
510deriving instance Binary PClause'
511deriving instance NFData PClause'
512!-}
514-- | Data declaration
515data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
516 d_tcon :: t, -- ^ Type constructor
517 d_cons :: [(Docstring, [(Name, Docstring)], Name, t, FC, [Name])] -- ^ Constructors
518 }
519 -- ^ Data declaration
520 | PLaterdecl { d_name :: Name, d_tcon :: t }
521 -- ^ "Placeholder" for data whose constructors are defined later
522 deriving Functor
523{-!
524deriving instance Binary PData'
525deriving instance NFData PData'
526!-}
528-- Handy to get a free function for applying PTerm -> PTerm functions
529-- across a program, by deriving Functor
531type PDecl = PDecl' PTerm
532type PData = PData' PTerm
533type PClause = PClause' PTerm
535-- get all the names declared in a decl
537declared :: PDecl -> [Name]
538declared (PFix _ _ _) = []
539declared (PTy _ _ _ _ _ n t) = [n]
540declared (PPostulate _ _ _ _ n t) = [n]
541declared (PClauses _ _ n _) = [] -- not a declaration
542declared (PCAF _ n _) = [n]
543declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
544 where fstt (_, _, a, _, _, _) = a
545declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
546declared (PParams _ _ ds) = concatMap declared ds
547declared (PNamespace _ ds) = concatMap declared ds
548declared (PRecord _ _ _ n _ _ c _) = [n, c]
549declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
550declared (PInstance _ _ _ _ _ _ _ _) = []
551declared (PDSL n _) = [n]
552declared (PSyntax _ _) = []
553declared (PMutual _ ds) = concatMap declared ds
554declared (PDirective _) = []
556-- get the names declared, not counting nested parameter blocks
557tldeclared :: PDecl -> [Name]
558tldeclared (PFix _ _ _) = []
559tldeclared (PTy _ _ _ _ _ n t) = [n]
560tldeclared (PPostulate _ _ _ _ n t) = [n]
561tldeclared (PClauses _ _ n _) = [] -- not a declaration
562tldeclared (PRecord _ _ _ n _ _ c _) = [n, c]
563tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
564 where fstt (_, _, a, _, _, _) = a
565tldeclared (PParams _ _ ds) = []
566tldeclared (PMutual _ ds) = concatMap tldeclared ds
567tldeclared (PNamespace _ ds) = concatMap tldeclared ds
568tldeclared (PClass _ _ _ _ n _ ms) = concatMap tldeclared ms
569tldeclared (PInstance _ _ _ _ _ _ _ _) = []
570tldeclared _ = []
572defined :: PDecl -> [Name]
573defined (PFix _ _ _) = []
574defined (PTy _ _ _ _ _ n t) = []
575defined (PPostulate _ _ _ _ n t) = []
576defined (PClauses _ _ n _) = [n] -- not a declaration
577defined (PCAF _ n _) = [n]
578defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
579 where fstt (_, _, a, _, _, _) = a
580defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
581defined (PParams _ _ ds) = concatMap defined ds
582defined (PNamespace _ ds) = concatMap defined ds
583defined (PRecord _ _ _ n _ _ c _) = [n, c]
584defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
585defined (PInstance _ _ _ _ _ _ _ _) = []
586defined (PDSL n _) = [n]
587defined (PSyntax _ _) = []
588defined (PMutual _ ds) = concatMap defined ds
589defined (PDirective _) = []
590--defined _ = []
592updateN :: [(Name, Name)] -> Name -> Name
593updateN ns n | Just n' <- lookup n ns = n'
594updateN _ n = n
596updateNs :: [(Name, Name)] -> PTerm -> PTerm
597updateNs [] t = t
598updateNs ns t = mapPT updateRef t
599 where updateRef (PRef fc f) = PRef fc (updateN ns f)
600 updateRef t = t
602-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
603-- updateDNs [] t = t
604-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
605-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
606-- where updateCNs ns (PClause n l ts r ds)
607-- = PClause (updateN ns n) (fmap (updateNs ns) l)
608-- (map (fmap (updateNs ns)) ts)
609-- (fmap (updateNs ns) r)
610-- (map (updateDNs ns) ds)
611-- updateDNs ns c = c
613data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
615-- | High level language terms
616data PTerm = PQuote Raw
617 | PRef FC Name
618 | PInferRef FC Name -- ^ A name to be defined later
619 | PPatvar FC Name
620 | PLam Name PTerm PTerm
621 | PPi Plicity Name PTerm PTerm
622 | PLet Name PTerm PTerm PTerm
623 | PTyped PTerm PTerm -- ^ Term with explicit type
624 | PApp FC PTerm [PArg]
625 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
626 | PMatchApp FC Name -- ^ Make an application by type matching
627 | PCase FC PTerm [(PTerm, PTerm)]
628 | PTrue FC PunInfo
629 | PFalse FC
630 | PRefl FC PTerm
631 | PResolveTC FC
632 | PEq FC PTerm PTerm
633 | PRewrite FC PTerm PTerm (Maybe PTerm)
634 | PPair FC PunInfo PTerm PTerm
635 | PDPair FC PunInfo PTerm PTerm PTerm
636 | PAlternative Bool [PTerm] -- True if only one may work
637 | PHidden PTerm -- ^ Irrelevant or hidden pattern
638 | PType
639 | PGoal FC PTerm Name PTerm
640 | PConstant Const
641 | Placeholder
642 | PDoBlock [PDo]
643 | PIdiom FC PTerm
644 | PReturn FC
645 | PMetavar Name
646 | PProof [PTactic] -- ^ Proof script
647 | PTactics [PTactic] -- ^ As PProof, but no auto solving
648 | PElabError Err -- ^ Error to report on elaboration
649 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
650 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
651 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
652 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
653 | PNoImplicits PTerm -- ^ never run implicit converions on the term
654 deriving Eq
657{-!
658deriving instance Binary PTerm
659deriving instance NFData PTerm
660!-}
662mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
663mapPT f t = f (mpt t) where
664 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
665 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
666 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
667 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
668 (fmap (mapPT f) g)
669 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
670 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
671 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
672 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
673 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
674 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
675 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
676 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
677 mpt (PHidden t) = PHidden (mapPT f t)
678 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
679 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
680 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
681 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
682 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
683 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
684 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
685 mpt x = x
688data PTactic' t = Intro [Name] | Intros | Focus Name
689 | Refine Name [Bool] | Rewrite t
690 | Induction Name
691 | Equiv t
692 | MatchRefine Name
693 | LetTac Name t | LetTacTy Name t t
694 | Exact t | Compute | Trivial | TCInstance
695 | ProofSearch (Maybe Name) [Name]
696 | Solve
697 | Attack
698 | ProofState | ProofTerm | Undo
699 | Try (PTactic' t) (PTactic' t)
700 | TSeq (PTactic' t) (PTactic' t)
701 | ApplyTactic t -- see Language.Reflection module
702 | ByReflection t
703 | Reflect t
704 | Fill t
705 | GoalType String (PTactic' t)
706 | TCheck t
707 | TEval t
708 | Qed | Abandon
709 deriving (Show, Eq, Functor)
710{-!
711deriving instance Binary PTactic'
712deriving instance NFData PTactic'
713!-}
714instance Sized a => Sized (PTactic' a) where
715 size (Intro nms) = 1 + size nms
716 size Intros = 1
717 size (Focus nm) = 1 + size nm
718 size (Refine nm bs) = 1 + size nm + length bs
719 size (Rewrite t) = 1 + size t
720 size (Induction t) = 1 + size t
721 size (LetTac nm t) = 1 + size nm + size t
722 size (Exact t) = 1 + size t
723 size Compute = 1
724 size Trivial = 1
725 size Solve = 1
726 size Attack = 1
727 size ProofState = 1
728 size ProofTerm = 1
729 size Undo = 1
730 size (Try l r) = 1 + size l + size r
731 size (TSeq l r) = 1 + size l + size r
732 size (ApplyTactic t) = 1 + size t
733 size (Reflect t) = 1 + size t
734 size (Fill t) = 1 + size t
735 size Qed = 1
736 size Abandon = 1
738type PTactic = PTactic' PTerm
740data PDo' t = DoExp FC t
741 | DoBind FC Name t
742 | DoBindP FC t t [(t,t)]
743 | DoLet FC Name t t
744 | DoLetP FC t t
745 deriving (Eq, Functor)
746{-!
747deriving instance Binary PDo'
748deriving instance NFData PDo'
749!-}
751instance Sized a => Sized (PDo' a) where
752 size (DoExp fc t) = 1 + size fc + size t
753 size (DoBind fc nm t) = 1 + size fc + size nm + size t
754 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
755 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
756 size (DoLetP fc l r) = 1 + size fc + size l + size r
758type PDo = PDo' PTerm
760-- The priority gives a hint as to elaboration order. Best to elaborate
761-- things early which will help give a more concrete type to other
762-- variables, e.g. a before (interpTy a).
764data PArg' t = PImp { priority :: Int,
765 machine_inf :: Bool, -- true if the machine inferred it
766 argopts :: [ArgOpt],
767 pname :: Name, getTm :: t }
768 | PExp { priority :: Int,
769 argopts :: [ArgOpt],
770 getTm :: t }
771 | PConstraint { priority :: Int,
772 argopts :: [ArgOpt],
773 getTm :: t }
774 | PTacImplicit { priority :: Int,
775 argopts :: [ArgOpt],
776 pname :: Name,
777 getScript :: t,
778 getTm :: t }
779 deriving (Show, Eq, Functor)
781data ArgOpt = Lazy | HideDisplay
782 deriving (Show, Eq)
784lazyarg :: PArg' t -> Bool
785lazyarg tm = Lazy `elem` argopts tm
787instance Sized a => Sized (PArg' a) where
788 size (PImp p _ l nm trm) = 1 + size nm + size trm
789 size (PExp p l trm) = 1 + size trm
790 size (PConstraint p l trm) = 1 + size trm
791 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
793{-!
794deriving instance Binary PArg'
795deriving instance NFData PArg'
796!-}
798pimp n t mach = PImp 1 mach [Lazy] n t
799pexp t = PExp 1 [] t
800pconst t = PConstraint 1 [] t
801ptacimp n s t = PTacImplicit 2 [Lazy] n s t
803type PArg = PArg' PTerm
805-- Type class data
807data ClassInfo = CI { instanceName :: Name,
808 class_methods :: [(Name, (FnOpts, PTerm))],
809 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
810 class_default_superclasses :: [PDecl],
811 class_params :: [Name],
812 class_instances :: [Name] }
813 deriving Show
814{-!
815deriving instance Binary ClassInfo
816deriving instance NFData ClassInfo
817!-}
819-- Type inference data
821data TIData = TIPartial -- ^ a function with a partially defined type
822 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
823 deriving Show
825-- An argument is conditionally forceable iff its forceability
826-- depends on the collapsibility of the whole type.
827data Forceability = Conditional | Unconditional deriving (Show, Enum, Bounded, Eq, Ord)
829{-!
830deriving instance Binary Forceability
831deriving instance NFData Forceability
832!-}
834data OptInfo = Optimise { collapsible :: Bool,
835 isnewtype :: Bool,
836 -- The following should actually be (IntMap Forceability)
837 -- but the corresponding Binary instance seems to be broken.
838 -- Let's store a list and convert it to IntMap whenever needed.
839 forceable :: [(Int, Forceability)],
840 recursive :: [Int] }
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 let open = if Lazy `elem` l then text "|" <> lparen else lparen in
1114 bracket p 2 . group $
1115 enclose open rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1116 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1117 | otherwise =
1118 bracket p 2 . group $
1119 group (prettySe 0 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1120 where
1121 st =
1122 case s of
1123 Static -> text "[static]" <> space
1124 _ -> empty
1125 prettySe p bnd (PPi (Imp l s _) n ty sc)
1126 | impl =
1127 let open = if Lazy `elem` l then text "|" <> lbrace else lbrace in
1128 bracket p 2 $
1129 open <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1130 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1131 | otherwise = prettySe 10 ((n, True):bnd) sc
1132 where
1133 st =
1134 case s of
1135 Static -> text "[static]" <> space
1136 _ -> empty
1137 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1138 bracket p 2 $
1139 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1140 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1141 bracket p 2 $
1142 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1143 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1144 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1145 | UN nm <- basename f
1146 , not impl && null (getExps args) = if isAlpha (thead nm)
1147 then prettyName impl bnd f
1148 else enclose lparen rparen $
1149 prettyName impl bnd f
1150 prettySe p bnd (PAppBind _ (PRef _ f) [])
1151 | not impl = text "!" <> prettyName impl bnd f
1152 prettySe p bnd (PApp _ (PRef _ op) args)
1153 | UN nm <- basename op
1154 , not (tnull nm) &&
1155 (not impl) && (not $ isAlpha (thead nm)) =
1156 case getExps args of
1157 [] -> enclose lparen rparen opName
1158 [x] -> group (enclose lparen rparen opName <$> group (prettySe 0 bnd x))
1159 [l,r] -> bracket p 1 $ inFix l r
1160 (l:r:rest) -> bracket p 1 $
1161 enclose lparen rparen (inFix l r) <+>
1162 align (group (vsep (map (prettyArgSe bnd) rest)))
1163 where opName = prettyName impl bnd op
1164 inFix l r = align . group $
1165 (prettySe 1 bnd l <+> opName) <$> group (prettySe 0 bnd r)
1166 prettySe p bnd (PApp _ hd@(PRef fc f) [tm])
1167 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1168 f == sUN "Symbol_" = char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1169 prettySe p bnd (PApp _ f as) =
1170 let args = getExps as
1171 fp = prettySe 1 bnd f
1172 in
1173 bracket p 1 . group $
1174 if impl
1175 then if null as
1176 then fp
1177 else fp <+> align (vsep (map (prettyArgS bnd) as))
1178 else if null args
1179 then fp
1180 else fp <+> align (vsep (map (prettyArgSe bnd) args))
1181 prettySe p bnd (PCase _ scr opts) =
1182 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1183 where
1184 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1186 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1187 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1188 prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
1189 prettySe p bnd (PResolveTC _) = text "resolvetc"
1190 prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1191 prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1192 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1193 prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
1194 prettySe p bnd (PEq _ l r) =
1195 bracket p 2 . align . group $
1196 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1197 where eq = annName eqTy (text "=")
1198 prettySe p bnd (PRewrite _ l r _) =
1199 bracket p 2 $
1200 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1201 prettySe p bnd (PTyped l r) =
1202 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1203 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1204 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1205 align . group . vsep . punctuate (ann comma) $
1206 map (prettySe 10 bnd) elts
1207 where ann = case pun of
1208 TypeOrTerm -> id
1209 IsType -> annName pairTy
1210 IsTerm -> annName pairCon
1211 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1212 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1213 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1214 annName sigmaTy lparen <>
1215 bindingOf n False <+>
1216 annName sigmaTy (text "**") <+>
1217 prettySe 10 ((n, False):bnd) r <>
1218 annName sigmaTy rparen
1219 prettySe p bnd (PDPair _ IsType l t r) =
1220 annName sigmaTy lparen <>
1221 prettySe 10 bnd l <+>
1222 annName sigmaTy (text "**") <+>
1223 prettySe 10 bnd r <>
1224 annName sigmaTy rparen
1225 prettySe p bnd (PDPair _ IsTerm l t r) =
1226 annName existsCon lparen <>
1227 prettySe 10 bnd l <+>
1228 annName existsCon (text "**") <+>
1229 prettySe 10 bnd r <>
1230 annName existsCon rparen
1231 prettySe p bnd (PAlternative a as) =
1232 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1233 where
1234 prettyAs =
1235 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1236 prettySe p bnd PType = annotate AnnConstType $ text "Type"
1237 prettySe p bnd (PConstant c) = annotate (annot c) (text (show c))
1238 where annot (AType _) = AnnConstType
1239 annot StrType = AnnConstType
1240 annot PtrType = AnnConstType
1241 annot VoidType = AnnConstType
1242 annot _ = AnnConstData
1243 -- XXX: add pretty for tactics
1244 prettySe p bnd (PProof ts) =
1245 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1246 prettySe p bnd (PTactics ts) =
1247 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1248 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1249 prettySe p bnd (PReturn f) = kwd "return"
1250 prettySe p bnd PImpossible = kwd "impossible"
1251 prettySe p bnd Placeholder = text "_"
1252 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1253 prettySe p bnd (PElabError s) = pretty s
1255 prettySe p bnd _ = text "test"
1257 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1258 prettyArgS bnd (PExp _ _ tm) = prettyArgSe bnd tm
1259 prettyArgS bnd (PConstraint _ _ tm) = prettyArgSc bnd tm
1260 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1262 prettyArgSe bnd arg = prettySe 0 bnd arg
1263 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1264 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1265 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1267 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1268 annName n = annotate (AnnName n Nothing Nothing Nothing)
1270 basename :: Name -> Name
1271 basename (NS n _) = basename n
1272 basename n = n
1274 slist' p bnd (PApp _ (PRef _ nil) _)
1275 | not impl && nsroot nil == sUN "Nil" = Just []
1276 slist' p bnd (PRef _ nil)
1277 | not impl && nsroot nil == sUN "Nil" = Just []
1278 slist' p bnd (PApp _ (PRef _ cons) args)
1279 | nsroot cons == sUN "::",
1280 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1281 all isImp imps,
1282 Just tl' <- slist' p bnd tl
1283 = Just (hd:tl')
1284 where
1285 isImp (PImp {}) = True
1286 isImp _ = False
1287 slist' _ _ tm = Nothing
1289 slist p bnd e | Just es <- slist' p bnd e = Just $
1290 case es of [] -> annotate AnnConstData $ text "[]"
1291 [x] -> enclose left right . group $
1292 prettySe p bnd x
1293 xs -> (enclose left right .
1294 align . group . vsep .
1295 punctuate comma .
1296 map (prettySe p bnd)) xs
1297 where left = (annotate AnnConstData (text "["))
1298 right = (annotate AnnConstData (text "]"))
1299 comma = (annotate AnnConstData (text ","))
1300 slist _ _ _ = Nothing
1302 pairElts :: PTerm -> Maybe [PTerm]
1303 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1304 | otherwise = Just [x, y]
1305 pairElts _ = Nothing
1307 natns = "Prelude.Nat."
1309 snat p (PRef _ z)
1310 | show z == (natns++"Z") || show z == "Z" = Just 0
1311 snat p (PApp _ s [PExp {getTm=n}])
1312 | show s == (natns++"S") || show s == "S",
1313 Just n' <- snat p n
1314 = Just $ 1 + n'
1315 snat _ _ = Nothing
1317 bracket outer inner doc
1318 | inner > outer = lparen <> doc <> rparen
1319 | otherwise = doc
1321 kwd = annotate AnnKeyword . text
1323-- | Pretty-printer helper for the binding site of a name
1324bindingOf :: Name -- ^^ the bound name
1325 -> Bool -- ^^ whether the name is implicit
1326 -> Doc OutputAnnotation
1327bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1329-- | Pretty-printer helper for names that attaches the correct annotations
1330prettyName :: Bool -- ^^ whether to show namespaces
1331 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1332 -> Name -- ^^ the name to pprint
1333 -> Doc OutputAnnotation
1334prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1335 | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
1336 where strName (UN n) = T.unpack n
1337 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1338 | otherwise = strName n
1339 strName (MN i s) = T.unpack s
1340 strName other = show other
1343showCImp :: Bool -> PClause -> Doc OutputAnnotation
1344showCImp impl (PClause _ n l ws r w)
1345 = prettyImp impl l <+> showWs ws <+> text "=" <+> prettyImp impl r
1346 <+> text "where" <+> text (show w)
1347 where
1348 showWs [] = empty
1349 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1350showCImp impl (PWith _ n l ws r w)
1351 = prettyImp impl l <+> showWs ws <+> text "with" <+> prettyImp impl r
1352 <+> braces (text (show w))
1353 where
1354 showWs [] = empty
1355 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1358showDImp :: Bool -> PData -> Doc OutputAnnotation
1359showDImp impl (PDatadecl n ty cons)
1360 = text "data" <+> text (show n) <+> colon <+> prettyImp impl ty <+> text "where" <$>
1361 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp impl t) cons))
1363showDecls :: Bool -> [PDecl] -> Doc OutputAnnotation
1364showDecls i ds = vsep (map (showDeclImp i) ds)
1366showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1367showDeclImp i (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp i t
1368showDeclImp i (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1369 indent 2 (vsep (map (showCImp i) cs))
1370showDeclImp _ (PData _ _ _ _ _ d) = showDImp True d
1371showDeclImp i (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls i ps <> line)
1372showDeclImp i (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls i ps <> line)
1373showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1374showDeclImp i (PClass _ _ _ cs n ps ds)
1375 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls i ds
1376showDeclImp i (PInstance _ _ cs n _ t _ ds)
1377 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp i t <> line <> showDecls i ds
1378showDeclImp _ _ = text "..."
1379-- showDeclImp (PImport i) = "import " ++ i
1381instance Show (Doc OutputAnnotation) where
1382 show = flip (displayS . renderCompact) ""
1384getImps :: [PArg] -> [(Name, PTerm)]
1385getImps [] = []
1386getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1387getImps (_ : xs) = getImps xs
1389getExps :: [PArg] -> [PTerm]
1390getExps [] = []
1391getExps (PExp _ _ tm : xs) = tm : getExps xs
1392getExps (_ : xs) = getExps xs
1394getConsts :: [PArg] -> [PTerm]
1395getConsts [] = []
1396getConsts (PConstraint _ _ tm : xs) = tm : getConsts xs
1397getConsts (_ : xs) = getConsts xs
1399getAll :: [PArg] -> [PTerm]
1400getAll = map getTm
1403-- | Show Idris name
1404showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1405 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1406 -> Bool -- ^^ whether to show implicits
1407 -> Bool -- ^^ whether to colourise
1408 -> Name -- ^^ the term to show
1409 -> String
1410showName ist bnd impl colour n = case ist of
1411 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1412 Nothing -> showbasic n
1413 where name = if impl then show n else showbasic n
1414 showbasic n@(UN _) = showCG n
1415 showbasic (MN _ s) = str s
1416 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1417 showbasic (SN s) = show s
1418 fst3 (x, _, _) = x
1419 colourise n t = let ctxt' = fmap tt_ctxt ist in
1420 case ctxt' of
1421 Nothing -> name
1422 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1423 else colouriseBound t name
1424 | isDConName n ctxt -> colouriseData t name
1425 | isFnName n ctxt -> colouriseFun t name
1426 | isTConName n ctxt -> colouriseType t name
1427 -- The assumption is that if a name is not bound and does not exist in the
1428 -- global context, then we're somewhere in which implicit info has been lost
1429 -- (like error messages). Thus, unknown vars are colourised as implicits.
1430 | otherwise -> colouriseImplicit t name
1432showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1433 -> PTerm -- ^^ the term to show
1434 -> String
1435showTm ist = displayDecorated (consoleDecorate ist) . renderCompact . 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
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 _ n ty sc) = 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-- Return all names defined in binders in the given term
1507boundNamesIn :: PTerm -> [Name]
1508boundNamesIn tm = nub $ ni tm
1509 where
1510 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1511 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1512 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1513 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1514 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1515 ni (PPi _ n ty sc) = n : (ni ty ++ ni sc)
1516 ni (PEq _ l r) = ni l ++ ni r
1517 ni (PRewrite _ l r _) = ni l ++ ni r
1518 ni (PTyped l r) = ni l ++ ni r
1519 ni (PPair _ _ l r) = ni l ++ ni r
1520 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1521 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1522 ni (PAlternative a as) = concatMap (ni) as
1523 ni (PHidden tm) = ni tm
1524 ni (PUnifyLog tm) = ni tm
1525 ni (PDisamb _ tm) = ni tm
1526 ni (PNoImplicits tm) = ni tm
1527 ni _ = []
1529-- Return names which are free in the given term.
1530namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1531namesIn uvars ist tm = nub $ ni [] tm
1532 where
1533 ni env (PRef _ n)
1534 | not (n `elem` env)
1535 = case lookupTy n (tt_ctxt ist) of
1536 [] -> [n]
1537 _ -> if n `elem` (map fst uvars) then [n] else []
1538 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1539 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1540 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1541 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1542 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1543 ni env (PEq _ l r) = ni env l ++ ni env r
1544 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1545 ni env (PTyped l r) = ni env l ++ ni env r
1546 ni env (PPair _ _ l r) = ni env l ++ ni env r
1547 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1548 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1549 ni env (PAlternative a as) = concatMap (ni env) as
1550 ni env (PHidden tm) = ni env tm
1551 ni env (PUnifyLog tm) = ni env tm
1552 ni env (PDisamb _ tm) = ni env tm
1553 ni env (PNoImplicits tm) = ni env tm
1554 ni env _ = []
1556-- Return which of the given names are used in the given term.
1558usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1559usedNamesIn vars ist tm = nub $ ni [] tm
1560 where
1561 ni env (PRef _ n)
1562 | n `elem` vars && not (n `elem` env)
1563 = case lookupTy n (tt_ctxt ist) of
1564 [] -> [n]
1565 _ -> []
1566 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1567 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1568 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1569 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1570 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1571 ni env (PEq _ l r) = ni env l ++ ni env r
1572 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1573 ni env (PTyped l r) = ni env l ++ ni env r
1574 ni env (PPair _ _ l r) = ni env l ++ ni env r
1575 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1576 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1577 ni env (PAlternative a as) = concatMap (ni env) as
1578 ni env (PHidden tm) = ni env tm
1579 ni env (PUnifyLog tm) = ni env tm
1580 ni env (PDisamb _ tm) = ni env tm
1581 ni env (PNoImplicits tm) = ni env tm
1582 ni env _ = []