1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 DeriveDataTypeable, TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntaxTree where
7import Idris.Core.Evaluate
8import Idris.Core.Elaborate hiding (Tactic(..))
9import Idris.Core.Typecheck
10import Idris.Docstrings
12import IRTS.CodegenCommon
14import Util.DynamicLinker
18import System.Console.Haskeline
21import Prelude hiding ((<$>))
23import Control.Applicative ((<|>))
25import Control.Monad.Trans.State.Strict
26import Control.Monad.Trans.Except
27import qualified Control.Monad.Trans.Class as Trans (lift)
29import Data.Data (Data)
30import Data.Function (on)
31import Data.Generics.Uniplate.Data (universe, children)
32import Data.List hiding (group)
34import qualified Data.Map.Strict as M
35import qualified Data.Text as T
37import qualified Data.Set as S
38import Data.Word (Word)
39import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
40import Data.Traversable (Traversable)
42import Data.Foldable (Foldable)
46import Text.PrettyPrint.Annotated.Leijen
48data ElabWhat = ETypes | EDefns | EAll
51-- Data to pass to recursively called elaborators; e.g. for where blocks,
52-- paramaterised declarations, etc.
54-- rec_elabDecl is used to pass the top level elaborator into other elaborators,
55-- so that we can have mutually recursive elaborators in separate modules without
56-- having to muck about with cyclic modules.
57data ElabInfo = EInfo { params :: [(Name, PTerm)],
58 inblock :: Ctxt [Name], -- names in the block, and their params
59 liftname :: Name -> Name,
60 namespace :: Maybe [String],
62 rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl ->
66toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented")
68eInfoNames :: ElabInfo -> [Name]
69eInfoNames info = map fst (params info) ++ M.keys (inblock info)
71data IOption = IOption {
73 , opt_logcats :: [LogCat] -- ^ List of logging categories.
74 , opt_typecase :: Bool
75 , opt_typeintype :: Bool
76 , opt_coverage :: Bool
77 , opt_showimp :: Bool -- ^ show implicits
78 , opt_errContext :: Bool
81 , opt_nobanner :: Bool
83 , opt_codegen :: Codegen
84 , opt_outputTy :: OutputType
85 , opt_ibcsubdir :: FilePath
86 , opt_importdirs :: [FilePath]
87 , opt_triple :: String
89 , opt_cmdline :: [Opt] -- remember whole command line
91 , opt_autoSolve :: Bool -- ^ automatically apply "solve" tactic in prover
92 , opt_autoImport :: [FilePath] -- ^ e.g. Builtins+Prelude
93 , opt_optimise :: [Optimisation]
94 , opt_printdepth :: Maybe Int
95 , opt_evaltypes :: Bool -- ^ normalise types in :t
96 , opt_desugarnats :: Bool
97 , opt_autoimpls :: Bool
100defaultOpts = IOption { opt_logLevel = 0
102 , opt_typecase = False
103 , opt_typeintype = False
104 , opt_coverage = True
105 , opt_showimp = False
106 , opt_errContext = False
109 , opt_nobanner = False
111 , opt_codegen = Via "c"
112 , opt_outputTy = Executable
114 , opt_importdirs = []
118 , opt_origerr = False
119 , opt_autoSolve = True
120 , opt_autoImport = []
121 , opt_optimise = defaultOptimise
122 , opt_printdepth = Just 5000
123 , opt_evaltypes = True
124 , opt_desugarnats = False
125 , opt_autoimpls = True
128data PPOption = PPOption {
129 ppopt_impl :: Bool -- ^^ whether to show implicits
130 , ppopt_desugarnats :: Bool
131 , ppopt_pinames :: Bool -- ^^ whether to show names in pi bindings
132 , ppopt_depth :: Maybe Int
135data Optimisation = PETransform -- partial eval and associated transforms
138defaultOptimise = [PETransform]
140-- | Pretty printing options with default verbosity.
141defaultPPOption :: PPOption
142defaultPPOption = PPOption { ppopt_impl = False,
143 ppopt_desugarnats = False,
144 ppopt_pinames = False,
145 ppopt_depth = Just 200 }
147-- | Pretty printing options with the most verbosity.
148verbosePPOption :: PPOption
149verbosePPOption = PPOption { ppopt_impl = True,
150 ppopt_desugarnats = True,
151 ppopt_pinames = True,
152 ppopt_depth = Just 200 }
154-- | Get pretty printing options from the big options record.
155ppOption :: IOption -> PPOption
156ppOption opt = PPOption {
157 ppopt_impl = opt_showimp opt,
158 ppopt_pinames = False,
159 ppopt_depth = opt_printdepth opt,
160 ppopt_desugarnats = opt_desugarnats opt
163-- | Get pretty printing options from an idris state record.
164ppOptionIst :: IState -> PPOption
165ppOptionIst = ppOption . idris_options
167data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
169-- | The output mode in use
170data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle
171 | IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle
174-- | How wide is the console?
175data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
176 | ColsWide Int -- ^ Manually specified - must be positive
177 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
181-- | The global state used in the Idris monad
182data IState = IState {
183 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
184 idris_constraints :: S.Set ConstraintFC,
185 -- ^ A list of universe constraints and their corresponding source locations
186 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
187 idris_implicits :: Ctxt [PArg],
188 idris_statics :: Ctxt [Bool],
189 idris_classes :: Ctxt ClassInfo,
190 idris_records :: Ctxt RecordInfo,
191 idris_dsls :: Ctxt DSL,
192 idris_optimisation :: Ctxt OptInfo,
193 idris_datatypes :: Ctxt TypeInfo,
194 idris_namehints :: Ctxt [Name],
195 idris_patdefs :: Ctxt ([([(Name, Term)], Term, Term)], [PTerm]), -- not exported
196 -- ^ list of lhs/rhs, and a list of missing clauses
197 idris_flags :: Ctxt [FnOpt],
198 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
199 idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]),
200 idris_moduledocs :: Ctxt (Docstring DocTerm),
201 -- ^ module documentation is saved in a special MN so the context
202 -- mechanism can be used for disambiguation
203 idris_tyinfodata :: Ctxt TIData,
204 idris_fninfo :: Ctxt FnInfo,
205 idris_transforms :: Ctxt [(Term, Term)],
206 idris_autohints :: Ctxt [Name],
207 idris_totcheck :: [(FC, Name)], -- names to check totality on
208 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
209 idris_totcheckfail :: [(FC, String)],
210 idris_options :: IOption,
212 idris_lineapps :: [((FilePath, Int), PTerm)],
213 -- ^ Full application LHS on source line
214 idris_metavars :: [(Name, (Maybe Name, Int, [Name], Bool, Bool))],
215 -- ^ The currently defined but not proven metavariables. The Int
216 -- is the number of vars to display as a context, the Maybe Name
217 -- is its top-level function, the [Name] is the list of local variables
218 -- available for proof search and the Bools are whether :p is
219 -- allowed, and whether the variable is definable at all
220 -- (Metavariables are not definable if they are applied in a term which
221 -- still has hole bindings)
222 idris_coercions :: [Name],
223 idris_errRev :: [(Term, Term)],
224 syntax_rules :: SyntaxRules,
225 syntax_keywords :: [String],
226 imported :: [FilePath], -- ^ The imported modules
227 idris_scprims :: [(Name, (Int, PrimFn))],
228 idris_objs :: [(Codegen, FilePath)],
229 idris_libs :: [(Codegen, String)],
230 idris_cgflags :: [(Codegen, String)],
231 idris_hdrs :: [(Codegen, String)],
232 idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public
233 proof_list :: [(Name, (Bool, [String]))],
235 parserWarnings :: [(FC, Err)],
236 lastParse :: Maybe Name,
237 indent_stack :: [Int],
238 brace_stack :: [Maybe Int],
239 lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
240 idris_parsedSpan :: Maybe FC,
241 hide_list :: Ctxt Accessibility,
242 default_access :: Accessibility,
243 default_total :: Bool,
244 ibc_write :: [IBCWrite],
245 compiled_so :: Maybe String,
246 idris_dynamic_libs :: [DynamicLib],
247 idris_language_extensions :: [LanguageExt],
248 idris_outputmode :: OutputMode,
249 idris_colourRepl :: Bool,
250 idris_colourTheme :: ColourTheme,
251 idris_errorhandlers :: [Name], -- ^ Global error handlers
252 idris_nameIdx :: (Int, Ctxt (Int, Name)),
253 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
254 module_aliases :: M.Map [T.Text] [T.Text],
255 idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
256 idris_postulates :: S.Set Name,
257 idris_externs :: S.Set (Name, Int),
258 idris_erasureUsed :: [(Name, Int)], -- ^ Function/constructor name, argument position is used
259 idris_whocalls :: Maybe (M.Map Name [Name]),
260 idris_callswho :: Maybe (M.Map Name [Name]),
261 idris_repl_defs :: [Name], -- ^ List of names that were defined in the repl, and can be re-/un-defined
262 elab_stack :: [(Name, Bool)], -- ^ Stack of names currently being elaborated, Bool set if it's an instance
263 -- (instances appear twice; also as a funtion name)
264 idris_symbols :: M.Map Name Name, -- ^ Symbol table (preserves sharing of names)
265 idris_exports :: [Name], -- ^ Functions with ExportList
266 idris_highlightedRegions :: [(FC, OutputAnnotation)], -- ^ Highlighting information to output
267 idris_parserHighlights :: [(FC, OutputAnnotation)], -- ^ Highlighting information from the parser
268 idris_deprecated :: Ctxt String, -- ^ Deprecated names and explanation
269 idris_inmodule :: S.Set Name, -- ^ Names defined in current module
270 idris_ttstats :: M.Map Term (Int, Term)
273-- Required for parsers library, and therefore trifecta
274instance Show IState where
275 show = const "{internal state}"
277data SizeChange = Smaller | Same | Bigger | Unknown
280deriving instance Binary SizeChange
281deriving instance NFData SizeChange
284type SCGEntry = (Name, [Maybe (Int, SizeChange)])
285type UsageReason = (Name, Int) -- fn_name, its_arg_number
287data CGInfo = CGInfo { calls :: [Name],
289 usedpos :: [(Int, [UsageReason])]
293deriving instance Binary CGInfo
294deriving instance NFData CGInfo
297primDefs = [sUN "unsafePerformPrimIO",
298 sUN "mkLazyForeignPrim",
302-- information that needs writing for the current module's .ibc file
303data IBCWrite = IBCFix FixDecl
308 | IBCInstance Bool Bool Name Name
315 | IBCImport (Bool, FilePath) -- True = import public
316 | IBCImportDir FilePath
317 | IBCObj Codegen FilePath
318 | IBCLib Codegen String
319 | IBCCGFlag Codegen String
321 | IBCHeader Codegen String
322 | IBCAccess Name Accessibility
323 | IBCMetaInformation Name MetaInformation
324 | IBCTotal Name Totality
325 | IBCFlags Name [FnOpt]
326 | IBCFnInfo Name FnInfo
327 | IBCTrans Name (Term, Term)
328 | IBCErrRev (Term, Term)
332 | IBCDef Name -- i.e. main context
333 | IBCNameHint (Name, Name)
334 | IBCLineApp FilePath Int PTerm
335 | IBCErrorHandler Name
336 | IBCFunctionErrorHandler Name Name Name
338 | IBCExtern (Name, Int)
339 | IBCTotCheckErr FC String
341 | IBCModDocs Name -- ^ The name is the special name used to track module docs
342 | IBCUsage (Name, Int)
344 | IBCAutoHint Name Name
345 | IBCDeprecate Name String
348-- | The initial state for the compiler
350idrisInit = IState initContext S.empty []
351 emptyContext emptyContext emptyContext emptyContext
352 emptyContext emptyContext emptyContext emptyContext
353 emptyContext emptyContext emptyContext emptyContext
354 emptyContext emptyContext emptyContext emptyContext
356 [] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []
357 [] [] Nothing [] Nothing [] [] Nothing Nothing emptyContext Private False [] Nothing [] []
358 (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty
359 AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] []
360 emptyContext S.empty M.empty
363-- | The monad for the main REPL - reading and processing files and updating
364-- global state (hence the IO inner monad).
365--type Idris = WriterT [Either String (IO ())] (State IState a))
366type Idris = StateT IState (ExceptT Err IO)
368catchError :: Idris a -> (Err -> Idris a) -> Idris a
369catchError = liftCatch catchE
371throwError :: Err -> Idris a
372throwError = Trans.lift . throwE
374-- Commands in the REPL
376data Codegen = Via String
385deriving instance NFData Codegen
388data HowMuchDocs = FullDocs | OverviewDocs
394 | NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
398 | DocStr (Either Name Const) HowMuchDocs
402 | Load FilePath (Maybe Int) -- up to maximum line number
403 | ChangeDirectory FilePath
406 | Compile Codegen String
410 | Prove Bool Name -- ^ If false, use prover, if true, use elab shell
411 | AddProof (Maybe Name)
417 | LogCategory [LogCat]
423 | DynamicLink FilePath
426 | Search [String] PTerm
427 | CaseSplitAt Bool Int Name
428 | AddClauseFrom Bool Int Name
429 | AddProofClauseFrom Bool Int Name
430 | AddMissing Bool Int Name
431 | MakeWith Bool Int Name
432 | MakeCase Bool Int Name
433 | MakeLemma Bool Int Name
434 | DoProofSearch Bool -- update file
435 Bool -- recursive search
437 Name -- top level name
442 | SetColour ColourType IdrisColour
446 | SetConsoleWidth ConsoleWidth
447 | SetPrinterDepth (Maybe Int)
448 | Apropos [String] String
452 | MakeDoc String -- IdrisDoc
455 | PPrint OutputFmt Int PTerm
457 -- Debugging commands
459 | DebugUnify PTerm PTerm
461data OutputFmt = HTMLOutput | LaTeXOutput
463-- | Recognised logging categories for the Idris compiler.
465-- @TODO add in sub categories.
472 deriving (Show, Eq, Ord)
474strLogCat :: LogCat -> String
475strLogCat IParse = "parser"
476strLogCat IElab = "elab"
477strLogCat ICodeGen = "codegen"
478strLogCat IErasure = "erasure"
479strLogCat ICoverage = "coverage"
480strLogCat IIBC = "ibc"
482codegenCats :: [LogCat]
483codegenCats = [ICodeGen]
485parserCats :: [LogCat]
491loggingCatsStr :: String
492loggingCatsStr = unlines
495 , (strLogCat ICodeGen)
496 , (strLogCat IErasure)
497 , (strLogCat ICoverage)
501data Opt = Filename String
514 | NoBuiltins -- only for the really primitive stuff!
531 | Port String -- REPL TCP port
539 | PkgMkDoc String -- IdrisDoc
549 | OutputTy OutputType
550 | Extension LanguageExt
551 | InterpretScript String
553 | TargetTriple String
556 | AddOpt Optimisation
557 | RemoveOpt Optimisation
560 | AutoWidth -- ^ Automatically adjust terminal width
561 | AutoSolve -- ^ Automatically issue "solve" tactic in old-style interactive prover
562 | UseConsoleWidth ConsoleWidth
565 | NoElimDeprecationWarnings -- ^ Don't show deprecation warnings for %elim
566 | NoOldTacticDeprecationWarnings -- ^ Don't show deprecation warnings for old-style tactics
569data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm
570 | EEval PTerm | ECheck PTerm | ESearch PTerm
571 | EDocStr (Either Name Const)
574-- Parsed declarations
576data Fixity = Infixl { prec :: Int }
577 | Infixr { prec :: Int }
578 | InfixN { prec :: Int }
579 | PrefixN { prec :: Int }
582deriving instance Binary Fixity
583deriving instance NFData Fixity
586instance Show Fixity where
587 show (Infixl i) = "infixl " ++ show i
588 show (Infixr i) = "infixr " ++ show i
589 show (InfixN i) = "infix " ++ show i
590 show (PrefixN i) = "prefix " ++ show i
592data FixDecl = Fix Fixity String
595instance Show FixDecl where
596 show (Fix f s) = show f ++ " " ++ s
599deriving instance Binary FixDecl
600deriving instance NFData FixDecl
603instance Ord FixDecl where
604 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
607data Static = Static | Dynamic
608 deriving (Show, Eq, Data, Typeable)
610deriving instance Binary Static
611deriving instance NFData Static
614-- Mark bindings with their explicitness, and laziness
615data Plicity = Imp { pargopts :: [ArgOpt],
618 pscoped :: Maybe ImplicitInfo -- Nothing, if top level
620 | Exp { pargopts :: [ArgOpt],
622 pparam :: Bool } -- this is a param (rather than index)
623 | Constraint { pargopts :: [ArgOpt],
625 | TacImp { pargopts :: [ArgOpt],
628 deriving (Show, Eq, Data, Typeable)
631deriving instance Binary Plicity
632deriving instance NFData Plicity
635is_scoped :: Plicity -> Maybe ImplicitInfo
636is_scoped (Imp _ _ _ s) = s
639impl = Imp [] Dynamic False (Just (Impl False True))
641forall_imp = Imp [] Dynamic False (Just (Impl False False))
642forall_constraint = Imp [] Dynamic False (Just (Impl True False))
644expl = Exp [] Dynamic False
645expl_param = Exp [] Dynamic True
647constraint = Constraint [] Static
649tacimpl t = TacImp [] Dynamic t
651data FnOpt = Inlinable -- always evaluate when simplifying
652 | TotalFn | PartialFn | CoveringFn
653 | Coinductive | AssertTotal
654 | Dictionary -- type class dictionary, eval only when
655 -- a function argument, and further evaluation resutls
656 | Implicit -- implicit coercion
657 | NoImplicit -- do not apply implicit coercions
658 | CExport String -- export, with a C name
659 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
660 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
661 | Reflection -- a reflecting function, compile-time only
662 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
663 | Constructor -- Data constructor type
664 | AutoHint -- use in auto implicit search
665 | PEGenerated -- generated by partial evaluator
668deriving instance Binary FnOpt
669deriving instance NFData FnOpt
674inlinable :: FnOpts -> Bool
675inlinable = elem Inlinable
677dictionary :: FnOpts -> Bool
678dictionary = elem Dictionary
681-- | Type provider - what to provide
682data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
683 | ProvPostulate t -- ^ goal type must be Type, so only term
684 deriving (Show, Eq, Functor)
686type ProvideWhat = ProvideWhat' PTerm
688-- | Top-level declarations such as compiler directives, definitions,
689-- datatypes and typeclasses.
691 = PFix FC Fixity [String] -- ^ Fixity declaration
692 | PTy (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location)
693 | PPostulate Bool -- external def if true
694 (Docstring (Either Err t)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location
695 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
696 | PCAF FC Name t -- ^ Top level constant
697 | PData (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
698 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
699 | PNamespace String FC [PDecl' t]
700 -- ^ New namespace, where FC is accurate location of the
701 -- namespace in the file
702 | PRecord (Docstring (Either Err t)) SyntaxInfo FC DataOpts
704 FC -- Record name precise location
705 [(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span
706 [(Name, Docstring (Either Err t))] -- Param Docs
707 [(Maybe (Name, FC), Plicity, t, Maybe (Docstring (Either Err t)))] -- Fields
708 (Maybe (Name, FC)) -- Optional constructor name and location
709 (Docstring (Either Err t)) -- Constructor doc
710 SyntaxInfo -- Constructor SyntaxInfo
711 -- ^ Record declaration
712 | PClass (Docstring (Either Err t)) SyntaxInfo FC
713 [(Name, t)] -- constraints
715 FC -- accurate location of class name
716 [(Name, FC, t)] -- parameters and precise locations
717 [(Name, Docstring (Either Err t))] -- parameter docstrings
718 [(Name, FC)] -- determining parameters and precise locations
719 [PDecl' t] -- declarations
720 (Maybe (Name, FC)) -- instance constructor name and location
721 (Docstring (Either Err t)) -- instance constructor docs
722 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
723 -- class name, class name location, parameters, method declarations, optional constructor name
725 (Docstring (Either Err t)) -- Instance docs
726 [(Name, Docstring (Either Err t))] -- Parameter docs
728 FC [(Name, t)] -- constraints
732 FC -- precise location of class
734 t -- full instance type
735 (Maybe Name) -- explicit name
737 -- ^ Instance declaration: arguments are documentation, syntax info, source
738 -- location, constraints, class name, parameters, full instance
739 -- type, optional explicit name, and definitions
740 | PDSL Name (DSL' t) -- ^ DSL declaration
741 | PSyntax FC Syntax -- ^ Syntax definition
742 | PMutual FC [PDecl' t] -- ^ Mutual block
743 | PDirective Directive -- ^ Compiler directive.
744 | PProvider (Docstring (Either Err t)) SyntaxInfo FC FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term. The second FC is precise highlighting location.
745 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
746 -- bool is True, lhs and rhs must be convertible
747 | PRunElabDecl FC t [String] -- ^ FC is decl-level, for errors, and
748 -- Strings represent the namespace
751deriving instance Binary PDecl'
752deriving instance NFData PDecl'
755-- | The set of source directives
756data Directive = DLib Codegen String |
757 DLink Codegen String |
758 DFlag Codegen String |
759 DInclude Codegen String |
762 DAccess Accessibility |
765 DDynamicLibs [String] |
766 DNameHint Name FC [(Name, FC)] |
767 DErrorHandlers Name FC Name FC [(Name, FC)] |
768 DLanguage LanguageExt |
769 DDeprecate Name String |
770 DAutoImplicits Bool |
773-- | A set of instructions for things that need to happen in IState
774-- after a term elaboration when there's been reflected elaboration.
775data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
776 | RClausesInstrs Name [([(Name, Term)], Term, Term)]
777 | RAddInstance Name Name
779-- | For elaborator state
780data EState = EState {
781 case_decls :: [(Name, PDecl)],
782 delayed_elab :: [(Int, Elab' EState ())],
783 new_tyDecls :: [RDeclInstructions],
784 highlighting :: [(FC, OutputAnnotation)]
788initEState = EState [] [] [] []
790type ElabD a = Elab' EState a
792highlightSource :: FC -> OutputAnnotation -> ElabD ()
793highlightSource fc annot =
794 updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux })
796-- | One clause of a top-level definition. Term arguments to constructors are:
798-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
800-- 2. The list of extra 'with' patterns
802-- 3. The right-hand side
804-- 4. The where block (PDecl' t)
806data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
807 | PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t]
808 | PClauseR FC [t] t [PDecl' t]
809 | PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t]
812deriving instance Binary PClause'
813deriving instance NFData PClause'
817data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
818 d_name_fc :: FC, -- ^ The precise location of the type constructor name
819 d_tcon :: t, -- ^ Type constructor
820 d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors
822 -- ^ Data declaration
823 | PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t }
824 -- ^ "Placeholder" for data whose constructors are defined later
827-- | Transform the FCs in a PData and its associated terms. The first
828-- function transforms the general-purpose FCs, and the second transforms
829-- those that are used for semantic source highlighting, so they can be
831mapPDataFC :: (FC -> FC) -> (FC -> FC) -> PData -> PData
832mapPDataFC f g (PDatadecl n nfc tycon ctors) =
833 PDatadecl n (g nfc) (mapPTermFC f g tycon) (map ctorFC ctors)
834 where ctorFC (doc, argDocs, n, nfc, ty, fc, ns) =
835 (doc, argDocs, n, g nfc, mapPTermFC f g ty, f fc, ns)
836mapPDataFC f g (PLaterdecl n nfc tycon) =
837 PLaterdecl n (g nfc) (mapPTermFC f g tycon)
839deriving instance Binary PData'
840deriving instance NFData PData'
843-- Handy to get a free function for applying PTerm -> PTerm functions
844-- across a program, by deriving Functor
846type PDecl = PDecl' PTerm
847type PData = PData' PTerm
848type PClause = PClause' PTerm
850-- | Transform the FCs in a PTerm. The first function transforms the
851-- general-purpose FCs, and the second transforms those that are used
852-- for semantic source highlighting, so they can be treated specially.
853mapPDeclFC :: (FC -> FC) -> (FC -> FC) -> PDecl -> PDecl
854mapPDeclFC f g (PFix fc fixity ops) =
855 PFix (f fc) fixity ops
856mapPDeclFC f g (PTy doc argdocs syn fc opts n nfc ty) =
857 PTy doc argdocs syn (f fc) opts n (g nfc) (mapPTermFC f g ty)
858mapPDeclFC f g (PPostulate ext doc syn fc nfc opts n ty) =
859 PPostulate ext doc syn (f fc) (g nfc) opts n (mapPTermFC f g ty)
861mapPDeclFC f g (PClauses fc opts n clauses) =
862 PClauses (f fc) opts n (map (fmap (mapPTermFC f g)) clauses)
863mapPDeclFC f g (PCAF fc n tm) = PCAF (f fc) n (mapPTermFC f g tm)
864mapPDeclFC f g (PData doc argdocs syn fc opts dat) =
865 PData doc argdocs syn (f fc) opts (mapPDataFC f g dat)
866mapPDeclFC f g (PParams fc params decls) =
868 (map (\(n, ty) -> (n, mapPTermFC f g ty)) params)
869 (map (mapPDeclFC f g) decls)
870mapPDeclFC f g (PNamespace ns fc decls) =
871 PNamespace ns (f fc) (map (mapPDeclFC f g) decls)
872mapPDeclFC f g (PRecord doc syn fc opts n nfc params paramdocs fields ctor ctorDoc syn') =
873 PRecord doc syn (f fc) opts n (g nfc)
874 (map (\(pn, pnfc, plic, ty) -> (pn, g pnfc, plic, mapPTermFC f g ty)) params)
876 (map (\(fn, plic, ty, fdoc) -> (fmap (\(fn', fnfc) -> (fn', g fnfc)) fn,
877 plic, mapPTermFC f g ty, fdoc))
879 (fmap (\(ctorN, ctorNFC) -> (ctorN, g ctorNFC)) ctor)
882mapPDeclFC f g (PClass doc syn fc constrs n nfc params paramDocs det body ctor ctorDoc) =
883 PClass doc syn (f fc)
884 (map (\(constrn, constr) -> (constrn, mapPTermFC f g constr)) constrs)
885 n (g nfc) (map (\(n, nfc, pty) -> (n, g nfc, mapPTermFC f g pty)) params)
886 paramDocs (map (\(dn, dnfc) -> (dn, g dnfc)) det)
887 (map (mapPDeclFC f g) body)
888 (fmap (\(n, nfc) -> (n, g nfc)) ctor)
890mapPDeclFC f g (PInstance doc paramDocs syn fc constrs cn acc opts cnfc params instTy instN body) =
891 PInstance doc paramDocs syn (f fc)
892 (map (\(constrN, constrT) -> (constrN, mapPTermFC f g constrT)) constrs)
893 cn acc opts (g cnfc) (map (mapPTermFC f g) params)
894 (mapPTermFC f g instTy)
896 (map (mapPDeclFC f g) body)
897mapPDeclFC f g (PDSL n dsl) = PDSL n (fmap (mapPTermFC f g) dsl)
898mapPDeclFC f g (PSyntax fc syn) = PSyntax (f fc) $
900 Rule syms tm ctxt -> Rule syms (mapPTermFC f g tm) ctxt
901 DeclRule syms decls -> DeclRule syms (map (mapPDeclFC f g) decls)
902mapPDeclFC f g (PMutual fc decls) =
903 PMutual (f fc) (map (mapPDeclFC f g) decls)
904mapPDeclFC f g (PDirective d) =
907 DNameHint n nfc ns ->
908 DNameHint n (g nfc) (map (\(hn, hnfc) -> (hn, g hnfc)) ns)
909 DErrorHandlers n nfc n' nfc' ns ->
910 DErrorHandlers n (g nfc) n' (g nfc') $
911 map (\(an, anfc) -> (an, g anfc)) ns
912mapPDeclFC f g (PProvider doc syn fc nfc what n) =
913 PProvider doc syn (f fc) (g nfc) (fmap (mapPTermFC f g) what) n
914mapPDeclFC f g (PTransform fc safe l r) =
915 PTransform (f fc) safe (mapPTermFC f g l) (mapPTermFC f g r)
916mapPDeclFC f g (PRunElabDecl fc script ns) =
917 PRunElabDecl (f fc) (mapPTermFC f g script) ns
919-- | Get all the names declared in a declaration
920declared :: PDecl -> [Name]
921declared (PFix _ _ _) = []
922declared (PTy _ _ _ _ _ n fc t) = [n]
923declared (PPostulate _ _ _ _ _ _ n t) = [n]
924declared (PClauses _ _ n _) = [] -- not a declaration
925declared (PCAF _ n _) = [n]
926declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
927 where fstt (_, _, a, _, _, _, _) = a
928declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n]
929declared (PParams _ _ ds) = concatMap declared ds
930declared (PNamespace _ _ ds) = concatMap declared ds
931declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
932declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms)
933declared (PInstance _ _ _ _ _ _ _ _ _ _ _ _ _) = []
934declared (PDSL n _) = [n]
935declared (PSyntax _ _) = []
936declared (PMutual _ ds) = concatMap declared ds
937declared (PDirective _) = []
940-- get the names declared, not counting nested parameter blocks
941tldeclared :: PDecl -> [Name]
942tldeclared (PFix _ _ _) = []
943tldeclared (PTy _ _ _ _ _ n _ t) = [n]
944tldeclared (PPostulate _ _ _ _ _ _ n t) = [n]
945tldeclared (PClauses _ _ n _) = [] -- not a declaration
946tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
947tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
948 where fstt (_, _, a, _, _, _, _) = a
949tldeclared (PParams _ _ ds) = []
950tldeclared (PMutual _ ds) = concatMap tldeclared ds
951tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds
952tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms)
953tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _ _ _) = []
956defined :: PDecl -> [Name]
957defined (PFix _ _ _) = []
958defined (PTy _ _ _ _ _ n _ t) = []
959defined (PPostulate _ _ _ _ _ _ n t) = []
960defined (PClauses _ _ n _) = [n] -- not a declaration
961defined (PCAF _ n _) = [n]
962defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
963 where fstt (_, _, a, _, _, _, _) = a
964defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = []
965defined (PParams _ _ ds) = concatMap defined ds
966defined (PNamespace _ _ ds) = concatMap defined ds
967defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
968defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms)
969defined (PInstance _ _ _ _ _ _ _ _ _ _ _ _ _) = []
970defined (PDSL n _) = [n]
971defined (PSyntax _ _) = []
972defined (PMutual _ ds) = concatMap defined ds
973defined (PDirective _) = []
976updateN :: [(Name, Name)] -> Name -> Name
977updateN ns n | Just n' <- lookup n ns = n'
980updateNs :: [(Name, Name)] -> PTerm -> PTerm
982updateNs ns t = mapPT updateRef t
983 where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)
986-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
988-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
989-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
990-- where updateCNs ns (PClause n l ts r ds)
991-- = PClause (updateN ns n) (fmap (updateNs ns) l)
992-- (map (fmap (updateNs ns)) ts)
993-- (fmap (updateNs ns) r)
994-- (map (updateDNs ns) ds)
997data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable)
999-- | High level language terms
1000data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language
1001 | PRef FC [FC] Name -- ^ A reference to a variable. The FC is its precise source location for highlighting. The list of FCs is a collection of additional highlighting locations.
1002 | PInferRef FC [FC] Name -- ^ A name to be defined later
1003 | PPatvar FC Name -- ^ A pattern variable
1004 | PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span.
1005 | PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable
1006 | PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location)
1007 | PTyped PTerm PTerm -- ^ Term with explicit type
1008 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
1009 | PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only)
1010 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
1011 | PMatchApp FC Name -- ^ Make an application by type matching
1012 | PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse
1013 | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
1014 | PTrue FC PunInfo -- ^ Unit type..?
1015 | PResolveTC FC -- ^ Solve this dictionary by type class resolution
1016 | PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type
1017 | PPair FC [FC] PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration). The list of FCs is its punctuation.
1018 | PDPair FC [FC] PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration). The [FC] is its punctuation.
1019 | PAs FC Name PTerm -- ^ @-pattern, valid LHS only
1020 | PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames.
1021 | PHidden PTerm -- ^ Irrelevant or hidden pattern
1022 | PType FC -- ^ 'Type' type
1023 | PUniverse Universe -- ^ Some universe
1024 | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
1025 | PConstant FC Const -- ^ Builtin types
1026 | Placeholder -- ^ Underscore
1027 | PDoBlock [PDo] -- ^ Do notation
1028 | PIdiom FC PTerm -- ^ Idiom brackets
1030 | PMetavar FC Name -- ^ A metavariable, ?name, and its precise location
1031 | PProof [PTactic] -- ^ Proof script
1032 | PTactics [PTactic] -- ^ As PProof, but no auto solving
1033 | PElabError Err -- ^ Error to report on elaboration
1034 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
1035 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
1036 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
1037 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
1038 | PNoImplicits PTerm -- ^ never run implicit converions on the term
1039 | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
1040 | PUnquote PTerm -- ^ ~Term
1041 | PQuoteName Name Bool FC -- ^ `{n} where the FC is the precise highlighting for the name in particular. If the Bool is False, then it's `{{n}} and the name won't be resolved.
1042 | PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace.
1043 | PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later.
1044 deriving (Eq, Data, Typeable)
1046data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed
1049 deriving (Eq, Data, Typeable)
1051-- | Transform the FCs in a PTerm. The first function transforms the
1052-- general-purpose FCs, and the second transforms those that are used
1053-- for semantic source highlighting, so they can be treated specially.
1054mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm
1055mapPTermFC f g (PQuote q) = PQuote q
1056mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n
1057mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n
1058mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n
1059mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2)
1060mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1061mapPTermFC 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)
1062mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2)
1063mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1064mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls
1065mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1066mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n
1067mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
1068mapPTermFC 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)
1069mapPTermFC f g (PTrue fc info) = PTrue (f fc) info
1070mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc)
1071mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3)
1072mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2)
1073mapPTermFC 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)
1074mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t)
1075mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts)
1076mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t)
1077mapPTermFC f g (PType fc) = PType (f fc)
1078mapPTermFC f g (PUniverse u) = PUniverse u
1079mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2)
1080mapPTermFC f g (PConstant fc c) = PConstant (f fc) c
1081mapPTermFC f g Placeholder = Placeholder
1082mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos)
1083 where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t)
1084 mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)
1085 mapPDoFC (DoBindP fc t1 t2 alts) =
1086 DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)
1087 mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1088 mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1089mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t)
1090mapPTermFC f g (PReturn fc) = PReturn (f fc)
1091mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n
1092mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs)
1093mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs)
1094mapPTermFC f g (PElabError err) = PElabError err
1095mapPTermFC f g PImpossible = PImpossible
1096mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t)
1097mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t)
1098mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t)
1099mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t)
1100mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2)
1101mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t)
1102mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns
1103mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm)
1104mapPTermFC f g (PQuoteName n x fc) = PQuoteName n x (g fc)
1107dg instance Binary PTerm
1108deriving instance NFData PTerm
1111mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
1112mapPT f t = f (mpt t) where
1113 mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s)
1114 mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s)
1115 mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)
1116 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s) (fmap (mapPT f) g)
1117 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
1118 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
1119 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
1120 mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e)
1121 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
1122 mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r)
1123 mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r)
1124 mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as)
1125 mpt (PHidden t) = PHidden (mapPT f t)
1126 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
1127 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
1128 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
1129 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
1130 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
1131 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
1132 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
1136data PTactic' t = Intro [Name] | Intros | Focus Name
1137 | Refine Name [Bool] | Rewrite t | DoUnify
1144 | LetTac Name t | LetTacTy Name t t
1145 | Exact t | Compute | Trivial | TCInstance
1146 | ProofSearch Bool Bool Int (Maybe Name)
1147 [Name] -- allowed local names
1149 -- ^ the bool is whether to search recursively
1152 | ProofState | ProofTerm | Undo
1153 | Try (PTactic' t) (PTactic' t)
1154 | TSeq (PTactic' t) (PTactic' t)
1155 | ApplyTactic t -- see Language.Reflection module
1159 | GoalType String (PTactic' t)
1162 | TDocStr (Either Name Const)
1165 | TFail [ErrorReportPart]
1168 deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable)
1170deriving instance Binary PTactic'
1171deriving instance NFData PTactic'
1173instance Sized a => Sized (PTactic' a) where
1174 size (Intro nms) = 1 + size nms
1176 size (Focus nm) = 1 + size nm
1177 size (Refine nm bs) = 1 + size nm + length bs
1178 size (Rewrite t) = 1 + size t
1179 size (Induction t) = 1 + size t
1180 size (LetTac nm t) = 1 + size nm + size t
1181 size (Exact t) = 1 + size t
1189 size (Try l r) = 1 + size l + size r
1190 size (TSeq l r) = 1 + size l + size r
1191 size (ApplyTactic t) = 1 + size t
1192 size (Reflect t) = 1 + size t
1193 size (Fill t) = 1 + size t
1197 size (TFail ts) = 1 + size ts
1200 size (CaseTac x) = 1 + size x
1201 size (Equiv t) = 1 + size t
1202 size (Claim x y) = 1 + size x + size y
1204 size (MatchRefine x) = 1 + size x
1205 size (LetTacTy x y z) = 1 + size x + size y + size z
1208type PTactic = PTactic' PTerm
1210data PDo' t = DoExp FC t
1211 | DoBind FC Name FC t -- ^ second FC is precise name location
1212 | DoBindP FC t t [(t,t)]
1213 | DoLet FC Name FC t t -- ^ second FC is precise name location
1215 deriving (Eq, Functor, Data, Typeable)
1217deriving instance Binary PDo'
1218deriving instance NFData PDo'
1221instance Sized a => Sized (PDo' a) where
1222 size (DoExp fc t) = 1 + size fc + size t
1223 size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t
1224 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
1225 size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r
1226 size (DoLetP fc l r) = 1 + size fc + size l + size r
1228type PDo = PDo' PTerm
1230-- The priority gives a hint as to elaboration order. Best to elaborate
1231-- things early which will help give a more concrete type to other
1232-- variables, e.g. a before (interpTy a).
1234data PArg' t = PImp { priority :: Int,
1235 machine_inf :: Bool, -- true if the machine inferred it
1236 argopts :: [ArgOpt],
1239 | PExp { priority :: Int,
1240 argopts :: [ArgOpt],
1243 | PConstraint { priority :: Int,
1244 argopts :: [ArgOpt],
1247 | PTacImplicit { priority :: Int,
1248 argopts :: [ArgOpt],
1252 deriving (Show, Eq, Functor, Data, Typeable)
1254data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp
1255 deriving (Show, Eq, Data, Typeable)
1257instance Sized a => Sized (PArg' a) where
1258 size (PImp p _ l nm trm) = 1 + size nm + size trm
1259 size (PExp p l nm trm) = 1 + size nm + size trm
1260 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
1261 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
1264deriving instance Binary PArg'
1265deriving instance NFData PArg'
1268pimp n t mach = PImp 1 mach [] n t
1269pexp t = PExp 1 [] (sMN 0 "arg") t
1270pconst t = PConstraint 1 [] (sMN 0 "carg") t
1271ptacimp n s t = PTacImplicit 2 [] n s t
1273type PArg = PArg' PTerm
1275-- | Get the highest FC in a term, if one exists
1276highestFC :: PTerm -> Maybe FC
1277highestFC (PQuote _) = Nothing
1278highestFC (PRef fc _ _) = Just fc
1279highestFC (PInferRef fc _ _) = Just fc
1280highestFC (PPatvar fc _) = Just fc
1281highestFC (PLam fc _ _ _ _) = Just fc
1282highestFC (PPi _ _ _ _ _) = Nothing
1283highestFC (PLet fc _ _ _ _ _) = Just fc
1284highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty
1285highestFC (PApp fc _ _) = Just fc
1286highestFC (PAppBind fc _ _) = Just fc
1287highestFC (PMatchApp fc _) = Just fc
1288highestFC (PCase fc _ _) = Just fc
1289highestFC (PIfThenElse fc _ _ _) = Just fc
1290highestFC (PTrue fc _) = Just fc
1291highestFC (PResolveTC fc) = Just fc
1292highestFC (PRewrite fc _ _ _) = Just fc
1293highestFC (PPair fc _ _ _ _) = Just fc
1294highestFC (PDPair fc _ _ _ _ _) = Just fc
1295highestFC (PAs fc _ _) = Just fc
1296highestFC (PAlternative _ _ args) =
1297 case mapMaybe highestFC args of
1300highestFC (PHidden _) = Nothing
1301highestFC (PType fc) = Just fc
1302highestFC (PUniverse _) = Nothing
1303highestFC (PGoal fc _ _ _) = Just fc
1304highestFC (PConstant fc _) = Just fc
1305highestFC Placeholder = Nothing
1306highestFC (PDoBlock lines) =
1307 case map getDoFC lines of
1311 getDoFC (DoExp fc t) = fc
1312 getDoFC (DoBind fc nm nfc t) = fc
1313 getDoFC (DoBindP fc l r alts) = fc
1314 getDoFC (DoLet fc nm nfc l r) = fc
1315 getDoFC (DoLetP fc l r) = fc
1317highestFC (PIdiom fc _) = Just fc
1318highestFC (PReturn fc) = Just fc
1319highestFC (PMetavar fc _) = Just fc
1320highestFC (PProof _) = Nothing
1321highestFC (PTactics _) = Nothing
1322highestFC (PElabError _) = Nothing
1323highestFC PImpossible = Nothing
1324highestFC (PCoerced tm) = highestFC tm
1325highestFC (PDisamb _ opts) = highestFC opts
1326highestFC (PUnifyLog tm) = highestFC tm
1327highestFC (PNoImplicits tm) = highestFC tm
1328highestFC (PQuasiquote _ _) = Nothing
1329highestFC (PUnquote tm) = highestFC tm
1330highestFC (PQuoteName _ _ fc) = Just fc
1331highestFC (PRunElab fc _ _) = Just fc
1332highestFC (PConstSugar fc _) = Just fc
1333highestFC (PAppImpl t _) = highestFC t
1337data ClassInfo = CI { instanceCtorName :: Name,
1338 class_methods :: [(Name, (FnOpts, PTerm))],
1339 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
1340 class_default_superclasses :: [PDecl],
1341 class_params :: [Name],
1342 class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded
1343 class_determiners :: [Int] }
1346deriving instance Binary ClassInfo
1347deriving instance NFData ClassInfo
1351data RecordInfo = RI { record_parameters :: [(Name,PTerm)],
1352 record_constructor :: Name,
1353 record_projections :: [Name] }
1356-- Type inference data
1358data TIData = TIPartial -- ^ a function with a partially defined type
1359 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
1362-- | Miscellaneous information about functions
1363data FnInfo = FnInfo { fn_params :: [Int] }
1366deriving instance Binary FnInfo
1367deriving instance NFData FnInfo
1370data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
1371 detaggable :: Bool }
1374deriving instance Binary OptInfo
1375deriving instance NFData OptInfo
1378-- | Syntactic sugar info
1379data DSL' t = DSL { dsl_bind :: t,
1384 index_first :: Maybe t,
1385 index_next :: Maybe t,
1386 dsl_lambda :: Maybe t,
1390 deriving (Show, Functor)
1392deriving instance Binary DSL'
1393deriving instance NFData DSL'
1396type DSL = DSL' PTerm
1398data SynContext = PatternSyntax | TermSyntax | AnySyntax
1401deriving instance Binary SynContext
1402deriving instance NFData SynContext
1405data Syntax = Rule [SSymbol] PTerm SynContext
1406 | DeclRule [SSymbol] [PDecl]
1409syntaxNames :: Syntax -> [Name]
1410syntaxNames (Rule syms _ _) = mapMaybe ename syms
1411 where ename (Keyword n) = Just n
1413syntaxNames (DeclRule syms _) = mapMaybe ename syms
1414 where ename (Keyword n) = Just n
1417syntaxSymbols :: Syntax -> [SSymbol]
1418syntaxSymbols (Rule ss _ _) = ss
1419syntaxSymbols (DeclRule ss _) = ss
1421deriving instance Binary Syntax
1422deriving instance NFData Syntax
1425data SSymbol = Keyword Name
1434deriving instance Binary SSymbol
1435deriving instance NFData SSymbol
1438newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
1440emptySyntaxRules :: SyntaxRules
1441emptySyntaxRules = SyntaxRules []
1443updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
1444updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
1446 newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
1451 ruleSort (s1:ss1) (s2:ss2) =
1452 case symCompare s1 s2 of
1453 EQ -> ruleSort ss1 ss2
1456 -- Better than creating Ord instance for SSymbol since
1457 -- in general this ordering does not really make sense.
1458 symCompare (Keyword n1) (Keyword n2) = compare n1 n2
1459 symCompare (Keyword _) _ = LT
1460 symCompare (Symbol _) (Keyword _) = GT
1461 symCompare (Symbol s1) (Symbol s2) = compare s1 s2
1462 symCompare (Symbol _) _ = LT
1463 symCompare (Binding _) (Keyword _) = GT
1464 symCompare (Binding _) (Symbol _) = GT
1465 symCompare (Binding b1) (Binding b2) = compare b1 b2
1466 symCompare (Binding _) _ = LT
1467 symCompare (Expr _) (Keyword _) = GT
1468 symCompare (Expr _) (Symbol _) = GT
1469 symCompare (Expr _) (Binding _) = GT
1470 symCompare (Expr e1) (Expr e2) = compare e1 e2
1471 symCompare (Expr _) _ = LT
1472 symCompare (SimpleExpr _) (Keyword _) = GT
1473 symCompare (SimpleExpr _) (Symbol _) = GT
1474 symCompare (SimpleExpr _) (Binding _) = GT
1475 symCompare (SimpleExpr _) (Expr _) = GT
1476 symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
1478initDSL = DSL (PRef f [] (sUN ">>="))
1479 (PRef f [] (sUN "return"))
1480 (PRef f [] (sUN "<*>"))
1481 (PRef f [] (sUN "pure"))
1488 where f = fileFC "(builtin)"
1490data Using = UImplicit Name PTerm
1491 | UConstraint Name [Name]
1492 deriving (Show, Eq, Data, Typeable)
1494deriving instance Binary Using
1495deriving instance NFData Using
1498data SyntaxInfo = Syn { using :: [Using],
1499 syn_params :: [(Name, PTerm)],
1500 syn_namespace :: [String],
1502 imp_methods :: [Name], -- class methods. When expanding
1503 -- implicits, these should be expanded even under
1505 decoration :: Name -> Name,
1507 implicitAllowed :: Bool,
1508 maxline :: Maybe Int,
1511 syn_in_quasiquote :: Int }
1514deriving instance NFData SyntaxInfo
1515deriving instance Binary SyntaxInfo
1518defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0
1520expandNS :: SyntaxInfo -> Name -> Name
1521expandNS syn n@(NS _ _) = n
1522expandNS syn n = case syn_namespace syn of
1527-- For inferring types of things
1529bi = fileFC "builtin"
1531inferTy = sMN 0 "__Infer"
1532inferCon = sMN 0 "__infer"
1533inferDecl = PDatadecl inferTy NoFC
1535 [(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) (
1536 PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType"))
1537 (PRef bi [] inferTy)), bi, [])]
1540infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
1541infP = P (TCon 6 0) inferTy (TType (UVal 0))
1543getInferTerm, getInferType :: Term -> Term
1544getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
1545getInferTerm (App _ (App _ _ _) tm) = tm
1546getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1548getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1549 where toTy (Lam t) = Pi Nothing t (TType (UVar 0))
1550 toTy (PVar t) = PVTy t
1552getInferType (App _ (App _ _ ty) _) = ty
1556-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
1558primNames = [inferTy, inferCon]
1561unitCon = sUN "MkUnit"
1563falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
1564 "The empty type, also known as the trivially false proposition." ++
1566 "Use `void` or `absurd` to prove anything if you have a variable " ++
1567 "of type `Void` in scope."
1570pairTy = sNS (sUN "Pair") ["Builtins"]
1571pairCon = sNS (sUN "MkPair") ["Builtins"]
1573upairTy = sNS (sUN "UPair") ["Builtins"]
1574upairCon = sNS (sUN "MkUPair") ["Builtins"]
1578eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
1579 "The propositional equality type. A proof that `x` = `y`." ++
1581 "To use such a proof, pattern-match on it, and the two equal things will " ++
1582 "then need to be the _same_ pattern." ++
1584 "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
1585 "is possible to state equalities between values of potentially different " ++
1586 "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
1588 "You may need to use `(~=~)` to explicitly request heterogeneous equality."
1590eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)]
1591 (piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))]
1593 [(reflDoc, reflParamDoc,
1594 eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) (
1595 PPi impl (n "x") NoFC (PRef bi [] (n "A"))
1596 (PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False,
1597 pimp (n "B") Placeholder False,
1598 pexp (PRef bi [] (n "x")),
1599 pexp (PRef bi [] (n "x"))])), bi, [])]
1601 reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
1602 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1603 "shown that both sides are in fact equal."
1604 reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
1605 (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1607eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
1608 (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
1614-- | The special name to be used in the module documentation context -
1615-- not for use in the main definition context. The namespace around it
1616-- will determine the module to which the docs adhere.
1618modDocName = sMN 0 "ModuleDocs"
1620-- Defined in builtins.idr
1621sigmaTy = sNS (sUN "DPair") ["Builtins"]
1622sigmaCon = sNS (sUN "MkDPair") ["Builtins"]
1624piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1625piBind = piBindp expl
1627piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1629piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t)
1632-- Pretty-printing declarations and terms
1634-- These "show" instances render to an absurdly wide screen because inserted line breaks
1635-- could interfere with interactive editing, which calls "show".
1637instance Show PTerm where
1638 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1640instance Show PDecl where
1641 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
1643instance Show PClause where
1644 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1646instance Show PData where
1647 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1649instance Pretty PTerm OutputAnnotation where
1650 pretty = prettyImp defaultPPOption
1652-- | Colourise annotations according to an Idris state. It ignores the names
1653-- in the annotation, as there's no good way to show extended information on a
1655annotationColour :: IState -> OutputAnnotation -> Maybe IdrisColour
1656annotationColour ist _ | not (idris_colourRepl ist) = Nothing
1657annotationColour ist (AnnConst c) =
1658 let theme = idris_colourTheme ist
1659 in Just $ if constIsType c
1660 then typeColour theme
1661 else dataColour theme
1662annotationColour ist (AnnData _ _) = Just $ dataColour (idris_colourTheme ist)
1663annotationColour ist (AnnType _ _) = Just $ typeColour (idris_colourTheme ist)
1664annotationColour ist (AnnBoundName _ True) = Just $ implicitColour (idris_colourTheme ist)
1665annotationColour ist (AnnBoundName _ False) = Just $ boundVarColour (idris_colourTheme ist)
1666annotationColour ist AnnKeyword = Just $ keywordColour (idris_colourTheme ist)
1667annotationColour ist (AnnName n _ _ _) =
1668 let ctxt = tt_ctxt ist
1669 theme = idris_colourTheme ist
1671 _ | isDConName n ctxt -> Just $ dataColour theme
1672 _ | isFnName n ctxt -> Just $ functionColour theme
1673 _ | isTConName n ctxt -> Just $ typeColour theme
1674 _ | isPostulateName n ist -> Just $ postulateColour theme
1675 _ | otherwise -> Nothing -- don't colourise unknown names
1676annotationColour ist (AnnTextFmt fmt) = Just (colour fmt)
1677 where colour BoldText = IdrisColour Nothing True False True False
1678 colour UnderlineText = IdrisColour Nothing True True False False
1679 colour ItalicText = IdrisColour Nothing True False False True
1680annotationColour ist _ = Nothing
1683-- | Colourise annotations according to an Idris state. It ignores the names
1684-- in the annotation, as there's no good way to show extended
1685-- information on a terminal. Note that strings produced this way will
1686-- not be coloured on Windows, so the use of the colour rendering
1687-- functions in Idris.Output is to be preferred.
1688consoleDecorate :: IState -> OutputAnnotation -> String -> String
1689consoleDecorate ist ann = maybe id colourise (annotationColour ist ann)
1691isPostulateName :: Name -> IState -> Bool
1692isPostulateName n ist = S.member n (idris_postulates ist)
1694-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1695prettyImp :: PPOption -- ^^ pretty printing options
1696 -> PTerm -- ^^ the term to pretty-print
1697 -> Doc OutputAnnotation
1698prettyImp impl = pprintPTerm impl [] [] []
1700-- | Serialise something to base64 using its Binary instance.
1702-- | Do the right thing for rendering a term in an IState
1703prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1704prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1706-- | Pretty-print a high-level Idris term in some bindings context with infix info
1707pprintPTerm :: PPOption -- ^^ pretty printing options
1708 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1709 -> [Name] -- ^^ names to always show in pi, even if not used
1710 -> [FixDecl] -- ^^ Fixity declarations
1711 -> PTerm -- ^^ the term to pretty-print
1712 -> Doc OutputAnnotation
1713pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1718 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1719 prettySe d p bnd (PQuote r) =
1720 text "![" <> pretty r <> text "]"
1721 prettySe d p bnd (PPatvar fc n) = pretty n
1723 | Just str <- slist d p bnd e = depth d $ str
1724 | Just n <- snat ppo d p e = depth d $ annotate (AnnData "Nat" "") (text (show n))
1725 prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n
1726 prettySe d p bnd (PLam fc n nfc ty sc) =
1727 depth d . bracket p startPrec . group . align . hang 2 $
1728 text "\\" <> prettyBindingOf n False <+> text "=>" <$>
1729 prettySe (decD d) startPrec ((n, False):bnd) sc
1730 prettySe d p bnd (PLet fc n nfc ty v sc) =
1731 depth d . bracket p startPrec . group . align $
1732 kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
1733 kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
1734 prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
1735 | n `elem` allNamesIn sc || ppopt_impl ppo && uname n || n `elem` docArgs
1736 || ppopt_pinames ppo && uname n =
1737 depth d . bracket p startPrec . group $
1738 enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
1739 st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
1741 depth d . bracket p startPrec . group $
1742 group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$>
1743 group (prettySe (decD d) startPrec ((n, False):bnd) sc)
1745 uname (UN n) = case str n of
1752 Static -> text "%static" <> space
1754 prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc)
1756 depth d . bracket p startPrec $
1757 lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
1758 st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1759 | otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
1763 Static -> text "%static" <> space
1765 prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
1766 depth d . bracket p startPrec $
1767 prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1768 prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch{}])) n _ ty sc) =
1769 lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1770 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1771 prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
1772 depth d . bracket p startPrec $
1773 lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1774 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1775 -- This case preserves the behavior of the former constructor PEq.
1776 -- It should be removed if feasible when the pretty-printing of infix
1777 -- operators in general is improved.
1778 prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r])
1779 | n == eqTy, ppopt_impl ppo =
1780 depth d . bracket p eqPrec $
1781 enclose lparen rparen eq <+>
1782 align (group (vsep (map (prettyArgS (decD d) bnd)
1785 depth d . bracket p eqPrec . align . group $
1786 prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r))
1787 where eq = annName eqTy (text "=")
1789 prettyTerm = prettySe (decD d) (eqPrec + 1) bnd
1790 prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args
1791 | UN nm <- basename f
1792 , not (ppopt_impl ppo) && null (getShowArgs args) =
1793 prettyName True (ppopt_impl ppo) bnd f
1794 prettySe d p bnd (PAppBind _ (PRef _ _ f) [])
1795 | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
1796 prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators
1797 | UN nm <- basename op
1799 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1800 case getShowArgs args of
1802 [x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x)))
1803 [l,r] -> let precedence = maybe (startPrec - 1) prec f
1804 in depth d . bracket p precedence $ inFix (getTm l) (getTm r)
1805 (l@(PExp{}) : r@(PExp{}) : rest) ->
1806 depth d . bracket p funcAppPrec $
1807 enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
1808 align (group (vsep (map (prettyArgS d bnd) rest)))
1809 as -> opName True <+> align (vsep (map (prettyArgS d bnd) as))
1810 where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
1811 f = getFixity (opStr op)
1813 Nothing -> funcAppPrec + 1
1814 Just (Infixl p') -> p'
1815 Just f' -> prec f' + 1
1817 Nothing -> funcAppPrec + 1
1818 Just (Infixr p') -> p'
1819 Just f' -> prec f' + 1
1820 inFix l r = align . group $
1821 (prettySe (decD d) left bnd l <+> opName False) <$>
1822 group (prettySe (decD d) right bnd r)
1823 prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo
1824 | PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm,
1825 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1826 char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str))
1827 prettySe d p bnd (PApp _ f as) = -- Normal prefix applications
1828 let args = getShowArgs as
1829 fp = prettySe (decD d) (startPrec + 1) bnd f
1830 shownArgs = if ppopt_impl ppo then as else args
1832 depth d . bracket p funcAppPrec . group $
1835 else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs))
1836 prettySe d p bnd (PCase _ scr cases) =
1837 align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$>
1838 depth d (indent 2 (vsep (map ppcase cases)))
1840 ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec
1841 ([(n, False) | n <- vars l] ++ bnd)
1842 in nest nestingSize $
1843 prettyCase l <+> text "=>" <+> prettyCase r
1844 -- Warning: this is a bit of a hack. At this stage, we don't have the
1845 -- global context, so we can't determine which names are constructors,
1846 -- which are types, and which are pattern variables on the LHS of the
1847 -- case pattern. We use the heuristic that names without a namespace
1848 -- are patvars, because right now case blocks in PTerms are always
1849 -- delaborated from TT before being sent to the pretty-printer. If they
1850 -- start getting printed directly, THIS WILL BREAK.
1851 -- Potential solution: add a list of known patvars to the cases in
1852 -- PCase, and have the delaborator fill it out, kind of like the pun
1853 -- disambiguation on PDPair.
1854 vars tm = filter noNS (allNamesIn tm)
1855 noNS (NS _ _) = False
1858 prettySe d p bnd (PIfThenElse _ c t f) =
1859 depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $
1860 [ kwd "if" <+> prettySe (decD d) startPrec bnd c
1861 , kwd "then" <+> prettySe (decD d) startPrec bnd t
1862 , kwd "else" <+> prettySe (decD d) startPrec bnd f
1864 prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
1865 prettySe d p bnd (PResolveTC _) = kwd "%instance"
1866 prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1867 prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1868 prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
1869 prettySe d p bnd (PRewrite _ l r _) =
1870 depth d . bracket p startPrec $
1871 text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r
1872 prettySe d p bnd (PTyped l r) =
1873 lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen
1874 prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser
1875 | Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) .
1876 align . group . vsep . punctuate (ann comma) $
1877 map (prettySe (decD d) startPrec bnd) elts
1878 where ann = case pun of
1880 IsType -> annName pairTy
1881 IsTerm -> annName pairCon
1882 prettySe d p bnd (PDPair _ _ pun l t r) =
1886 annotated (text "**") <+>
1887 prettySe (decD d) startPrec (addBinding bnd) r <>
1889 where annotated = case pun of
1890 IsType -> annName sigmaTy
1891 IsTerm -> annName sigmaCon
1893 (left, addBinding) = case (l, pun) of
1894 (PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :))
1895 _ -> (prettySe (decD d) startPrec bnd l, id)
1896 prettySe d p bnd (PAlternative ns a as) =
1897 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1900 foldr ((\ l r -> l <+> text "," <+> r) .
1901 depth d . prettySe (decD d) startPrec bnd)
1903 prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type"
1904 prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
1905 prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c))
1906 -- XXX: add pretty for tactics
1907 prettySe d p bnd (PProof ts) =
1908 kwd "proof" <+> lbrace <> ellipsis <> rbrace
1909 prettySe d p bnd (PTactics ts) =
1910 kwd "tactics" <+> lbrace <> ellipsis <> rbrace
1911 prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n
1912 prettySe d p bnd (PReturn f) = kwd "return"
1913 prettySe d p bnd PImpossible = kwd "impossible"
1914 prettySe d p bnd Placeholder = text "_"
1915 prettySe d p bnd (PDoBlock dos) =
1916 bracket p startPrec $
1917 kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos)))
1918 where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos
1919 ppdo bnd (DoBind _ bn _ tm : dos) =
1920 (prettyBindingOf bn False <+> text "<-" <+>
1921 group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) :
1922 ppdo ((bn, False):bnd) dos
1923 ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab
1924 text "no pretty printer for pattern-matching do binding" :
1926 ppdo bnd (DoLet _ ln _ ty v : dos) =
1927 (kwd "let" <+> prettyBindingOf ln False <+>
1928 (if ty /= Placeholder
1929 then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="
1931 group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :
1932 ppdo ((ln, False):bnd) dos
1933 ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab
1934 text "no pretty printer for pattern-matching do binding" :
1937 prettySe d p bnd (PCoerced t) = prettySe d p bnd t
1938 prettySe d p bnd (PElabError s) = pretty s
1939 -- Quasiquote pprinting ignores bound vars
1940 prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")"
1941 prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")"
1942 prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t
1943 prettySe d p bnd (PQuoteName n res _) = text start <> prettyName True (ppopt_impl ppo) bnd n <> text end
1944 where start = if res then "`{" else "`{{"
1945 end = if res then "}" else "}}"
1946 prettySe d p bnd (PRunElab _ tm _) =
1947 bracket p funcAppPrec . group . align . hang 2 $
1949 prettySe (decD d) funcAppPrec bnd tm
1950 prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
1951 prettySe d p bnd _ = text "missing pretty-printer for term"
1953 prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
1954 prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
1955 where display (UN n) = T.unpack n
1956 display (MN _ n) = T.unpack n
1957 -- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
1958 display (NS n ns) = (intercalate "." . map T.unpack . reverse) ns ++ "." ++ display n
1961 prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm)
1962 prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm
1963 prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm
1964 prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm)
1966 prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg
1967 prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
1968 prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace
1969 prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
1971 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1972 annName n = annotate (AnnName n Nothing Nothing Nothing)
1974 opStr :: Name -> String
1975 opStr (NS n _) = opStr n
1976 opStr (UN n) = T.unpack n
1978 slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation]
1979 slist' (Just d) _ _ _ | d <= 0 = Nothing
1981 | containsHole e = Nothing
1982 slist' d p bnd (PApp _ (PRef _ _ nil) _)
1983 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1984 slist' d p bnd (PRef _ _ nil)
1985 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1986 slist' d p bnd (PApp _ (PRef _ _ cons) args)
1987 | nsroot cons == sUN "::",
1988 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1990 Just tl' <- slist' (decD d) p bnd tl
1991 = Just (prettySe d startPrec bnd hd : tl')
1993 isImp (PImp {}) = True
1995 slist' _ _ _ tm = Nothing
1997 slist d p bnd e | Just es <- slist' d p bnd e = Just $
1999 [] -> annotate (AnnData "" "") $ text "[]"
2000 [x] -> enclose left right . group $ x
2001 xs -> enclose left right .
2002 align . group . vsep .
2003 punctuate comma $ xs
2004 where left = (annotate (AnnData "" "") (text "["))
2005 right = (annotate (AnnData "" "") (text "]"))
2006 comma = (annotate (AnnData "" "") (text ","))
2007 slist _ _ _ _ = Nothing
2009 pairElts :: PTerm -> Maybe [PTerm]
2010 pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts)
2011 | otherwise = Just [x, y]
2012 pairElts _ = Nothing
2014 natns = "Prelude.Nat."
2016 snat :: PPOption -> Maybe Int -> Int -> PTerm -> Maybe Integer
2018 | ppopt_desugarnats ppo = Nothing
2019 | otherwise = snat' d p e
2021 snat' :: Maybe Int -> Int -> PTerm -> Maybe Integer
2022 snat' (Just x) _ _ | x <= 0 = Nothing
2023 snat' d p (PRef _ _ z)
2024 | show z == (natns++"Z") || show z == "Z" = Just 0
2025 snat' d p (PApp _ s [PExp {getTm=n}])
2026 | show s == (natns++"S") || show s == "S",
2027 Just n' <- snat' (decD d) p n
2029 snat' _ _ _ = Nothing
2031 bracket outer inner doc
2032 | outer > inner = lparen <> doc <> rparen
2035 ellipsis = text "..."
2038 depth (Just d) = if d <= 0 then const ellipsis else id
2040 decD = fmap (\x -> x - 1)
2042 kwd = annotate AnnKeyword . text
2044 fixities :: M.Map String Fixity
2045 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
2047 getFixity :: String -> Maybe Fixity
2048 getFixity = flip M.lookup fixities
2050-- | Strip away namespace information
2051basename :: Name -> Name
2052basename (NS n _) = basename n
2055-- | Determine whether a name was the one inserted for a hole or
2056-- guess by the delaborator
2057isHoleName :: Name -> Bool
2058isHoleName (UN n) = n == T.pack "[__]"
2061-- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess
2062containsHole :: PTerm -> Bool
2063containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm]
2065-- | Pretty-printer helper for names that attaches the correct annotations
2067 :: Bool -- ^^ whether the name should be parenthesised if it is an infix operator
2068 -> Bool -- ^^ whether to show namespaces
2069 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
2070 -> Name -- ^^ the name to pprint
2071 -> Doc OutputAnnotation
2072prettyName infixParen showNS bnd n
2073 | (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_"
2074 | (UN n') <- n, T.unpack n' == "_" = text "_"
2075 | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
2076 | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
2077 where fullName = text nameSpace <> parenthesise (text (baseName n))
2078 baseName (UN n) = T.unpack n
2079 baseName (NS n ns) = baseName n
2080 baseName (MN i s) = T.unpack s
2081 baseName other = show other
2082 nameSpace = case n of
2083 (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
2085 isInfix = case baseName n of
2087 (c : _) -> not (isAlpha c)
2088 parenthesise = if isInfix && infixParen then enclose lparen rparen else id
2091showCImp :: PPOption -> PClause -> Doc OutputAnnotation
2092showCImp ppo (PClause _ n l ws r w)
2093 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
2094 <+> text "where" <+> text (show w)
2097 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2098showCImp ppo (PWith _ n l ws r pn w)
2099 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
2100 <+> braces (text (show w))
2103 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2106showDImp :: PPOption -> PData -> Doc OutputAnnotation
2107showDImp ppo (PDatadecl n nfc ty cons)
2108 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
2109 (indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
2111showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
2112showDecls o ds = vsep (map (showDeclImp o) ds)
2114showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
2115showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
2116showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
2117 indent 2 (vsep (map (showCImp o) cs))
2118showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
2119showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
2120showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
2121showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
2122showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _)
2123 = text "interface" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
2124showDeclImp o (PInstance _ _ _ _ cs acc _ n _ _ t _ ds)
2125 = text "implementation" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
2126showDeclImp _ _ = text "..."
2127-- showDeclImp (PImport o) = "import " ++ o
2129getImps :: [PArg] -> [(Name, PTerm)]
2131getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
2132getImps (_ : xs) = getImps xs
2134getExps :: [PArg] -> [PTerm]
2136getExps (PExp _ _ _ tm : xs) = tm : getExps xs
2137getExps (_ : xs) = getExps xs
2139getShowArgs :: [PArg] -> [PArg]
2141getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
2142getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
2143 | PImp _ _ _ _ tm <- e
2144 , containsHole tm = e : getShowArgs xs
2145getShowArgs (_ : xs) = getShowArgs xs
2147getConsts :: [PArg] -> [PTerm]
2149getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
2150getConsts (_ : xs) = getConsts xs
2152getAll :: [PArg] -> [PTerm]
2157showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
2158 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
2159 -> PPOption -- ^^ pretty printing options
2160 -> Bool -- ^^ whether to colourise
2161 -> Name -- ^^ the term to show
2163showName ist bnd ppo colour n = case ist of
2164 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
2165 Nothing -> showbasic n
2166 where name = if ppopt_impl ppo then show n else showbasic n
2167 showbasic n@(UN _) = showCG n
2168 showbasic (MN i s) = str s
2169 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
2170 showbasic (SN s) = show s
2172 colourise n t = let ctxt' = fmap tt_ctxt ist in
2175 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
2176 else colouriseBound t name
2177 | isDConName n ctxt -> colouriseData t name
2178 | isFnName n ctxt -> colouriseFun t name
2179 | isTConName n ctxt -> colouriseType t name
2180 -- The assumption is that if a name is not bound and does not exist in the
2181 -- global context, then we're somewhere in which implicit info has been lost
2182 -- (like error messages). Thus, unknown vars are colourised as implicits.
2183 | otherwise -> colouriseImplicit t name
2185showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
2186 -> PTerm -- ^^ the term to show
2188showTm ist = displayDecorated (consoleDecorate ist) .
2189 renderPretty 0.8 100000 .
2190 prettyImp (ppOptionIst ist)
2192-- | Show a term with implicits, no colours
2193showTmImpls :: PTerm -> String
2194showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
2196-- | Show a term with specific options
2197showTmOpts :: PPOption -> PTerm -> String
2198showTmOpts opt = flip (displayS . renderPretty 1.0 10000000 . prettyImp opt) ""
2201instance Sized PTerm where
2202 size (PQuote rawTerm) = size rawTerm
2203 size (PRef fc _ name) = size name
2204 size (PLam fc name _ ty bdy) = 1 + size ty + size bdy
2205 size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy
2206 size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy
2207 size (PTyped trm ty) = 1 + size trm + size ty
2208 size (PApp fc name args) = 1 + size args
2209 size (PAppBind fc name args) = 1 + size args
2210 size (PCase fc trm bdy) = 1 + size trm + size bdy
2211 size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f])
2212 size (PTrue fc _) = 1
2213 size (PResolveTC fc) = 1
2214 size (PRewrite fc left right _) = 1 + size left + size right
2215 size (PPair fc _ _ left right) = 1 + size left + size right
2216 size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right
2217 size (PAlternative _ a alts) = 1 + size alts
2218 size (PHidden hidden) = size hidden
2219 size (PUnifyLog tm) = size tm
2220 size (PDisamb _ tm) = size tm
2221 size (PNoImplicits tm) = size tm
2223 size (PUniverse _) = 1
2224 size (PConstant fc const) = 1 + size fc + size const
2225 size Placeholder = 1
2226 size (PDoBlock dos) = 1 + size dos
2227 size (PIdiom fc term) = 1 + size term
2228 size (PReturn fc) = 1
2229 size (PMetavar _ name) = 1
2230 size (PProof tactics) = size tactics
2231 size (PElabError err) = size err
2232 size PImpossible = 1
2235getPArity :: PTerm -> Int
2236getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc
2239-- Return all names, free or globally bound, in the given term.
2241allNamesIn :: PTerm -> [Name]
2242allNamesIn tm = nub $ ni 0 [] tm
2243 where -- TODO THINK added niTacImp, but is it right?
2244 ni 0 env (PRef _ _ n)
2245 | not (n `elem` env) = [n]
2246 ni 0 env (PPatvar _ n) = [n]
2247 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2248 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2249 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env . snd) os
2250 ni 0 env (PIfThenElse _ c t f) = ni 0 env c ++ ni 0 env t ++ ni 0 env f
2251 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2252 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2253 ni 0 env (PLet _ n _ ty val sc) = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc
2254 ni 0 env (PHidden tm) = ni 0 env tm
2255 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2256 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2257 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2258 ni 0 env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni 0 env r
2259 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2260 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2261 ni 0 env (PAlternative ns a ls) = concatMap (ni 0 env) ls
2262 ni 0 env (PUnifyLog tm) = ni 0 env tm
2263 ni 0 env (PDisamb _ tm) = ni 0 env tm
2264 ni 0 env (PNoImplicits tm) = ni 0 env tm
2266 ni i env (PQuasiquote tm ty) = ni (i+1) env tm ++ maybe [] (ni i env) ty
2267 ni i env (PUnquote tm) = ni (i - 1) env tm
2268 ni i env tm = concatMap (ni i env) (children tm)
2270 niTacImp i env (TacImp _ _ scr) = ni i env scr
2274-- Return all names defined in binders in the given term
2275boundNamesIn :: PTerm -> [Name]
2276boundNamesIn tm = S.toList (ni 0 S.empty tm)
2277 where -- TODO THINK Added niTacImp, but is it right?
2278 ni :: Int -> S.Set Name -> PTerm -> S.Set Name
2279 ni 0 set (PApp _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2280 ni 0 set (PAppBind _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2281 ni 0 set (PCase _ c os) = niTms 0 (ni 0 set c) (map snd os)
2282 ni 0 set (PIfThenElse _ c t f) = niTms 0 set [c, t, f]
2283 ni 0 set (PLam fc n _ ty sc) = S.insert n $ ni 0 (ni 0 set ty) sc
2284 ni 0 set (PLet fc n nfc ty val sc) = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc
2285 ni 0 set (PPi p n _ ty sc) = niTacImp 0 (S.insert n $ ni 0 (ni 0 set ty) sc) p
2286 ni 0 set (PRewrite _ l r _) = ni 0 (ni 0 set l) r
2287 ni 0 set (PTyped l r) = ni 0 (ni 0 set l) r
2288 ni 0 set (PPair _ _ _ l r) = ni 0 (ni 0 set l) r
2289 ni 0 set (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 (ni 0 set t) r
2290 ni 0 set (PDPair _ _ _ l t r) = ni 0 (ni 0 (ni 0 set l) t) r
2291 ni 0 set (PAlternative ns a as) = niTms 0 set as
2292 ni 0 set (PHidden tm) = ni 0 set tm
2293 ni 0 set (PUnifyLog tm) = ni 0 set tm
2294 ni 0 set (PDisamb _ tm) = ni 0 set tm
2295 ni 0 set (PNoImplicits tm) = ni 0 set tm
2297 ni i set (PQuasiquote tm ty) = ni (i + 1) set tm `S.union` maybe S.empty (ni i set) ty
2298 ni i set (PUnquote tm) = ni (i - 1) set tm
2300 ni i set tm = foldr (S.union . ni i set) set (children tm)
2302 niTms :: Int -> S.Set Name -> [PTerm] -> S.Set Name
2303 niTms i set [] = set
2304 niTms i set (x : xs) = niTms i (ni i set x) xs
2306 niTacImp i set (TacImp _ _ scr) = ni i set scr
2307 niTacImp i set _ = set
2309-- Return names which are valid implicits in the given term (type).
2310implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
2311implicitNamesIn uvars ist tm
2312 = let (imps, fns) = execState (ni 0 [] tm) ([], []) in
2315 addImp n = do (imps, fns) <- get
2317 addFn n = do (imps, fns) <- get
2321 notCAF (PExp _ _ _ _ : _) = True
2322 notCAF (_ : xs) = notCAF xs
2324 notHidden (n, _) = case getAccessibility n of
2330 = case lookupDefAccExact n False (tt_ctxt ist) of
2334 ni 0 env (PRef _ _ n@(NS _ _))
2335 | not (n `elem` env)
2336 -- Never implicitly bind if there's a namespace
2338 ni 0 env (PRef _ _ n)
2339 | not (n `elem` env) && implicitable n || n `elem` uvars = addImp n
2340 ni 0 env (PApp _ f@(PRef _ _ n) as)
2341 | n `elem` uvars = do ni 0 env f
2342 mapM_ (ni 0 env . getTm) as
2343 | otherwise = do case lookupTy n (tt_ctxt ist) of
2346 mapM_ (ni 0 env . getTm) as
2347 ni 0 env (PApp _ f as) = do ni 0 env f
2348 mapM_ (ni 0 env . getTm) as
2349 ni 0 env (PAppBind _ f as) = do ni 0 env f
2350 mapM_ (ni 0 env . getTm) as
2351 ni 0 env (PCase _ c os) = do ni 0 env c
2352 -- names in 'os', not counting the names bound in the cases
2353 mapM_ (ni 0 env . snd) os
2356 mapM_ (ni 0 env . fst) os
2358 put (nub imps \\ nub impsfst, fns)
2359 ni 0 env (PIfThenElse _ c t f) = mapM_ (ni 0 env) [c, t, f]
2360 ni 0 env (PLam fc n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2361 ni 0 env (PPi p n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2362 ni 0 env (PRewrite _ l r _) = do ni 0 env l; ni 0 env r
2363 ni 0 env (PTyped l r) = do ni 0 env l; ni 0 env r
2364 ni 0 env (PPair _ _ _ l r) = do ni 0 env l; ni 0 env r
2365 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = do ni 0 env t; ni 0 (n:env) r
2366 ni 0 env (PDPair _ _ _ l t r) = do ni 0 env l
2369 ni 0 env (PAlternative ns a as) = mapM_ (ni 0 env) as
2370 ni 0 env (PHidden tm) = ni 0 env tm
2371 ni 0 env (PUnifyLog tm) = ni 0 env tm
2372 ni 0 env (PDisamb _ tm) = ni 0 env tm
2373 ni 0 env (PNoImplicits tm) = ni 0 env tm
2375 ni i env (PQuasiquote tm ty) = do ni (i + 1) env tm
2376 maybe (return ()) (ni i env) ty
2377 ni i env (PUnquote tm) = ni (i - 1) env tm
2379 ni i env tm = mapM_ (ni i env) (children tm)
2381-- Return names which are free in the given term.
2382namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
2383namesIn uvars ist tm = nub $ ni 0 [] tm
2385 ni 0 env (PRef _ _ n)
2386 | not (n `elem` env)
2387 = case lookupTy n (tt_ctxt ist) of
2389 _ -> [n | n `elem` (map fst uvars)]
2390 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2391 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2392 ni 0 env (PCase _ c os) = ni 0 env c ++
2393 -- names in 'os', not counting the names bound in the cases
2394 (nub (concatMap (ni 0 env . snd) os)
2395 \\ nub (concatMap (ni 0 env . fst) os))
2396 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2397 ni 0 env (PLam fc n nfc ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2398 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2399 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2400 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2401 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2402 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2403 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2404 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2405 ni 0 env (PHidden tm) = ni 0 env tm
2406 ni 0 env (PUnifyLog tm) = ni 0 env tm
2407 ni 0 env (PDisamb _ tm) = ni 0 env tm
2408 ni 0 env (PNoImplicits tm) = ni 0 env tm
2410 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2411 ni i env (PUnquote tm) = ni (i - 1) env tm
2413 ni i env tm = concatMap (ni i env) (children tm)
2415 niTacImp i env (TacImp _ _ scr) = ni i env scr
2418-- Return which of the given names are used in the given term.
2420usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
2421usedNamesIn vars ist tm = nub $ ni 0 [] tm
2422 where -- TODO THINK added niTacImp, but is it right?
2423 ni 0 env (PRef _ _ n)
2424 | n `elem` vars && not (n `elem` env)
2425 = case lookupDefExact n (tt_ctxt ist) of
2428 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2429 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2430 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env . snd) os
2431 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2432 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2433 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2434 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2435 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2436 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2437 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2438 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2439 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2440 ni 0 env (PHidden tm) = ni 0 env tm
2441 ni 0 env (PUnifyLog tm) = ni 0 env tm
2442 ni 0 env (PDisamb _ tm) = ni 0 env tm
2443 ni 0 env (PNoImplicits tm) = ni 0 env tm
2445 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2446 ni i env (PUnquote tm) = ni (i - 1) env tm
2448 ni i env tm = concatMap (ni i env) (children tm)
2450 niTacImp i env (TacImp _ _ scr) = ni i env scr
2453-- Return the list of inaccessible (= dotted) positions for a name.
2454getErasureInfo :: IState -> Name -> [Int]
2455getErasureInfo ist n =
2456 case lookupCtxtExact n (idris_optimisation ist) of
2457 Just (Optimise inacc detagg) -> map fst inacc
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list