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
99defaultOpts = IOption { opt_logLevel = 0
101 , opt_typecase = False
102 , opt_typeintype = False
103 , opt_coverage = True
104 , opt_showimp = False
105 , opt_errContext = False
108 , opt_nobanner = False
110 , opt_codegen = Via "c"
111 , opt_outputTy = Executable
113 , opt_importdirs = []
117 , opt_origerr = False
118 , opt_autoSolve = True
119 , opt_autoImport = []
120 , opt_optimise = defaultOptimise
121 , opt_printdepth = Just 5000
122 , opt_evaltypes = True
123 , opt_desugarnats = False
126data PPOption = PPOption {
127 ppopt_impl :: Bool -- ^^ whether to show implicits
128 , ppopt_desugarnats :: Bool
129 , ppopt_pinames :: Bool -- ^^ whether to show names in pi bindings
130 , ppopt_depth :: Maybe Int
133data Optimisation = PETransform -- partial eval and associated transforms
136defaultOptimise = [PETransform]
138-- | Pretty printing options with default verbosity.
139defaultPPOption :: PPOption
140defaultPPOption = PPOption { ppopt_impl = False,
141 ppopt_desugarnats = False,
142 ppopt_pinames = False,
143 ppopt_depth = Just 200 }
145-- | Pretty printing options with the most verbosity.
146verbosePPOption :: PPOption
147verbosePPOption = PPOption { ppopt_impl = True,
148 ppopt_desugarnats = True,
149 ppopt_pinames = True,
150 ppopt_depth = Just 200 }
152-- | Get pretty printing options from the big options record.
153ppOption :: IOption -> PPOption
154ppOption opt = PPOption {
155 ppopt_impl = opt_showimp opt,
156 ppopt_pinames = False,
157 ppopt_depth = opt_printdepth opt,
158 ppopt_desugarnats = opt_desugarnats opt
161-- | Get pretty printing options from an idris state record.
162ppOptionIst :: IState -> PPOption
163ppOptionIst = ppOption . idris_options
165data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
167-- | The output mode in use
168data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle
169 | IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle
172-- | How wide is the console?
173data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
174 | ColsWide Int -- ^ Manually specified - must be positive
175 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
179-- | The global state used in the Idris monad
180data IState = IState {
181 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
182 idris_constraints :: S.Set ConstraintFC,
183 -- ^ A list of universe constraints and their corresponding source locations
184 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
185 idris_implicits :: Ctxt [PArg],
186 idris_statics :: Ctxt [Bool],
187 idris_classes :: Ctxt ClassInfo,
188 idris_records :: Ctxt RecordInfo,
189 idris_dsls :: Ctxt DSL,
190 idris_optimisation :: Ctxt OptInfo,
191 idris_datatypes :: Ctxt TypeInfo,
192 idris_namehints :: Ctxt [Name],
193 idris_patdefs :: Ctxt ([([(Name, Term)], Term, Term)], [PTerm]), -- not exported
194 -- ^ list of lhs/rhs, and a list of missing clauses
195 idris_flags :: Ctxt [FnOpt],
196 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
197 idris_calledgraph :: Ctxt [Name],
198 idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]),
199 idris_moduledocs :: Ctxt (Docstring DocTerm),
200 -- ^ module documentation is saved in a special MN so the context
201 -- mechanism can be used for disambiguation
202 idris_tyinfodata :: Ctxt TIData,
203 idris_fninfo :: Ctxt FnInfo,
204 idris_transforms :: Ctxt [(Term, Term)],
205 idris_autohints :: Ctxt [Name],
206 idris_totcheck :: [(FC, Name)], -- names to check totality on
207 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
208 idris_totcheckfail :: [(FC, String)],
209 idris_options :: IOption,
211 idris_lineapps :: [((FilePath, Int), PTerm)],
212 -- ^ Full application LHS on source line
213 idris_metavars :: [(Name, (Maybe Name, Int, [Name], Bool))],
214 -- ^ The currently defined but not proven metavariables. The Int
215 -- is the number of vars to display as a context, the Maybe Name
216 -- is its top-level function, the [Name] is the list of local variables
217 -- available for proof search and the Bool is whether :p is
219 idris_coercions :: [Name],
220 idris_errRev :: [(Term, Term)],
221 syntax_rules :: SyntaxRules,
222 syntax_keywords :: [String],
223 imported :: [FilePath], -- ^ The imported modules
224 idris_scprims :: [(Name, (Int, PrimFn))],
225 idris_objs :: [(Codegen, FilePath)],
226 idris_libs :: [(Codegen, String)],
227 idris_cgflags :: [(Codegen, String)],
228 idris_hdrs :: [(Codegen, String)],
229 idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public
230 proof_list :: [(Name, (Bool, [String]))],
232 parserWarnings :: [(FC, Err)],
233 lastParse :: Maybe Name,
234 indent_stack :: [Int],
235 brace_stack :: [Maybe Int],
236 lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
237 idris_parsedSpan :: Maybe FC,
238 hide_list :: [(Name, Maybe Accessibility)],
239 default_access :: Accessibility,
240 default_total :: Bool,
241 ibc_write :: [IBCWrite],
242 compiled_so :: Maybe String,
243 idris_dynamic_libs :: [DynamicLib],
244 idris_language_extensions :: [LanguageExt],
245 idris_outputmode :: OutputMode,
246 idris_colourRepl :: Bool,
247 idris_colourTheme :: ColourTheme,
248 idris_errorhandlers :: [Name], -- ^ Global error handlers
249 idris_nameIdx :: (Int, Ctxt (Int, Name)),
250 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
251 module_aliases :: M.Map [T.Text] [T.Text],
252 idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
253 idris_postulates :: S.Set Name,
254 idris_externs :: S.Set (Name, Int),
255 idris_erasureUsed :: [(Name, Int)], -- ^ Function/constructor name, argument position is used
256 idris_whocalls :: Maybe (M.Map Name [Name]),
257 idris_callswho :: Maybe (M.Map Name [Name]),
258 idris_repl_defs :: [Name], -- ^ List of names that were defined in the repl, and can be re-/un-defined
259 elab_stack :: [(Name, Bool)], -- ^ Stack of names currently being elaborated, Bool set if it's an instance
260 -- (instances appear twice; also as a funtion name)
261 idris_symbols :: M.Map Name Name, -- ^ Symbol table (preserves sharing of names)
262 idris_exports :: [Name], -- ^ Functions with ExportList
263 idris_highlightedRegions :: [(FC, OutputAnnotation)], -- ^ Highlighting information to output
264 idris_parserHighlights :: [(FC, OutputAnnotation)], -- ^ Highlighting information from the parser
265 idris_deprecated :: Ctxt String -- ^ Deprecated names and explanation
268-- Required for parsers library, and therefore trifecta
269instance Show IState where
270 show = const "{internal state}"
272data SizeChange = Smaller | Same | Bigger | Unknown
275deriving instance Binary SizeChange
276deriving instance NFData SizeChange
279type SCGEntry = (Name, [Maybe (Int, SizeChange)])
280type UsageReason = (Name, Int) -- fn_name, its_arg_number
282data CGInfo = CGInfo { argsdef :: [Name],
283 calls :: [(Name, [[Name]])],
286 usedpos :: [(Int, [UsageReason])] }
289deriving instance Binary CGInfo
290deriving instance NFData CGInfo
293primDefs = [sUN "unsafePerformPrimIO",
294 sUN "mkLazyForeignPrim",
298-- information that needs writing for the current module's .ibc file
299data IBCWrite = IBCFix FixDecl
304 | IBCInstance Bool Bool Name Name
311 | IBCImport (Bool, FilePath) -- True = import public
312 | IBCImportDir FilePath
313 | IBCObj Codegen FilePath
314 | IBCLib Codegen String
315 | IBCCGFlag Codegen String
317 | IBCHeader Codegen String
318 | IBCAccess Name Accessibility
319 | IBCMetaInformation Name MetaInformation
320 | IBCTotal Name Totality
321 | IBCFlags Name [FnOpt]
322 | IBCFnInfo Name FnInfo
323 | IBCTrans Name (Term, Term)
324 | IBCErrRev (Term, Term)
328 | IBCDef Name -- i.e. main context
329 | IBCNameHint (Name, Name)
330 | IBCLineApp FilePath Int PTerm
331 | IBCErrorHandler Name
332 | IBCFunctionErrorHandler Name Name Name
334 | IBCExtern (Name, Int)
335 | IBCTotCheckErr FC String
337 | IBCModDocs Name -- ^ The name is the special name used to track module docs
338 | IBCUsage (Name, Int)
340 | IBCAutoHint Name Name
341 | IBCDeprecate Name String
344-- | The initial state for the compiler
346idrisInit = IState initContext S.empty []
347 emptyContext emptyContext emptyContext emptyContext
348 emptyContext emptyContext emptyContext emptyContext
349 emptyContext emptyContext emptyContext emptyContext
350 emptyContext emptyContext emptyContext emptyContext
351 emptyContext emptyContext
352 [] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []
353 [] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] []
354 (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty
355 AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] []
358-- | The monad for the main REPL - reading and processing files and updating
359-- global state (hence the IO inner monad).
360--type Idris = WriterT [Either String (IO ())] (State IState a))
361type Idris = StateT IState (ExceptT Err IO)
363catchError :: Idris a -> (Err -> Idris a) -> Idris a
364catchError = liftCatch catchE
366throwError :: Err -> Idris a
367throwError = Trans.lift . throwE
369-- Commands in the REPL
371data Codegen = Via String
380deriving instance NFData Codegen
383data HowMuchDocs = FullDocs | OverviewDocs
389 | NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
393 | DocStr (Either Name Const) HowMuchDocs
397 | Load FilePath (Maybe Int) -- up to maximum line number
398 | ChangeDirectory FilePath
401 | Compile Codegen String
405 | Prove Bool Name -- ^ If false, use prover, if true, use elab shell
406 | AddProof (Maybe Name)
412 | LogCategory [LogCat]
418 | DynamicLink FilePath
421 | Search [String] PTerm
422 | CaseSplitAt Bool Int Name
423 | AddClauseFrom Bool Int Name
424 | AddProofClauseFrom Bool Int Name
425 | AddMissing Bool Int Name
426 | MakeWith Bool Int Name
427 | MakeCase Bool Int Name
428 | MakeLemma Bool Int Name
429 | DoProofSearch Bool -- update file
430 Bool -- recursive search
432 Name -- top level name
437 | SetColour ColourType IdrisColour
441 | SetConsoleWidth ConsoleWidth
442 | SetPrinterDepth (Maybe Int)
443 | Apropos [String] String
447 | MakeDoc String -- IdrisDoc
450 | PPrint OutputFmt Int PTerm
452 -- Debugging commands
454 | DebugUnify PTerm PTerm
456data OutputFmt = HTMLOutput | LaTeXOutput
458-- | Recognised logging categories for the Idris compiler.
460-- @TODO add in sub categories.
467 deriving (Show, Eq, Ord)
469strLogCat :: LogCat -> String
470strLogCat IParse = "parser"
471strLogCat IElab = "elab"
472strLogCat ICodeGen = "codegen"
473strLogCat IErasure = "erasure"
474strLogCat ICoverage = "coverage"
475strLogCat IIBC = "ibc"
477codegenCats :: [LogCat]
478codegenCats = [ICodeGen]
480parserCats :: [LogCat]
486loggingCatsStr :: String
487loggingCatsStr = unlines
490 , (strLogCat ICodeGen)
491 , (strLogCat IErasure)
492 , (strLogCat ICoverage)
496data Opt = Filename String
509 | NoBuiltins -- only for the really primitive stuff!
526 | Port String -- REPL TCP port
534 | PkgMkDoc String -- IdrisDoc
544 | OutputTy OutputType
545 | Extension LanguageExt
546 | InterpretScript String
548 | TargetTriple String
551 | AddOpt Optimisation
552 | RemoveOpt Optimisation
555 | AutoWidth -- ^ Automatically adjust terminal width
556 | AutoSolve -- ^ Automatically issue "solve" tactic in old-style interactive prover
557 | UseConsoleWidth ConsoleWidth
560 | NoElimDeprecationWarnings -- ^ Don't show deprecation warnings for %elim
561 | NoOldTacticDeprecationWarnings -- ^ Don't show deprecation warnings for old-style tactics
564data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm
565 | EEval PTerm | ECheck PTerm | ESearch PTerm
566 | EDocStr (Either Name Const)
569-- Parsed declarations
571data Fixity = Infixl { prec :: Int }
572 | Infixr { prec :: Int }
573 | InfixN { prec :: Int }
574 | PrefixN { prec :: Int }
577deriving instance Binary Fixity
578deriving instance NFData Fixity
581instance Show Fixity where
582 show (Infixl i) = "infixl " ++ show i
583 show (Infixr i) = "infixr " ++ show i
584 show (InfixN i) = "infix " ++ show i
585 show (PrefixN i) = "prefix " ++ show i
587data FixDecl = Fix Fixity String
590instance Show FixDecl where
591 show (Fix f s) = show f ++ " " ++ s
594deriving instance Binary FixDecl
595deriving instance NFData FixDecl
598instance Ord FixDecl where
599 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
602data Static = Static | Dynamic
603 deriving (Show, Eq, Data, Typeable)
605deriving instance Binary Static
606deriving instance NFData Static
609-- Mark bindings with their explicitness, and laziness
610data Plicity = Imp { pargopts :: [ArgOpt],
613 pscoped :: Maybe ImplicitInfo -- Nothing, if top level
615 | Exp { pargopts :: [ArgOpt],
617 pparam :: Bool } -- this is a param (rather than index)
618 | Constraint { pargopts :: [ArgOpt],
620 | TacImp { pargopts :: [ArgOpt],
623 deriving (Show, Eq, Data, Typeable)
626deriving instance Binary Plicity
627deriving instance NFData Plicity
630is_scoped :: Plicity -> Maybe ImplicitInfo
631is_scoped (Imp _ _ _ s) = s
634impl = Imp [] Dynamic False (Just (Impl False True))
635forall_imp = Imp [] Dynamic False (Just (Impl False False))
636forall_constraint = Imp [] Dynamic False (Just (Impl True False))
637expl = Exp [] Dynamic False
638expl_param = Exp [] Dynamic True
639constraint = Constraint [] Static
640tacimpl t = TacImp [] Dynamic t
642data FnOpt = Inlinable -- always evaluate when simplifying
643 | TotalFn | PartialFn | CoveringFn
644 | Coinductive | AssertTotal
645 | Dictionary -- type class dictionary, eval only when
646 -- a function argument, and further evaluation resutls
647 | Implicit -- implicit coercion
648 | NoImplicit -- do not apply implicit coercions
649 | CExport String -- export, with a C name
650 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
651 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
652 | Reflection -- a reflecting function, compile-time only
653 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
654 | Constructor -- Data constructor type
655 | AutoHint -- use in auto implicit search
656 | PEGenerated -- generated by partial evaluator
659deriving instance Binary FnOpt
660deriving instance NFData FnOpt
665inlinable :: FnOpts -> Bool
666inlinable = elem Inlinable
668dictionary :: FnOpts -> Bool
669dictionary = elem Dictionary
672-- | Type provider - what to provide
673data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
674 | ProvPostulate t -- ^ goal type must be Type, so only term
675 deriving (Show, Eq, Functor)
677type ProvideWhat = ProvideWhat' PTerm
679-- | Top-level declarations such as compiler directives, definitions,
680-- datatypes and typeclasses.
682 = PFix FC Fixity [String] -- ^ Fixity declaration
683 | PTy (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location)
684 | PPostulate Bool -- external def if true
685 (Docstring (Either Err t)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location
686 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
687 | PCAF FC Name t -- ^ Top level constant
688 | PData (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
689 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
690 | PNamespace String FC [PDecl' t]
691 -- ^ New namespace, where FC is accurate location of the
692 -- namespace in the file
693 | PRecord (Docstring (Either Err t)) SyntaxInfo FC DataOpts
695 FC -- Record name precise location
696 [(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span
697 [(Name, Docstring (Either Err t))] -- Param Docs
698 [((Maybe (Name, FC)), Plicity, t, Maybe (Docstring (Either Err t)))] -- Fields
699 (Maybe (Name, FC)) -- Optional constructor name and location
700 (Docstring (Either Err t)) -- Constructor doc
701 SyntaxInfo -- Constructor SyntaxInfo
702 -- ^ Record declaration
703 | PClass (Docstring (Either Err t)) SyntaxInfo FC
704 [(Name, t)] -- constraints
706 FC -- accurate location of class name
707 [(Name, FC, t)] -- parameters and precise locations
708 [(Name, Docstring (Either Err t))] -- parameter docstrings
709 [(Name, FC)] -- determining parameters and precise locations
710 [PDecl' t] -- declarations
711 (Maybe (Name, FC)) -- instance constructor name and location
712 (Docstring (Either Err t)) -- instance constructor docs
713 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
714 -- class name, class name location, parameters, method declarations, optional constructor name
716 (Docstring (Either Err t)) -- Instance docs
717 [(Name, Docstring (Either Err t))] -- Parameter docs
719 FC [(Name, t)] -- constraints
721 FC -- precise location of class
723 t -- full instance type
724 (Maybe Name) -- explicit name
726 -- ^ Instance declaration: arguments are documentation, syntax info, source
727 -- location, constraints, class name, parameters, full instance
728 -- type, optional explicit name, and definitions
729 | PDSL Name (DSL' t) -- ^ DSL declaration
730 | PSyntax FC Syntax -- ^ Syntax definition
731 | PMutual FC [PDecl' t] -- ^ Mutual block
732 | PDirective Directive -- ^ Compiler directive.
733 | 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.
734 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
735 -- bool is True, lhs and rhs must be convertible
736 | PRunElabDecl FC t [String] -- ^ FC is decl-level, for errors, and
737 -- Strings represent the namespace
740deriving instance Binary PDecl'
741deriving instance NFData PDecl'
744-- | The set of source directives
745data Directive = DLib Codegen String |
746 DLink Codegen String |
747 DFlag Codegen String |
748 DInclude Codegen String |
751 DAccess Accessibility |
754 DDynamicLibs [String] |
755 DNameHint Name FC [(Name, FC)] |
756 DErrorHandlers Name FC Name FC [(Name, FC)] |
757 DLanguage LanguageExt |
758 DDeprecate Name String |
761-- | A set of instructions for things that need to happen in IState
762-- after a term elaboration when there's been reflected elaboration.
763data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
764 | RClausesInstrs Name [([(Name, Term)], Term, Term)]
765 | RAddInstance Name Name
767-- | For elaborator state
768data EState = EState {
769 case_decls :: [(Name, PDecl)],
770 delayed_elab :: [(Int, Elab' EState ())],
771 new_tyDecls :: [RDeclInstructions],
772 highlighting :: [(FC, OutputAnnotation)]
776initEState = EState [] [] [] []
778type ElabD a = Elab' EState a
780highlightSource :: FC -> OutputAnnotation -> ElabD ()
781highlightSource fc annot =
782 updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux })
784-- | One clause of a top-level definition. Term arguments to constructors are:
786-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
788-- 2. The list of extra 'with' patterns
790-- 3. The right-hand side
792-- 4. The where block (PDecl' t)
794data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
795 | PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t]
796 | PClauseR FC [t] t [PDecl' t]
797 | PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t]
800deriving instance Binary PClause'
801deriving instance NFData PClause'
805data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
806 d_name_fc :: FC, -- ^ The precise location of the type constructor name
807 d_tcon :: t, -- ^ Type constructor
808 d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors
810 -- ^ Data declaration
811 | PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t }
812 -- ^ "Placeholder" for data whose constructors are defined later
815-- | Transform the FCs in a PData and its associated terms. The first
816-- function transforms the general-purpose FCs, and the second transforms
817-- those that are used for semantic source highlighting, so they can be
819mapPDataFC :: (FC -> FC) -> (FC -> FC) -> PData -> PData
820mapPDataFC f g (PDatadecl n nfc tycon ctors) =
821 PDatadecl n (g nfc) (mapPTermFC f g tycon) (map ctorFC ctors)
822 where ctorFC (doc, argDocs, n, nfc, ty, fc, ns) =
823 (doc, argDocs, n, g nfc, mapPTermFC f g ty, f fc, ns)
824mapPDataFC f g (PLaterdecl n nfc tycon) =
825 PLaterdecl n (g nfc) (mapPTermFC f g tycon)
827deriving instance Binary PData'
828deriving instance NFData PData'
831-- Handy to get a free function for applying PTerm -> PTerm functions
832-- across a program, by deriving Functor
834type PDecl = PDecl' PTerm
835type PData = PData' PTerm
836type PClause = PClause' PTerm
838-- | Transform the FCs in a PTerm. The first function transforms the
839-- general-purpose FCs, and the second transforms those that are used
840-- for semantic source highlighting, so they can be treated specially.
841mapPDeclFC :: (FC -> FC) -> (FC -> FC) -> PDecl -> PDecl
842mapPDeclFC f g (PFix fc fixity ops) =
843 PFix (f fc) fixity ops
844mapPDeclFC f g (PTy doc argdocs syn fc opts n nfc ty) =
845 PTy doc argdocs syn (f fc) opts n (g nfc) (mapPTermFC f g ty)
846mapPDeclFC f g (PPostulate ext doc syn fc nfc opts n ty) =
847 PPostulate ext doc syn (f fc) (g nfc) opts n (mapPTermFC f g ty)
849mapPDeclFC f g (PClauses fc opts n clauses) =
850 PClauses (f fc) opts n (map (fmap (mapPTermFC f g)) clauses)
851mapPDeclFC f g (PCAF fc n tm) = PCAF (f fc) n (mapPTermFC f g tm)
852mapPDeclFC f g (PData doc argdocs syn fc opts dat) =
853 PData doc argdocs syn (f fc) opts (mapPDataFC f g dat)
854mapPDeclFC f g (PParams fc params decls) =
856 (map (\(n, ty) -> (n, mapPTermFC f g ty)) params)
857 (map (mapPDeclFC f g) decls)
858mapPDeclFC f g (PNamespace ns fc decls) =
859 PNamespace ns (f fc) (map (mapPDeclFC f g) decls)
860mapPDeclFC f g (PRecord doc syn fc opts n nfc params paramdocs fields ctor ctorDoc syn') =
861 PRecord doc syn (f fc) opts n (g nfc)
862 (map (\(pn, pnfc, plic, ty) -> (pn, g pnfc, plic, mapPTermFC f g ty)) params)
864 (map (\(fn, plic, ty, fdoc) -> (fmap (\(fn', fnfc) -> (fn', g fnfc)) fn,
865 plic, mapPTermFC f g ty, fdoc))
867 (fmap (\(ctorN, ctorNFC) -> (ctorN, g ctorNFC)) ctor)
870mapPDeclFC f g (PClass doc syn fc constrs n nfc params paramDocs det body ctor ctorDoc) =
871 PClass doc syn (f fc)
872 (map (\(constrn, constr) -> (constrn, mapPTermFC f g constr)) constrs)
873 n (g nfc) (map (\(n, nfc, pty) -> (n, g nfc, mapPTermFC f g pty)) params)
874 paramDocs (map (\(dn, dnfc) -> (dn, g dnfc)) det)
875 (map (mapPDeclFC f g) body)
876 (fmap (\(n, nfc) -> (n, g nfc)) ctor)
878mapPDeclFC f g (PInstance doc paramDocs syn fc constrs cn cnfc params instTy instN body) =
879 PInstance doc paramDocs syn (f fc)
880 (map (\(constrN, constrT) -> (constrN, mapPTermFC f g constrT)) constrs)
881 cn (g cnfc) (map (mapPTermFC f g) params)
882 (mapPTermFC f g instTy)
884 (map (mapPDeclFC f g) body)
885mapPDeclFC f g (PDSL n dsl) = PDSL n (fmap (mapPTermFC f g) dsl)
886mapPDeclFC f g (PSyntax fc syn) = PSyntax (f fc) $
888 Rule syms tm ctxt -> Rule syms (mapPTermFC f g tm) ctxt
889 DeclRule syms decls -> DeclRule syms (map (mapPDeclFC f g) decls)
890mapPDeclFC f g (PMutual fc decls) =
891 PMutual (f fc) (map (mapPDeclFC f g) decls)
892mapPDeclFC f g (PDirective d) =
895 DNameHint n nfc ns ->
896 DNameHint n (g nfc) (map (\(hn, hnfc) -> (hn, g hnfc)) ns)
897 DErrorHandlers n nfc n' nfc' ns ->
898 DErrorHandlers n (g nfc) n' (g nfc') $
899 map (\(an, anfc) -> (an, g anfc)) ns
900mapPDeclFC f g (PProvider doc syn fc nfc what n) =
901 PProvider doc syn (f fc) (g nfc) (fmap (mapPTermFC f g) what) n
902mapPDeclFC f g (PTransform fc safe l r) =
903 PTransform (f fc) safe (mapPTermFC f g l) (mapPTermFC f g r)
904mapPDeclFC f g (PRunElabDecl fc script ns) =
905 PRunElabDecl (f fc) (mapPTermFC f g script) ns
907-- | Get all the names declared in a declaration
908declared :: PDecl -> [Name]
909declared (PFix _ _ _) = []
910declared (PTy _ _ _ _ _ n fc t) = [n]
911declared (PPostulate _ _ _ _ _ _ n t) = [n]
912declared (PClauses _ _ n _) = [] -- not a declaration
913declared (PCAF _ n _) = [n]
914declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
915 where fstt (_, _, a, _, _, _, _) = a
916declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n]
917declared (PParams _ _ ds) = concatMap declared ds
918declared (PNamespace _ _ ds) = concatMap declared ds
919declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
920declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms)
921declared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
922declared (PDSL n _) = [n]
923declared (PSyntax _ _) = []
924declared (PMutual _ ds) = concatMap declared ds
925declared (PDirective _) = []
928-- get the names declared, not counting nested parameter blocks
929tldeclared :: PDecl -> [Name]
930tldeclared (PFix _ _ _) = []
931tldeclared (PTy _ _ _ _ _ n _ t) = [n]
932tldeclared (PPostulate _ _ _ _ _ _ n t) = [n]
933tldeclared (PClauses _ _ n _) = [] -- not a declaration
934tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
935tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
936 where fstt (_, _, a, _, _, _, _) = a
937tldeclared (PParams _ _ ds) = []
938tldeclared (PMutual _ ds) = concatMap tldeclared ds
939tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds
940tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms)
941tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
944defined :: PDecl -> [Name]
945defined (PFix _ _ _) = []
946defined (PTy _ _ _ _ _ n _ t) = []
947defined (PPostulate _ _ _ _ _ _ n t) = []
948defined (PClauses _ _ n _) = [n] -- not a declaration
949defined (PCAF _ n _) = [n]
950defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
951 where fstt (_, _, a, _, _, _, _) = a
952defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = []
953defined (PParams _ _ ds) = concatMap defined ds
954defined (PNamespace _ _ ds) = concatMap defined ds
955defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
956defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms)
957defined (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
958defined (PDSL n _) = [n]
959defined (PSyntax _ _) = []
960defined (PMutual _ ds) = concatMap defined ds
961defined (PDirective _) = []
964updateN :: [(Name, Name)] -> Name -> Name
965updateN ns n | Just n' <- lookup n ns = n'
968updateNs :: [(Name, Name)] -> PTerm -> PTerm
970updateNs ns t = mapPT updateRef t
971 where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)
974-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
976-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
977-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
978-- where updateCNs ns (PClause n l ts r ds)
979-- = PClause (updateN ns n) (fmap (updateNs ns) l)
980-- (map (fmap (updateNs ns)) ts)
981-- (fmap (updateNs ns) r)
982-- (map (updateDNs ns) ds)
985data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable)
987-- | High level language terms
988data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language
989 | 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.
990 | PInferRef FC [FC] Name -- ^ A name to be defined later
991 | PPatvar FC Name -- ^ A pattern variable
992 | PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span.
993 | PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable
994 | PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location)
995 | PTyped PTerm PTerm -- ^ Term with explicit type
996 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
997 | PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only)
998 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
999 | PMatchApp FC Name -- ^ Make an application by type matching
1000 | PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse
1001 | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
1002 | PTrue FC PunInfo -- ^ Unit type..?
1003 | PResolveTC FC -- ^ Solve this dictionary by type class resolution
1004 | PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type
1005 | 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.
1006 | 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.
1007 | PAs FC Name PTerm -- ^ @-pattern, valid LHS only
1008 | PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames.
1009 | PHidden PTerm -- ^ Irrelevant or hidden pattern
1010 | PType FC -- ^ 'Type' type
1011 | PUniverse Universe -- ^ Some universe
1012 | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
1013 | PConstant FC Const -- ^ Builtin types
1014 | Placeholder -- ^ Underscore
1015 | PDoBlock [PDo] -- ^ Do notation
1016 | PIdiom FC PTerm -- ^ Idiom brackets
1018 | PMetavar FC Name -- ^ A metavariable, ?name, and its precise location
1019 | PProof [PTactic] -- ^ Proof script
1020 | PTactics [PTactic] -- ^ As PProof, but no auto solving
1021 | PElabError Err -- ^ Error to report on elaboration
1022 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
1023 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
1024 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
1025 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
1026 | PNoImplicits PTerm -- ^ never run implicit converions on the term
1027 | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
1028 | PUnquote PTerm -- ^ ~Term
1029 | 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.
1030 | PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace.
1031 | PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later.
1032 deriving (Eq, Data, Typeable)
1034data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed
1037 deriving (Eq, Data, Typeable)
1039-- | Transform the FCs in a PTerm. The first function transforms the
1040-- general-purpose FCs, and the second transforms those that are used
1041-- for semantic source highlighting, so they can be treated specially.
1042mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm
1043mapPTermFC f g (PQuote q) = PQuote q
1044mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n
1045mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n
1046mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n
1047mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2)
1048mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1049mapPTermFC 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)
1050mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2)
1051mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1052mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls
1053mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1054mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n
1055mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
1056mapPTermFC 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)
1057mapPTermFC f g (PTrue fc info) = PTrue (f fc) info
1058mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc)
1059mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3)
1060mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2)
1061mapPTermFC 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)
1062mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t)
1063mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts)
1064mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t)
1065mapPTermFC f g (PType fc) = PType (f fc)
1066mapPTermFC f g (PUniverse u) = PUniverse u
1067mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2)
1068mapPTermFC f g (PConstant fc c) = PConstant (f fc) c
1069mapPTermFC f g Placeholder = Placeholder
1070mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos)
1071 where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t)
1072 mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)
1073 mapPDoFC (DoBindP fc t1 t2 alts) =
1074 DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)
1075 mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1076 mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1077mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t)
1078mapPTermFC f g (PReturn fc) = PReturn (f fc)
1079mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n
1080mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs)
1081mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs)
1082mapPTermFC f g (PElabError err) = PElabError err
1083mapPTermFC f g PImpossible = PImpossible
1084mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t)
1085mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t)
1086mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t)
1087mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t)
1088mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2)
1089mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t)
1090mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns
1091mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm)
1092mapPTermFC f g (PQuoteName n x fc) = PQuoteName n x (g fc)
1095dg instance Binary PTerm
1096deriving instance NFData PTerm
1099mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
1100mapPT f t = f (mpt t) where
1101 mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s)
1102 mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s)
1103 mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)
1104 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
1106 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
1107 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
1108 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
1109 mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e)
1110 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
1111 mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r)
1112 mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r)
1113 mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as)
1114 mpt (PHidden t) = PHidden (mapPT f t)
1115 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
1116 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
1117 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
1118 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
1119 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
1120 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
1121 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
1125data PTactic' t = Intro [Name] | Intros | Focus Name
1126 | Refine Name [Bool] | Rewrite t | DoUnify
1133 | LetTac Name t | LetTacTy Name t t
1134 | Exact t | Compute | Trivial | TCInstance
1135 | ProofSearch Bool Bool Int (Maybe Name)
1136 [Name] -- allowed local names
1138 -- ^ the bool is whether to search recursively
1141 | ProofState | ProofTerm | Undo
1142 | Try (PTactic' t) (PTactic' t)
1143 | TSeq (PTactic' t) (PTactic' t)
1144 | ApplyTactic t -- see Language.Reflection module
1148 | GoalType String (PTactic' t)
1151 | TDocStr (Either Name Const)
1154 | TFail [ErrorReportPart]
1157 deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable)
1159deriving instance Binary PTactic'
1160deriving instance NFData PTactic'
1162instance Sized a => Sized (PTactic' a) where
1163 size (Intro nms) = 1 + size nms
1165 size (Focus nm) = 1 + size nm
1166 size (Refine nm bs) = 1 + size nm + length bs
1167 size (Rewrite t) = 1 + size t
1168 size (Induction t) = 1 + size t
1169 size (LetTac nm t) = 1 + size nm + size t
1170 size (Exact t) = 1 + size t
1178 size (Try l r) = 1 + size l + size r
1179 size (TSeq l r) = 1 + size l + size r
1180 size (ApplyTactic t) = 1 + size t
1181 size (Reflect t) = 1 + size t
1182 size (Fill t) = 1 + size t
1186 size (TFail ts) = 1 + size ts
1189 size (CaseTac x) = 1 + size x
1190 size (Equiv t) = 1 + size t
1191 size (Claim x y) = 1 + size x + size y
1193 size (MatchRefine x) = 1 + size x
1194 size (LetTacTy x y z) = 1 + size x + size y + size z
1197type PTactic = PTactic' PTerm
1199data PDo' t = DoExp FC t
1200 | DoBind FC Name FC t -- ^ second FC is precise name location
1201 | DoBindP FC t t [(t,t)]
1202 | DoLet FC Name FC t t -- ^ second FC is precise name location
1204 deriving (Eq, Functor, Data, Typeable)
1206deriving instance Binary PDo'
1207deriving instance NFData PDo'
1210instance Sized a => Sized (PDo' a) where
1211 size (DoExp fc t) = 1 + size fc + size t
1212 size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t
1213 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
1214 size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r
1215 size (DoLetP fc l r) = 1 + size fc + size l + size r
1217type PDo = PDo' PTerm
1219-- The priority gives a hint as to elaboration order. Best to elaborate
1220-- things early which will help give a more concrete type to other
1221-- variables, e.g. a before (interpTy a).
1223data PArg' t = PImp { priority :: Int,
1224 machine_inf :: Bool, -- true if the machine inferred it
1225 argopts :: [ArgOpt],
1228 | PExp { priority :: Int,
1229 argopts :: [ArgOpt],
1232 | PConstraint { priority :: Int,
1233 argopts :: [ArgOpt],
1236 | PTacImplicit { priority :: Int,
1237 argopts :: [ArgOpt],
1241 deriving (Show, Eq, Functor, Data, Typeable)
1243data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp
1244 deriving (Show, Eq, Data, Typeable)
1246instance Sized a => Sized (PArg' a) where
1247 size (PImp p _ l nm trm) = 1 + size nm + size trm
1248 size (PExp p l nm trm) = 1 + size nm + size trm
1249 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
1250 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
1253deriving instance Binary PArg'
1254deriving instance NFData PArg'
1257pimp n t mach = PImp 1 mach [] n t
1258pexp t = PExp 1 [] (sMN 0 "arg") t
1259pconst t = PConstraint 1 [] (sMN 0 "carg") t
1260ptacimp n s t = PTacImplicit 2 [] n s t
1262type PArg = PArg' PTerm
1264-- | Get the highest FC in a term, if one exists
1265highestFC :: PTerm -> Maybe FC
1266highestFC (PQuote _) = Nothing
1267highestFC (PRef fc _ _) = Just fc
1268highestFC (PInferRef fc _ _) = Just fc
1269highestFC (PPatvar fc _) = Just fc
1270highestFC (PLam fc _ _ _ _) = Just fc
1271highestFC (PPi _ _ _ _ _) = Nothing
1272highestFC (PLet fc _ _ _ _ _) = Just fc
1273highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty
1274highestFC (PApp fc _ _) = Just fc
1275highestFC (PAppBind fc _ _) = Just fc
1276highestFC (PMatchApp fc _) = Just fc
1277highestFC (PCase fc _ _) = Just fc
1278highestFC (PIfThenElse fc _ _ _) = Just fc
1279highestFC (PTrue fc _) = Just fc
1280highestFC (PResolveTC fc) = Just fc
1281highestFC (PRewrite fc _ _ _) = Just fc
1282highestFC (PPair fc _ _ _ _) = Just fc
1283highestFC (PDPair fc _ _ _ _ _) = Just fc
1284highestFC (PAs fc _ _) = Just fc
1285highestFC (PAlternative _ _ args) =
1286 case mapMaybe highestFC args of
1289highestFC (PHidden _) = Nothing
1290highestFC (PType fc) = Just fc
1291highestFC (PUniverse _) = Nothing
1292highestFC (PGoal fc _ _ _) = Just fc
1293highestFC (PConstant fc _) = Just fc
1294highestFC Placeholder = Nothing
1295highestFC (PDoBlock lines) =
1296 case map getDoFC lines of
1300 getDoFC (DoExp fc t) = fc
1301 getDoFC (DoBind fc nm nfc t) = fc
1302 getDoFC (DoBindP fc l r alts) = fc
1303 getDoFC (DoLet fc nm nfc l r) = fc
1304 getDoFC (DoLetP fc l r) = fc
1306highestFC (PIdiom fc _) = Just fc
1307highestFC (PReturn fc) = Just fc
1308highestFC (PMetavar fc _) = Just fc
1309highestFC (PProof _) = Nothing
1310highestFC (PTactics _) = Nothing
1311highestFC (PElabError _) = Nothing
1312highestFC PImpossible = Nothing
1313highestFC (PCoerced tm) = highestFC tm
1314highestFC (PDisamb _ opts) = highestFC opts
1315highestFC (PUnifyLog tm) = highestFC tm
1316highestFC (PNoImplicits tm) = highestFC tm
1317highestFC (PQuasiquote _ _) = Nothing
1318highestFC (PUnquote tm) = highestFC tm
1319highestFC (PQuoteName _ _ fc) = Just fc
1320highestFC (PRunElab fc _ _) = Just fc
1321highestFC (PConstSugar fc _) = Just fc
1322highestFC (PAppImpl t _) = highestFC t
1326data ClassInfo = CI { instanceCtorName :: Name,
1327 class_methods :: [(Name, (FnOpts, PTerm))],
1328 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
1329 class_default_superclasses :: [PDecl],
1330 class_params :: [Name],
1331 class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded
1332 class_determiners :: [Int] }
1335deriving instance Binary ClassInfo
1336deriving instance NFData ClassInfo
1340data RecordInfo = RI { record_parameters :: [(Name,PTerm)],
1341 record_constructor :: Name,
1342 record_projections :: [Name] }
1345-- Type inference data
1347data TIData = TIPartial -- ^ a function with a partially defined type
1348 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
1351-- | Miscellaneous information about functions
1352data FnInfo = FnInfo { fn_params :: [Int] }
1355deriving instance Binary FnInfo
1356deriving instance NFData FnInfo
1359data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
1360 detaggable :: Bool }
1363deriving instance Binary OptInfo
1364deriving instance NFData OptInfo
1367-- | Syntactic sugar info
1368data DSL' t = DSL { dsl_bind :: t,
1373 index_first :: Maybe t,
1374 index_next :: Maybe t,
1375 dsl_lambda :: Maybe t,
1379 deriving (Show, Functor)
1381deriving instance Binary DSL'
1382deriving instance NFData DSL'
1385type DSL = DSL' PTerm
1387data SynContext = PatternSyntax | TermSyntax | AnySyntax
1390deriving instance Binary SynContext
1391deriving instance NFData SynContext
1394data Syntax = Rule [SSymbol] PTerm SynContext
1395 | DeclRule [SSymbol] [PDecl]
1398syntaxNames :: Syntax -> [Name]
1399syntaxNames (Rule syms _ _) = mapMaybe ename syms
1400 where ename (Keyword n) = Just n
1402syntaxNames (DeclRule syms _) = mapMaybe ename syms
1403 where ename (Keyword n) = Just n
1406syntaxSymbols :: Syntax -> [SSymbol]
1407syntaxSymbols (Rule ss _ _) = ss
1408syntaxSymbols (DeclRule ss _) = ss
1410deriving instance Binary Syntax
1411deriving instance NFData Syntax
1414data SSymbol = Keyword Name
1423deriving instance Binary SSymbol
1424deriving instance NFData SSymbol
1427newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
1429emptySyntaxRules :: SyntaxRules
1430emptySyntaxRules = SyntaxRules []
1432updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
1433updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
1435 newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
1440 ruleSort (s1:ss1) (s2:ss2) =
1441 case symCompare s1 s2 of
1442 EQ -> ruleSort ss1 ss2
1445 -- Better than creating Ord instance for SSymbol since
1446 -- in general this ordering does not really make sense.
1447 symCompare (Keyword n1) (Keyword n2) = compare n1 n2
1448 symCompare (Keyword _) _ = LT
1449 symCompare (Symbol _) (Keyword _) = GT
1450 symCompare (Symbol s1) (Symbol s2) = compare s1 s2
1451 symCompare (Symbol _) _ = LT
1452 symCompare (Binding _) (Keyword _) = GT
1453 symCompare (Binding _) (Symbol _) = GT
1454 symCompare (Binding b1) (Binding b2) = compare b1 b2
1455 symCompare (Binding _) _ = LT
1456 symCompare (Expr _) (Keyword _) = GT
1457 symCompare (Expr _) (Symbol _) = GT
1458 symCompare (Expr _) (Binding _) = GT
1459 symCompare (Expr e1) (Expr e2) = compare e1 e2
1460 symCompare (Expr _) _ = LT
1461 symCompare (SimpleExpr _) (Keyword _) = GT
1462 symCompare (SimpleExpr _) (Symbol _) = GT
1463 symCompare (SimpleExpr _) (Binding _) = GT
1464 symCompare (SimpleExpr _) (Expr _) = GT
1465 symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
1467initDSL = DSL (PRef f [] (sUN ">>="))
1468 (PRef f [] (sUN "return"))
1469 (PRef f [] (sUN "<*>"))
1470 (PRef f [] (sUN "pure"))
1477 where f = fileFC "(builtin)"
1479data Using = UImplicit Name PTerm
1480 | UConstraint Name [Name]
1481 deriving (Show, Eq, Data, Typeable)
1483deriving instance Binary Using
1484deriving instance NFData Using
1487data SyntaxInfo = Syn { using :: [Using],
1488 syn_params :: [(Name, PTerm)],
1489 syn_namespace :: [String],
1491 imp_methods :: [Name], -- class methods. When expanding
1492 -- implicits, these should be expanded even under
1494 decoration :: Name -> Name,
1496 implicitAllowed :: Bool,
1497 maxline :: Maybe Int,
1500 syn_in_quasiquote :: Int }
1503deriving instance NFData SyntaxInfo
1504deriving instance Binary SyntaxInfo
1507defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0
1509expandNS :: SyntaxInfo -> Name -> Name
1510expandNS syn n@(NS _ _) = n
1511expandNS syn n = case syn_namespace syn of
1516-- For inferring types of things
1518bi = fileFC "builtin"
1520inferTy = sMN 0 "__Infer"
1521inferCon = sMN 0 "__infer"
1522inferDecl = PDatadecl inferTy NoFC
1524 [(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) (
1525 PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType"))
1526 (PRef bi [] inferTy)), bi, [])]
1529infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
1530infP = P (TCon 6 0) inferTy (TType (UVal 0))
1532getInferTerm, getInferType :: Term -> Term
1533getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
1534getInferTerm (App _ (App _ _ _) tm) = tm
1535getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1537getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1538 where toTy (Lam t) = Pi Nothing t (TType (UVar 0))
1539 toTy (PVar t) = PVTy t
1541getInferType (App _ (App _ _ ty) _) = ty
1545-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
1547primNames = [inferTy, inferCon]
1550unitCon = sUN "MkUnit"
1552falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
1553 "The empty type, also known as the trivially false proposition." ++
1555 "Use `void` or `absurd` to prove anything if you have a variable " ++
1556 "of type `Void` in scope."
1559pairTy = sNS (sUN "Pair") ["Builtins"]
1560pairCon = sNS (sUN "MkPair") ["Builtins"]
1562upairTy = sNS (sUN "UPair") ["Builtins"]
1563upairCon = sNS (sUN "MkUPair") ["Builtins"]
1567eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
1568 "The propositional equality type. A proof that `x` = `y`." ++
1570 "To use such a proof, pattern-match on it, and the two equal things will " ++
1571 "then need to be the _same_ pattern." ++
1573 "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
1574 "is possible to state equalities between values of potentially different " ++
1575 "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
1577 "You may need to use `(~=~)` to explicitly request heterogeneous equality."
1579eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)]
1580 (piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))]
1582 [(reflDoc, reflParamDoc,
1583 eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) (
1584 PPi impl (n "x") NoFC (PRef bi [] (n "A"))
1585 (PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False,
1586 pimp (n "B") Placeholder False,
1587 pexp (PRef bi [] (n "x")),
1588 pexp (PRef bi [] (n "x"))])), bi, [])]
1590 reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
1591 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1592 "shown that both sides are in fact equal."
1593 reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
1594 (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1596eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
1597 (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
1603-- | The special name to be used in the module documentation context -
1604-- not for use in the main definition context. The namespace around it
1605-- will determine the module to which the docs adhere.
1607modDocName = sMN 0 "ModuleDocs"
1609-- Defined in builtins.idr
1610sigmaTy = sNS (sUN "Sigma") ["Builtins"]
1611sigmaCon = sNS (sUN "MkSigma") ["Builtins"]
1613piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1614piBind = piBindp expl
1616piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1618piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t)
1621-- Pretty-printing declarations and terms
1623-- These "show" instances render to an absurdly wide screen because inserted line breaks
1624-- could interfere with interactive editing, which calls "show".
1626instance Show PTerm where
1627 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1629instance Show PDecl where
1630 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
1632instance Show PClause where
1633 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1635instance Show PData where
1636 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1638instance Pretty PTerm OutputAnnotation where
1639 pretty = prettyImp defaultPPOption
1641-- | Colourise annotations according to an Idris state. It ignores the names
1642-- in the annotation, as there's no good way to show extended information on a
1644annotationColour :: IState -> OutputAnnotation -> Maybe IdrisColour
1645annotationColour ist _ | not (idris_colourRepl ist) = Nothing
1646annotationColour ist (AnnConst c) =
1647 let theme = idris_colourTheme ist
1648 in Just $ if constIsType c
1649 then typeColour theme
1650 else dataColour theme
1651annotationColour ist (AnnData _ _) = Just $ dataColour (idris_colourTheme ist)
1652annotationColour ist (AnnType _ _) = Just $ typeColour (idris_colourTheme ist)
1653annotationColour ist (AnnBoundName _ True) = Just $ implicitColour (idris_colourTheme ist)
1654annotationColour ist (AnnBoundName _ False) = Just $ boundVarColour (idris_colourTheme ist)
1655annotationColour ist AnnKeyword = Just $ keywordColour (idris_colourTheme ist)
1656annotationColour ist (AnnName n _ _ _) =
1657 let ctxt = tt_ctxt ist
1658 theme = idris_colourTheme ist
1660 _ | isDConName n ctxt -> Just $ dataColour theme
1661 _ | isFnName n ctxt -> Just $ functionColour theme
1662 _ | isTConName n ctxt -> Just $ typeColour theme
1663 _ | isPostulateName n ist -> Just $ postulateColour theme
1664 _ | otherwise -> Nothing -- don't colourise unknown names
1665annotationColour ist (AnnTextFmt fmt) = Just (colour fmt)
1666 where colour BoldText = IdrisColour Nothing True False True False
1667 colour UnderlineText = IdrisColour Nothing True True False False
1668 colour ItalicText = IdrisColour Nothing True False False True
1669annotationColour ist _ = Nothing
1672-- | Colourise annotations according to an Idris state. It ignores the names
1673-- in the annotation, as there's no good way to show extended
1674-- information on a terminal. Note that strings produced this way will
1675-- not be coloured on Windows, so the use of the colour rendering
1676-- functions in Idris.Output is to be preferred.
1677consoleDecorate :: IState -> OutputAnnotation -> String -> String
1678consoleDecorate ist ann = maybe id colourise (annotationColour ist ann)
1680isPostulateName :: Name -> IState -> Bool
1681isPostulateName n ist = S.member n (idris_postulates ist)
1683-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1684prettyImp :: PPOption -- ^^ pretty printing options
1685 -> PTerm -- ^^ the term to pretty-print
1686 -> Doc OutputAnnotation
1687prettyImp impl = pprintPTerm impl [] [] []
1689-- | Serialise something to base64 using its Binary instance.
1691-- | Do the right thing for rendering a term in an IState
1692prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1693prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1695-- | Pretty-print a high-level Idris term in some bindings context with infix info
1696pprintPTerm :: PPOption -- ^^ pretty printing options
1697 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1698 -> [Name] -- ^^ names to always show in pi, even if not used
1699 -> [FixDecl] -- ^^ Fixity declarations
1700 -> PTerm -- ^^ the term to pretty-print
1701 -> Doc OutputAnnotation
1702pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1707 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1708 prettySe d p bnd (PQuote r) =
1709 text "![" <> pretty r <> text "]"
1710 prettySe d p bnd (PPatvar fc n) = pretty n
1712 | Just str <- slist d p bnd e = depth d $ str
1713 | Just n <- snat ppo d p e = depth d $ annotate (AnnData "Nat" "") (text (show n))
1714 prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n
1715 prettySe d p bnd (PLam fc n nfc ty sc) =
1716 depth d . bracket p startPrec . group . align . hang 2 $
1717 text "\\" <> prettyBindingOf n False <+> text "=>" <$>
1718 prettySe (decD d) startPrec ((n, False):bnd) sc
1719 prettySe d p bnd (PLet fc n nfc ty v sc) =
1720 depth d . bracket p startPrec . group . align $
1721 kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
1722 kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
1723 prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
1724 | n `elem` allNamesIn sc || ppopt_impl ppo && uname n || n `elem` docArgs
1725 || ppopt_pinames ppo && uname n =
1726 depth d . bracket p startPrec . group $
1727 enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
1728 st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
1730 depth d . bracket p startPrec . group $
1731 group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$>
1732 group (prettySe (decD d) startPrec ((n, False):bnd) sc)
1734 uname (UN n) = case str n of
1741 Static -> text "[static]" <> space
1743 prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc)
1745 depth d . bracket p startPrec $
1746 lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
1747 st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1748 | otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
1752 Static -> text "[static]" <> space
1754 prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
1755 depth d . bracket p startPrec $
1756 prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1757 prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch _ _ _ _ _ _])) n _ ty sc) =
1758 lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1759 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1760 prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
1761 depth d . bracket p startPrec $
1762 lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1763 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1764 -- This case preserves the behavior of the former constructor PEq.
1765 -- It should be removed if feasible when the pretty-printing of infix
1766 -- operators in general is improved.
1767 prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r])
1768 | n == eqTy, ppopt_impl ppo =
1769 depth d . bracket p eqPrec $
1770 enclose lparen rparen eq <+>
1771 align (group (vsep (map (prettyArgS (decD d) bnd)
1774 depth d . bracket p eqPrec . align . group $
1775 prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r))
1776 where eq = annName eqTy (text "=")
1778 prettyTerm = prettySe (decD d) (eqPrec + 1) bnd
1779 prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args
1780 | UN nm <- basename f
1781 , not (ppopt_impl ppo) && null (getShowArgs args) =
1782 prettyName True (ppopt_impl ppo) bnd f
1783 prettySe d p bnd (PAppBind _ (PRef _ _ f) [])
1784 | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
1785 prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators
1786 | UN nm <- basename op
1788 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1789 case getShowArgs args of
1791 [x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x)))
1792 [l,r] -> let precedence = maybe (startPrec - 1) prec f
1793 in depth d . bracket p precedence $ inFix (getTm l) (getTm r)
1794 (l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) ->
1795 depth d . bracket p funcAppPrec $
1796 enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
1797 align (group (vsep (map (prettyArgS d bnd) rest)))
1798 as -> opName True <+> align (vsep (map (prettyArgS d bnd) as))
1799 where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
1800 f = getFixity (opStr op)
1802 Nothing -> funcAppPrec + 1
1803 Just (Infixl p') -> p'
1804 Just f' -> prec f' + 1
1806 Nothing -> funcAppPrec + 1
1807 Just (Infixr p') -> p'
1808 Just f' -> prec f' + 1
1809 inFix l r = align . group $
1810 (prettySe (decD d) left bnd l <+> opName False) <$>
1811 group (prettySe (decD d) right bnd r)
1812 prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo
1813 | PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm,
1814 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1815 char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str))
1816 prettySe d p bnd (PApp _ f as) = -- Normal prefix applications
1817 let args = getShowArgs as
1818 fp = prettySe (decD d) (startPrec + 1) bnd f
1819 shownArgs = if ppopt_impl ppo then as else args
1821 depth d . bracket p funcAppPrec . group $
1824 else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs))
1825 prettySe d p bnd (PCase _ scr cases) =
1826 align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$>
1827 depth d (indent 2 (vsep (map ppcase cases)))
1829 ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec
1830 ([(n, False) | n <- vars l] ++ bnd)
1831 in nest nestingSize $
1832 prettyCase l <+> text "=>" <+> prettyCase r
1833 -- Warning: this is a bit of a hack. At this stage, we don't have the
1834 -- global context, so we can't determine which names are constructors,
1835 -- which are types, and which are pattern variables on the LHS of the
1836 -- case pattern. We use the heuristic that names without a namespace
1837 -- are patvars, because right now case blocks in PTerms are always
1838 -- delaborated from TT before being sent to the pretty-printer. If they
1839 -- start getting printed directly, THIS WILL BREAK.
1840 -- Potential solution: add a list of known patvars to the cases in
1841 -- PCase, and have the delaborator fill it out, kind of like the pun
1842 -- disambiguation on PDPair.
1843 vars tm = filter noNS (allNamesIn tm)
1844 noNS (NS _ _) = False
1847 prettySe d p bnd (PIfThenElse _ c t f) =
1848 depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $
1849 [ kwd "if" <+> prettySe (decD d) startPrec bnd c
1850 , kwd "then" <+> prettySe (decD d) startPrec bnd t
1851 , kwd "else" <+> prettySe (decD d) startPrec bnd f
1853 prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
1854 prettySe d p bnd (PResolveTC _) = kwd "%instance"
1855 prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1856 prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1857 prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
1858 prettySe d p bnd (PRewrite _ l r _) =
1859 depth d . bracket p startPrec $
1860 text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r
1861 prettySe d p bnd (PTyped l r) =
1862 lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen
1863 prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser
1864 | Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) .
1865 align . group . vsep . punctuate (ann comma) $
1866 map (prettySe (decD d) startPrec bnd) elts
1867 where ann = case pun of
1869 IsType -> annName pairTy
1870 IsTerm -> annName pairCon
1871 prettySe d p bnd (PDPair _ _ pun l t r) =
1875 annotated (text "**") <+>
1876 prettySe (decD d) startPrec (addBinding bnd) r <>
1878 where annotated = case pun of
1879 IsType -> annName sigmaTy
1880 IsTerm -> annName sigmaCon
1882 (left, addBinding) = case (l, pun) of
1883 (PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :))
1884 _ -> (prettySe (decD d) startPrec bnd l, id)
1885 prettySe d p bnd (PAlternative ns a as) =
1886 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1889 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (depth d . prettySe (decD d) startPrec bnd) as
1890 prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type"
1891 prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
1892 prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c))
1893 -- XXX: add pretty for tactics
1894 prettySe d p bnd (PProof ts) =
1895 kwd "proof" <+> lbrace <> ellipsis <> rbrace
1896 prettySe d p bnd (PTactics ts) =
1897 kwd "tactics" <+> lbrace <> ellipsis <> rbrace
1898 prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n
1899 prettySe d p bnd (PReturn f) = kwd "return"
1900 prettySe d p bnd PImpossible = kwd "impossible"
1901 prettySe d p bnd Placeholder = text "_"
1902 prettySe d p bnd (PDoBlock dos) =
1903 bracket p startPrec $
1904 kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos)))
1905 where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos
1906 ppdo bnd (DoBind _ bn _ tm : dos) =
1907 (prettyBindingOf bn False <+> text "<-" <+>
1908 group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) :
1909 ppdo ((bn, False):bnd) dos
1910 ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab
1911 text "no pretty printer for pattern-matching do binding" :
1913 ppdo bnd (DoLet _ ln _ ty v : dos) =
1914 (kwd "let" <+> prettyBindingOf ln False <+>
1915 (if ty /= Placeholder
1916 then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="
1918 group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :
1919 ppdo ((ln, False):bnd) dos
1920 ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab
1921 text "no pretty printer for pattern-matching do binding" :
1924 prettySe d p bnd (PCoerced t) = prettySe d p bnd t
1925 prettySe d p bnd (PElabError s) = pretty s
1926 -- Quasiquote pprinting ignores bound vars
1927 prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")"
1928 prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")"
1929 prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t
1930 prettySe d p bnd (PQuoteName n res _) = text start <> prettyName True (ppopt_impl ppo) bnd n <> text end
1931 where start = if res then "`{" else "`{{"
1932 end = if res then "}" else "}}"
1933 prettySe d p bnd (PRunElab _ tm _) =
1934 bracket p funcAppPrec . group . align . hang 2 $
1936 prettySe (decD d) funcAppPrec bnd tm
1937 prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
1939 prettySe d p bnd _ = text "missing pretty-printer for term"
1941 prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
1942 prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
1943 where display (UN n) = T.unpack n
1944 display (MN _ n) = T.unpack n
1945 -- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
1946 display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n
1949 prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm)
1950 prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm
1951 prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm
1952 prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm)
1954 prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg
1955 prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
1956 prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace
1957 prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
1959 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1960 annName n = annotate (AnnName n Nothing Nothing Nothing)
1962 opStr :: Name -> String
1963 opStr (NS n _) = opStr n
1964 opStr (UN n) = T.unpack n
1966 slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation]
1967 slist' (Just d) _ _ _ | d <= 0 = Nothing
1969 | containsHole e = Nothing
1970 slist' d p bnd (PApp _ (PRef _ _ nil) _)
1971 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1972 slist' d p bnd (PRef _ _ nil)
1973 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1974 slist' d p bnd (PApp _ (PRef _ _ cons) args)
1975 | nsroot cons == sUN "::",
1976 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1978 Just tl' <- slist' (decD d) p bnd tl
1979 = Just (prettySe d startPrec bnd hd : tl')
1981 isImp (PImp {}) = True
1983 slist' _ _ _ tm = Nothing
1985 slist d p bnd e | Just es <- slist' d p bnd e = Just $
1987 [] -> annotate (AnnData "" "") $ text "[]"
1988 [x] -> enclose left right . group $ x
1989 xs -> enclose left right .
1990 align . group . vsep .
1991 punctuate comma $ xs
1992 where left = (annotate (AnnData "" "") (text "["))
1993 right = (annotate (AnnData "" "") (text "]"))
1994 comma = (annotate (AnnData "" "") (text ","))
1995 slist _ _ _ _ = Nothing
1997 pairElts :: PTerm -> Maybe [PTerm]
1998 pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1999 | otherwise = Just [x, y]
2000 pairElts _ = Nothing
2002 natns = "Prelude.Nat."
2004 snat :: PPOption -> Maybe Int -> Int -> PTerm -> Maybe Integer
2006 | ppopt_desugarnats ppo = Nothing
2007 | otherwise = snat' d p e
2009 snat' :: Maybe Int -> Int -> PTerm -> Maybe Integer
2010 snat' (Just x) _ _ | x <= 0 = Nothing
2011 snat' d p (PRef _ _ z)
2012 | show z == (natns++"Z") || show z == "Z" = Just 0
2013 snat' d p (PApp _ s [PExp {getTm=n}])
2014 | show s == (natns++"S") || show s == "S",
2015 Just n' <- snat' (decD d) p n
2017 snat' _ _ _ = Nothing
2019 bracket outer inner doc
2020 | outer > inner = lparen <> doc <> rparen
2023 ellipsis = text "..."
2026 depth (Just d) = if d <= 0 then const (ellipsis) else id
2028 decD = fmap (\x -> x - 1)
2030 kwd = annotate AnnKeyword . text
2032 fixities :: M.Map String Fixity
2033 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
2035 getFixity :: String -> Maybe Fixity
2036 getFixity = flip M.lookup fixities
2038-- | Strip away namespace information
2039basename :: Name -> Name
2040basename (NS n _) = basename n
2043-- | Determine whether a name was the one inserted for a hole or
2044-- guess by the delaborator
2045isHoleName :: Name -> Bool
2046isHoleName (UN n) = n == T.pack "[__]"
2049-- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess
2050containsHole :: PTerm -> Bool
2051containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm]
2053-- | Pretty-printer helper for names that attaches the correct annotations
2055 :: Bool -- ^^ whether the name should be parenthesised if it is an infix operator
2056 -> Bool -- ^^ whether to show namespaces
2057 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
2058 -> Name -- ^^ the name to pprint
2059 -> Doc OutputAnnotation
2060prettyName infixParen showNS bnd n
2061 | (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_"
2062 | (UN n') <- n, T.unpack n' == "_" = text "_"
2063 | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
2064 | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
2065 where fullName = text nameSpace <> parenthesise (text (baseName n))
2066 baseName (UN n) = T.unpack n
2067 baseName (NS n ns) = baseName n
2068 baseName (MN i s) = T.unpack s
2069 baseName other = show other
2070 nameSpace = case n of
2071 (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
2073 isInfix = case baseName n of
2075 (c : _) -> not (isAlpha c)
2076 parenthesise = if isInfix && infixParen then enclose lparen rparen else id
2079showCImp :: PPOption -> PClause -> Doc OutputAnnotation
2080showCImp ppo (PClause _ n l ws r w)
2081 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
2082 <+> text "where" <+> text (show w)
2085 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2086showCImp ppo (PWith _ n l ws r pn w)
2087 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
2088 <+> braces (text (show w))
2091 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2094showDImp :: PPOption -> PData -> Doc OutputAnnotation
2095showDImp ppo (PDatadecl n nfc ty cons)
2096 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
2097 (indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
2099showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
2100showDecls o ds = vsep (map (showDeclImp o) ds)
2102showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
2103showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
2104showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
2105 indent 2 (vsep (map (showCImp o) cs))
2106showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
2107showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
2108showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
2109showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
2110showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _)
2111 = text "interface" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
2112showDeclImp o (PInstance _ _ _ _ cs n _ _ t _ ds)
2113 = text "implementation" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
2114showDeclImp _ _ = text "..."
2115-- showDeclImp (PImport o) = "import " ++ o
2117getImps :: [PArg] -> [(Name, PTerm)]
2119getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
2120getImps (_ : xs) = getImps xs
2122getExps :: [PArg] -> [PTerm]
2124getExps (PExp _ _ _ tm : xs) = tm : getExps xs
2125getExps (_ : xs) = getExps xs
2127getShowArgs :: [PArg] -> [PArg]
2129getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
2130getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
2131 | PImp _ _ _ _ tm <- e
2132 , containsHole tm = e : getShowArgs xs
2133getShowArgs (_ : xs) = getShowArgs xs
2135getConsts :: [PArg] -> [PTerm]
2137getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
2138getConsts (_ : xs) = getConsts xs
2140getAll :: [PArg] -> [PTerm]
2145showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
2146 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
2147 -> PPOption -- ^^ pretty printing options
2148 -> Bool -- ^^ whether to colourise
2149 -> Name -- ^^ the term to show
2151showName ist bnd ppo colour n = case ist of
2152 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
2153 Nothing -> showbasic n
2154 where name = if ppopt_impl ppo then show n else showbasic n
2155 showbasic n@(UN _) = showCG n
2156 showbasic (MN i s) = str s
2157 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
2158 showbasic (SN s) = show s
2160 colourise n t = let ctxt' = fmap tt_ctxt ist in
2163 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
2164 else colouriseBound t name
2165 | isDConName n ctxt -> colouriseData t name
2166 | isFnName n ctxt -> colouriseFun t name
2167 | isTConName n ctxt -> colouriseType t name
2168 -- The assumption is that if a name is not bound and does not exist in the
2169 -- global context, then we're somewhere in which implicit info has been lost
2170 -- (like error messages). Thus, unknown vars are colourised as implicits.
2171 | otherwise -> colouriseImplicit t name
2173showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
2174 -> PTerm -- ^^ the term to show
2176showTm ist = displayDecorated (consoleDecorate ist) .
2177 renderPretty 0.8 100000 .
2178 prettyImp (ppOptionIst ist)
2180-- | Show a term with implicits, no colours
2181showTmImpls :: PTerm -> String
2182showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
2184-- | Show a term with specific options
2185showTmOpts :: PPOption -> PTerm -> String
2186showTmOpts opt = flip (displayS . renderPretty 1.0 10000000 . prettyImp opt) ""
2189instance Sized PTerm where
2190 size (PQuote rawTerm) = size rawTerm
2191 size (PRef fc _ name) = size name
2192 size (PLam fc name _ ty bdy) = 1 + size ty + size bdy
2193 size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy
2194 size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy
2195 size (PTyped trm ty) = 1 + size trm + size ty
2196 size (PApp fc name args) = 1 + size args
2197 size (PAppBind fc name args) = 1 + size args
2198 size (PCase fc trm bdy) = 1 + size trm + size bdy
2199 size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f])
2200 size (PTrue fc _) = 1
2201 size (PResolveTC fc) = 1
2202 size (PRewrite fc left right _) = 1 + size left + size right
2203 size (PPair fc _ _ left right) = 1 + size left + size right
2204 size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right
2205 size (PAlternative _ a alts) = 1 + size alts
2206 size (PHidden hidden) = size hidden
2207 size (PUnifyLog tm) = size tm
2208 size (PDisamb _ tm) = size tm
2209 size (PNoImplicits tm) = size tm
2211 size (PUniverse _) = 1
2212 size (PConstant fc const) = 1 + size fc + size const
2213 size Placeholder = 1
2214 size (PDoBlock dos) = 1 + size dos
2215 size (PIdiom fc term) = 1 + size term
2216 size (PReturn fc) = 1
2217 size (PMetavar _ name) = 1
2218 size (PProof tactics) = size tactics
2219 size (PElabError err) = size err
2220 size PImpossible = 1
2223getPArity :: PTerm -> Int
2224getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc
2227-- Return all names, free or globally bound, in the given term.
2229allNamesIn :: PTerm -> [Name]
2230allNamesIn tm = nub $ ni 0 [] tm
2231 where -- TODO THINK added niTacImp, but is it right?
2232 ni 0 env (PRef _ _ n)
2233 | not (n `elem` env) = [n]
2234 ni 0 env (PPatvar _ n) = [n]
2235 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2236 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2237 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os)
2238 ni 0 env (PIfThenElse _ c t f) = ni 0 env c ++ ni 0 env t ++ ni 0 env f
2239 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2240 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2241 ni 0 env (PLet _ n _ ty val sc) = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc
2242 ni 0 env (PHidden tm) = ni 0 env tm
2243 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2244 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2245 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2246 ni 0 env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni 0 env r
2247 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2248 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2249 ni 0 env (PAlternative ns a ls) = concatMap (ni 0 env) ls
2250 ni 0 env (PUnifyLog tm) = ni 0 env tm
2251 ni 0 env (PDisamb _ tm) = ni 0 env tm
2252 ni 0 env (PNoImplicits tm) = ni 0 env tm
2254 ni i env (PQuasiquote tm ty) = ni (i+1) env tm ++ maybe [] (ni i env) ty
2255 ni i env (PUnquote tm) = ni (i - 1) env tm
2257 ni i env tm = concatMap (ni i env) (children tm)
2259 niTacImp i env (TacImp _ _ scr) = ni i env scr
2263-- Return all names defined in binders in the given term
2264boundNamesIn :: PTerm -> [Name]
2265boundNamesIn tm = S.toList (ni 0 S.empty tm)
2266 where -- TODO THINK Added niTacImp, but is it right?
2267 ni :: Int -> S.Set Name -> PTerm -> S.Set Name
2268 ni 0 set (PApp _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2269 ni 0 set (PAppBind _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2270 ni 0 set (PCase _ c os) = niTms 0 (ni 0 set c) (map snd os)
2271 ni 0 set (PIfThenElse _ c t f) = niTms 0 set [c, t, f]
2272 ni 0 set (PLam fc n _ ty sc) = S.insert n $ ni 0 (ni 0 set ty) sc
2273 ni 0 set (PLet fc n nfc ty val sc) = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc
2274 ni 0 set (PPi p n _ ty sc) = niTacImp 0 (S.insert n $ ni 0 (ni 0 set ty) sc) p
2275 ni 0 set (PRewrite _ l r _) = ni 0 (ni 0 set l) r
2276 ni 0 set (PTyped l r) = ni 0 (ni 0 set l) r
2277 ni 0 set (PPair _ _ _ l r) = ni 0 (ni 0 set l) r
2278 ni 0 set (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 (ni 0 set t) r
2279 ni 0 set (PDPair _ _ _ l t r) = ni 0 (ni 0 (ni 0 set l) t) r
2280 ni 0 set (PAlternative ns a as) = niTms 0 set as
2281 ni 0 set (PHidden tm) = ni 0 set tm
2282 ni 0 set (PUnifyLog tm) = ni 0 set tm
2283 ni 0 set (PDisamb _ tm) = ni 0 set tm
2284 ni 0 set (PNoImplicits tm) = ni 0 set tm
2286 ni i set (PQuasiquote tm ty) = ni (i + 1) set tm `S.union` maybe S.empty (ni i set) ty
2287 ni i set (PUnquote tm) = ni (i - 1) set tm
2289 ni i set tm = foldr S.union set (map (ni i set) (children tm))
2291 niTms :: Int -> S.Set Name -> [PTerm] -> S.Set Name
2292 niTms i set [] = set
2293 niTms i set (x : xs) = niTms i (ni i set x) xs
2295 niTacImp i set (TacImp _ _ scr) = ni i set scr
2296 niTacImp i set _ = set
2298-- Return names which are valid implicits in the given term (type).
2299implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
2300implicitNamesIn uvars ist tm
2301 = let (imps, fns) = execState (ni 0 [] tm) ([], []) in
2304 addImp n = do (imps, fns) <- get
2306 addFn n = do (imps, fns) <- get
2310 notCAF (PExp _ _ _ _ : _) = True
2311 notCAF (_ : xs) = notCAF xs
2313 notHidden (n, _) = case getAccessibility n of
2318 = case lookupDefAccExact n False (tt_ctxt ist) of
2322 ni 0 env (PRef _ _ n@(NS _ _))
2323 | not (n `elem` env)
2324 -- Never implicitly bind if there's a namespace
2326 ni 0 env (PRef _ _ n)
2327 | not (n `elem` env) && implicitable n || n `elem` uvars = addImp n
2328 ni 0 env (PApp _ f@(PRef _ _ n) as)
2329 | n `elem` uvars = do ni 0 env f
2330 mapM_ (ni 0 env) (map getTm as)
2331 | otherwise = do case lookupTy n (tt_ctxt ist) of
2334 mapM_ (ni 0 env) (map getTm as)
2335 ni 0 env (PApp _ f as) = do ni 0 env f
2336 mapM_ (ni 0 env) (map getTm as)
2337 ni 0 env (PAppBind _ f as) = do ni 0 env f
2338 mapM_ (ni 0 env) (map getTm as)
2339 ni 0 env (PCase _ c os) = do ni 0 env c
2340 -- names in 'os', not counting the names bound in the cases
2341 mapM_ (ni 0 env) (map snd os)
2344 mapM_ (ni 0 env) (map fst os)
2346 put (nub imps \\ nub impsfst, fns)
2347 ni 0 env (PIfThenElse _ c t f) = mapM_ (ni 0 env) [c, t, f]
2348 ni 0 env (PLam fc n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2349 ni 0 env (PPi p n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2350 ni 0 env (PRewrite _ l r _) = do ni 0 env l; ni 0 env r
2351 ni 0 env (PTyped l r) = do ni 0 env l; ni 0 env r
2352 ni 0 env (PPair _ _ _ l r) = do ni 0 env l; ni 0 env r
2353 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = do ni 0 env t; ni 0 (n:env) r
2354 ni 0 env (PDPair _ _ _ l t r) = do ni 0 env l
2357 ni 0 env (PAlternative ns a as) = mapM_ (ni 0 env) as
2358 ni 0 env (PHidden tm) = ni 0 env tm
2359 ni 0 env (PUnifyLog tm) = ni 0 env tm
2360 ni 0 env (PDisamb _ tm) = ni 0 env tm
2361 ni 0 env (PNoImplicits tm) = ni 0 env tm
2363 ni i env (PQuasiquote tm ty) = do ni (i + 1) env tm
2364 maybe (return ()) (ni i env) ty
2365 ni i env (PUnquote tm) = ni (i - 1) env tm
2367 ni i env tm = mapM_ (ni i env) (children tm)
2369-- Return names which are free in the given term.
2370namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
2371namesIn uvars ist tm = nub $ ni 0 [] tm
2373 ni 0 env (PRef _ _ n)
2374 | not (n `elem` env)
2375 = case lookupTy n (tt_ctxt ist) of
2377 _ -> if n `elem` (map fst uvars) then [n] else []
2378 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2379 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2380 ni 0 env (PCase _ c os) = ni 0 env c ++
2381 -- names in 'os', not counting the names bound in the cases
2382 (nub (concatMap (ni 0 env) (map snd os))
2383 \\ nub (concatMap (ni 0 env) (map fst os)))
2384 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2385 ni 0 env (PLam fc n nfc ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2386 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2387 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2388 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2389 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2390 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2391 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2392 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2393 ni 0 env (PHidden tm) = ni 0 env tm
2394 ni 0 env (PUnifyLog tm) = ni 0 env tm
2395 ni 0 env (PDisamb _ tm) = ni 0 env tm
2396 ni 0 env (PNoImplicits tm) = ni 0 env tm
2398 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2399 ni i env (PUnquote tm) = ni (i - 1) env tm
2401 ni i env tm = concatMap (ni i env) (children tm)
2403 niTacImp i env (TacImp _ _ scr) = ni i env scr
2406-- Return which of the given names are used in the given term.
2408usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
2409usedNamesIn vars ist tm = nub $ ni 0 [] tm
2410 where -- TODO THINK added niTacImp, but is it right?
2411 ni 0 env (PRef _ _ n)
2412 | n `elem` vars && not (n `elem` env)
2413 = case lookupDefExact n (tt_ctxt ist) of
2416 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2417 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2418 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os)
2419 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2420 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2421 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2422 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2423 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2424 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2425 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2426 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2427 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2428 ni 0 env (PHidden tm) = ni 0 env tm
2429 ni 0 env (PUnifyLog tm) = ni 0 env tm
2430 ni 0 env (PDisamb _ tm) = ni 0 env tm
2431 ni 0 env (PNoImplicits tm) = ni 0 env tm
2433 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2434 ni i env (PUnquote tm) = ni (i - 1) env tm
2436 ni i env tm = concatMap (ni i env) (children tm)
2438 niTacImp i env (TacImp _ _ scr) = ni i env scr
2441-- Return the list of inaccessible (= dotted) positions for a name.
2442getErasureInfo :: IState -> Name -> [Int]
2443getErasureInfo ist n =
2444 case lookupCtxtExact n (idris_optimisation ist) of
2445 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