on bfe6499 help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1647 lines 65 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 | Missing Name
289 | DynamicLink FilePath
290 | ListDynamic
291 | Pattelab PTerm
292 | DebugInfo Name
293 | Search PTerm
294 | CaseSplitAt Bool Int Name
295 | AddClauseFrom Bool Int Name
296 | AddProofClauseFrom Bool Int Name
297 | AddMissing Bool Int Name
298 | MakeWith Bool Int Name
299 | DoProofSearch Bool -- ^ update
300 Bool -- ^ recursive (i.e. do arguments too)
301 Int Name [Name]
302 | SetOpt Opt
303 | UnsetOpt Opt
304 | NOP
305 | SetColour ColourType IdrisColour
306 | ColourOn
307 | ColourOff
308 | ListErrorHandlers
309 | SetConsoleWidth ConsoleWidth
310 | Apropos String
311 | WhoCalls Name
312 | CallsWho Name
313 | MakeDoc String -- IdrisDoc
316data Opt = Filename String
317 | Ver
318 | Usage
319 | Quiet
320 | NoBanner
321 | ColourREPL Bool
322 | Ideslave
323 | ShowLibs
324 | ShowLibdir
325 | ShowIncs
326 | NoBasePkgs
327 | NoPrelude
328 | NoBuiltins -- only for the really primitive stuff!
329 | NoREPL
330 | OLogging Int
331 | Output String
332 | TypeCase
333 | TypeInType
334 | DefaultTotal
335 | DefaultPartial
336 | WarnPartial
337 | WarnReach
338 | NoCoverage
339 | ErrContext
340 | ShowImpl
341 | Verbose
342 | IBCSubDir String
343 | ImportDir String
344 | PkgBuild String
345 | PkgInstall String
346 | PkgClean String
347 | PkgCheck String
348 | PkgREPL String
349 | PkgMkDoc String -- IdrisDoc
350 | WarnOnly
351 | Pkg String
352 | BCAsm String
353 | DumpDefun String
354 | DumpCases String
355 | UseCodegen Codegen
356 | OutputTy OutputType
357 | Extension LanguageExt
358 | InterpretScript String
359 | EvalExpr String
360 | TargetTriple String
361 | TargetCPU String
362 | OptLevel Word
363 | Client String
364 | ShowOrigErr
365 | AutoWidth -- ^ Automatically adjust terminal width
366 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
367 deriving (Show, Eq)
369-- Parsed declarations
371data Fixity = Infixl { prec :: Int }
372 | Infixr { prec :: Int }
373 | InfixN { prec :: Int }
374 | PrefixN { prec :: Int }
375 deriving Eq
376{-!
377deriving instance Binary Fixity
378deriving instance NFData Fixity
379!-}
381instance Show Fixity where
382 show (Infixl i) = "infixl " ++ show i
383 show (Infixr i) = "infixr " ++ show i
384 show (InfixN i) = "infix " ++ show i
385 show (PrefixN i) = "prefix " ++ show i
387data FixDecl = Fix Fixity String
388 deriving Eq
390instance Show FixDecl where
391 show (Fix f s) = show f ++ " " ++ s
393{-!
394deriving instance Binary FixDecl
395deriving instance NFData FixDecl
396!-}
398instance Ord FixDecl where
399 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
402data Static = Static | Dynamic
403 deriving (Show, Eq)
404{-!
405deriving instance Binary Static
406deriving instance NFData Static
407!-}
409-- Mark bindings with their explicitness, and laziness
410data Plicity = Imp { pargopts :: [ArgOpt],
411 pstatic :: Static,
412 pparam :: Bool }
413 | Exp { pargopts :: [ArgOpt],
414 pstatic :: Static,
415 pparam :: Bool } -- this is a param (rather than index)
416 | Constraint { pargopts :: [ArgOpt],
417 pstatic :: Static }
418 | TacImp { pargopts :: [ArgOpt],
419 pstatic :: Static,
420 pscript :: PTerm }
421 deriving (Show, Eq)
423{-!
424deriving instance Binary Plicity
425deriving instance NFData Plicity
426!-}
428impl = Imp [] Dynamic False
429expl = Exp [] Dynamic False
430expl_param = Exp [] Dynamic True
431constraint = Constraint [] Dynamic
432tacimpl t = TacImp [] Dynamic t
434data FnOpt = Inlinable -- always evaluate when simplifying
435 | TotalFn | PartialFn | CoveringFn
436 | Coinductive | AssertTotal
437 | Dictionary -- type class dictionary, eval only when
438 -- a function argument, and further evaluation resutls
439 | Implicit -- implicit coercion
440 | CExport String -- export, with a C name
441 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
442 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
443 | Reflection -- a reflecting function, compile-time only
444 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
445 deriving (Show, Eq)
446{-!
447deriving instance Binary FnOpt
448deriving instance NFData FnOpt
449!-}
451type FnOpts = [FnOpt]
453inlinable :: FnOpts -> Bool
454inlinable = elem Inlinable
456dictionary :: FnOpts -> Bool
457dictionary = elem Dictionary
460-- | Data declaration options
461data DataOpt = Codata -- Set if the the data-type is coinductive
462 | DefaultEliminator -- Set if an eliminator should be generated for data type
463 | DataErrRev
464 deriving (Show, Eq)
466type DataOpts = [DataOpt]
468-- | Type provider - what to provide
469data ProvideWhat = ProvTerm -- ^ only allow providing terms
470 | ProvPostulate -- ^ only allow postulates
471 | ProvAny -- ^ either is ok
472 deriving (Show, Eq)
474-- | Top-level declarations such as compiler directives, definitions,
475-- datatypes and typeclasses.
476data PDecl' t
477 = PFix FC Fixity [String] -- ^ Fixity declaration
478 | PTy Docstring [(Name, Docstring)] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
479 | PPostulate Docstring SyntaxInfo FC FnOpts Name t -- ^ Postulate
480 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
481 | PCAF FC Name t -- ^ Top level constant
482 | PData Docstring [(Name, Docstring)] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
483 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
484 | PNamespace String [PDecl' t] -- ^ New namespace
485 | PRecord Docstring SyntaxInfo FC Name t DataOpts Docstring Name t -- ^ Record declaration
486 | PClass Docstring SyntaxInfo FC
487 [t] -- constraints
488 Name
489 [(Name, t)] -- parameters
490 [(Name, Docstring)] -- parameter docstrings
491 [PDecl' t] -- declarations
492 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
493 -- class name, parameters, method declarations
494 | PInstance SyntaxInfo FC [t] -- constraints
495 Name -- class
496 [t] -- parameters
497 t -- full instance type
498 (Maybe Name) -- explicit name
499 [PDecl' t]
500 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
501 -- class name, parameters, full instance type, optional explicit name, and definitions
502 | PDSL Name (DSL' t) -- ^ DSL declaration
503 | PSyntax FC Syntax -- ^ Syntax definition
504 | PMutual FC [PDecl' t] -- ^ Mutual block
505 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
506 | PProvider SyntaxInfo FC ProvideWhat Name t t -- ^ Type provider. The first t is the type, the second is the term
507 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
508 -- bool is True, lhs and rhs must be convertible
509 deriving Functor
510{-!
511deriving instance Binary PDecl'
512deriving instance NFData PDecl'
513!-}
515-- For elaborator state
516type ElabD a = Elab' [PDecl] a
518-- | One clause of a top-level definition. Term arguments to constructors are:
519--
520-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
521--
522-- 2. The list of extra 'with' patterns
523--
524-- 3. The right-hand side
525--
526-- 4. The where block (PDecl' t)
528data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
529 | PWith FC Name t [t] t [PDecl' t]
530 | PClauseR FC [t] t [PDecl' t]
531 | PWithR FC [t] t [PDecl' t]
532 deriving Functor
533{-!
534deriving instance Binary PClause'
535deriving instance NFData PClause'
536!-}
538-- | Data declaration
539data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
540 d_tcon :: t, -- ^ Type constructor
541 d_cons :: [(Docstring, [(Name, Docstring)], Name, t, FC, [Name])] -- ^ Constructors
542 }
543 -- ^ Data declaration
544 | PLaterdecl { d_name :: Name, d_tcon :: t }
545 -- ^ "Placeholder" for data whose constructors are defined later
546 deriving Functor
547{-!
548deriving instance Binary PData'
549deriving instance NFData PData'
550!-}
552-- Handy to get a free function for applying PTerm -> PTerm functions
553-- across a program, by deriving Functor
555type PDecl = PDecl' PTerm
556type PData = PData' PTerm
557type PClause = PClause' PTerm
559-- get all the names declared in a decl
561declared :: PDecl -> [Name]
562declared (PFix _ _ _) = []
563declared (PTy _ _ _ _ _ n t) = [n]
564declared (PPostulate _ _ _ _ n t) = [n]
565declared (PClauses _ _ n _) = [] -- not a declaration
566declared (PCAF _ n _) = [n]
567declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
568 where fstt (_, _, a, _, _, _) = a
569declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
570declared (PParams _ _ ds) = concatMap declared ds
571declared (PNamespace _ ds) = concatMap declared ds
572declared (PRecord _ _ _ n _ _ _ c _) = [n, c]
573declared (PClass _ _ _ _ n _ _ ms) = n : concatMap declared ms
574declared (PInstance _ _ _ _ _ _ _ _) = []
575declared (PDSL n _) = [n]
576declared (PSyntax _ _) = []
577declared (PMutual _ ds) = concatMap declared ds
578declared (PDirective _) = []
580-- get the names declared, not counting nested parameter blocks
581tldeclared :: PDecl -> [Name]
582tldeclared (PFix _ _ _) = []
583tldeclared (PTy _ _ _ _ _ n t) = [n]
584tldeclared (PPostulate _ _ _ _ n t) = [n]
585tldeclared (PClauses _ _ n _) = [] -- not a declaration
586tldeclared (PRecord _ _ _ n _ _ _ c _) = [n, c]
587tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
588 where fstt (_, _, a, _, _, _) = a
589tldeclared (PParams _ _ ds) = []
590tldeclared (PMutual _ ds) = concatMap tldeclared ds
591tldeclared (PNamespace _ ds) = concatMap tldeclared ds
592tldeclared (PClass _ _ _ _ n _ _ ms) = concatMap tldeclared ms
593tldeclared (PInstance _ _ _ _ _ _ _ _) = []
594tldeclared _ = []
596defined :: PDecl -> [Name]
597defined (PFix _ _ _) = []
598defined (PTy _ _ _ _ _ n t) = []
599defined (PPostulate _ _ _ _ n t) = []
600defined (PClauses _ _ n _) = [n] -- not a declaration
601defined (PCAF _ n _) = [n]
602defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
603 where fstt (_, _, a, _, _, _) = a
604defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
605defined (PParams _ _ ds) = concatMap defined ds
606defined (PNamespace _ ds) = concatMap defined ds
607defined (PRecord _ _ _ n _ _ _ c _) = [n, c]
608defined (PClass _ _ _ _ n _ _ ms) = n : concatMap defined ms
609defined (PInstance _ _ _ _ _ _ _ _) = []
610defined (PDSL n _) = [n]
611defined (PSyntax _ _) = []
612defined (PMutual _ ds) = concatMap defined ds
613defined (PDirective _) = []
614--defined _ = []
616updateN :: [(Name, Name)] -> Name -> Name
617updateN ns n | Just n' <- lookup n ns = n'
618updateN _ n = n
620updateNs :: [(Name, Name)] -> PTerm -> PTerm
621updateNs [] t = t
622updateNs ns t = mapPT updateRef t
623 where updateRef (PRef fc f) = PRef fc (updateN ns f)
624 updateRef t = t
626-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
627-- updateDNs [] t = t
628-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
629-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
630-- where updateCNs ns (PClause n l ts r ds)
631-- = PClause (updateN ns n) (fmap (updateNs ns) l)
632-- (map (fmap (updateNs ns)) ts)
633-- (fmap (updateNs ns) r)
634-- (map (updateDNs ns) ds)
635-- updateDNs ns c = c
637data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
639-- | High level language terms
640data PTerm = PQuote Raw
641 | PRef FC Name
642 | PInferRef FC Name -- ^ A name to be defined later
643 | PPatvar FC Name
644 | PLam Name PTerm PTerm
645 | PPi Plicity Name PTerm PTerm -- ^ (n : t1) -> t2
646 | PLet Name PTerm PTerm PTerm
647 | PTyped PTerm PTerm -- ^ Term with explicit type
648 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
649 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
650 | PMatchApp FC Name -- ^ Make an application by type matching
651 | PCase FC PTerm [(PTerm, PTerm)]
652 | PTrue FC PunInfo -- ^ Unit type..?
653 | PFalse FC -- ^ _|_
654 | PRefl FC PTerm
655 | PResolveTC FC
656 | PEq FC PTerm PTerm -- ^ Equality type: A = B
657 | PRewrite FC PTerm PTerm (Maybe PTerm)
658 | PPair FC PunInfo PTerm PTerm
659 | PDPair FC PunInfo PTerm PTerm PTerm
660 | PAlternative Bool [PTerm] -- True if only one may work
661 | PHidden PTerm -- ^ Irrelevant or hidden pattern
662 | PType -- ^ 'Type' type
663 | PGoal FC PTerm Name PTerm
664 | PConstant Const -- ^ Builtin types
665 | Placeholder
666 | PDoBlock [PDo]
667 | PIdiom FC PTerm
668 | PReturn FC
669 | PMetavar Name
670 | PProof [PTactic] -- ^ Proof script
671 | PTactics [PTactic] -- ^ As PProof, but no auto solving
672 | PElabError Err -- ^ Error to report on elaboration
673 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
674 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
675 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
676 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
677 | PNoImplicits PTerm -- ^ never run implicit converions on the term
678 deriving Eq
681{-!
682deriving instance Binary PTerm
683deriving instance NFData PTerm
684!-}
686mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
687mapPT f t = f (mpt t) where
688 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
689 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
690 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
691 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
692 (fmap (mapPT f) g)
693 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
694 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
695 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
696 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
697 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
698 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
699 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
700 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
701 mpt (PHidden t) = PHidden (mapPT f t)
702 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
703 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
704 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
705 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
706 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
707 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
708 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
709 mpt x = x
712data PTactic' t = Intro [Name] | Intros | Focus Name
713 | Refine Name [Bool] | Rewrite t | DoUnify
714 | Induction Name
715 | Equiv t
716 | MatchRefine Name
717 | LetTac Name t | LetTacTy Name t t
718 | Exact t | Compute | Trivial | TCInstance
719 | ProofSearch Bool -- ^ recursive
720 (Maybe Name) [Name]
721 | Solve
722 | Attack
723 | ProofState | ProofTerm | Undo
724 | Try (PTactic' t) (PTactic' t)
725 | TSeq (PTactic' t) (PTactic' t)
726 | ApplyTactic t -- see Language.Reflection module
727 | ByReflection t
728 | Reflect t
729 | Fill t
730 | GoalType String (PTactic' t)
731 | TCheck t
732 | TEval t
733 | Qed | Abandon
734 deriving (Show, Eq, Functor)
735{-!
736deriving instance Binary PTactic'
737deriving instance NFData PTactic'
738!-}
739instance Sized a => Sized (PTactic' a) where
740 size (Intro nms) = 1 + size nms
741 size Intros = 1
742 size (Focus nm) = 1 + size nm
743 size (Refine nm bs) = 1 + size nm + length bs
744 size (Rewrite t) = 1 + size t
745 size (Induction t) = 1 + size t
746 size (LetTac nm t) = 1 + size nm + size t
747 size (Exact t) = 1 + size t
748 size Compute = 1
749 size Trivial = 1
750 size Solve = 1
751 size Attack = 1
752 size ProofState = 1
753 size ProofTerm = 1
754 size Undo = 1
755 size (Try l r) = 1 + size l + size r
756 size (TSeq l r) = 1 + size l + size r
757 size (ApplyTactic t) = 1 + size t
758 size (Reflect t) = 1 + size t
759 size (Fill t) = 1 + size t
760 size Qed = 1
761 size Abandon = 1
763type PTactic = PTactic' PTerm
765data PDo' t = DoExp FC t
766 | DoBind FC Name t
767 | DoBindP FC t t [(t,t)]
768 | DoLet FC Name t t
769 | DoLetP FC t t
770 deriving (Eq, Functor)
771{-!
772deriving instance Binary PDo'
773deriving instance NFData PDo'
774!-}
776instance Sized a => Sized (PDo' a) where
777 size (DoExp fc t) = 1 + size fc + size t
778 size (DoBind fc nm t) = 1 + size fc + size nm + size t
779 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
780 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
781 size (DoLetP fc l r) = 1 + size fc + size l + size r
783type PDo = PDo' PTerm
785-- The priority gives a hint as to elaboration order. Best to elaborate
786-- things early which will help give a more concrete type to other
787-- variables, e.g. a before (interpTy a).
789data PArg' t = PImp { priority :: Int,
790 machine_inf :: Bool, -- true if the machine inferred it
791 argopts :: [ArgOpt],
792 pname :: Name, getTm :: t }
793 | PExp { priority :: Int,
794 argopts :: [ArgOpt],
795 pname :: Name,
796 getTm :: t }
797 | PConstraint { priority :: Int,
798 argopts :: [ArgOpt],
799 pname :: Name,
800 getTm :: t }
801 | PTacImplicit { priority :: Int,
802 argopts :: [ArgOpt],
803 pname :: Name,
804 getScript :: t,
805 getTm :: t }
806 deriving (Show, Eq, Functor)
808data ArgOpt = HideDisplay | InaccessibleArg
809 deriving (Show, Eq)
811instance Sized a => Sized (PArg' a) where
812 size (PImp p _ l nm trm) = 1 + size nm + size trm
813 size (PExp p l nm trm) = 1 + size nm + size trm
814 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
815 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
817{-!
818deriving instance Binary PArg'
819deriving instance NFData PArg'
820!-}
822pimp n t mach = PImp 1 mach [] n t
823pexp t = PExp 1 [] (sMN 0 "arg") t
824pconst t = PConstraint 1 [] (sMN 0 "carg") t
825ptacimp n s t = PTacImplicit 2 [] n s t
827type PArg = PArg' PTerm
829-- Type class data
831data ClassInfo = CI { instanceName :: Name,
832 class_methods :: [(Name, (FnOpts, PTerm))],
833 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
834 class_default_superclasses :: [PDecl],
835 class_params :: [Name],
836 class_instances :: [Name] }
837 deriving Show
838{-!
839deriving instance Binary ClassInfo
840deriving instance NFData ClassInfo
841!-}
843-- Type inference data
845data TIData = TIPartial -- ^ a function with a partially defined type
846 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
847 deriving Show
849data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
850 detaggable :: Bool }
851 deriving Show
852{-!
853deriving instance Binary OptInfo
854deriving instance NFData OptInfo
855!-}
858data TypeInfo = TI { con_names :: [Name],
859 codata :: Bool,
860 data_opts :: DataOpts,
861 param_pos :: [Int] }
862 deriving Show
863{-!
864deriving instance Binary TypeInfo
865deriving instance NFData TypeInfo
866!-}
868-- Syntactic sugar info
870data DSL' t = DSL { dsl_bind :: t,
871 dsl_return :: t,
872 dsl_apply :: t,
873 dsl_pure :: t,
874 dsl_var :: Maybe t,
875 index_first :: Maybe t,
876 index_next :: Maybe t,
877 dsl_lambda :: Maybe t,
878 dsl_let :: Maybe t
879 }
880 deriving (Show, Functor)
881{-!
882deriving instance Binary DSL'
883deriving instance NFData DSL'
884!-}
886type DSL = DSL' PTerm
888data SynContext = PatternSyntax | TermSyntax | AnySyntax
889 deriving Show
890{-!
891deriving instance Binary SynContext
892deriving instance NFData SynContext
893!-}
895data Syntax = Rule [SSymbol] PTerm SynContext
896 deriving Show
897{-!
898deriving instance Binary Syntax
899deriving instance NFData Syntax
900!-}
902data SSymbol = Keyword Name
903 | Symbol String
904 | Binding Name
905 | Expr Name
906 | SimpleExpr Name
907 deriving Show
908{-!
909deriving instance Binary SSymbol
910deriving instance NFData SSymbol
911!-}
913initDSL = DSL (PRef f (sUN ">>="))
914 (PRef f (sUN "return"))
915 (PRef f (sUN "<$>"))
916 (PRef f (sUN "pure"))
917 Nothing
918 Nothing
919 Nothing
920 Nothing
921 Nothing
922 where f = fileFC "(builtin)"
924data Using = UImplicit Name PTerm
925 | UConstraint Name [Name]
926 deriving (Show, Eq)
927{-!
928deriving instance Binary Using
929deriving instance NFData Using
930!-}
932data SyntaxInfo = Syn { using :: [Using],
933 syn_params :: [(Name, PTerm)],
934 syn_namespace :: [String],
935 no_imp :: [Name],
936 decoration :: Name -> Name,
937 inPattern :: Bool,
938 implicitAllowed :: Bool,
939 dsl_info :: DSL }
940 deriving Show
941{-!
942deriving instance NFData SyntaxInfo
943deriving instance Binary SyntaxInfo
944!-}
946defaultSyntax = Syn [] [] [] [] id False False initDSL
948expandNS :: SyntaxInfo -> Name -> Name
949expandNS syn n@(NS _ _) = n
950expandNS syn n = case syn_namespace syn of
951 [] -> n
952 xs -> sNS n xs
955-- For inferring types of things
957bi = fileFC "builtin"
959inferTy = sMN 0 "__Infer"
960inferCon = sMN 0 "__infer"
961inferDecl = PDatadecl inferTy
962 PType
963 [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType (
964 PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType"))
965 (PRef bi inferTy)), bi, [])]
966inferOpts = []
968infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
969infP = P (TCon 6 0) inferTy (TType (UVal 0))
971getInferTerm, getInferType :: Term -> Term
972getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
973getInferTerm (App (App _ _) tm) = tm
974getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
976getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
977 where toTy (Lam t) = Pi t
978 toTy (PVar t) = PVTy t
979 toTy b = b
980getInferType (App (App _ ty) _) = ty
984-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign, Elim type class
986primNames = [unitTy, unitCon,
987 falseTy, pairTy, pairCon,
988 eqTy, eqCon, inferTy, inferCon]
990unitDoc = parseDocstring . T.pack $ "The canonical single-element type, also known as the trivially true proposition."
991unitTy = sMN 0 "__Unit"
992unitCon = sMN 0 "__II"
993unitDecl = PDatadecl unitTy PType
994 [(parseDocstring . T.pack $ "The trivial constructor for `()`. ", [], unitCon, PRef bi unitTy, bi, [])]
995unitOpts = [DefaultEliminator]
997falseDoc = parseDocstring . T.pack $
998 "The empty type, also known as the trivially false proposition." ++
999 "\n\n" ++
1000 "Use `FalseElim` or `absurd` to prove anything if you have a variable " ++
1001 "of type `_|_` in scope."
1002falseTy = sMN 0 "__False"
1003falseDecl = PDatadecl falseTy PType []
1004falseOpts = []
1006pairDoc = parseDocstring . T.pack $ "The non-dependent pair type, also known as conjunction."
1007pairTy = sMN 0 "__Pair"
1008pairCon = sMN 0 "__MkPair"
1009pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
1010 [(pairConDoc, pairConParamDoc,
1011 pairCon, PPi impl (n "A") PType (
1012 PPi impl (n "B") PType (
1013 PPi expl (n "a") (PRef bi (n "A")) (
1014 PPi expl (n "b") (PRef bi (n "B"))
1015 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
1016 pexp (PRef bi (n "B"))])))), bi, [])]
1017 where n a = sMN 0 a
1018 pairConDoc = parseDocstring . T.pack $ "A pair of elements"
1019 pairConParamDoc = [(n "a", parseDocstring . T.pack $ "the left element of the pair"),
1020 (n "b", parseDocstring . T.pack $ "the right element of the pair")]
1021pairOpts = []
1022pairParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left elements in the pair"),
1023 (n "B", parseDocstring . T.pack $ "the type of the left elements in the pair")]
1024 where n a = sMN 0 a
1026eqTy = sUN "="
1027eqCon = sUN "refl"
1028eqDoc = parseDocstring . T.pack $
1029 "The propositional equality type. A proof that `x` = `y`." ++
1030 "\n\n" ++
1031 "To use such a proof, pattern-match on it, and the two equal things will " ++
1032 "then need to be the _same_ pattern." ++
1033 "\n\n" ++
1034 "**Note**: Idris's equality type is _heterogeneous_, which means that it " ++
1035 "is possible to state equalities between values of potentially different " ++
1036 "types. This is sometimes referred to in the literature as \"John Major\" " ++
1037 "equality." ++
1038 "\n\n" ++
1039 "Thus, if Idris can't infer the type of one side of the equality, then " ++
1040 "you may need to annotate it. See the function `the`."
1042eqDecl = PDatadecl eqTy (piBind [(n "A", PType), (n "B", PType),
1043 (n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))]
1044 PType)
1045 [(reflDoc, reflParamDoc,
1046 eqCon, PPi impl (n "A") PType (
1047 PPi impl (n "x") (PRef bi (n "A"))
1048 (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False,
1049 pimp (n "B") Placeholder False,
1050 pexp (PRef bi (n "x")),
1051 pexp (PRef bi (n "x"))])), bi, [])]
1052 where n a = sMN 0 a
1053 reflDoc = parseDocstring . T.pack $
1054 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1055 "shown that both sides are in fact equal."
1056 reflParamDoc = [(n "A", parseDocstring . T.pack $ "the type at which the equality is proven"),
1057 (n "x", parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1059eqParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left side of the equality"),
1060 (n "B", parseDocstring . T.pack $ "the type of the right side of the equality")
1062 where n a = sMN 0 a
1064eqOpts = []
1066elimName = sUN "__Elim"
1067elimMethElimTy = sUN "__elimTy"
1068elimMethElim = sUN "elim"
1069elimDecl = PClass (parseDocstring . T.pack $ "Type class for eliminators") defaultSyntax bi [] elimName [(sUN "scrutineeType", PType)] []
1070 [PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElimTy PType,
1071 PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElim (PRef bi elimMethElimTy)]
1073-- Defined in builtins.idr
1074sigmaTy = sUN "Exists"
1075existsCon = sUN "Ex_intro"
1077piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1078piBind = piBindp expl
1080piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1081piBindp p [] t = t
1082piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t)
1085-- Pretty-printing declarations and terms
1087-- These "show" instances render to an absurdly wide screen because inserted line breaks
1088-- could interfere with interactive editing, which calls "show".
1090instance Show PTerm where
1091 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp False) tm
1093instance Show PDecl where
1094 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp False) d
1096instance Show PClause where
1097 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp True) c
1099instance Show PData where
1100 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp False) d
1102instance Pretty PTerm OutputAnnotation where
1103 pretty = prettyImp False
1105-- | Colourise annotations according to an Idris state. It ignores the names
1106-- in the annotation, as there's no good way to show extended information on a
1107-- terminal.
1108consoleDecorate :: IState -> OutputAnnotation -> String -> String
1109consoleDecorate ist _ | not (idris_colourRepl ist) = id
1110consoleDecorate ist AnnConstData = let theme = idris_colourTheme ist
1111 in colouriseData theme
1112consoleDecorate ist AnnConstType = let theme = idris_colourTheme ist
1113 in colouriseType theme
1114consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
1115consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
1116consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1117consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1118 theme = idris_colourTheme ist
1119 in case () of
1120 _ | isDConName n ctxt -> colouriseData theme
1121 _ | isFnName n ctxt -> colouriseFun theme
1122 _ | isTConName n ctxt -> colouriseType theme
1123 _ | otherwise -> id -- don't colourise unknown names
1124consoleDecorate ist (AnnFC _) = id
1125consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
1126 where colour BoldText = IdrisColour Nothing True False True False
1127 colour UnderlineText = IdrisColour Nothing True True False False
1128 colour ItalicText = IdrisColour Nothing True False False True
1130-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1131prettyImp :: Bool -- ^^ whether to show implicits
1132 -> PTerm -- ^^ the term to pretty-print
1133 -> Doc OutputAnnotation
1134prettyImp impl = pprintPTerm impl [] [] []
1136-- | Pretty-print a high-level Idris term in some bindings context with infix info
1137pprintPTerm :: Bool -- ^^ whether to show implicits
1138 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1139 -> [Name] -- ^^ names to always show in pi, even if not used
1140 -> [FixDecl] -- ^^ Fixity declarations
1141 -> PTerm -- ^^ the term to pretty-print
1142 -> Doc OutputAnnotation
1143pprintPTerm impl bnd docArgs infixes = prettySe 10 bnd
1144 where
1145 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1146 prettySe p bnd (PQuote r) =
1147 text "![" <> pretty r <> text "]"
1148 prettySe p bnd (PPatvar fc n) = pretty n
1149 prettySe p bnd e
1150 | Just str <- slist p bnd e = str
1151 | Just n <- snat p e = annotate AnnConstData (text (show n))
1152 prettySe p bnd (PRef fc n) = prettyName impl bnd n
1153 prettySe p bnd (PLam n ty sc) =
1154 bracket p 2 . group . align . hang 2 $
1155 text "\\" <> bindingOf n False <+> text "=>" <$>
1156 prettySe 10 ((n, False):bnd) sc
1157 prettySe p bnd (PLet n ty v sc) =
1158 bracket p 2 $
1159 kwd "let" <+> bindingOf n False <+> text "=" </>
1160 prettySe 10 bnd v <+> kwd "in" </>
1161 prettySe 10 ((n, False):bnd) sc
1162 prettySe p bnd (PPi (Exp l s _) n ty sc)
1163 | n `elem` allNamesIn sc || impl || n `elem` docArgs =
1164 bracket p 2 . group $
1165 enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1166 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1167 | otherwise =
1168 bracket p 2 . group $
1169 group (prettySe 0 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1170 where
1171 st =
1172 case s of
1173 Static -> text "[static]" <> space
1174 _ -> empty
1175 prettySe p bnd (PPi (Imp l s _) n ty sc)
1176 | impl =
1177 bracket p 2 $
1178 lbrace <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1179 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1180 | otherwise = prettySe 10 ((n, True):bnd) sc
1181 where
1182 st =
1183 case s of
1184 Static -> text "[static]" <> space
1185 _ -> empty
1186 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1187 bracket p 2 $
1188 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1189 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1190 bracket p 2 $
1191 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1192 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1193 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1194 | UN nm <- basename f
1195 , not impl && null (getExps args) = if isAlpha (thead nm)
1196 then prettyName impl bnd f
1197 else enclose lparen rparen $
1198 prettyName impl bnd f
1199 prettySe p bnd (PAppBind _ (PRef _ f) [])
1200 | not impl = text "!" <> prettyName impl bnd f
1201 prettySe p bnd (PApp _ (PRef _ op) args)
1202 | UN nm <- basename op
1203 , not (tnull nm) &&
1204 (not impl) && (not $ isAlpha (thead nm)) =
1205 case getExps args of
1206 [] -> enclose lparen rparen opName
1207 [x] -> group (enclose lparen rparen opName <$> group (prettySe 0 bnd x))
1208 [l,r] -> bracket p 1 $ inFix l r
1209 (l:r:rest) -> bracket p 1 $
1210 enclose lparen rparen (inFix l r) <+>
1211 align (group (vsep (map (prettyArgSe bnd) rest)))
1212 where opName = prettyName impl bnd op
1213 inFix l r = align . group $
1214 (prettySe 1 bnd l <+> opName) <$> group (prettySe 0 bnd r)
1215 prettySe p bnd (PApp _ hd@(PRef fc f) [tm])
1216 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1217 f == sUN "Symbol_" = char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1218 prettySe p bnd (PApp _ f as) =
1219 let args = getExps as
1220 fp = prettySe 1 bnd f
1221 in
1222 bracket p 1 . group $
1223 if impl
1224 then if null as
1225 then fp
1226 else fp <+> align (vsep (map (prettyArgS bnd) as))
1227 else if null args
1228 then fp
1229 else fp <+> align (vsep (map (prettyArgSe bnd) args))
1230 prettySe p bnd (PCase _ scr opts) =
1231 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1232 where
1233 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1235 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1236 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1237 prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
1238 prettySe p bnd (PResolveTC _) = text "resolvetc"
1239 prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1240 prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1241 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1242 prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
1243 prettySe p bnd (PEq _ l r) =
1244 bracket p 2 . align . group $
1245 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1246 where eq = annName eqTy (text "=")
1247 prettySe p bnd (PRewrite _ l r _) =
1248 bracket p 2 $
1249 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1250 prettySe p bnd (PTyped l r) =
1251 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1252 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1253 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1254 align . group . vsep . punctuate (ann comma) $
1255 map (prettySe 10 bnd) elts
1256 where ann = case pun of
1257 TypeOrTerm -> id
1258 IsType -> annName pairTy
1259 IsTerm -> annName pairCon
1260 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1261 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1262 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1263 annName sigmaTy lparen <>
1264 bindingOf n False <+>
1265 annName sigmaTy (text "**") <+>
1266 prettySe 10 ((n, False):bnd) r <>
1267 annName sigmaTy rparen
1268 prettySe p bnd (PDPair _ IsType l t r) =
1269 annName sigmaTy lparen <>
1270 prettySe 10 bnd l <+>
1271 annName sigmaTy (text "**") <+>
1272 prettySe 10 bnd r <>
1273 annName sigmaTy rparen
1274 prettySe p bnd (PDPair _ IsTerm l t r) =
1275 annName existsCon lparen <>
1276 prettySe 10 bnd l <+>
1277 annName existsCon (text "**") <+>
1278 prettySe 10 bnd r <>
1279 annName existsCon rparen
1280 prettySe p bnd (PAlternative a as) =
1281 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1282 where
1283 prettyAs =
1284 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1285 prettySe p bnd PType = annotate AnnConstType $ text "Type"
1286 prettySe p bnd (PConstant c) = annotate (annot c) (text (show c))
1287 where annot (AType _) = AnnConstType
1288 annot StrType = AnnConstType
1289 annot PtrType = AnnConstType
1290 annot VoidType = AnnConstType
1291 annot _ = AnnConstData
1292 -- XXX: add pretty for tactics
1293 prettySe p bnd (PProof ts) =
1294 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1295 prettySe p bnd (PTactics ts) =
1296 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1297 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1298 prettySe p bnd (PReturn f) = kwd "return"
1299 prettySe p bnd PImpossible = kwd "impossible"
1300 prettySe p bnd Placeholder = text "_"
1301 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1302 prettySe p bnd (PElabError s) = pretty s
1304 prettySe p bnd _ = text "test"
1306 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1307 prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm
1308 prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm
1309 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1311 prettyArgSe bnd arg = prettySe 0 bnd arg
1312 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1313 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1314 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1316 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1317 annName n = annotate (AnnName n Nothing Nothing Nothing)
1319 basename :: Name -> Name
1320 basename (NS n _) = basename n
1321 basename n = n
1323 slist' p bnd (PApp _ (PRef _ nil) _)
1324 | not impl && nsroot nil == sUN "Nil" = Just []
1325 slist' p bnd (PRef _ nil)
1326 | not impl && nsroot nil == sUN "Nil" = Just []
1327 slist' p bnd (PApp _ (PRef _ cons) args)
1328 | nsroot cons == sUN "::",
1329 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1330 all isImp imps,
1331 Just tl' <- slist' p bnd tl
1332 = Just (hd:tl')
1333 where
1334 isImp (PImp {}) = True
1335 isImp _ = False
1336 slist' _ _ tm = Nothing
1338 slist p bnd e | Just es <- slist' p bnd e = Just $
1339 case es of [] -> annotate AnnConstData $ text "[]"
1340 [x] -> enclose left right . group $
1341 prettySe p bnd x
1342 xs -> (enclose left right .
1343 align . group . vsep .
1344 punctuate comma .
1345 map (prettySe p bnd)) xs
1346 where left = (annotate AnnConstData (text "["))
1347 right = (annotate AnnConstData (text "]"))
1348 comma = (annotate AnnConstData (text ","))
1349 slist _ _ _ = Nothing
1351 pairElts :: PTerm -> Maybe [PTerm]
1352 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1353 | otherwise = Just [x, y]
1354 pairElts _ = Nothing
1356 natns = "Prelude.Nat."
1358 snat p (PRef _ z)
1359 | show z == (natns++"Z") || show z == "Z" = Just 0
1360 snat p (PApp _ s [PExp {getTm=n}])
1361 | show s == (natns++"S") || show s == "S",
1362 Just n' <- snat p n
1363 = Just $ 1 + n'
1364 snat _ _ = Nothing
1366 bracket outer inner doc
1367 | inner > outer = lparen <> doc <> rparen
1368 | otherwise = doc
1370 kwd = annotate AnnKeyword . text
1372-- | Pretty-printer helper for the binding site of a name
1373bindingOf :: Name -- ^^ the bound name
1374 -> Bool -- ^^ whether the name is implicit
1375 -> Doc OutputAnnotation
1376bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1378-- | Pretty-printer helper for names that attaches the correct annotations
1379prettyName :: Bool -- ^^ whether to show namespaces
1380 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1381 -> Name -- ^^ the name to pprint
1382 -> Doc OutputAnnotation
1383prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1384 | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
1385 where strName (UN n) = T.unpack n
1386 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1387 | otherwise = strName n
1388 strName n | n == falseTy = "_|_"
1389 strName (MN i s) = T.unpack s
1390 strName other = show other
1393showCImp :: Bool -> PClause -> Doc OutputAnnotation
1394showCImp impl (PClause _ n l ws r w)
1395 = prettyImp impl l <+> showWs ws <+> text "=" <+> prettyImp impl r
1396 <+> text "where" <+> text (show w)
1397 where
1398 showWs [] = empty
1399 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1400showCImp impl (PWith _ n l ws r w)
1401 = prettyImp impl l <+> showWs ws <+> text "with" <+> prettyImp impl r
1402 <+> braces (text (show w))
1403 where
1404 showWs [] = empty
1405 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1408showDImp :: Bool -> PData -> Doc OutputAnnotation
1409showDImp impl (PDatadecl n ty cons)
1410 = text "data" <+> text (show n) <+> colon <+> prettyImp impl ty <+> text "where" <$>
1411 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp impl t) cons))
1413showDecls :: Bool -> [PDecl] -> Doc OutputAnnotation
1414showDecls i ds = vsep (map (showDeclImp i) ds)
1416showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1417showDeclImp i (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp i t
1418showDeclImp i (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1419 indent 2 (vsep (map (showCImp i) cs))
1420showDeclImp _ (PData _ _ _ _ _ d) = showDImp True d
1421showDeclImp i (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls i ps <> line)
1422showDeclImp i (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls i ps <> line)
1423showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1424showDeclImp i (PClass _ _ _ cs n ps _ ds)
1425 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls i ds
1426showDeclImp i (PInstance _ _ cs n _ t _ ds)
1427 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp i t <> line <> showDecls i ds
1428showDeclImp _ _ = text "..."
1429-- showDeclImp (PImport i) = "import " ++ i
1431instance Show (Doc OutputAnnotation) where
1432 show = flip (displayS . renderCompact) ""
1434getImps :: [PArg] -> [(Name, PTerm)]
1435getImps [] = []
1436getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1437getImps (_ : xs) = getImps xs
1439getExps :: [PArg] -> [PTerm]
1440getExps [] = []
1441getExps (PExp _ _ _ tm : xs) = tm : getExps xs
1442getExps (_ : xs) = getExps xs
1444getConsts :: [PArg] -> [PTerm]
1445getConsts [] = []
1446getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
1447getConsts (_ : xs) = getConsts xs
1449getAll :: [PArg] -> [PTerm]
1450getAll = map getTm
1453-- | Show Idris name
1454showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1455 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1456 -> Bool -- ^^ whether to show implicits
1457 -> Bool -- ^^ whether to colourise
1458 -> Name -- ^^ the term to show
1459 -> String
1460showName ist bnd impl colour n = case ist of
1461 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1462 Nothing -> showbasic n
1463 where name = if impl then show n else showbasic n
1464 showbasic n@(UN _) = showCG n
1465 showbasic (MN _ s) = str s
1466 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1467 showbasic (SN s) = show s
1468 fst3 (x, _, _) = x
1469 colourise n t = let ctxt' = fmap tt_ctxt ist in
1470 case ctxt' of
1471 Nothing -> name
1472 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1473 else colouriseBound t name
1474 | isDConName n ctxt -> colouriseData t name
1475 | isFnName n ctxt -> colouriseFun t name
1476 | isTConName n ctxt -> colouriseType t name
1477 -- The assumption is that if a name is not bound and does not exist in the
1478 -- global context, then we're somewhere in which implicit info has been lost
1479 -- (like error messages). Thus, unknown vars are colourised as implicits.
1480 | otherwise -> colouriseImplicit t name
1482showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1483 -> PTerm -- ^^ the term to show
1484 -> String
1485showTm ist = displayDecorated (consoleDecorate ist) .
1486 renderPretty 0.8 100000 .
1487 prettyImp (opt_showimp (idris_options ist))
1489-- | Show a term with implicits, no colours
1490showTmImpls :: PTerm -> String
1491showTmImpls = flip (displayS . renderCompact . prettyImp True) ""
1494instance Sized PTerm where
1495 size (PQuote rawTerm) = size rawTerm
1496 size (PRef fc name) = size name
1497 size (PLam name ty bdy) = 1 + size ty + size bdy
1498 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1499 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1500 size (PTyped trm ty) = 1 + size trm + size ty
1501 size (PApp fc name args) = 1 + size args
1502 size (PAppBind fc name args) = 1 + size args
1503 size (PCase fc trm bdy) = 1 + size trm + size bdy
1504 size (PTrue fc _) = 1
1505 size (PFalse fc) = 1
1506 size (PRefl fc _) = 1
1507 size (PResolveTC fc) = 1
1508 size (PEq fc left right) = 1 + size left + size right
1509 size (PRewrite fc left right _) = 1 + size left + size right
1510 size (PPair fc _ left right) = 1 + size left + size right
1511 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1512 size (PAlternative a alts) = 1 + size alts
1513 size (PHidden hidden) = size hidden
1514 size (PUnifyLog tm) = size tm
1515 size (PDisamb _ tm) = size tm
1516 size (PNoImplicits tm) = size tm
1517 size PType = 1
1518 size (PConstant const) = 1 + size const
1519 size Placeholder = 1
1520 size (PDoBlock dos) = 1 + size dos
1521 size (PIdiom fc term) = 1 + size term
1522 size (PReturn fc) = 1
1523 size (PMetavar name) = 1
1524 size (PProof tactics) = size tactics
1525 size (PElabError err) = size err
1526 size PImpossible = 1
1528getPArity :: PTerm -> Int
1529getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1530getPArity _ = 0
1532-- Return all names, free or globally bound, in the given term.
1534allNamesIn :: PTerm -> [Name]
1535allNamesIn tm = nub $ ni [] tm
1536 where -- TODO THINK added niTacImp, but is it right?
1537 ni env (PRef _ n)
1538 | not (n `elem` env) = [n]
1539 ni env (PPatvar _ n) = [n]
1540 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1541 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1542 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1543 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1544 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1545 ni env (PHidden tm) = ni env tm
1546 ni env (PEq _ l r) = ni env l ++ ni env r
1547 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1548 ni env (PTyped l r) = ni env l ++ ni env r
1549 ni env (PPair _ _ l r) = ni env l ++ ni env r
1550 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1551 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1552 ni env (PAlternative a ls) = concatMap (ni env) ls
1553 ni env (PUnifyLog tm) = ni env tm
1554 ni env (PDisamb _ tm) = ni env tm
1555 ni env (PNoImplicits tm) = ni env tm
1556 ni env _ = []
1558 niTacImp env (TacImp _ _ scr) = ni env scr
1559 niTacImp _ _ = []
1561-- Return all names defined in binders in the given term
1562boundNamesIn :: PTerm -> [Name]
1563boundNamesIn tm = nub $ ni tm
1564 where -- TODO THINK Added niTacImp, but is it right?
1565 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1566 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1567 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1568 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1569 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1570 ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc))
1571 ni (PEq _ l r) = ni l ++ ni r
1572 ni (PRewrite _ l r _) = ni l ++ ni r
1573 ni (PTyped l r) = ni l ++ ni r
1574 ni (PPair _ _ l r) = ni l ++ ni r
1575 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1576 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1577 ni (PAlternative a as) = concatMap (ni) as
1578 ni (PHidden tm) = ni tm
1579 ni (PUnifyLog tm) = ni tm
1580 ni (PDisamb _ tm) = ni tm
1581 ni (PNoImplicits tm) = ni tm
1582 ni _ = []
1584 niTacImp (TacImp _ _ scr) = ni scr
1585 niTacImp _ = []
1587-- Return names which are free in the given term.
1588namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1589namesIn uvars ist tm = nub $ ni [] tm
1590 where
1591 ni env (PRef _ n)
1592 | not (n `elem` env)
1593 = case lookupTy n (tt_ctxt ist) of
1594 [] -> [n]
1595 _ -> if n `elem` (map fst uvars) then [n] else []
1596 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1597 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1598 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1599 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1600 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1601 ni env (PEq _ l r) = ni env l ++ ni env r
1602 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1603 ni env (PTyped l r) = ni env l ++ ni env r
1604 ni env (PPair _ _ l r) = ni env l ++ ni env r
1605 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1606 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1607 ni env (PAlternative a as) = concatMap (ni env) as
1608 ni env (PHidden tm) = ni env tm
1609 ni env (PUnifyLog tm) = ni env tm
1610 ni env (PDisamb _ tm) = ni env tm
1611 ni env (PNoImplicits tm) = ni env tm
1612 ni env _ = []
1614 niTacImp env (TacImp _ _ scr) = ni env scr
1615 niTacImp _ _ = []
1617-- Return which of the given names are used in the given term.
1619usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1620usedNamesIn vars ist tm = nub $ ni [] tm
1621 where -- TODO THINK added niTacImp, but is it right?
1622 ni env (PRef _ n)
1623 | n `elem` vars && not (n `elem` env)
1624 = case lookupDefExact n (tt_ctxt ist) of
1625 Nothing -> [n]
1626 _ -> []
1627 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1628 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1629 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1630 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1631 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1632 ni env (PEq _ l r) = ni env l ++ ni env r
1633 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1634 ni env (PTyped l r) = ni env l ++ ni env r
1635 ni env (PPair _ _ l r) = ni env l ++ ni env r
1636 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1637 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1638 ni env (PAlternative a as) = concatMap (ni env) as
1639 ni env (PHidden tm) = ni env tm
1640 ni env (PUnifyLog tm) = ni env tm
1641 ni env (PDisamb _ tm) = ni env tm
1642 ni env (PNoImplicits tm) = ni env tm
1643 ni env _ = []
1645 niTacImp env (TacImp _ _ scr) = ni env scr
1646 niTacImp _ _ = []