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