on ebbae35 help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
2402 lines 105 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 DeriveDataTypeable, 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 System.Console.Haskeline
19import System.IO
21import Prelude hiding ((<$>))
23import Control.Applicative ((<|>))
25import Control.Monad.Trans.State.Strict
26import Control.Monad.Trans.Except
27import qualified Control.Monad.Trans.Class as Trans (lift)
29import Data.Data (Data)
30import Data.Function (on)
31import Data.Generics.Uniplate.Data (universe, children)
32import Data.List hiding (group)
33import Data.Char
34import qualified Data.Map.Strict as M
35import qualified Data.Text as T
36import Data.Either
37import qualified Data.Set as S
38import Data.Word (Word)
39import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
40import Data.Traversable (Traversable)
41import Data.Typeable
42import Data.Foldable (Foldable)
44import Debug.Trace
46import Text.PrettyPrint.Annotated.Leijen
48data ElabWhat = ETypes | EDefns | EAll
49 deriving (Show, Eq)
51-- Data to pass to recursively called elaborators; e.g. for where blocks,
52-- paramaterised declarations, etc.
54-- rec_elabDecl is used to pass the top level elaborator into other elaborators,
55-- so that we can have mutually recursive elaborators in separate modules without
56-- having to muck about with cyclic modules.
57data ElabInfo = EInfo { params :: [(Name, PTerm)],
58 inblock :: Ctxt [Name], -- names in the block, and their params
59 liftname :: Name -> Name,
60 namespace :: Maybe [String],
61 elabFC :: Maybe FC,
62 rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl ->
63 Idris () }
65toplevel :: ElabInfo
66toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented")
68eInfoNames :: ElabInfo -> [Name]
69eInfoNames info = map fst (params info) ++ M.keys (inblock info)
71data IOption = IOption { opt_logLevel :: Int,
72 opt_typecase :: Bool,
73 opt_typeintype :: Bool,
74 opt_coverage :: Bool,
75 opt_showimp :: Bool, -- ^^ show implicits
76 opt_errContext :: Bool,
77 opt_repl :: Bool,
78 opt_verbose :: Bool,
79 opt_nobanner :: Bool,
80 opt_quiet :: Bool,
81 opt_codegen :: Codegen,
82 opt_outputTy :: OutputType,
83 opt_ibcsubdir :: FilePath,
84 opt_importdirs :: [FilePath],
85 opt_triple :: String,
86 opt_cpu :: String,
87 opt_cmdline :: [Opt], -- remember whole command line
88 opt_origerr :: Bool,
89 opt_autoSolve :: Bool, -- ^ automatically apply "solve" tactic in prover
90 opt_autoImport :: [FilePath], -- ^ e.g. Builtins+Prelude
91 opt_optimise :: [Optimisation],
92 opt_printdepth :: Maybe Int,
93 opt_evaltypes :: Bool, -- ^ normalise types in :t
94 opt_desugarnats :: Bool
95 }
96 deriving (Show, Eq)
98defaultOpts = IOption { opt_logLevel = 0
99 , opt_typecase = False
100 , opt_typeintype = False
101 , opt_coverage = True
102 , opt_showimp = False
103 , opt_errContext = False
104 , opt_repl = True
105 , opt_verbose = True
106 , opt_nobanner = False
107 , opt_quiet = False
108 , opt_codegen = Via "c"
109 , opt_outputTy = Executable
110 , opt_ibcsubdir = ""
111 , opt_importdirs = []
112 , opt_triple = ""
113 , opt_cpu = ""
114 , opt_cmdline = []
115 , opt_origerr = False
116 , opt_autoSolve = True
117 , opt_autoImport = []
118 , opt_optimise = defaultOptimise
119 , opt_printdepth = Just 5000
120 , opt_evaltypes = True
121 , opt_desugarnats = False
122 }
124data PPOption = PPOption {
125 ppopt_impl :: Bool -- ^^ whether to show implicits
126 , ppopt_desugarnats :: Bool
127 , ppopt_pinames :: Bool -- ^^ whether to show names in pi bindings
128 , ppopt_depth :: Maybe Int
129} deriving (Show)
131data Optimisation = PETransform -- partial eval and associated transforms
132 deriving (Show, Eq)
134defaultOptimise = [PETransform]
136-- | Pretty printing options with default verbosity.
137defaultPPOption :: PPOption
138defaultPPOption = PPOption { ppopt_impl = False,
139 ppopt_desugarnats = False,
140 ppopt_pinames = False,
141 ppopt_depth = Just 200 }
143-- | Pretty printing options with the most verbosity.
144verbosePPOption :: PPOption
145verbosePPOption = PPOption { ppopt_impl = True,
146 ppopt_desugarnats = True,
147 ppopt_pinames = True,
148 ppopt_depth = Just 200 }
150-- | Get pretty printing options from the big options record.
151ppOption :: IOption -> PPOption
152ppOption opt = PPOption {
153 ppopt_impl = opt_showimp opt,
154 ppopt_pinames = False,
155 ppopt_depth = opt_printdepth opt,
156 ppopt_desugarnats = opt_desugarnats opt
159-- | Get pretty printing options from an idris state record.
160ppOptionIst :: IState -> PPOption
161ppOptionIst = ppOption . idris_options
163data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
165-- | The output mode in use
166data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle
167 | IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle
168 deriving Show
170-- | How wide is the console?
171data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
172 | ColsWide Int -- ^ Manually specified - must be positive
173 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
174 deriving (Show, Eq)
177-- | The global state used in the Idris monad
178data IState = IState {
179 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
180 idris_constraints :: S.Set ConstraintFC,
181 -- ^ A list of universe constraints and their corresponding source locations
182 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
183 idris_implicits :: Ctxt [PArg],
184 idris_statics :: Ctxt [Bool],
185 idris_classes :: Ctxt ClassInfo,
186 idris_records :: Ctxt RecordInfo,
187 idris_dsls :: Ctxt DSL,
188 idris_optimisation :: Ctxt OptInfo,
189 idris_datatypes :: Ctxt TypeInfo,
190 idris_namehints :: Ctxt [Name],
191 idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
192 -- ^ list of lhs/rhs, and a list of missing clauses
193 idris_flags :: Ctxt [FnOpt],
194 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
195 idris_calledgraph :: Ctxt [Name],
196 idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]),
197 idris_moduledocs :: Ctxt (Docstring DocTerm),
198 -- ^ module documentation is saved in a special MN so the context
199 -- mechanism can be used for disambiguation
200 idris_tyinfodata :: Ctxt TIData,
201 idris_fninfo :: Ctxt FnInfo,
202 idris_transforms :: Ctxt [(Term, Term)],
203 idris_autohints :: Ctxt [Name],
204 idris_totcheck :: [(FC, Name)], -- names to check totality on
205 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
206 idris_totcheckfail :: [(FC, String)],
207 idris_options :: IOption,
208 idris_name :: Int,
209 idris_lineapps :: [((FilePath, Int), PTerm)],
210 -- ^ Full application LHS on source line
211 idris_metavars :: [(Name, (Maybe Name, Int, [Name], Bool))],
212 -- ^ The currently defined but not proven metavariables. The Int
213 -- is the number of vars to display as a context, the Maybe Name
214 -- is its top-level function, the [Name] is the list of local variables
215 -- available for proof search and the Bool is whether :p is
216 -- allowed
217 idris_coercions :: [Name],
218 idris_errRev :: [(Term, Term)],
219 syntax_rules :: SyntaxRules,
220 syntax_keywords :: [String],
221 imported :: [FilePath], -- ^ The imported modules
222 idris_scprims :: [(Name, (Int, PrimFn))],
223 idris_objs :: [(Codegen, FilePath)],
224 idris_libs :: [(Codegen, String)],
225 idris_cgflags :: [(Codegen, String)],
226 idris_hdrs :: [(Codegen, String)],
227 idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public
228 proof_list :: [(Name, (Bool, [String]))],
229 errSpan :: Maybe FC,
230 parserWarnings :: [(FC, Err)],
231 lastParse :: Maybe Name,
232 indent_stack :: [Int],
233 brace_stack :: [Maybe Int],
234 lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
235 idris_parsedSpan :: Maybe FC,
236 hide_list :: [(Name, Maybe Accessibility)],
237 default_access :: Accessibility,
238 default_total :: Bool,
239 ibc_write :: [IBCWrite],
240 compiled_so :: Maybe String,
241 idris_dynamic_libs :: [DynamicLib],
242 idris_language_extensions :: [LanguageExt],
243 idris_outputmode :: OutputMode,
244 idris_colourRepl :: Bool,
245 idris_colourTheme :: ColourTheme,
246 idris_errorhandlers :: [Name], -- ^ Global error handlers
247 idris_nameIdx :: (Int, Ctxt (Int, Name)),
248 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
249 module_aliases :: M.Map [T.Text] [T.Text],
250 idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
251 idris_postulates :: S.Set Name,
252 idris_externs :: S.Set (Name, Int),
253 idris_erasureUsed :: [(Name, Int)], -- ^ Function/constructor name, argument position is used
254 idris_whocalls :: Maybe (M.Map Name [Name]),
255 idris_callswho :: Maybe (M.Map Name [Name]),
256 idris_repl_defs :: [Name], -- ^ List of names that were defined in the repl, and can be re-/un-defined
257 elab_stack :: [(Name, Bool)], -- ^ Stack of names currently being elaborated, Bool set if it's an instance
258 -- (instances appear twice; also as a funtion name)
259 idris_symbols :: M.Map Name Name, -- ^ Symbol table (preserves sharing of names)
260 idris_exports :: [Name], -- ^ Functions with ExportList
261 idris_highlightedRegions :: [(FC, OutputAnnotation)], -- ^ Highlighting information to output
262 idris_parserHighlights :: [(FC, OutputAnnotation)], -- ^ Highlighting information from the parser
263 idris_deprecated :: Ctxt String -- ^ Deprecated names and explanation
264 }
266-- Required for parsers library, and therefore trifecta
267instance Show IState where
268 show = const "{internal state}"
270data SizeChange = Smaller | Same | Bigger | Unknown
271 deriving (Show, Eq)
272{-!
273deriving instance Binary SizeChange
274deriving instance NFData SizeChange
275!-}
277type SCGEntry = (Name, [Maybe (Int, SizeChange)])
278type UsageReason = (Name, Int) -- fn_name, its_arg_number
280data CGInfo = CGInfo { argsdef :: [Name],
281 calls :: [(Name, [[Name]])],
282 scg :: [SCGEntry],
283 argsused :: [Name],
284 usedpos :: [(Int, [UsageReason])] }
285 deriving Show
286{-!
287deriving instance Binary CGInfo
288deriving instance NFData CGInfo
289!-}
291primDefs = [sUN "unsafePerformPrimIO",
292 sUN "mkLazyForeignPrim",
293 sUN "mkForeignPrim",
294 sUN "void"]
296-- information that needs writing for the current module's .ibc file
297data IBCWrite = IBCFix FixDecl
298 | IBCImp Name
299 | IBCStatic Name
300 | IBCClass Name
301 | IBCRecord Name
302 | IBCInstance Bool Bool Name Name
303 | IBCDSL Name
304 | IBCData Name
305 | IBCOpt Name
306 | IBCMetavar Name
307 | IBCSyntax Syntax
308 | IBCKeyword String
309 | IBCImport (Bool, FilePath) -- True = import public
310 | IBCImportDir FilePath
311 | IBCObj Codegen FilePath
312 | IBCLib Codegen String
313 | IBCCGFlag Codegen String
314 | IBCDyLib String
315 | IBCHeader Codegen String
316 | IBCAccess Name Accessibility
317 | IBCMetaInformation Name MetaInformation
318 | IBCTotal Name Totality
319 | IBCFlags Name [FnOpt]
320 | IBCFnInfo Name FnInfo
321 | IBCTrans Name (Term, Term)
322 | IBCErrRev (Term, Term)
323 | IBCCG Name
324 | IBCDoc Name
325 | IBCCoercion Name
326 | IBCDef Name -- i.e. main context
327 | IBCNameHint (Name, Name)
328 | IBCLineApp FilePath Int PTerm
329 | IBCErrorHandler Name
330 | IBCFunctionErrorHandler Name Name Name
331 | IBCPostulate Name
332 | IBCExtern (Name, Int)
333 | IBCTotCheckErr FC String
334 | IBCParsedRegion FC
335 | IBCModDocs Name -- ^ The name is the special name used to track module docs
336 | IBCUsage (Name, Int)
337 | IBCExport Name
338 | IBCAutoHint Name Name
339 | IBCDeprecate Name String
340 deriving Show
342-- | The initial state for the compiler
343idrisInit :: IState
344idrisInit = IState initContext S.empty []
345 emptyContext emptyContext emptyContext emptyContext
346 emptyContext emptyContext emptyContext emptyContext
347 emptyContext emptyContext emptyContext emptyContext
348 emptyContext emptyContext emptyContext emptyContext
349 emptyContext emptyContext
350 [] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []
351 [] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] []
352 (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty
353 AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] []
354 emptyContext
356-- | The monad for the main REPL - reading and processing files and updating
357-- global state (hence the IO inner monad).
358--type Idris = WriterT [Either String (IO ())] (State IState a))
359type Idris = StateT IState (ExceptT Err IO)
361catchError :: Idris a -> (Err -> Idris a) -> Idris a
362catchError = liftCatch catchE
364throwError :: Err -> Idris a
365throwError = Trans.lift . throwE
367-- Commands in the REPL
369data Codegen = Via String
370-- | ViaC
371-- | ViaJava
372-- | ViaNode
373-- | ViaJavaScript
374-- | ViaLLVM
375 | Bytecode
376 deriving (Show, Eq)
377{-!
378deriving instance NFData Codegen
379!-}
381data HowMuchDocs = FullDocs | OverviewDocs
383-- | REPL commands
384data Command = Quit
385 | Help
386 | Eval PTerm
387 | NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
388 | Undefine [Name]
389 | Check PTerm
390 | Core PTerm
391 | DocStr (Either Name Const) HowMuchDocs
392 | TotCheck Name
393 | Reload
394 | Load FilePath (Maybe Int) -- up to maximum line number
395 | ChangeDirectory FilePath
396 | ModImport String
397 | Edit
398 | Compile Codegen String
399 | Execute PTerm
400 | ExecVal PTerm
401 | Metavars
402 | Prove Bool Name -- ^ If false, use prover, if true, use elab shell
403 | AddProof (Maybe Name)
404 | RmProof Name
405 | ShowProof Name
406 | Proofs
407 | Universes
408 | LogLvl Int
409 | Spec PTerm
410 | WHNF PTerm
411 | TestInline PTerm
412 | Defn Name
413 | Missing Name
414 | DynamicLink FilePath
415 | ListDynamic
416 | Pattelab PTerm
417 | Search [String] PTerm
418 | CaseSplitAt Bool Int Name
419 | AddClauseFrom Bool Int Name
420 | AddProofClauseFrom Bool Int Name
421 | AddMissing Bool Int Name
422 | MakeWith Bool Int Name
423 | MakeCase Bool Int Name
424 | MakeLemma Bool Int Name
425 | DoProofSearch Bool -- update file
426 Bool -- recursive search
427 Int -- depth
428 Name -- top level name
429 [Name] -- hints
430 | SetOpt Opt
431 | UnsetOpt Opt
432 | NOP
433 | SetColour ColourType IdrisColour
434 | ColourOn
435 | ColourOff
436 | ListErrorHandlers
437 | SetConsoleWidth ConsoleWidth
438 | SetPrinterDepth (Maybe Int)
439 | Apropos [String] String
440 | WhoCalls Name
441 | CallsWho Name
442 | Browse [String]
443 | MakeDoc String -- IdrisDoc
444 | Warranty
445 | PrintDef Name
446 | PPrint OutputFmt Int PTerm
447 | TransformInfo Name
448 -- Debugging commands
449 | DebugInfo Name
450 | DebugUnify PTerm PTerm
452data OutputFmt = HTMLOutput | LaTeXOutput
454data Opt = Filename String
455 | Quiet
456 | NoBanner
457 | ColourREPL Bool
458 | Idemode
459 | IdemodeSocket
460 | ShowLibs
461 | ShowLibdir
462 | ShowIncs
463 | ShowPkgs
464 | NoBasePkgs
465 | NoPrelude
466 | NoBuiltins -- only for the really primitive stuff!
467 | NoREPL
468 | OLogging Int
469 | Output String
470 | Interface
471 | TypeCase
472 | TypeInType
473 | DefaultTotal
474 | DefaultPartial
475 | WarnPartial
476 | WarnReach
477 | EvalTypes
478 | NoCoverage
479 | ErrContext
480 | ShowImpl
481 | Verbose
482 | Port String -- REPL TCP port
483 | IBCSubDir String
484 | ImportDir String
485 | PkgBuild String
486 | PkgInstall String
487 | PkgClean String
488 | PkgCheck String
489 | PkgREPL String
490 | PkgMkDoc String -- IdrisDoc
491 | PkgTest String
492 | PkgIndex FilePath
493 | WarnOnly
494 | Pkg String
495 | BCAsm String
496 | DumpDefun String
497 | DumpCases String
498 | UseCodegen Codegen
499 | CodegenArgs String
500 | OutputTy OutputType
501 | Extension LanguageExt
502 | InterpretScript String
503 | EvalExpr String
504 | TargetTriple String
505 | TargetCPU String
506 | OptLevel Int
507 | AddOpt Optimisation
508 | RemoveOpt Optimisation
509 | Client String
510 | ShowOrigErr
511 | AutoWidth -- ^ Automatically adjust terminal width
512 | AutoSolve -- ^ Automatically issue "solve" tactic in old-style interactive prover
513 | UseConsoleWidth ConsoleWidth
514 | DumpHighlights
515 | DesugarNats
516 | NoElimDeprecationWarnings -- ^ Don't show deprecation warnings for %elim
517 | NoOldTacticDeprecationWarnings -- ^ Don't show deprecation warnings for old-style tactics
518 deriving (Show, Eq)
520data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm
521 | EEval PTerm | ECheck PTerm | ESearch PTerm
522 | EDocStr (Either Name Const)
523 deriving (Show, Eq)
525-- Parsed declarations
527data Fixity = Infixl { prec :: Int }
528 | Infixr { prec :: Int }
529 | InfixN { prec :: Int }
530 | PrefixN { prec :: Int }
531 deriving Eq
532{-!
533deriving instance Binary Fixity
534deriving instance NFData Fixity
535!-}
537instance Show Fixity where
538 show (Infixl i) = "infixl " ++ show i
539 show (Infixr i) = "infixr " ++ show i
540 show (InfixN i) = "infix " ++ show i
541 show (PrefixN i) = "prefix " ++ show i
543data FixDecl = Fix Fixity String
544 deriving Eq
546instance Show FixDecl where
547 show (Fix f s) = show f ++ " " ++ s
549{-!
550deriving instance Binary FixDecl
551deriving instance NFData FixDecl
552!-}
554instance Ord FixDecl where
555 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
558data Static = Static | Dynamic
559 deriving (Show, Eq, Data, Typeable)
560{-!
561deriving instance Binary Static
562deriving instance NFData Static
563!-}
565-- Mark bindings with their explicitness, and laziness
566data Plicity = Imp { pargopts :: [ArgOpt],
567 pstatic :: Static,
568 pparam :: Bool,
569 pscoped :: Maybe ImplicitInfo -- Nothing, if top level
570 }
571 | Exp { pargopts :: [ArgOpt],
572 pstatic :: Static,
573 pparam :: Bool } -- this is a param (rather than index)
574 | Constraint { pargopts :: [ArgOpt],
575 pstatic :: Static }
576 | TacImp { pargopts :: [ArgOpt],
577 pstatic :: Static,
578 pscript :: PTerm }
579 deriving (Show, Eq, Data, Typeable)
581{-!
582deriving instance Binary Plicity
583deriving instance NFData Plicity
584!-}
586is_scoped :: Plicity -> Maybe ImplicitInfo
587is_scoped (Imp _ _ _ s) = s
588is_scoped _ = Nothing
590impl = Imp [] Dynamic False (Just (Impl False True))
591forall_imp = Imp [] Dynamic False (Just (Impl False False))
592forall_constraint = Imp [] Dynamic False (Just (Impl True False))
593expl = Exp [] Dynamic False
594expl_param = Exp [] Dynamic True
595constraint = Constraint [] Static
596tacimpl t = TacImp [] Dynamic t
598data FnOpt = Inlinable -- always evaluate when simplifying
599 | TotalFn | PartialFn | CoveringFn
600 | Coinductive | AssertTotal
601 | Dictionary -- type class dictionary, eval only when
602 -- a function argument, and further evaluation resutls
603 | Implicit -- implicit coercion
604 | NoImplicit -- do not apply implicit coercions
605 | CExport String -- export, with a C name
606 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
607 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
608 | Reflection -- a reflecting function, compile-time only
609 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
610 | Constructor -- Data constructor type
611 | AutoHint -- use in auto implicit search
612 | PEGenerated -- generated by partial evaluator
613 deriving (Show, Eq)
614{-!
615deriving instance Binary FnOpt
616deriving instance NFData FnOpt
617!-}
619type FnOpts = [FnOpt]
621inlinable :: FnOpts -> Bool
622inlinable = elem Inlinable
624dictionary :: FnOpts -> Bool
625dictionary = elem Dictionary
628-- | Type provider - what to provide
629data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
630 | ProvPostulate t -- ^ goal type must be Type, so only term
631 deriving (Show, Eq, Functor)
633type ProvideWhat = ProvideWhat' PTerm
635-- | Top-level declarations such as compiler directives, definitions,
636-- datatypes and typeclasses.
637data PDecl' t
638 = PFix FC Fixity [String] -- ^ Fixity declaration
639 | PTy (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location)
640 | PPostulate Bool -- external def if true
641 (Docstring (Either Err t)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location
642 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
643 | PCAF FC Name t -- ^ Top level constant
644 | PData (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
645 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
646 | PNamespace String FC [PDecl' t]
647 -- ^ New namespace, where FC is accurate location of the
648 -- namespace in the file
649 | PRecord (Docstring (Either Err t)) SyntaxInfo FC DataOpts
650 Name -- Record name
651 FC -- Record name precise location
652 [(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span
653 [(Name, Docstring (Either Err t))] -- Param Docs
654 [((Maybe (Name, FC)), Plicity, t, Maybe (Docstring (Either Err t)))] -- Fields
655 (Maybe (Name, FC)) -- Optional constructor name and location
656 (Docstring (Either Err t)) -- Constructor doc
657 SyntaxInfo -- Constructor SyntaxInfo
658 -- ^ Record declaration
659 | PClass (Docstring (Either Err t)) SyntaxInfo FC
660 [(Name, t)] -- constraints
661 Name -- class name
662 FC -- accurate location of class name
663 [(Name, FC, t)] -- parameters and precise locations
664 [(Name, Docstring (Either Err t))] -- parameter docstrings
665 [(Name, FC)] -- determining parameters and precise locations
666 [PDecl' t] -- declarations
667 (Maybe (Name, FC)) -- instance constructor name and location
668 (Docstring (Either Err t)) -- instance constructor docs
669 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
670 -- class name, class name location, parameters, method declarations, optional constructor name
671 | PInstance
672 (Docstring (Either Err t)) -- Instance docs
673 [(Name, Docstring (Either Err t))] -- Parameter docs
674 SyntaxInfo
675 FC [(Name, t)] -- constraints
676 Name -- class
677 FC -- precise location of class
678 [t] -- parameters
679 t -- full instance type
680 (Maybe Name) -- explicit name
681 [PDecl' t]
682 -- ^ Instance declaration: arguments are documentation, syntax info, source
683 -- location, constraints, class name, parameters, full instance
684 -- type, optional explicit name, and definitions
685 | PDSL Name (DSL' t) -- ^ DSL declaration
686 | PSyntax FC Syntax -- ^ Syntax definition
687 | PMutual FC [PDecl' t] -- ^ Mutual block
688 | PDirective Directive -- ^ Compiler directive.
689 | PProvider (Docstring (Either Err t)) SyntaxInfo FC FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term. The second FC is precise highlighting location.
690 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
691 -- bool is True, lhs and rhs must be convertible
692 | PRunElabDecl FC t [String] -- ^ FC is decl-level, for errors, and
693 -- Strings represent the namespace
694 deriving Functor
695{-!
696deriving instance Binary PDecl'
697deriving instance NFData PDecl'
698!-}
700-- | The set of source directives
701data Directive = DLib Codegen String |
702 DLink Codegen String |
703 DFlag Codegen String |
704 DInclude Codegen String |
705 DHide Name |
706 DFreeze Name |
707 DAccess Accessibility |
708 DDefault Bool |
709 DLogging Integer |
710 DDynamicLibs [String] |
711 DNameHint Name FC [(Name, FC)] |
712 DErrorHandlers Name FC Name FC [(Name, FC)] |
713 DLanguage LanguageExt |
714 DDeprecate Name String |
715 DUsed FC Name Name
717-- | A set of instructions for things that need to happen in IState
718-- after a term elaboration when there's been reflected elaboration.
719data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
720 | RClausesInstrs Name [([Name], Term, Term)]
721 | RAddInstance Name Name
723-- | For elaborator state
724data EState = EState {
725 case_decls :: [(Name, PDecl)],
726 delayed_elab :: [(Int, Elab' EState ())],
727 new_tyDecls :: [RDeclInstructions],
728 highlighting :: [(FC, OutputAnnotation)]
729 }
731initEState :: EState
732initEState = EState [] [] [] []
734type ElabD a = Elab' EState a
736highlightSource :: FC -> OutputAnnotation -> ElabD ()
737highlightSource fc annot =
738 updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux })
740-- | One clause of a top-level definition. Term arguments to constructors are:
741--
742-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
743--
744-- 2. The list of extra 'with' patterns
745--
746-- 3. The right-hand side
747--
748-- 4. The where block (PDecl' t)
750data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
751 | PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t]
752 | PClauseR FC [t] t [PDecl' t]
753 | PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t]
754 deriving Functor
755{-!
756deriving instance Binary PClause'
757deriving instance NFData PClause'
758!-}
760-- | Data declaration
761data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
762 d_name_fc :: FC, -- ^ The precise location of the type constructor name
763 d_tcon :: t, -- ^ Type constructor
764 d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors
765 }
766 -- ^ Data declaration
767 | PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t }
768 -- ^ "Placeholder" for data whose constructors are defined later
769 deriving Functor
771-- | Transform the FCs in a PData and its associated terms. The first
772-- function transforms the general-purpose FCs, and the second transforms
773-- those that are used for semantic source highlighting, so they can be
774-- treated specially.
775mapPDataFC :: (FC -> FC) -> (FC -> FC) -> PData -> PData
776mapPDataFC f g (PDatadecl n nfc tycon ctors) =
777 PDatadecl n (g nfc) (mapPTermFC f g tycon) (map ctorFC ctors)
778 where ctorFC (doc, argDocs, n, nfc, ty, fc, ns) =
779 (doc, argDocs, n, g nfc, mapPTermFC f g ty, f fc, ns)
780mapPDataFC f g (PLaterdecl n nfc tycon) =
781 PLaterdecl n (g nfc) (mapPTermFC f g tycon)
782{-!
783deriving instance Binary PData'
784deriving instance NFData PData'
785!-}
787-- Handy to get a free function for applying PTerm -> PTerm functions
788-- across a program, by deriving Functor
790type PDecl = PDecl' PTerm
791type PData = PData' PTerm
792type PClause = PClause' PTerm
794-- | Transform the FCs in a PTerm. The first function transforms the
795-- general-purpose FCs, and the second transforms those that are used
796-- for semantic source highlighting, so they can be treated specially.
797mapPDeclFC :: (FC -> FC) -> (FC -> FC) -> PDecl -> PDecl
798mapPDeclFC f g (PFix fc fixity ops) =
799 PFix (f fc) fixity ops
800mapPDeclFC f g (PTy doc argdocs syn fc opts n nfc ty) =
801 PTy doc argdocs syn (f fc) opts n (g nfc) (mapPTermFC f g ty)
802mapPDeclFC f g (PPostulate ext doc syn fc nfc opts n ty) =
803 PPostulate ext doc syn (f fc) (g nfc) opts n (mapPTermFC f g ty)
805mapPDeclFC f g (PClauses fc opts n clauses) =
806 PClauses (f fc) opts n (map (fmap (mapPTermFC f g)) clauses)
807mapPDeclFC f g (PCAF fc n tm) = PCAF (f fc) n (mapPTermFC f g tm)
808mapPDeclFC f g (PData doc argdocs syn fc opts dat) =
809 PData doc argdocs syn (f fc) opts (mapPDataFC f g dat)
810mapPDeclFC f g (PParams fc params decls) =
811 PParams (f fc)
812 (map (\(n, ty) -> (n, mapPTermFC f g ty)) params)
813 (map (mapPDeclFC f g) decls)
814mapPDeclFC f g (PNamespace ns fc decls) =
815 PNamespace ns (f fc) (map (mapPDeclFC f g) decls)
816mapPDeclFC f g (PRecord doc syn fc opts n nfc params paramdocs fields ctor ctorDoc syn') =
817 PRecord doc syn (f fc) opts n (g nfc)
818 (map (\(pn, pnfc, plic, ty) -> (pn, g pnfc, plic, mapPTermFC f g ty)) params)
819 paramdocs
820 (map (\(fn, plic, ty, fdoc) -> (fmap (\(fn', fnfc) -> (fn', g fnfc)) fn,
821 plic, mapPTermFC f g ty, fdoc))
822 fields)
823 (fmap (\(ctorN, ctorNFC) -> (ctorN, g ctorNFC)) ctor)
824 ctorDoc
825 syn'
826mapPDeclFC f g (PClass doc syn fc constrs n nfc params paramDocs det body ctor ctorDoc) =
827 PClass doc syn (f fc)
828 (map (\(constrn, constr) -> (constrn, mapPTermFC f g constr)) constrs)
829 n (g nfc) (map (\(n, nfc, pty) -> (n, g nfc, mapPTermFC f g pty)) params)
830 paramDocs (map (\(dn, dnfc) -> (dn, g dnfc)) det)
831 (map (mapPDeclFC f g) body)
832 (fmap (\(n, nfc) -> (n, g nfc)) ctor)
833 ctorDoc
834mapPDeclFC f g (PInstance doc paramDocs syn fc constrs cn cnfc params instTy instN body) =
835 PInstance doc paramDocs syn (f fc)
836 (map (\(constrN, constrT) -> (constrN, mapPTermFC f g constrT)) constrs)
837 cn (g cnfc) (map (mapPTermFC f g) params)
838 (mapPTermFC f g instTy)
839 instN
840 (map (mapPDeclFC f g) body)
841mapPDeclFC f g (PDSL n dsl) = PDSL n (fmap (mapPTermFC f g) dsl)
842mapPDeclFC f g (PSyntax fc syn) = PSyntax (f fc) $
843 case syn of
844 Rule syms tm ctxt -> Rule syms (mapPTermFC f g tm) ctxt
845 DeclRule syms decls -> DeclRule syms (map (mapPDeclFC f g) decls)
846mapPDeclFC f g (PMutual fc decls) =
847 PMutual (f fc) (map (mapPDeclFC f g) decls)
848mapPDeclFC f g (PDirective d) =
849 PDirective $
850 case d of
851 DNameHint n nfc ns ->
852 DNameHint n (g nfc) (map (\(hn, hnfc) -> (hn, g hnfc)) ns)
853 DErrorHandlers n nfc n' nfc' ns ->
854 DErrorHandlers n (g nfc) n' (g nfc') $
855 map (\(an, anfc) -> (an, g anfc)) ns
856mapPDeclFC f g (PProvider doc syn fc nfc what n) =
857 PProvider doc syn (f fc) (g nfc) (fmap (mapPTermFC f g) what) n
858mapPDeclFC f g (PTransform fc safe l r) =
859 PTransform (f fc) safe (mapPTermFC f g l) (mapPTermFC f g r)
860mapPDeclFC f g (PRunElabDecl fc script ns) =
861 PRunElabDecl (f fc) (mapPTermFC f g script) ns
863-- | Get all the names declared in a declaration
864declared :: PDecl -> [Name]
865declared (PFix _ _ _) = []
866declared (PTy _ _ _ _ _ n fc t) = [n]
867declared (PPostulate _ _ _ _ _ _ n t) = [n]
868declared (PClauses _ _ n _) = [] -- not a declaration
869declared (PCAF _ n _) = [n]
870declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
871 where fstt (_, _, a, _, _, _, _) = a
872declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n]
873declared (PParams _ _ ds) = concatMap declared ds
874declared (PNamespace _ _ ds) = concatMap declared ds
875declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
876declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms)
877declared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
878declared (PDSL n _) = [n]
879declared (PSyntax _ _) = []
880declared (PMutual _ ds) = concatMap declared ds
881declared (PDirective _) = []
882declared _ = []
884-- get the names declared, not counting nested parameter blocks
885tldeclared :: PDecl -> [Name]
886tldeclared (PFix _ _ _) = []
887tldeclared (PTy _ _ _ _ _ n _ t) = [n]
888tldeclared (PPostulate _ _ _ _ _ _ n t) = [n]
889tldeclared (PClauses _ _ n _) = [] -- not a declaration
890tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
891tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
892 where fstt (_, _, a, _, _, _, _) = a
893tldeclared (PParams _ _ ds) = []
894tldeclared (PMutual _ ds) = concatMap tldeclared ds
895tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds
896tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms)
897tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
898tldeclared _ = []
900defined :: PDecl -> [Name]
901defined (PFix _ _ _) = []
902defined (PTy _ _ _ _ _ n _ t) = []
903defined (PPostulate _ _ _ _ _ _ n t) = []
904defined (PClauses _ _ n _) = [n] -- not a declaration
905defined (PCAF _ n _) = [n]
906defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
907 where fstt (_, _, a, _, _, _, _) = a
908defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = []
909defined (PParams _ _ ds) = concatMap defined ds
910defined (PNamespace _ _ ds) = concatMap defined ds
911defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
912defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms)
913defined (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
914defined (PDSL n _) = [n]
915defined (PSyntax _ _) = []
916defined (PMutual _ ds) = concatMap defined ds
917defined (PDirective _) = []
918defined _ = []
920updateN :: [(Name, Name)] -> Name -> Name
921updateN ns n | Just n' <- lookup n ns = n'
922updateN _ n = n
924updateNs :: [(Name, Name)] -> PTerm -> PTerm
925updateNs [] t = t
926updateNs ns t = mapPT updateRef t
927 where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)
928 updateRef t = t
930-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
931-- updateDNs [] t = t
932-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
933-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
934-- where updateCNs ns (PClause n l ts r ds)
935-- = PClause (updateN ns n) (fmap (updateNs ns) l)
936-- (map (fmap (updateNs ns)) ts)
937-- (fmap (updateNs ns) r)
938-- (map (updateDNs ns) ds)
939-- updateDNs ns c = c
941data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable)
943-- | High level language terms
944data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language
945 | PRef FC [FC] Name -- ^ A reference to a variable. The FC is its precise source location for highlighting. The list of FCs is a collection of additional highlighting locations.
946 | PInferRef FC [FC] Name -- ^ A name to be defined later
947 | PPatvar FC Name -- ^ A pattern variable
948 | PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span.
949 | PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable
950 | PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location)
951 | PTyped PTerm PTerm -- ^ Term with explicit type
952 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
953 | PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only)
954 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
955 | PMatchApp FC Name -- ^ Make an application by type matching
956 | PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse
957 | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
958 | PTrue FC PunInfo -- ^ Unit type..?
959 | PResolveTC FC -- ^ Solve this dictionary by type class resolution
960 | PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type
961 | PPair FC [FC] PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration). The list of FCs is its punctuation.
962 | PDPair FC [FC] PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration). The [FC] is its punctuation.
963 | PAs FC Name PTerm -- ^ @-pattern, valid LHS only
964 | PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames.
965 | PHidden PTerm -- ^ Irrelevant or hidden pattern
966 | PType FC -- ^ 'Type' type
967 | PUniverse Universe -- ^ Some universe
968 | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
969 | PConstant FC Const -- ^ Builtin types
970 | Placeholder -- ^ Underscore
971 | PDoBlock [PDo] -- ^ Do notation
972 | PIdiom FC PTerm -- ^ Idiom brackets
973 | PReturn FC
974 | PMetavar FC Name -- ^ A metavariable, ?name, and its precise location
975 | PProof [PTactic] -- ^ Proof script
976 | PTactics [PTactic] -- ^ As PProof, but no auto solving
977 | PElabError Err -- ^ Error to report on elaboration
978 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
979 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
980 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
981 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
982 | PNoImplicits PTerm -- ^ never run implicit converions on the term
983 | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
984 | PUnquote PTerm -- ^ ~Term
985 | PQuoteName Name Bool FC -- ^ `{n} where the FC is the precise highlighting for the name in particular. If the Bool is False, then it's `{{n}} and the name won't be resolved.
986 | PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace.
987 | PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later.
988 deriving (Eq, Data, Typeable)
990data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed
991 | FirstSuccess
992 | TryImplicit
993 deriving (Eq, Data, Typeable)
995-- | Transform the FCs in a PTerm. The first function transforms the
996-- general-purpose FCs, and the second transforms those that are used
997-- for semantic source highlighting, so they can be treated specially.
998mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm
999mapPTermFC f g (PQuote q) = PQuote q
1000mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n
1001mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n
1002mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n
1003mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2)
1004mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1005mapPTermFC f g (PLet fc n fc' t1 t2 t3) = PLet (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
1006mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2)
1007mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1008mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls
1009mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1010mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n
1011mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
1012mapPTermFC f g (PCase fc t cases) = PCase (f fc) (mapPTermFC f g t) (map (\(l,r) -> (mapPTermFC f g l, mapPTermFC f g r)) cases)
1013mapPTermFC f g (PTrue fc info) = PTrue (f fc) info
1014mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc)
1015mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3)
1016mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2)
1017mapPTermFC f g (PDPair fc hls info t1 t2 t3) = PDPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
1018mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t)
1019mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts)
1020mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t)
1021mapPTermFC f g (PType fc) = PType (f fc)
1022mapPTermFC f g (PUniverse u) = PUniverse u
1023mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2)
1024mapPTermFC f g (PConstant fc c) = PConstant (f fc) c
1025mapPTermFC f g Placeholder = Placeholder
1026mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos)
1027 where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t)
1028 mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)
1029 mapPDoFC (DoBindP fc t1 t2 alts) =
1030 DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)
1031 mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1032 mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1033mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t)
1034mapPTermFC f g (PReturn fc) = PReturn (f fc)
1035mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n
1036mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs)
1037mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs)
1038mapPTermFC f g (PElabError err) = PElabError err
1039mapPTermFC f g PImpossible = PImpossible
1040mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t)
1041mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t)
1042mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t)
1043mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t)
1044mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2)
1045mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t)
1046mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns
1047mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm)
1048mapPTermFC f g (PQuoteName n x fc) = PQuoteName n x (g fc)
1050{-!
1051dg instance Binary PTerm
1052deriving instance NFData PTerm
1053!-}
1055mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
1056mapPT f t = f (mpt t) where
1057 mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s)
1058 mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s)
1059 mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)
1060 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
1061 (fmap (mapPT f) g)
1062 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
1063 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
1064 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
1065 mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e)
1066 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
1067 mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r)
1068 mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r)
1069 mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as)
1070 mpt (PHidden t) = PHidden (mapPT f t)
1071 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
1072 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
1073 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
1074 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
1075 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
1076 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
1077 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
1078 mpt x = x
1081data PTactic' t = Intro [Name] | Intros | Focus Name
1082 | Refine Name [Bool] | Rewrite t | DoUnify
1083 | Induction t
1084 | CaseTac t
1085 | Equiv t
1086 | Claim Name t
1087 | Unfocus
1088 | MatchRefine Name
1089 | LetTac Name t | LetTacTy Name t t
1090 | Exact t | Compute | Trivial | TCInstance
1091 | ProofSearch Bool Bool Int (Maybe Name)
1092 [Name] -- allowed local names
1093 [Name] -- hints
1094 -- ^ the bool is whether to search recursively
1095 | Solve
1096 | Attack
1097 | ProofState | ProofTerm | Undo
1098 | Try (PTactic' t) (PTactic' t)
1099 | TSeq (PTactic' t) (PTactic' t)
1100 | ApplyTactic t -- see Language.Reflection module
1101 | ByReflection t
1102 | Reflect t
1103 | Fill t
1104 | GoalType String (PTactic' t)
1105 | TCheck t
1106 | TEval t
1107 | TDocStr (Either Name Const)
1108 | TSearch t
1109 | Skip
1110 | TFail [ErrorReportPart]
1111 | Qed | Abandon
1112 | SourceFC
1113 deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable)
1114{-!
1115deriving instance Binary PTactic'
1116deriving instance NFData PTactic'
1117!-}
1118instance Sized a => Sized (PTactic' a) where
1119 size (Intro nms) = 1 + size nms
1120 size Intros = 1
1121 size (Focus nm) = 1 + size nm
1122 size (Refine nm bs) = 1 + size nm + length bs
1123 size (Rewrite t) = 1 + size t
1124 size (Induction t) = 1 + size t
1125 size (LetTac nm t) = 1 + size nm + size t
1126 size (Exact t) = 1 + size t
1127 size Compute = 1
1128 size Trivial = 1
1129 size Solve = 1
1130 size Attack = 1
1131 size ProofState = 1
1132 size ProofTerm = 1
1133 size Undo = 1
1134 size (Try l r) = 1 + size l + size r
1135 size (TSeq l r) = 1 + size l + size r
1136 size (ApplyTactic t) = 1 + size t
1137 size (Reflect t) = 1 + size t
1138 size (Fill t) = 1 + size t
1139 size Qed = 1
1140 size Abandon = 1
1141 size Skip = 1
1142 size (TFail ts) = 1 + size ts
1143 size SourceFC = 1
1144 size DoUnify = 1
1145 size (CaseTac x) = 1 + size x
1146 size (Equiv t) = 1 + size t
1147 size (Claim x y) = 1 + size x + size y
1148 size Unfocus = 1
1149 size (MatchRefine x) = 1 + size x
1150 size (LetTacTy x y z) = 1 + size x + size y + size z
1151 size TCInstance = 1
1153type PTactic = PTactic' PTerm
1155data PDo' t = DoExp FC t
1156 | DoBind FC Name FC t -- ^ second FC is precise name location
1157 | DoBindP FC t t [(t,t)]
1158 | DoLet FC Name FC t t -- ^ second FC is precise name location
1159 | DoLetP FC t t
1160 deriving (Eq, Functor, Data, Typeable)
1161{-!
1162deriving instance Binary PDo'
1163deriving instance NFData PDo'
1164!-}
1166instance Sized a => Sized (PDo' a) where
1167 size (DoExp fc t) = 1 + size fc + size t
1168 size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t
1169 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
1170 size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r
1171 size (DoLetP fc l r) = 1 + size fc + size l + size r
1173type PDo = PDo' PTerm
1175-- The priority gives a hint as to elaboration order. Best to elaborate
1176-- things early which will help give a more concrete type to other
1177-- variables, e.g. a before (interpTy a).
1179data PArg' t = PImp { priority :: Int,
1180 machine_inf :: Bool, -- true if the machine inferred it
1181 argopts :: [ArgOpt],
1182 pname :: Name,
1183 getTm :: t }
1184 | PExp { priority :: Int,
1185 argopts :: [ArgOpt],
1186 pname :: Name,
1187 getTm :: t }
1188 | PConstraint { priority :: Int,
1189 argopts :: [ArgOpt],
1190 pname :: Name,
1191 getTm :: t }
1192 | PTacImplicit { priority :: Int,
1193 argopts :: [ArgOpt],
1194 pname :: Name,
1195 getScript :: t,
1196 getTm :: t }
1197 deriving (Show, Eq, Functor, Data, Typeable)
1199data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp
1200 deriving (Show, Eq, Data, Typeable)
1202instance Sized a => Sized (PArg' a) where
1203 size (PImp p _ l nm trm) = 1 + size nm + size trm
1204 size (PExp p l nm trm) = 1 + size nm + size trm
1205 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
1206 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
1208{-!
1209deriving instance Binary PArg'
1210deriving instance NFData PArg'
1211!-}
1213pimp n t mach = PImp 1 mach [] n t
1214pexp t = PExp 1 [] (sMN 0 "arg") t
1215pconst t = PConstraint 1 [] (sMN 0 "carg") t
1216ptacimp n s t = PTacImplicit 2 [] n s t
1218type PArg = PArg' PTerm
1220-- | Get the highest FC in a term, if one exists
1221highestFC :: PTerm -> Maybe FC
1222highestFC (PQuote _) = Nothing
1223highestFC (PRef fc _ _) = Just fc
1224highestFC (PInferRef fc _ _) = Just fc
1225highestFC (PPatvar fc _) = Just fc
1226highestFC (PLam fc _ _ _ _) = Just fc
1227highestFC (PPi _ _ _ _ _) = Nothing
1228highestFC (PLet fc _ _ _ _ _) = Just fc
1229highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty
1230highestFC (PApp fc _ _) = Just fc
1231highestFC (PAppBind fc _ _) = Just fc
1232highestFC (PMatchApp fc _) = Just fc
1233highestFC (PCase fc _ _) = Just fc
1234highestFC (PIfThenElse fc _ _ _) = Just fc
1235highestFC (PTrue fc _) = Just fc
1236highestFC (PResolveTC fc) = Just fc
1237highestFC (PRewrite fc _ _ _) = Just fc
1238highestFC (PPair fc _ _ _ _) = Just fc
1239highestFC (PDPair fc _ _ _ _ _) = Just fc
1240highestFC (PAs fc _ _) = Just fc
1241highestFC (PAlternative _ _ args) =
1242 case mapMaybe highestFC args of
1243 [] -> Nothing
1244 (fc:_) -> Just fc
1245highestFC (PHidden _) = Nothing
1246highestFC (PType fc) = Just fc
1247highestFC (PUniverse _) = Nothing
1248highestFC (PGoal fc _ _ _) = Just fc
1249highestFC (PConstant fc _) = Just fc
1250highestFC Placeholder = Nothing
1251highestFC (PDoBlock lines) =
1252 case map getDoFC lines of
1253 [] -> Nothing
1254 (fc:_) -> Just fc
1255 where
1256 getDoFC (DoExp fc t) = fc
1257 getDoFC (DoBind fc nm nfc t) = fc
1258 getDoFC (DoBindP fc l r alts) = fc
1259 getDoFC (DoLet fc nm nfc l r) = fc
1260 getDoFC (DoLetP fc l r) = fc
1262highestFC (PIdiom fc _) = Just fc
1263highestFC (PReturn fc) = Just fc
1264highestFC (PMetavar fc _) = Just fc
1265highestFC (PProof _) = Nothing
1266highestFC (PTactics _) = Nothing
1267highestFC (PElabError _) = Nothing
1268highestFC PImpossible = Nothing
1269highestFC (PCoerced tm) = highestFC tm
1270highestFC (PDisamb _ opts) = highestFC opts
1271highestFC (PUnifyLog tm) = highestFC tm
1272highestFC (PNoImplicits tm) = highestFC tm
1273highestFC (PQuasiquote _ _) = Nothing
1274highestFC (PUnquote tm) = highestFC tm
1275highestFC (PQuoteName _ _ fc) = Just fc
1276highestFC (PRunElab fc _ _) = Just fc
1277highestFC (PConstSugar fc _) = Just fc
1278highestFC (PAppImpl t _) = highestFC t
1280-- Type class data
1282data ClassInfo = CI { instanceCtorName :: Name,
1283 class_methods :: [(Name, (FnOpts, PTerm))],
1284 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
1285 class_default_superclasses :: [PDecl],
1286 class_params :: [Name],
1287 class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded
1288 class_determiners :: [Int] }
1289 deriving Show
1290{-!
1291deriving instance Binary ClassInfo
1292deriving instance NFData ClassInfo
1293!-}
1295-- Record data
1296data RecordInfo = RI { record_parameters :: [(Name,PTerm)],
1297 record_constructor :: Name,
1298 record_projections :: [Name] }
1299 deriving Show
1301-- Type inference data
1303data TIData = TIPartial -- ^ a function with a partially defined type
1304 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
1305 deriving Show
1307-- | Miscellaneous information about functions
1308data FnInfo = FnInfo { fn_params :: [Int] }
1309 deriving Show
1310{-!
1311deriving instance Binary FnInfo
1312deriving instance NFData FnInfo
1313!-}
1315data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
1316 detaggable :: Bool }
1317 deriving Show
1318{-!
1319deriving instance Binary OptInfo
1320deriving instance NFData OptInfo
1321!-}
1323-- | Syntactic sugar info
1324data DSL' t = DSL { dsl_bind :: t,
1325 dsl_return :: t,
1326 dsl_apply :: t,
1327 dsl_pure :: t,
1328 dsl_var :: Maybe t,
1329 index_first :: Maybe t,
1330 index_next :: Maybe t,
1331 dsl_lambda :: Maybe t,
1332 dsl_let :: Maybe t,
1333 dsl_pi :: Maybe t
1335 deriving (Show, Functor)
1336{-!
1337deriving instance Binary DSL'
1338deriving instance NFData DSL'
1339!-}
1341type DSL = DSL' PTerm
1343data SynContext = PatternSyntax | TermSyntax | AnySyntax
1344 deriving Show
1345{-!
1346deriving instance Binary SynContext
1347deriving instance NFData SynContext
1348!-}
1350data Syntax = Rule [SSymbol] PTerm SynContext
1351 | DeclRule [SSymbol] [PDecl]
1352 deriving Show
1354syntaxNames :: Syntax -> [Name]
1355syntaxNames (Rule syms _ _) = mapMaybe ename syms
1356 where ename (Keyword n) = Just n
1357 ename _ = Nothing
1358syntaxNames (DeclRule syms _) = mapMaybe ename syms
1359 where ename (Keyword n) = Just n
1360 ename _ = Nothing
1362syntaxSymbols :: Syntax -> [SSymbol]
1363syntaxSymbols (Rule ss _ _) = ss
1364syntaxSymbols (DeclRule ss _) = ss
1365{-!
1366deriving instance Binary Syntax
1367deriving instance NFData Syntax
1368!-}
1370data SSymbol = Keyword Name
1371 | Symbol String
1372 | Binding Name
1373 | Expr Name
1374 | SimpleExpr Name
1375 deriving (Show, Eq)
1378{-!
1379deriving instance Binary SSymbol
1380deriving instance NFData SSymbol
1381!-}
1383newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
1385emptySyntaxRules :: SyntaxRules
1386emptySyntaxRules = SyntaxRules []
1388updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
1389updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
1390 where
1391 newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
1393 ruleSort [] [] = EQ
1394 ruleSort [] _ = LT
1395 ruleSort _ [] = GT
1396 ruleSort (s1:ss1) (s2:ss2) =
1397 case symCompare s1 s2 of
1398 EQ -> ruleSort ss1 ss2
1399 r -> r
1401 -- Better than creating Ord instance for SSymbol since
1402 -- in general this ordering does not really make sense.
1403 symCompare (Keyword n1) (Keyword n2) = compare n1 n2
1404 symCompare (Keyword _) _ = LT
1405 symCompare (Symbol _) (Keyword _) = GT
1406 symCompare (Symbol s1) (Symbol s2) = compare s1 s2
1407 symCompare (Symbol _) _ = LT
1408 symCompare (Binding _) (Keyword _) = GT
1409 symCompare (Binding _) (Symbol _) = GT
1410 symCompare (Binding b1) (Binding b2) = compare b1 b2
1411 symCompare (Binding _) _ = LT
1412 symCompare (Expr _) (Keyword _) = GT
1413 symCompare (Expr _) (Symbol _) = GT
1414 symCompare (Expr _) (Binding _) = GT
1415 symCompare (Expr e1) (Expr e2) = compare e1 e2
1416 symCompare (Expr _) _ = LT
1417 symCompare (SimpleExpr _) (Keyword _) = GT
1418 symCompare (SimpleExpr _) (Symbol _) = GT
1419 symCompare (SimpleExpr _) (Binding _) = GT
1420 symCompare (SimpleExpr _) (Expr _) = GT
1421 symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
1423initDSL = DSL (PRef f [] (sUN ">>="))
1424 (PRef f [] (sUN "return"))
1425 (PRef f [] (sUN "<*>"))
1426 (PRef f [] (sUN "pure"))
1427 Nothing
1428 Nothing
1429 Nothing
1430 Nothing
1431 Nothing
1432 Nothing
1433 where f = fileFC "(builtin)"
1435data Using = UImplicit Name PTerm
1436 | UConstraint Name [Name]
1437 deriving (Show, Eq, Data, Typeable)
1438{-!
1439deriving instance Binary Using
1440deriving instance NFData Using
1441!-}
1443data SyntaxInfo = Syn { using :: [Using],
1444 syn_params :: [(Name, PTerm)],
1445 syn_namespace :: [String],
1446 no_imp :: [Name],
1447 imp_methods :: [Name], -- class methods. When expanding
1448 -- implicits, these should be expanded even under
1449 -- binders
1450 decoration :: Name -> Name,
1451 inPattern :: Bool,
1452 implicitAllowed :: Bool,
1453 maxline :: Maybe Int,
1454 mut_nesting :: Int,
1455 dsl_info :: DSL,
1456 syn_in_quasiquote :: Int }
1457 deriving Show
1458{-!
1459deriving instance NFData SyntaxInfo
1460deriving instance Binary SyntaxInfo
1461!-}
1463defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0
1465expandNS :: SyntaxInfo -> Name -> Name
1466expandNS syn n@(NS _ _) = n
1467expandNS syn n = case syn_namespace syn of
1468 [] -> n
1469 xs -> sNS n xs
1472-- For inferring types of things
1474bi = fileFC "builtin"
1476inferTy = sMN 0 "__Infer"
1477inferCon = sMN 0 "__infer"
1478inferDecl = PDatadecl inferTy NoFC
1479 (PType bi)
1480 [(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) (
1481 PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType"))
1482 (PRef bi [] inferTy)), bi, [])]
1483inferOpts = []
1485infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
1486infP = P (TCon 6 0) inferTy (TType (UVal 0))
1488getInferTerm, getInferType :: Term -> Term
1489getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
1490getInferTerm (App _ (App _ _ _) tm) = tm
1491getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1493getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1494 where toTy (Lam t) = Pi Nothing t (TType (UVar 0))
1495 toTy (PVar t) = PVTy t
1496 toTy b = b
1497getInferType (App _ (App _ _ ty) _) = ty
1501-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
1503primNames = [inferTy, inferCon]
1505unitTy = sUN "Unit"
1506unitCon = sUN "MkUnit"
1508falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
1509 "The empty type, also known as the trivially false proposition." ++
1510 "\n\n" ++
1511 "Use `void` or `absurd` to prove anything if you have a variable " ++
1512 "of type `Void` in scope."
1513falseTy = sUN "Void"
1515pairTy = sNS (sUN "Pair") ["Builtins"]
1516pairCon = sNS (sUN "MkPair") ["Builtins"]
1518upairTy = sNS (sUN "UPair") ["Builtins"]
1519upairCon = sNS (sUN "MkUPair") ["Builtins"]
1521eqTy = sUN "="
1522eqCon = sUN "Refl"
1523eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
1524 "The propositional equality type. A proof that `x` = `y`." ++
1525 "\n\n" ++
1526 "To use such a proof, pattern-match on it, and the two equal things will " ++
1527 "then need to be the _same_ pattern." ++
1528 "\n\n" ++
1529 "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
1530 "is possible to state equalities between values of potentially different " ++
1531 "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
1532 "\n\n" ++
1533 "You may need to use `(~=~)` to explicitly request heterogeneous equality."
1535eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)]
1536 (piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))]
1537 (PType bi)))
1538 [(reflDoc, reflParamDoc,
1539 eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) (
1540 PPi impl (n "x") NoFC (PRef bi [] (n "A"))
1541 (PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False,
1542 pimp (n "B") Placeholder False,
1543 pexp (PRef bi [] (n "x")),
1544 pexp (PRef bi [] (n "x"))])), bi, [])]
1545 where n a = sUN a
1546 reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
1547 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1548 "shown that both sides are in fact equal."
1549 reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
1550 (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1552eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
1553 (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
1555 where n a = sUN a
1557eqOpts = []
1559-- | The special name to be used in the module documentation context -
1560-- not for use in the main definition context. The namespace around it
1561-- will determine the module to which the docs adhere.
1562modDocName :: Name
1563modDocName = sMN 0 "ModuleDocs"
1565-- Defined in builtins.idr
1566sigmaTy = sNS (sUN "Sigma") ["Builtins"]
1567sigmaCon = sNS (sUN "MkSigma") ["Builtins"]
1569piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1570piBind = piBindp expl
1572piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1573piBindp p [] t = t
1574piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t)
1577-- Pretty-printing declarations and terms
1579-- These "show" instances render to an absurdly wide screen because inserted line breaks
1580-- could interfere with interactive editing, which calls "show".
1582instance Show PTerm where
1583 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1585instance Show PDecl where
1586 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
1588instance Show PClause where
1589 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1591instance Show PData where
1592 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1594instance Pretty PTerm OutputAnnotation where
1595 pretty = prettyImp defaultPPOption
1597-- | Colourise annotations according to an Idris state. It ignores the names
1598-- in the annotation, as there's no good way to show extended information on a
1599-- terminal.
1600annotationColour :: IState -> OutputAnnotation -> Maybe IdrisColour
1601annotationColour ist _ | not (idris_colourRepl ist) = Nothing
1602annotationColour ist (AnnConst c) =
1603 let theme = idris_colourTheme ist
1604 in Just $ if constIsType c
1605 then typeColour theme
1606 else dataColour theme
1607annotationColour ist (AnnData _ _) = Just $ dataColour (idris_colourTheme ist)
1608annotationColour ist (AnnType _ _) = Just $ typeColour (idris_colourTheme ist)
1609annotationColour ist (AnnBoundName _ True) = Just $ implicitColour (idris_colourTheme ist)
1610annotationColour ist (AnnBoundName _ False) = Just $ boundVarColour (idris_colourTheme ist)
1611annotationColour ist AnnKeyword = Just $ keywordColour (idris_colourTheme ist)
1612annotationColour ist (AnnName n _ _ _) =
1613 let ctxt = tt_ctxt ist
1614 theme = idris_colourTheme ist
1615 in case () of
1616 _ | isDConName n ctxt -> Just $ dataColour theme
1617 _ | isFnName n ctxt -> Just $ functionColour theme
1618 _ | isTConName n ctxt -> Just $ typeColour theme
1619 _ | isPostulateName n ist -> Just $ postulateColour theme
1620 _ | otherwise -> Nothing -- don't colourise unknown names
1621annotationColour ist (AnnTextFmt fmt) = Just (colour fmt)
1622 where colour BoldText = IdrisColour Nothing True False True False
1623 colour UnderlineText = IdrisColour Nothing True True False False
1624 colour ItalicText = IdrisColour Nothing True False False True
1625annotationColour ist _ = Nothing
1628-- | Colourise annotations according to an Idris state. It ignores the names
1629-- in the annotation, as there's no good way to show extended
1630-- information on a terminal. Note that strings produced this way will
1631-- not be coloured on Windows, so the use of the colour rendering
1632-- functions in Idris.Output is to be preferred.
1633consoleDecorate :: IState -> OutputAnnotation -> String -> String
1634consoleDecorate ist ann = maybe id colourise (annotationColour ist ann)
1636isPostulateName :: Name -> IState -> Bool
1637isPostulateName n ist = S.member n (idris_postulates ist)
1639-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1640prettyImp :: PPOption -- ^^ pretty printing options
1641 -> PTerm -- ^^ the term to pretty-print
1642 -> Doc OutputAnnotation
1643prettyImp impl = pprintPTerm impl [] [] []
1645-- | Serialise something to base64 using its Binary instance.
1647-- | Do the right thing for rendering a term in an IState
1648prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1649prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1651-- | Pretty-print a high-level Idris term in some bindings context with infix info
1652pprintPTerm :: PPOption -- ^^ pretty printing options
1653 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1654 -> [Name] -- ^^ names to always show in pi, even if not used
1655 -> [FixDecl] -- ^^ Fixity declarations
1656 -> PTerm -- ^^ the term to pretty-print
1657 -> Doc OutputAnnotation
1658pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1659 where
1660 startPrec = 0
1661 funcAppPrec = 10
1663 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1664 prettySe d p bnd (PQuote r) =
1665 text "![" <> pretty r <> text "]"
1666 prettySe d p bnd (PPatvar fc n) = pretty n
1667 prettySe d p bnd e
1668 | Just str <- slist d p bnd e = depth d $ str
1669 | Just n <- snat ppo d p e = depth d $ annotate (AnnData "Nat" "") (text (show n))
1670 prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n
1671 prettySe d p bnd (PLam fc n nfc ty sc) =
1672 depth d . bracket p startPrec . group . align . hang 2 $
1673 text "\\" <> prettyBindingOf n False <+> text "=>" <$>
1674 prettySe (decD d) startPrec ((n, False):bnd) sc
1675 prettySe d p bnd (PLet fc n nfc ty v sc) =
1676 depth d . bracket p startPrec . group . align $
1677 kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
1678 kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
1679 prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
1680 | n `elem` allNamesIn sc || ppopt_impl ppo && uname n || n `elem` docArgs
1681 || ppopt_pinames ppo && uname n =
1682 depth d . bracket p startPrec . group $
1683 enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
1684 st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
1685 | otherwise =
1686 depth d . bracket p startPrec . group $
1687 group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$>
1688 group (prettySe (decD d) startPrec ((n, False):bnd) sc)
1689 where
1690 uname (UN n) = case str n of
1691 ('_':_) -> False
1692 _ -> True
1693 uname _ = False
1695 st =
1696 case s of
1697 Static -> text "[static]" <> space
1698 _ -> empty
1699 prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc)
1700 | ppopt_impl ppo =
1701 depth d . bracket p startPrec $
1702 lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
1703 st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1704 | otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
1705 where
1706 st =
1707 case s of
1708 Static -> text "[static]" <> space
1709 _ -> empty
1710 prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
1711 depth d . bracket p startPrec $
1712 prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1713 prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch _ _ _ _ _ _])) n _ ty sc) =
1714 lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1715 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1716 prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
1717 depth d . bracket p startPrec $
1718 lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1719 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1720 -- This case preserves the behavior of the former constructor PEq.
1721 -- It should be removed if feasible when the pretty-printing of infix
1722 -- operators in general is improved.
1723 prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r])
1724 | n == eqTy, ppopt_impl ppo =
1725 depth d . bracket p eqPrec $
1726 enclose lparen rparen eq <+>
1727 align (group (vsep (map (prettyArgS (decD d) bnd)
1728 [lt, rt, l, r])))
1729 | n == eqTy =
1730 depth d . bracket p eqPrec . align . group $
1731 prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r))
1732 where eq = annName eqTy (text "=")
1733 eqPrec = startPrec
1734 prettyTerm = prettySe (decD d) (eqPrec + 1) bnd
1735 prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args
1736 | UN nm <- basename f
1737 , not (ppopt_impl ppo) && null (getShowArgs args) =
1738 prettyName True (ppopt_impl ppo) bnd f
1739 prettySe d p bnd (PAppBind _ (PRef _ _ f) [])
1740 | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
1741 prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators
1742 | UN nm <- basename op
1743 , not (tnull nm) &&
1744 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1745 case getShowArgs args of
1746 [] -> opName True
1747 [x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x)))
1748 [l,r] -> let precedence = maybe (startPrec - 1) prec f
1749 in depth d . bracket p precedence $ inFix (getTm l) (getTm r)
1750 (l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) ->
1751 depth d . bracket p funcAppPrec $
1752 enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
1753 align (group (vsep (map (prettyArgS d bnd) rest)))
1754 as -> opName True <+> align (vsep (map (prettyArgS d bnd) as))
1755 where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
1756 f = getFixity (opStr op)
1757 left = case f of
1758 Nothing -> funcAppPrec + 1
1759 Just (Infixl p') -> p'
1760 Just f' -> prec f' + 1
1761 right = case f of
1762 Nothing -> funcAppPrec + 1
1763 Just (Infixr p') -> p'
1764 Just f' -> prec f' + 1
1765 inFix l r = align . group $
1766 (prettySe (decD d) left bnd l <+> opName False) <$>
1767 group (prettySe (decD d) right bnd r)
1768 prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo
1769 | PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm,
1770 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1771 char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str))
1772 prettySe d p bnd (PApp _ f as) = -- Normal prefix applications
1773 let args = getShowArgs as
1774 fp = prettySe (decD d) (startPrec + 1) bnd f
1775 shownArgs = if ppopt_impl ppo then as else args
1776 in
1777 depth d . bracket p funcAppPrec . group $
1778 if null shownArgs
1779 then fp
1780 else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs))
1781 prettySe d p bnd (PCase _ scr cases) =
1782 align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$>
1783 depth d (indent 2 (vsep (map ppcase cases)))
1784 where
1785 ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec
1786 ([(n, False) | n <- vars l] ++ bnd)
1787 in nest nestingSize $
1788 prettyCase l <+> text "=>" <+> prettyCase r
1789 -- Warning: this is a bit of a hack. At this stage, we don't have the
1790 -- global context, so we can't determine which names are constructors,
1791 -- which are types, and which are pattern variables on the LHS of the
1792 -- case pattern. We use the heuristic that names without a namespace
1793 -- are patvars, because right now case blocks in PTerms are always
1794 -- delaborated from TT before being sent to the pretty-printer. If they
1795 -- start getting printed directly, THIS WILL BREAK.
1796 -- Potential solution: add a list of known patvars to the cases in
1797 -- PCase, and have the delaborator fill it out, kind of like the pun
1798 -- disambiguation on PDPair.
1799 vars tm = filter noNS (allNamesIn tm)
1800 noNS (NS _ _) = False
1801 noNS _ = True
1803 prettySe d p bnd (PIfThenElse _ c t f) =
1804 depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $
1805 [ kwd "if" <+> prettySe (decD d) startPrec bnd c
1806 , kwd "then" <+> prettySe (decD d) startPrec bnd t
1807 , kwd "else" <+> prettySe (decD d) startPrec bnd f
1809 prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
1810 prettySe d p bnd (PResolveTC _) = kwd "%instance"
1811 prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1812 prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1813 prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
1814 prettySe d p bnd (PRewrite _ l r _) =
1815 depth d . bracket p startPrec $
1816 text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r
1817 prettySe d p bnd (PTyped l r) =
1818 lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen
1819 prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser
1820 | Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) .
1821 align . group . vsep . punctuate (ann comma) $
1822 map (prettySe (decD d) startPrec bnd) elts
1823 where ann = case pun of
1824 TypeOrTerm -> id
1825 IsType -> annName pairTy
1826 IsTerm -> annName pairCon
1827 prettySe d p bnd (PDPair _ _ pun l t r) =
1828 depth d $
1829 annotated lparen <>
1830 left <+>
1831 annotated (text "**") <+>
1832 prettySe (decD d) startPrec (addBinding bnd) r <>
1833 annotated rparen
1834 where annotated = case pun of
1835 IsType -> annName sigmaTy
1836 IsTerm -> annName sigmaCon
1837 TypeOrTerm -> id
1838 (left, addBinding) = case (l, pun) of
1839 (PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :))
1840 _ -> (prettySe (decD d) startPrec bnd l, id)
1841 prettySe d p bnd (PAlternative ns a as) =
1842 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1843 where
1844 prettyAs =
1845 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (depth d . prettySe (decD d) startPrec bnd) as
1846 prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type"
1847 prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
1848 prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c))
1849 -- XXX: add pretty for tactics
1850 prettySe d p bnd (PProof ts) =
1851 kwd "proof" <+> lbrace <> ellipsis <> rbrace
1852 prettySe d p bnd (PTactics ts) =
1853 kwd "tactics" <+> lbrace <> ellipsis <> rbrace
1854 prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n
1855 prettySe d p bnd (PReturn f) = kwd "return"
1856 prettySe d p bnd PImpossible = kwd "impossible"
1857 prettySe d p bnd Placeholder = text "_"
1858 prettySe d p bnd (PDoBlock dos) =
1859 bracket p startPrec $
1860 kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos)))
1861 where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos
1862 ppdo bnd (DoBind _ bn _ tm : dos) =
1863 (prettyBindingOf bn False <+> text "<-" <+>
1864 group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) :
1865 ppdo ((bn, False):bnd) dos
1866 ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab
1867 text "no pretty printer for pattern-matching do binding" :
1868 ppdo bnd dos
1869 ppdo bnd (DoLet _ ln _ ty v : dos) =
1870 (kwd "let" <+> prettyBindingOf ln False <+>
1871 (if ty /= Placeholder
1872 then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="
1873 else text "=") <+>
1874 group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :
1875 ppdo ((ln, False):bnd) dos
1876 ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab
1877 text "no pretty printer for pattern-matching do binding" :
1878 ppdo bnd dos
1879 ppdo _ [] = []
1880 prettySe d p bnd (PCoerced t) = prettySe d p bnd t
1881 prettySe d p bnd (PElabError s) = pretty s
1882 -- Quasiquote pprinting ignores bound vars
1883 prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")"
1884 prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")"
1885 prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t
1886 prettySe d p bnd (PQuoteName n res _) = text start <> prettyName True (ppopt_impl ppo) bnd n <> text end
1887 where start = if res then "`{" else "`{{"
1888 end = if res then "}" else "}}"
1889 prettySe d p bnd (PRunElab _ tm _) =
1890 bracket p funcAppPrec . group . align . hang 2 $
1891 text "%runElab" <$>
1892 prettySe (decD d) funcAppPrec bnd tm
1893 prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
1895 prettySe d p bnd _ = text "missing pretty-printer for term"
1897 prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
1898 prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
1899 where display (UN n) = T.unpack n
1900 display (MN _ n) = T.unpack n
1901 -- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
1902 display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n
1903 display n = show n
1905 prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm)
1906 prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm
1907 prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm
1908 prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm)
1910 prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg
1911 prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
1912 prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace
1913 prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
1915 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1916 annName n = annotate (AnnName n Nothing Nothing Nothing)
1918 opStr :: Name -> String
1919 opStr (NS n _) = opStr n
1920 opStr (UN n) = T.unpack n
1922 slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation]
1923 slist' (Just d) _ _ _ | d <= 0 = Nothing
1924 slist' d _ _ e
1925 | containsHole e = Nothing
1926 slist' d p bnd (PApp _ (PRef _ _ nil) _)
1927 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1928 slist' d p bnd (PRef _ _ nil)
1929 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1930 slist' d p bnd (PApp _ (PRef _ _ cons) args)
1931 | nsroot cons == sUN "::",
1932 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1933 all isImp imps,
1934 Just tl' <- slist' (decD d) p bnd tl
1935 = Just (prettySe d startPrec bnd hd : tl')
1936 where
1937 isImp (PImp {}) = True
1938 isImp _ = False
1939 slist' _ _ _ tm = Nothing
1941 slist d p bnd e | Just es <- slist' d p bnd e = Just $
1942 case es of
1943 [] -> annotate (AnnData "" "") $ text "[]"
1944 [x] -> enclose left right . group $ x
1945 xs -> enclose left right .
1946 align . group . vsep .
1947 punctuate comma $ xs
1948 where left = (annotate (AnnData "" "") (text "["))
1949 right = (annotate (AnnData "" "") (text "]"))
1950 comma = (annotate (AnnData "" "") (text ","))
1951 slist _ _ _ _ = Nothing
1953 pairElts :: PTerm -> Maybe [PTerm]
1954 pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1955 | otherwise = Just [x, y]
1956 pairElts _ = Nothing
1958 natns = "Prelude.Nat."
1960 snat :: PPOption -> Maybe Int -> Int -> PTerm -> Maybe Integer
1961 snat ppo d p e
1962 | ppopt_desugarnats ppo = Nothing
1963 | otherwise = snat' d p e
1964 where
1965 snat' :: Maybe Int -> Int -> PTerm -> Maybe Integer
1966 snat' (Just x) _ _ | x <= 0 = Nothing
1967 snat' d p (PRef _ _ z)
1968 | show z == (natns++"Z") || show z == "Z" = Just 0
1969 snat' d p (PApp _ s [PExp {getTm=n}])
1970 | show s == (natns++"S") || show s == "S",
1971 Just n' <- snat' (decD d) p n
1972 = Just $ 1 + n'
1973 snat' _ _ _ = Nothing
1975 bracket outer inner doc
1976 | outer > inner = lparen <> doc <> rparen
1977 | otherwise = doc
1979 ellipsis = text "..."
1981 depth Nothing = id
1982 depth (Just d) = if d <= 0 then const (ellipsis) else id
1984 decD = fmap (\x -> x - 1)
1986 kwd = annotate AnnKeyword . text
1988 fixities :: M.Map String Fixity
1989 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
1991 getFixity :: String -> Maybe Fixity
1992 getFixity = flip M.lookup fixities
1994-- | Strip away namespace information
1995basename :: Name -> Name
1996basename (NS n _) = basename n
1997basename n = n
1999-- | Determine whether a name was the one inserted for a hole or
2000-- guess by the delaborator
2001isHoleName :: Name -> Bool
2002isHoleName (UN n) = n == T.pack "[__]"
2003isHoleName _ = False
2005-- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess
2006containsHole :: PTerm -> Bool
2007containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm]
2009-- | Pretty-printer helper for names that attaches the correct annotations
2010prettyName
2011 :: Bool -- ^^ whether the name should be parenthesised if it is an infix operator
2012 -> Bool -- ^^ whether to show namespaces
2013 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
2014 -> Name -- ^^ the name to pprint
2015 -> Doc OutputAnnotation
2016prettyName infixParen showNS bnd n
2017 | (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_"
2018 | (UN n') <- n, T.unpack n' == "_" = text "_"
2019 | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
2020 | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
2021 where fullName = text nameSpace <> parenthesise (text (baseName n))
2022 baseName (UN n) = T.unpack n
2023 baseName (NS n ns) = baseName n
2024 baseName (MN i s) = T.unpack s
2025 baseName other = show other
2026 nameSpace = case n of
2027 (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
2028 _ -> ""
2029 isInfix = case baseName n of
2030 "" -> False
2031 (c : _) -> not (isAlpha c)
2032 parenthesise = if isInfix && infixParen then enclose lparen rparen else id
2035showCImp :: PPOption -> PClause -> Doc OutputAnnotation
2036showCImp ppo (PClause _ n l ws r w)
2037 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
2038 <+> text "where" <+> text (show w)
2039 where
2040 showWs [] = empty
2041 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2042showCImp ppo (PWith _ n l ws r pn w)
2043 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
2044 <+> braces (text (show w))
2045 where
2046 showWs [] = empty
2047 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2050showDImp :: PPOption -> PData -> Doc OutputAnnotation
2051showDImp ppo (PDatadecl n nfc ty cons)
2052 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
2053 (indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
2055showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
2056showDecls o ds = vsep (map (showDeclImp o) ds)
2058showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
2059showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
2060showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
2061 indent 2 (vsep (map (showCImp o) cs))
2062showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
2063showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
2064showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
2065showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
2066showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _)
2067 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
2068showDeclImp o (PInstance _ _ _ _ cs n _ _ t _ ds)
2069 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
2070showDeclImp _ _ = text "..."
2071-- showDeclImp (PImport o) = "import " ++ o
2073getImps :: [PArg] -> [(Name, PTerm)]
2074getImps [] = []
2075getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
2076getImps (_ : xs) = getImps xs
2078getExps :: [PArg] -> [PTerm]
2079getExps [] = []
2080getExps (PExp _ _ _ tm : xs) = tm : getExps xs
2081getExps (_ : xs) = getExps xs
2083getShowArgs :: [PArg] -> [PArg]
2084getShowArgs [] = []
2085getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
2086getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
2087 | PImp _ _ _ _ tm <- e
2088 , containsHole tm = e : getShowArgs xs
2089getShowArgs (_ : xs) = getShowArgs xs
2091getConsts :: [PArg] -> [PTerm]
2092getConsts [] = []
2093getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
2094getConsts (_ : xs) = getConsts xs
2096getAll :: [PArg] -> [PTerm]
2097getAll = map getTm
2100-- | Show Idris name
2101showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
2102 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
2103 -> PPOption -- ^^ pretty printing options
2104 -> Bool -- ^^ whether to colourise
2105 -> Name -- ^^ the term to show
2106 -> String
2107showName ist bnd ppo colour n = case ist of
2108 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
2109 Nothing -> showbasic n
2110 where name = if ppopt_impl ppo then show n else showbasic n
2111 showbasic n@(UN _) = showCG n
2112 showbasic (MN i s) = str s
2113 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
2114 showbasic (SN s) = show s
2115 fst3 (x, _, _) = x
2116 colourise n t = let ctxt' = fmap tt_ctxt ist in
2117 case ctxt' of
2118 Nothing -> name
2119 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
2120 else colouriseBound t name
2121 | isDConName n ctxt -> colouriseData t name
2122 | isFnName n ctxt -> colouriseFun t name
2123 | isTConName n ctxt -> colouriseType t name
2124 -- The assumption is that if a name is not bound and does not exist in the
2125 -- global context, then we're somewhere in which implicit info has been lost
2126 -- (like error messages). Thus, unknown vars are colourised as implicits.
2127 | otherwise -> colouriseImplicit t name
2129showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
2130 -> PTerm -- ^^ the term to show
2131 -> String
2132showTm ist = displayDecorated (consoleDecorate ist) .
2133 renderPretty 0.8 100000 .
2134 prettyImp (ppOptionIst ist)
2136-- | Show a term with implicits, no colours
2137showTmImpls :: PTerm -> String
2138showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
2140-- | Show a term with specific options
2141showTmOpts :: PPOption -> PTerm -> String
2142showTmOpts opt = flip (displayS . renderPretty 1.0 10000000 . prettyImp opt) ""
2145instance Sized PTerm where
2146 size (PQuote rawTerm) = size rawTerm
2147 size (PRef fc _ name) = size name
2148 size (PLam fc name _ ty bdy) = 1 + size ty + size bdy
2149 size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy
2150 size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy
2151 size (PTyped trm ty) = 1 + size trm + size ty
2152 size (PApp fc name args) = 1 + size args
2153 size (PAppBind fc name args) = 1 + size args
2154 size (PCase fc trm bdy) = 1 + size trm + size bdy
2155 size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f])
2156 size (PTrue fc _) = 1
2157 size (PResolveTC fc) = 1
2158 size (PRewrite fc left right _) = 1 + size left + size right
2159 size (PPair fc _ _ left right) = 1 + size left + size right
2160 size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right
2161 size (PAlternative _ a alts) = 1 + size alts
2162 size (PHidden hidden) = size hidden
2163 size (PUnifyLog tm) = size tm
2164 size (PDisamb _ tm) = size tm
2165 size (PNoImplicits tm) = size tm
2166 size (PType _) = 1
2167 size (PUniverse _) = 1
2168 size (PConstant fc const) = 1 + size fc + size const
2169 size Placeholder = 1
2170 size (PDoBlock dos) = 1 + size dos
2171 size (PIdiom fc term) = 1 + size term
2172 size (PReturn fc) = 1
2173 size (PMetavar _ name) = 1
2174 size (PProof tactics) = size tactics
2175 size (PElabError err) = size err
2176 size PImpossible = 1
2177 size _ = 0
2179getPArity :: PTerm -> Int
2180getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc
2181getPArity _ = 0
2183-- Return all names, free or globally bound, in the given term.
2185allNamesIn :: PTerm -> [Name]
2186allNamesIn tm = nub $ ni 0 [] tm
2187 where -- TODO THINK added niTacImp, but is it right?
2188 ni 0 env (PRef _ _ n)
2189 | not (n `elem` env) = [n]
2190 ni 0 env (PPatvar _ n) = [n]
2191 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2192 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2193 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os)
2194 ni 0 env (PIfThenElse _ c t f) = ni 0 env c ++ ni 0 env t ++ ni 0 env f
2195 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2196 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2197 ni 0 env (PLet _ n _ ty val sc) = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc
2198 ni 0 env (PHidden tm) = ni 0 env tm
2199 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2200 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2201 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2202 ni 0 env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni 0 env r
2203 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2204 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2205 ni 0 env (PAlternative ns a ls) = concatMap (ni 0 env) ls
2206 ni 0 env (PUnifyLog tm) = ni 0 env tm
2207 ni 0 env (PDisamb _ tm) = ni 0 env tm
2208 ni 0 env (PNoImplicits tm) = ni 0 env tm
2210 ni i env (PQuasiquote tm ty) = ni (i+1) env tm ++ maybe [] (ni i env) ty
2211 ni i env (PUnquote tm) = ni (i - 1) env tm
2213 ni i env tm = concatMap (ni i env) (children tm)
2215 niTacImp i env (TacImp _ _ scr) = ni i env scr
2216 niTacImp _ _ _ = []
2219-- Return all names defined in binders in the given term
2220boundNamesIn :: PTerm -> [Name]
2221boundNamesIn tm = S.toList (ni 0 S.empty tm)
2222 where -- TODO THINK Added niTacImp, but is it right?
2223 ni :: Int -> S.Set Name -> PTerm -> S.Set Name
2224 ni 0 set (PApp _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2225 ni 0 set (PAppBind _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2226 ni 0 set (PCase _ c os) = niTms 0 (ni 0 set c) (map snd os)
2227 ni 0 set (PIfThenElse _ c t f) = niTms 0 set [c, t, f]
2228 ni 0 set (PLam fc n _ ty sc) = S.insert n $ ni 0 (ni 0 set ty) sc
2229 ni 0 set (PLet fc n nfc ty val sc) = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc
2230 ni 0 set (PPi p n _ ty sc) = niTacImp 0 (S.insert n $ ni 0 (ni 0 set ty) sc) p
2231 ni 0 set (PRewrite _ l r _) = ni 0 (ni 0 set l) r
2232 ni 0 set (PTyped l r) = ni 0 (ni 0 set l) r
2233 ni 0 set (PPair _ _ _ l r) = ni 0 (ni 0 set l) r
2234 ni 0 set (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 (ni 0 set t) r
2235 ni 0 set (PDPair _ _ _ l t r) = ni 0 (ni 0 (ni 0 set l) t) r
2236 ni 0 set (PAlternative ns a as) = niTms 0 set as
2237 ni 0 set (PHidden tm) = ni 0 set tm
2238 ni 0 set (PUnifyLog tm) = ni 0 set tm
2239 ni 0 set (PDisamb _ tm) = ni 0 set tm
2240 ni 0 set (PNoImplicits tm) = ni 0 set tm
2242 ni i set (PQuasiquote tm ty) = ni (i + 1) set tm `S.union` maybe S.empty (ni i set) ty
2243 ni i set (PUnquote tm) = ni (i - 1) set tm
2245 ni i set tm = foldr S.union set (map (ni i set) (children tm))
2247 niTms :: Int -> S.Set Name -> [PTerm] -> S.Set Name
2248 niTms i set [] = set
2249 niTms i set (x : xs) = niTms i (ni i set x) xs
2251 niTacImp i set (TacImp _ _ scr) = ni i set scr
2252 niTacImp i set _ = set
2254-- Return names which are valid implicits in the given term (type).
2255implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
2256implicitNamesIn uvars ist tm
2257 = let (imps, fns) = execState (ni 0 [] tm) ([], []) in
2258 nub imps \\ nub fns
2259 where
2260 addImp n = do (imps, fns) <- get
2261 put (n : imps, fns)
2262 addFn n = do (imps, fns) <- get
2263 put (imps, n: fns)
2265 notCAF [] = False
2266 notCAF (PExp _ _ _ _ : _) = True
2267 notCAF (_ : xs) = notCAF xs
2269 notHidden (n, _) = case getAccessibility n of
2270 Hidden -> False
2271 _ -> True
2273 getAccessibility n
2274 = case lookupDefAccExact n False (tt_ctxt ist) of
2275 Just (n,t) -> t
2276 _ -> Public
2278 ni 0 env (PRef _ _ n@(NS _ _))
2279 | not (n `elem` env)
2280 -- Never implicitly bind if there's a namespace
2281 = addFn n
2282 ni 0 env (PRef _ _ n)
2283 | not (n `elem` env) && implicitable n || n `elem` uvars = addImp n
2284 ni 0 env (PApp _ f@(PRef _ _ n) as)
2285 | n `elem` uvars = do ni 0 env f
2286 mapM_ (ni 0 env) (map getTm as)
2287 | otherwise = do case lookupTy n (tt_ctxt ist) of
2288 [] -> return ()
2289 _ -> addFn n
2290 mapM_ (ni 0 env) (map getTm as)
2291 ni 0 env (PApp _ f as) = do ni 0 env f
2292 mapM_ (ni 0 env) (map getTm as)
2293 ni 0 env (PAppBind _ f as) = do ni 0 env f
2294 mapM_ (ni 0 env) (map getTm as)
2295 ni 0 env (PCase _ c os) = do ni 0 env c
2296 -- names in 'os', not counting the names bound in the cases
2297 mapM_ (ni 0 env) (map snd os)
2298 (imps, fns) <- get
2299 put ([] ,[])
2300 mapM_ (ni 0 env) (map fst os)
2301 (impsfst, _) <- get
2302 put (nub imps \\ nub impsfst, fns)
2303 ni 0 env (PIfThenElse _ c t f) = mapM_ (ni 0 env) [c, t, f]
2304 ni 0 env (PLam fc n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2305 ni 0 env (PPi p n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2306 ni 0 env (PRewrite _ l r _) = do ni 0 env l; ni 0 env r
2307 ni 0 env (PTyped l r) = do ni 0 env l; ni 0 env r
2308 ni 0 env (PPair _ _ _ l r) = do ni 0 env l; ni 0 env r
2309 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = do ni 0 env t; ni 0 (n:env) r
2310 ni 0 env (PDPair _ _ _ l t r) = do ni 0 env l
2311 ni 0 env t
2312 ni 0 env r
2313 ni 0 env (PAlternative ns a as) = mapM_ (ni 0 env) as
2314 ni 0 env (PHidden tm) = ni 0 env tm
2315 ni 0 env (PUnifyLog tm) = ni 0 env tm
2316 ni 0 env (PDisamb _ tm) = ni 0 env tm
2317 ni 0 env (PNoImplicits tm) = ni 0 env tm
2319 ni i env (PQuasiquote tm ty) = do ni (i + 1) env tm
2320 maybe (return ()) (ni i env) ty
2321 ni i env (PUnquote tm) = ni (i - 1) env tm
2323 ni i env tm = mapM_ (ni i env) (children tm)
2325-- Return names which are free in the given term.
2326namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
2327namesIn uvars ist tm = nub $ ni 0 [] tm
2328 where
2329 ni 0 env (PRef _ _ n)
2330 | not (n `elem` env)
2331 = case lookupTy n (tt_ctxt ist) of
2332 [] -> [n]
2333 _ -> if n `elem` (map fst uvars) then [n] else []
2334 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2335 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2336 ni 0 env (PCase _ c os) = ni 0 env c ++
2337 -- names in 'os', not counting the names bound in the cases
2338 (nub (concatMap (ni 0 env) (map snd os))
2339 \\ nub (concatMap (ni 0 env) (map fst os)))
2340 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2341 ni 0 env (PLam fc n nfc ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2342 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2343 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2344 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2345 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2346 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2347 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2348 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2349 ni 0 env (PHidden tm) = ni 0 env tm
2350 ni 0 env (PUnifyLog tm) = ni 0 env tm
2351 ni 0 env (PDisamb _ tm) = ni 0 env tm
2352 ni 0 env (PNoImplicits tm) = ni 0 env tm
2354 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2355 ni i env (PUnquote tm) = ni (i - 1) env tm
2357 ni i env tm = concatMap (ni i env) (children tm)
2359 niTacImp i env (TacImp _ _ scr) = ni i env scr
2360 niTacImp _ _ _ = []
2362-- Return which of the given names are used in the given term.
2364usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
2365usedNamesIn vars ist tm = nub $ ni 0 [] tm
2366 where -- TODO THINK added niTacImp, but is it right?
2367 ni 0 env (PRef _ _ n)
2368 | n `elem` vars && not (n `elem` env)
2369 = case lookupDefExact n (tt_ctxt ist) of
2370 Nothing -> [n]
2371 _ -> []
2372 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2373 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2374 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os)
2375 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2376 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2377 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2378 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2379 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2380 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2381 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2382 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2383 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2384 ni 0 env (PHidden tm) = ni 0 env tm
2385 ni 0 env (PUnifyLog tm) = ni 0 env tm
2386 ni 0 env (PDisamb _ tm) = ni 0 env tm
2387 ni 0 env (PNoImplicits tm) = ni 0 env tm
2389 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2390 ni i env (PUnquote tm) = ni (i - 1) env tm
2392 ni i env tm = concatMap (ni i env) (children tm)
2394 niTacImp i env (TacImp _ _ scr) = ni i env scr
2395 niTacImp _ _ _ = []
2397-- Return the list of inaccessible (= dotted) positions for a name.
2398getErasureInfo :: IState -> Name -> [Int]
2399getErasureInfo ist n =
2400 case lookupCtxtExact n (idris_optimisation ist) of
2401 Just (Optimise inacc detagg) -> map fst inacc
2402 Nothing -> []