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