2Module : Idris.AbsSyntaxTree
3Description : Core data definitions used in Idris.
6Maintainer : The Idris Community.
8{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
9 DeriveDataTypeable, TypeSynonymInstances, PatternGuards #-}
11module Idris.AbsSyntaxTree where
14import Idris.Core.Evaluate
15import Idris.Core.Elaborate hiding (Tactic(..))
16import Idris.Core.Typecheck
17import Idris.Docstrings
19import IRTS.CodegenCommon
21import Util.DynamicLinker
25import System.Console.Haskeline
28import Prelude hiding ((<$>))
30import Control.Applicative ((<|>))
32import Control.Monad.Trans.State.Strict
33import Control.Monad.Trans.Except
34import qualified Control.Monad.Trans.Class as Trans (lift)
36import Data.Data (Data)
37import Data.Function (on)
38import Data.Generics.Uniplate.Data (universe, children)
39import Data.List hiding (group)
41import qualified Data.Map.Strict as M
42import qualified Data.Text as T
44import qualified Data.Set as S
45import Data.Word (Word)
46import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
47import Data.Traversable (Traversable)
49import Data.Foldable (Foldable)
53import Text.PrettyPrint.Annotated.Leijen
55data ElabWhat = ETypes | EDefns | EAll
58-- | Data to pass to recursively called elaborators; e.g. for where blocks,
59-- paramaterised declarations, etc.
61-- rec_elabDecl is used to pass the top level elaborator into other elaborators,
62-- so that we can have mutually recursive elaborators in separate modules without
63-- having to muck about with cyclic modules.
64data ElabInfo = EInfo {
65 params :: [(Name, PTerm)]
66 , inblock :: Ctxt [Name] -- ^ names in the block, and their params
67 , liftname :: Name -> Name
68 , namespace :: [String]
70 , constraintNS :: String -- ^ filename for adding to constraint variables
73 -- | We may, recursively, collect transformations to do on the rhs,
74 -- e.g. rewriting recursive calls to functions defined by 'with'
75 , rhs_trans :: PTerm -> PTerm
76 , rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl -> Idris ()
80toplevel = EInfo [] emptyContext id [] Nothing "(toplevel)" 0 id (\_ _ _ -> fail "Not implemented")
82toplevelWith :: String -> ElabInfo
83toplevelWith ns = EInfo [] emptyContext id [] Nothing ns 0 id (\_ _ _ -> fail "Not implemented")
85eInfoNames :: ElabInfo -> [Name]
86eInfoNames info = map fst (params info) ++ M.keys (inblock info)
88data IOption = IOption {
90 , opt_logcats :: [LogCat] -- ^ List of logging categories.
91 , opt_typecase :: Bool
92 , opt_typeintype :: Bool
93 , opt_coverage :: Bool
94 , opt_showimp :: Bool -- ^ show implicits
95 , opt_errContext :: Bool
98 , opt_nobanner :: Bool
100 , opt_codegen :: Codegen
101 , opt_outputTy :: OutputType
102 , opt_ibcsubdir :: FilePath
103 , opt_importdirs :: [FilePath]
104 , opt_triple :: String
106 , opt_cmdline :: [Opt] -- ^ remember whole command line
107 , opt_origerr :: Bool
108 , opt_autoSolve :: Bool -- ^ automatically apply "solve" tactic in prover
109 , opt_autoImport :: [FilePath] -- ^ List of modules to auto import i.e. `Builtins+Prelude`
110 , opt_optimise :: [Optimisation]
111 , opt_printdepth :: Maybe Int
112 , opt_evaltypes :: Bool -- ^ normalise types in `:t`
113 , opt_desugarnats :: Bool
114 , opt_autoimpls :: Bool
115 } deriving (Show, Eq)
117defaultOpts = IOption { opt_logLevel = 0
119 , opt_typecase = False
120 , opt_typeintype = False
121 , opt_coverage = True
122 , opt_showimp = False
123 , opt_errContext = False
126 , opt_nobanner = False
128 , opt_codegen = Via IBCFormat "c"
129 , opt_outputTy = Executable
131 , opt_importdirs = []
135 , opt_origerr = False
136 , opt_autoSolve = True
137 , opt_autoImport = []
138 , opt_optimise = defaultOptimise
139 , opt_printdepth = Just 5000
140 , opt_evaltypes = True
141 , opt_desugarnats = False
142 , opt_autoimpls = True
145data PPOption = PPOption {
146 ppopt_impl :: Bool -- ^ whether to show implicits
147 , ppopt_desugarnats :: Bool
148 , ppopt_pinames :: Bool -- ^ whether to show names in pi bindings
149 , ppopt_depth :: Maybe Int
152data Optimisation = PETransform -- ^ partial eval and associated transforms
155defaultOptimise = [PETransform]
157-- | Pretty printing options with default verbosity.
158defaultPPOption :: PPOption
159defaultPPOption = PPOption {
161 , ppopt_desugarnats = False
162 , ppopt_pinames = False
163 , ppopt_depth = Just 200
166-- | Pretty printing options with the most verbosity.
167verbosePPOption :: PPOption
168verbosePPOption = PPOption {
170 , ppopt_desugarnats = True
171 , ppopt_pinames = True
172 , ppopt_depth = Just 200
175-- | Get pretty printing options from the big options record.
176ppOption :: IOption -> PPOption
177ppOption opt = PPOption {
178 ppopt_impl = opt_showimp opt
179 , ppopt_pinames = False
180 , ppopt_depth = opt_printdepth opt
181 , ppopt_desugarnats = opt_desugarnats opt
184-- | Get pretty printing options from an idris state record.
185ppOptionIst :: IState -> PPOption
186ppOptionIst = ppOption . idris_options
188data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
190-- | The output mode in use
191data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle
192 | IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle
195-- | How wide is the console?
196data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
197 | ColsWide Int -- ^ Manually specified - must be positive
198 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
201-- | If a function has no totality annotation, what do we assume?
202data DefaultTotality = DefaultCheckingTotal -- ^ Total
203 | DefaultCheckingPartial -- ^ Partial
204 | DefaultCheckingCovering -- ^Total coverage, but may diverge
207-- | The global state used in the Idris monad
208data IState = IState {
209 tt_ctxt :: Context -- ^ All the currently defined names and their terms
210 , idris_constraints :: S.Set ConstraintFC -- ^ A list of universe constraints and their corresponding source locations
211 , idris_infixes :: [FixDecl] -- ^ Currently defined infix operators
212 , idris_implicits :: Ctxt [PArg]
213 , idris_statics :: Ctxt [Bool]
214 , idris_classes :: Ctxt ClassInfo
215 , idris_openimpls :: [Name] -- ^ Privileged implementations, will resolve immediately
216 , idris_records :: Ctxt RecordInfo
217 , idris_dsls :: Ctxt DSL
218 , idris_optimisation :: Ctxt OptInfo
219 , idris_datatypes :: Ctxt TypeInfo
220 , idris_namehints :: Ctxt [Name]
222 -- | list of lhs/rhs, and a list of missing clauses. These are not
224 , idris_patdefs :: Ctxt ([([(Name, Term)], Term, Term)], [PTerm])
225 , idris_flags :: Ctxt [FnOpt]
226 , idris_callgraph :: Ctxt CGInfo -- ^ name, args used in each pos
227 , idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)])
229 -- | module documentation is saved in a special MN so the context
230 -- mechanism can be used for disambiguation.
231 , idris_moduledocs :: Ctxt (Docstring DocTerm)
232 , idris_tyinfodata :: Ctxt TIData
233 , idris_fninfo :: Ctxt FnInfo
234 , idris_transforms :: Ctxt [(Term, Term)]
235 , idris_autohints :: Ctxt [Name]
236 , idris_totcheck :: [(FC, Name)] -- ^ names to check totality on
237 , idris_defertotcheck :: [(FC, Name)] -- ^ names to check at the end
238 , idris_totcheckfail :: [(FC, String)]
239 , idris_options :: IOption
241 , idris_lineapps :: [((FilePath, Int), PTerm)] -- ^ Full application LHS on source line
243 -- | The currently defined but not proven metavariables. The Int is
244 -- the number of vars to display as a context, the Maybe Name is its
245 -- top-level function, the [Name] is the list of local variables
246 -- available for proof search and the Bools are whether :p is
247 -- allowed, and whether the variable is definable at all
248 -- (Metavariables are not definable if they are applied in a term
249 -- which still has hole bindings)
250 , idris_metavars :: [(Name, (Maybe Name, Int, [Name], Bool, Bool))]
251 , idris_coercions :: [Name]
252 , idris_errRev :: [(Term, Term)]
253 , syntax_rules :: SyntaxRules
254 , syntax_keywords :: [String]
255 , imported :: [FilePath] -- ^ The imported modules
256 , idris_scprims :: [(Name, (Int, PrimFn))]
257 , idris_objs :: [(Codegen, FilePath)]
258 , idris_libs :: [(Codegen, String)]
259 , idris_cgflags :: [(Codegen, String)]
260 , idris_hdrs :: [(Codegen, String)]
261 , idris_imported :: [(FilePath, Bool)] -- ^ Imported ibc file names, whether public
262 , proof_list :: [(Name, (Bool, [String]))]
263 , errSpan :: Maybe FC
264 , parserWarnings :: [(FC, Err)]
265 , lastParse :: Maybe Name
266 , indent_stack :: [Int]
267 , brace_stack :: [Maybe Int]
268 , lastTokenSpan :: Maybe FC -- ^ What was the span of the latest token parsed?
269 , idris_parsedSpan :: Maybe FC
270 , hide_list :: Ctxt Accessibility
271 , default_access :: Accessibility
272 , default_total :: DefaultTotality
273 , ibc_write :: [IBCWrite]
274 , compiled_so :: Maybe String
275 , idris_dynamic_libs :: [DynamicLib]
276 , idris_language_extensions :: [LanguageExt]
277 , idris_outputmode :: OutputMode
278 , idris_colourRepl :: Bool
279 , idris_colourTheme :: ColourTheme
280 , idris_errorhandlers :: [Name] -- ^ Global error handlers
281 , idris_nameIdx :: (Int, Ctxt (Int, Name))
282 , idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)) -- ^ Specific error handlers
283 , module_aliases :: M.Map [T.Text] [T.Text]
284 , idris_consolewidth :: ConsoleWidth -- ^ How many chars wide is the console?
285 , idris_postulates :: S.Set Name
286 , idris_externs :: S.Set (Name, Int)
287 , idris_erasureUsed :: [(Name, Int)] -- ^ Function/constructor name, argument position is used
288 , idris_whocalls :: Maybe (M.Map Name [Name])
289 , idris_callswho :: Maybe (M.Map Name [Name])
291 -- | List of names that were defined in the repl, and can be re-/un-defined
292 , idris_repl_defs :: [Name]
294 -- | Stack of names currently being elaborated, Bool set if it's an
295 -- instance (instances appear twice; also as a funtion name)
296 , elab_stack :: [(Name, Bool)]
299 , idris_symbols :: M.Map Name Name -- ^ Symbol table (preserves sharing of names)
300 , idris_exports :: [Name] -- ^ Functions with ExportList
301 , idris_highlightedRegions :: [(FC, OutputAnnotation)] -- ^ Highlighting information to output
302 , idris_parserHighlights :: [(FC, OutputAnnotation)] -- ^ Highlighting information from the parser
303 , idris_deprecated :: Ctxt String -- ^ Deprecated names and explanation
304 , idris_inmodule :: S.Set Name -- ^ Names defined in current module
305 , idris_ttstats :: M.Map Term (Int, Term)
306 , idris_fragile :: Ctxt String -- ^ Fragile names and explanation.
309-- Required for parsers library, and therefore trifecta
310instance Show IState where
311 show = const "{internal state}"
313data SizeChange = Smaller | Same | Bigger | Unknown
316deriving instance Binary SizeChange
317deriving instance NFData SizeChange
320type SCGEntry = (Name, [Maybe (Int, SizeChange)])
321type UsageReason = (Name, Int) -- fn_name, its_arg_number
323data CGInfo = CGInfo {
326 , usedpos :: [(Int, [UsageReason])]
329deriving instance Binary CGInfo
330deriving instance NFData CGInfo
333primDefs = [ sUN "unsafePerformPrimIO"
334 , sUN "mkLazyForeignPrim"
335 , sUN "mkForeignPrim"
339-- information that needs writing for the current module's .ibc file
340data IBCWrite = IBCFix FixDecl
345 | IBCInstance Bool Bool Name Name
352 | IBCImport (Bool, FilePath) -- ^ True = import public
353 | IBCImportDir FilePath
354 | IBCObj Codegen FilePath
355 | IBCLib Codegen String
356 | IBCCGFlag Codegen String
358 | IBCHeader Codegen String
359 | IBCAccess Name Accessibility
360 | IBCMetaInformation Name MetaInformation
361 | IBCTotal Name Totality
362 | IBCInjective Name Injectivity
363 | IBCFlags Name [FnOpt]
364 | IBCFnInfo Name FnInfo
365 | IBCTrans Name (Term, Term)
366 | IBCErrRev (Term, Term)
370 | IBCDef Name -- ^ The main context.
371 | IBCNameHint (Name, Name)
372 | IBCLineApp FilePath Int PTerm
373 | IBCErrorHandler Name
374 | IBCFunctionErrorHandler Name Name Name
376 | IBCExtern (Name, Int)
377 | IBCTotCheckErr FC String
379 | IBCModDocs Name -- ^ The name is the special name used to track module docs
380 | IBCUsage (Name, Int)
382 | IBCAutoHint Name Name
383 | IBCDeprecate Name String
384 | IBCFragile Name String
385 | IBCConstraint FC UConstraint
388-- | The initial state for the compiler
390idrisInit = IState initContext S.empty []
391 emptyContext emptyContext emptyContext [] emptyContext
392 emptyContext emptyContext emptyContext emptyContext
393 emptyContext emptyContext emptyContext emptyContext
394 emptyContext emptyContext emptyContext emptyContext
396 [] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] []
397 [] [] Nothing [] Nothing [] [] Nothing Nothing emptyContext Private DefaultCheckingPartial [] Nothing [] []
398 (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty
399 AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] []
400 emptyContext S.empty M.empty emptyContext
403-- | The monad for the main REPL - reading and processing files and
404-- updating global state (hence the IO inner monad).
407-- type Idris = WriterT [Either String (IO ())] (State IState a))
410type Idris = StateT IState (ExceptT Err IO)
412catchError :: Idris a -> (Err -> Idris a) -> Idris a
413catchError = liftCatch catchE
415throwError :: Err -> Idris a
416throwError = Trans.lift . throwE
418-- Commands in the REPL
420data Codegen = Via IRFormat String
424deriving instance NFData Codegen
427data IRFormat = IBCFormat | JSONFormat deriving (Show, Eq)
429data HowMuchDocs = FullDocs | OverviewDocs
435 | NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name.
439 | DocStr (Either Name Const) HowMuchDocs
443 | Load FilePath (Maybe Int) -- up to maximum line number
444 | ChangeDirectory FilePath
447 | Compile Codegen String
451 | Prove Bool Name -- ^ If false, use prover, if true, use elab shell
452 | AddProof (Maybe Name)
458 | LogCategory [LogCat]
464 | DynamicLink FilePath
467 | Search [String] PTerm
468 | CaseSplitAt Bool Int Name
469 | AddClauseFrom Bool Int Name
470 | AddProofClauseFrom Bool Int Name
471 | AddMissing Bool Int Name
472 | MakeWith Bool Int Name
473 | MakeCase Bool Int Name
474 | MakeLemma Bool Int Name
475 | DoProofSearch Bool -- update file
476 Bool -- recursive search
478 Name -- top level name
483 | SetColour ColourType IdrisColour
487 | SetConsoleWidth ConsoleWidth
488 | SetPrinterDepth (Maybe Int)
489 | Apropos [String] String
493 | MakeDoc String -- IdrisDoc
496 | PPrint OutputFmt Int PTerm
498 -- Debugging commands
500 | DebugUnify PTerm PTerm
502data OutputFmt = HTMLOutput | LaTeXOutput
504-- | Recognised logging categories for the Idris compiler.
506-- @TODO add in sub categories.
513 deriving (Show, Eq, Ord)
515strLogCat :: LogCat -> String
516strLogCat IParse = "parser"
517strLogCat IElab = "elab"
518strLogCat ICodeGen = "codegen"
519strLogCat IErasure = "erasure"
520strLogCat ICoverage = "coverage"
521strLogCat IIBC = "ibc"
523codegenCats :: [LogCat]
524codegenCats = [ICodeGen]
526parserCats :: [LogCat]
532loggingCatsStr :: String
533loggingCatsStr = unlines
536 , (strLogCat ICodeGen)
537 , (strLogCat IErasure)
538 , (strLogCat ICoverage)
542data Opt = Filename String
555 | NoBuiltins -- only for the really primitive stuff!
572 | Port String -- ^ REPL TCP port
580 | PkgMkDoc String -- IdrisDoc
590 | OutputTy OutputType
591 | Extension LanguageExt
592 | InterpretScript String
594 | TargetTriple String
597 | AddOpt Optimisation
598 | RemoveOpt Optimisation
601 | AutoWidth -- ^ Automatically adjust terminal width
602 | AutoSolve -- ^ Automatically issue "solve" tactic in old-style interactive prover
603 | UseConsoleWidth ConsoleWidth
606 | NoElimDeprecationWarnings -- ^ Don't show deprecation warnings for %elim
607 | NoOldTacticDeprecationWarnings -- ^ Don't show deprecation warnings for old-style tactics
610data ElabShellCmd = EQED
618 | EDocStr (Either Name Const)
621-- Parsed declarations
623data Fixity = Infixl { prec :: Int }
624 | Infixr { prec :: Int }
625 | InfixN { prec :: Int }
626 | PrefixN { prec :: Int }
629deriving instance Binary Fixity
630deriving instance NFData Fixity
633instance Show Fixity where
634 show (Infixl i) = "infixl " ++ show i
635 show (Infixr i) = "infixr " ++ show i
636 show (InfixN i) = "infix " ++ show i
637 show (PrefixN i) = "prefix " ++ show i
639data FixDecl = Fix Fixity String
642instance Show FixDecl where
643 show (Fix f s) = show f ++ " " ++ s
646deriving instance Binary FixDecl
647deriving instance NFData FixDecl
650instance Ord FixDecl where
651 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
654data Static = Static | Dynamic
655 deriving (Show, Eq, Data, Typeable)
657deriving instance Binary Static
658deriving instance NFData Static
661-- ^ Mark bindings with their explicitness, and laziness
662data Plicity = Imp { pargopts :: [ArgOpt]
665 , pscoped :: Maybe ImplicitInfo -- ^ Nothing, if top level
666 , pinsource :: Bool -- ^ Explicitly written in source
668 | Exp { pargopts :: [ArgOpt]
670 , pparam :: Bool -- ^ this is a param (rather than index)
672 | Constraint { pargopts :: [ArgOpt]
675 | TacImp { pargopts :: [ArgOpt]
679 deriving (Show, Eq, Data, Typeable)
682deriving instance Binary Plicity
683deriving instance NFData Plicity
686is_scoped :: Plicity -> Maybe ImplicitInfo
687is_scoped (Imp _ _ _ s _) = s
691impl = Imp [] Dynamic False (Just (Impl False True False)) False
692-- Machine generated top level implicit
693impl_gen = Imp [] Dynamic False (Just (Impl False True True)) False
696forall_imp = Imp [] Dynamic False (Just (Impl False False True)) False
697forall_constraint = Imp [] Dynamic False (Just (Impl True False True)) False
699expl = Exp [] Dynamic False
700expl_param = Exp [] Dynamic True
702constraint = Constraint [] Static
704tacimpl t = TacImp [] Dynamic t
706data FnOpt = Inlinable -- ^ always evaluate when simplifying
707 | TotalFn | PartialFn | CoveringFn
708 | Coinductive | AssertTotal
710 -- | type class dictionary, eval only when a function
711 -- argument, and further evaluation results.
713 | Implicit -- ^ implicit coercion
714 | NoImplicit -- ^ do not apply implicit coercions
715 | CExport String -- ^ export, with a C name
716 | ErrorHandler -- ^ an error handler for use with the ErrorReflection extension
717 | ErrorReverse -- ^ attempt to reverse normalise before showing in error
718 | Reflection -- ^ a reflecting function, compile-time only
719 | Specialise [(Name, Maybe Int)] -- ^ specialise it, freeze these names
720 | Constructor -- ^ Data constructor type
721 | AutoHint -- ^ use in auto implicit search
722 | PEGenerated -- ^ generated by partial evaluator
725deriving instance Binary FnOpt
726deriving instance NFData FnOpt
731inlinable :: FnOpts -> Bool
732inlinable = elem Inlinable
734dictionary :: FnOpts -> Bool
735dictionary = elem Dictionary
738-- | Type provider - what to provide
739data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
740 | ProvPostulate t -- ^ goal type must be Type, so only term
741 deriving (Show, Eq, Functor)
743type ProvideWhat = ProvideWhat' PTerm
745-- | Top-level declarations such as compiler directives, definitions,
746-- datatypes and typeclasses.
748 -- | Fixity declaration
749 = PFix FC Fixity [String]
750 -- | Type declaration (last FC is precise name location)
751 | PTy (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC FnOpts Name FC t
752 -- | Postulate, second FC is precise name location
753 | PPostulate Bool -- external def if true
754 (Docstring (Either Err t)) SyntaxInfo FC FC FnOpts Name t
756 | PClauses FC FnOpts Name [PClause' t]
757 -- | Top level constant
759 -- | Data declaration.
760 | PData (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC DataOpts (PData' t)
762 | PParams FC [(Name, t)] [PDecl' t]
763 -- | Open block/declaration
764 | POpenInterfaces FC [Name] [PDecl' t]
765 -- | New namespace, where FC is accurate location of the namespace
767 | PNamespace String FC [PDecl' t]
769 | PRecord (Docstring (Either Err t)) SyntaxInfo FC DataOpts
771 FC -- Record name precise location
772 [(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span
773 [(Name, Docstring (Either Err t))] -- Param Docs
774 [(Maybe (Name, FC), Plicity, t, Maybe (Docstring (Either Err t)))] -- Fields
775 (Maybe (Name, FC)) -- Optional constructor name and location
776 (Docstring (Either Err t)) -- Constructor doc
777 SyntaxInfo -- Constructor SyntaxInfo
779 -- | Type class: arguments are documentation, syntax info, source
780 -- location, constraints, class name, class name location,
781 -- parameters, method declarations, optional constructor name
782 | PClass (Docstring (Either Err t)) SyntaxInfo FC
783 [(Name, t)] -- constraints
785 FC -- accurate location of class name
786 [(Name, FC, t)] -- parameters and precise locations
787 [(Name, Docstring (Either Err t))] -- parameter docstrings
788 [(Name, FC)] -- determining parameters and precise locations
789 [PDecl' t] -- declarations
790 (Maybe (Name, FC)) -- instance constructor name and location
791 (Docstring (Either Err t)) -- instance constructor docs
793 -- | Instance declaration: arguments are documentation, syntax
794 -- info, source location, constraints, class name, parameters, full
795 -- instance type, optional explicit name, and definitions
796 | PInstance (Docstring (Either Err t)) -- Instance docs
797 [(Name, Docstring (Either Err t))] -- Parameter docs
799 FC [(Name, t)] -- constraints
800 [Name] -- parent dictionaries to search for constraints
804 FC -- precise location of class
806 [(Name, t)] -- Extra names in scope in the body
807 t -- full instance type
808 (Maybe Name) -- explicit name
810 | PDSL Name (DSL' t) -- ^ DSL declaration
811 | PSyntax FC Syntax -- ^ Syntax definition
812 | PMutual FC [PDecl' t] -- ^ Mutual block
813 | PDirective Directive -- ^ Compiler directive.
815 -- | Type provider. The first t is the type, the second is the
816 -- term. The second FC is precise highlighting location.
817 | PProvider (Docstring (Either Err t)) SyntaxInfo FC FC (ProvideWhat' t) Name
819 -- | Source-to-source transformation rule. If bool is True, lhs and
820 -- rhs must be convertible.
821 | PTransform FC Bool t t
823 -- | FC is decl-level, for errors, and Strings represent the
825 | PRunElabDecl FC t [String]
828deriving instance Binary PDecl'
829deriving instance NFData PDecl'
832-- | The set of source directives
833data Directive = DLib Codegen String
834 | DLink Codegen String
835 | DFlag Codegen String
836 | DInclude Codegen String
841 | DSetTotal Name -- assert totality after checking
842 | DAccess Accessibility
843 | DDefault DefaultTotality
845 | DDynamicLibs [String]
846 | DNameHint Name FC [(Name, FC)]
847 | DErrorHandlers Name FC Name FC [(Name, FC)]
848 | DLanguage LanguageExt
849 | DDeprecate Name String
850 | DFragile Name String
851 | DAutoImplicits Bool
854-- | A set of instructions for things that need to happen in IState
855-- after a term elaboration when there's been reflected elaboration.
856data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
857 | RClausesInstrs Name [([(Name, Term)], Term, Term)]
858 | RAddInstance Name Name
859 | RDatatypeDeclInstrs Name [PArg]
860 -- | Datatype, constructors
861 | RDatatypeDefnInstrs Name Type [(Name, [PArg], Type)]
864-- | For elaborator state
865data EState = EState {
866 case_decls :: [(Name, PDecl)]
867 , delayed_elab :: [(Int, Elab' EState ())]
868 , new_tyDecls :: [RDeclInstructions]
869 , highlighting :: [(FC, OutputAnnotation)]
870 , auto_binds :: [Name] -- ^ names bound as auto implicits
871 , implicit_warnings :: [(FC, Name)] -- ^ Implicit warnings to report (location and global name)
875initEState = EState [] [] [] [] [] []
877type ElabD a = Elab' EState a
879highlightSource :: FC -> OutputAnnotation -> ElabD ()
880highlightSource fc annot =
881 updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux })
883-- | One clause of a top-level definition. Term arguments to constructors are:
885-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
887-- 2. The list of extra 'with' patterns
889-- 3. The right-hand side
891-- 4. The where block (PDecl' t)
893data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
894 | PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t]
895 | PClauseR FC [t] t [PDecl' t]
896 | PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t]
899deriving instance Binary PClause'
900deriving instance NFData PClause'
905 -- | Data declaration
906 PDatadecl { d_name :: Name -- ^ The name of the datatype
907 , d_name_fc :: FC -- ^ The precise location of the type constructor name
908 , d_tcon :: t -- ^ Type constructor
909 , d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors
911 -- | "Placeholder" for data whose constructors are defined later
912 | PLaterdecl { d_name :: Name
917-- | Transform the FCs in a PData and its associated terms. The first
918-- function transforms the general-purpose FCs, and the second
919-- transforms those that are used for semantic source highlighting, so
920-- they can be treated specially.
921mapPDataFC :: (FC -> FC) -> (FC -> FC) -> PData -> PData
922mapPDataFC f g (PDatadecl n nfc tycon ctors) =
923 PDatadecl n (g nfc) (mapPTermFC f g tycon) (map ctorFC ctors)
924 where ctorFC (doc, argDocs, n, nfc, ty, fc, ns) =
925 (doc, argDocs, n, g nfc, mapPTermFC f g ty, f fc, ns)
926mapPDataFC f g (PLaterdecl n nfc tycon) =
927 PLaterdecl n (g nfc) (mapPTermFC f g tycon)
929deriving instance Binary PData'
930deriving instance NFData PData'
933-- Handy to get a free function for applying PTerm -> PTerm functions
934-- across a program, by deriving Functor
936type PDecl = PDecl' PTerm
937type PData = PData' PTerm
938type PClause = PClause' PTerm
940-- | Transform the FCs in a PTerm. The first function transforms the
941-- general-purpose FCs, and the second transforms those that are used
942-- for semantic source highlighting, so they can be treated specially.
943mapPDeclFC :: (FC -> FC) -> (FC -> FC) -> PDecl -> PDecl
944mapPDeclFC f g (PFix fc fixity ops) =
945 PFix (f fc) fixity ops
946mapPDeclFC f g (PTy doc argdocs syn fc opts n nfc ty) =
947 PTy doc argdocs syn (f fc) opts n (g nfc) (mapPTermFC f g ty)
948mapPDeclFC f g (PPostulate ext doc syn fc nfc opts n ty) =
949 PPostulate ext doc syn (f fc) (g nfc) opts n (mapPTermFC f g ty)
951mapPDeclFC f g (PClauses fc opts n clauses) =
952 PClauses (f fc) opts n (map (fmap (mapPTermFC f g)) clauses)
953mapPDeclFC f g (PCAF fc n tm) = PCAF (f fc) n (mapPTermFC f g tm)
954mapPDeclFC f g (PData doc argdocs syn fc opts dat) =
955 PData doc argdocs syn (f fc) opts (mapPDataFC f g dat)
956mapPDeclFC f g (PParams fc params decls) =
958 (map (\(n, ty) -> (n, mapPTermFC f g ty)) params)
959 (map (mapPDeclFC f g) decls)
960mapPDeclFC f g (POpenInterfaces fc ifs decls) =
961 POpenInterfaces (f fc) ifs (map (mapPDeclFC f g) decls)
962mapPDeclFC f g (PNamespace ns fc decls) =
963 PNamespace ns (f fc) (map (mapPDeclFC f g) decls)
964mapPDeclFC f g (PRecord doc syn fc opts n nfc params paramdocs fields ctor ctorDoc syn') =
965 PRecord doc syn (f fc) opts n (g nfc)
966 (map (\(pn, pnfc, plic, ty) -> (pn, g pnfc, plic, mapPTermFC f g ty)) params)
968 (map (\(fn, plic, ty, fdoc) -> (fmap (\(fn', fnfc) -> (fn', g fnfc)) fn,
969 plic, mapPTermFC f g ty, fdoc))
971 (fmap (\(ctorN, ctorNFC) -> (ctorN, g ctorNFC)) ctor)
974mapPDeclFC f g (PClass doc syn fc constrs n nfc params paramDocs det body ctor ctorDoc) =
975 PClass doc syn (f fc)
976 (map (\(constrn, constr) -> (constrn, mapPTermFC f g constr)) constrs)
977 n (g nfc) (map (\(n, nfc, pty) -> (n, g nfc, mapPTermFC f g pty)) params)
978 paramDocs (map (\(dn, dnfc) -> (dn, g dnfc)) det)
979 (map (mapPDeclFC f g) body)
980 (fmap (\(n, nfc) -> (n, g nfc)) ctor)
982mapPDeclFC f g (PInstance doc paramDocs syn fc constrs pnames cn acc opts cnfc params pextra instTy instN body) =
983 PInstance doc paramDocs syn (f fc)
984 (map (\(constrN, constrT) -> (constrN, mapPTermFC f g constrT)) constrs)
985 pnames cn acc opts (g cnfc) (map (mapPTermFC f g) params)
986 (map (\(en, et) -> (en, mapPTermFC f g et)) pextra)
987 (mapPTermFC f g instTy)
989 (map (mapPDeclFC f g) body)
990mapPDeclFC f g (PDSL n dsl) = PDSL n (fmap (mapPTermFC f g) dsl)
991mapPDeclFC f g (PSyntax fc syn) = PSyntax (f fc) $
993 Rule syms tm ctxt -> Rule syms (mapPTermFC f g tm) ctxt
994 DeclRule syms decls -> DeclRule syms (map (mapPDeclFC f g) decls)
995mapPDeclFC f g (PMutual fc decls) =
996 PMutual (f fc) (map (mapPDeclFC f g) decls)
997mapPDeclFC f g (PDirective d) =
1000 DNameHint n nfc ns ->
1001 DNameHint n (g nfc) (map (\(hn, hnfc) -> (hn, g hnfc)) ns)
1002 DErrorHandlers n nfc n' nfc' ns ->
1003 DErrorHandlers n (g nfc) n' (g nfc') $
1004 map (\(an, anfc) -> (an, g anfc)) ns
1005mapPDeclFC f g (PProvider doc syn fc nfc what n) =
1006 PProvider doc syn (f fc) (g nfc) (fmap (mapPTermFC f g) what) n
1007mapPDeclFC f g (PTransform fc safe l r) =
1008 PTransform (f fc) safe (mapPTermFC f g l) (mapPTermFC f g r)
1009mapPDeclFC f g (PRunElabDecl fc script ns) =
1010 PRunElabDecl (f fc) (mapPTermFC f g script) ns
1012-- | Get all the names declared in a declaration
1013declared :: PDecl -> [Name]
1014declared (PFix _ _ _) = []
1015declared (PTy _ _ _ _ _ n fc t) = [n]
1016declared (PPostulate _ _ _ _ _ _ n t) = [n]
1017declared (PClauses _ _ n _) = [] -- not a declaration
1018declared (PCAF _ n _) = [n]
1019declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
1020 where fstt (_, _, a, _, _, _, _) = a
1021declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n]
1022declared (PParams _ _ ds) = concatMap declared ds
1023declared (POpenInterfaces _ _ ds) = concatMap declared ds
1024declared (PNamespace _ _ ds) = concatMap declared ds
1025declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
1026declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms)
1027declared (PInstance _ _ _ _ _ _ _ _ _ _ _ _ _ mn _)
1031declared (PDSL n _) = [n]
1032declared (PSyntax _ _) = []
1033declared (PMutual _ ds) = concatMap declared ds
1034declared (PDirective _) = []
1037-- get the names declared, not counting nested parameter blocks
1038tldeclared :: PDecl -> [Name]
1039tldeclared (PFix _ _ _) = []
1040tldeclared (PTy _ _ _ _ _ n _ t) = [n]
1041tldeclared (PPostulate _ _ _ _ _ _ n t) = [n]
1042tldeclared (PClauses _ _ n _) = [] -- not a declaration
1043tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
1044tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
1045 where fstt (_, _, a, _, _, _, _) = a
1046tldeclared (PParams _ _ ds) = []
1047tldeclared (POpenInterfaces _ _ ds) = concatMap tldeclared ds
1048tldeclared (PMutual _ ds) = concatMap tldeclared ds
1049tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds
1050tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms)
1051tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _ _ _ mn _)
1057defined :: PDecl -> [Name]
1058defined (PFix _ _ _) = []
1059defined (PTy _ _ _ _ _ n _ t) = []
1060defined (PPostulate _ _ _ _ _ _ n t) = []
1061defined (PClauses _ _ n _) = [n] -- not a declaration
1062defined (PCAF _ n _) = [n]
1063defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
1064 where fstt (_, _, a, _, _, _, _) = a
1065defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = []
1066defined (PParams _ _ ds) = concatMap defined ds
1067defined (POpenInterfaces _ _ ds) = concatMap defined ds
1068defined (PNamespace _ _ ds) = concatMap defined ds
1069defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
1070defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms)
1071defined (PInstance _ _ _ _ _ _ _ _ _ _ _ _ _ mn _)
1075defined (PDSL n _) = [n]
1076defined (PSyntax _ _) = []
1077defined (PMutual _ ds) = concatMap defined ds
1078defined (PDirective _) = []
1081updateN :: [(Name, Name)] -> Name -> Name
1082updateN ns n | Just n' <- lookup n ns = n'
1085updateNs :: [(Name, Name)] -> PTerm -> PTerm
1087updateNs ns t = mapPT updateRef t
1088 where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)
1091-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
1092-- updateDNs [] t = t
1093-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
1094-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
1095-- where updateCNs ns (PClause n l ts r ds)
1096-- = PClause (updateN ns n) (fmap (updateNs ns) l)
1097-- (map (fmap (updateNs ns)) ts)
1098-- (fmap (updateNs ns) r)
1099-- (map (updateDNs ns) ds)
1100-- updateDNs ns c = c
1102data PunInfo = IsType
1105 deriving (Eq, Show, Data, Typeable)
1107-- | High level language terms
1108data PTerm = PQuote Raw -- ^ Inclusion of a core term into the
1109 -- high-level language
1111 -- ^ A reference to a variable. The FC is its precise
1112 -- source location for highlighting. The list of FCs is a
1113 -- collection of additional highlighting locations.
1114 | PInferRef FC [FC] Name -- ^ A name to be defined later
1115 | PPatvar FC Name -- ^ A pattern variable
1116 | PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span.
1117 | PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable
1118 | PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location)
1119 | PTyped PTerm PTerm -- ^ Term with explicit type
1120 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
1121 | PWithApp FC PTerm PTerm -- ^ Application plus a 'with' argument
1122 | PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only)
1123 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
1124 | PMatchApp FC Name -- ^ Make an application by type matching
1125 | PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse
1126 | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
1127 | PTrue FC PunInfo -- ^ Unit type..?
1128 | PResolveTC FC -- ^ Solve this dictionary by type class resolution
1129 | PRewrite FC (Maybe Name) PTerm PTerm (Maybe PTerm)
1130 -- ^ "rewrite" syntax, with optional rewriting function and
1131 -- optional result type
1132 | PPair FC [FC] PunInfo PTerm PTerm
1133 -- ^ A pair (a, b) and whether it's a product type or a
1134 -- pair (solved by elaboration). The list of FCs is its
1136 | PDPair FC [FC] PunInfo PTerm PTerm PTerm
1137 -- ^ A dependent pair (tm : a ** b) and whether it's a
1138 -- sigma type or a pair that inhabits one (solved by
1139 -- elaboration). The [FC] is its punctuation.
1140 | PAs FC Name PTerm -- ^ @-pattern, valid LHS only
1141 | PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames.
1142 | PHidden PTerm -- ^ Irrelevant or hidden pattern
1143 | PType FC -- ^ 'Type' type
1144 | PUniverse Universe -- ^ Some universe
1145 | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
1146 | PConstant FC Const -- ^ Builtin types
1147 | Placeholder -- ^ Underscore
1148 | PDoBlock [PDo] -- ^ Do notation
1149 | PIdiom FC PTerm -- ^ Idiom brackets
1151 | PMetavar FC Name -- ^ A metavariable, ?name, and its precise location
1152 | PProof [PTactic] -- ^ Proof script
1153 | PTactics [PTactic] -- ^ As PProof, but no auto solving
1154 | PElabError Err -- ^ Error to report on elaboration
1155 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
1156 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
1157 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
1158 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
1159 | PNoImplicits PTerm -- ^ never run implicit converions on the term
1160 | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
1161 | PUnquote PTerm -- ^ ~Term
1162 | PQuoteName Name Bool FC
1163 -- ^ `{n} where the FC is the precise highlighting for
1164 -- the name in particular. If the Bool is False, then
1165 -- it's `{{n}} and the name won't be resolved.
1166 | PRunElab FC PTerm [String]
1167 -- ^ %runElab tm - New-style proof script. Args are
1168 -- location, script, enclosing namespace.
1169 | PConstSugar FC PTerm
1170 -- ^ A desugared constant. The FC is a precise source
1171 -- location that will be used to highlight it later.
1172 deriving (Eq, Data, Typeable)
1174data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed
1177 deriving (Eq, Data, Typeable)
1179-- | Transform the FCs in a PTerm. The first function transforms the
1180-- general-purpose FCs, and the second transforms those that are used
1181-- for semantic source highlighting, so they can be treated specially.
1182mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm
1183mapPTermFC f g (PQuote q) = PQuote q
1184mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n
1185mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n
1186mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n
1187mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2)
1188mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1189mapPTermFC 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)
1190mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2)
1191mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1192mapPTermFC f g (PWithApp fc t arg) = PWithApp (f fc) (mapPTermFC f g t) (mapPTermFC f g arg)
1193mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls
1194mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1195mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n
1196mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
1197mapPTermFC 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)
1198mapPTermFC f g (PTrue fc info) = PTrue (f fc) info
1199mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc)
1200mapPTermFC f g (PRewrite fc by t1 t2 t3) = PRewrite (f fc) by (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3)
1201mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2)
1202mapPTermFC 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)
1203mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t)
1204mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts)
1205mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t)
1206mapPTermFC f g (PType fc) = PType (f fc)
1207mapPTermFC f g (PUniverse u) = PUniverse u
1208mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2)
1209mapPTermFC f g (PConstant fc c) = PConstant (f fc) c
1210mapPTermFC f g Placeholder = Placeholder
1211mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos)
1212 where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t)
1213 mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)
1214 mapPDoFC (DoBindP fc t1 t2 alts) =
1215 DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)
1216 mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1217 mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1218mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t)
1219mapPTermFC f g (PReturn fc) = PReturn (f fc)
1220mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n
1221mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs)
1222mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs)
1223mapPTermFC f g (PElabError err) = PElabError err
1224mapPTermFC f g PImpossible = PImpossible
1225mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t)
1226mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t)
1227mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t)
1228mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t)
1229mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2)
1230mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t)
1231mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns
1232mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm)
1233mapPTermFC f g (PQuoteName n x fc) = PQuoteName n x (g fc)
1236dg instance Binary PTerm
1237deriving instance NFData PTerm
1240mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
1241mapPT f t = f (mpt t) where
1242 mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s)
1243 mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s)
1244 mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)
1245 mpt (PRewrite fc by t s g) = PRewrite fc by (mapPT f t) (mapPT f s) (fmap (mapPT f) g)
1246 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
1247 mpt (PWithApp fc t a) = PWithApp fc (mapPT f t) (mapPT f a)
1248 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
1249 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
1250 mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e)
1251 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
1252 mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r)
1253 mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r)
1254 mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as)
1255 mpt (PHidden t) = PHidden (mapPT f t)
1256 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
1257 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
1258 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
1259 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
1260 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
1261 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
1262 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
1266data PTactic' t = Intro [Name] | Intros | Focus Name
1267 | Refine Name [Bool] | Rewrite t | DoUnify
1274 | LetTac Name t | LetTacTy Name t t
1275 | Exact t | Compute | Trivial | TCInstance
1276 | ProofSearch Bool Bool Int (Maybe Name)
1277 [Name] -- allowed local names
1279 -- ^ the bool is whether to search recursively
1282 | ProofState | ProofTerm | Undo
1283 | Try (PTactic' t) (PTactic' t)
1284 | TSeq (PTactic' t) (PTactic' t)
1285 | ApplyTactic t -- see Language.Reflection module
1289 | GoalType String (PTactic' t)
1292 | TDocStr (Either Name Const)
1295 | TFail [ErrorReportPart]
1298 deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable)
1300deriving instance Binary PTactic'
1301deriving instance NFData PTactic'
1303instance Sized a => Sized (PTactic' a) where
1304 size (Intro nms) = 1 + size nms
1306 size (Focus nm) = 1 + size nm
1307 size (Refine nm bs) = 1 + size nm + length bs
1308 size (Rewrite t) = 1 + size t
1309 size (Induction t) = 1 + size t
1310 size (LetTac nm t) = 1 + size nm + size t
1311 size (Exact t) = 1 + size t
1319 size (Try l r) = 1 + size l + size r
1320 size (TSeq l r) = 1 + size l + size r
1321 size (ApplyTactic t) = 1 + size t
1322 size (Reflect t) = 1 + size t
1323 size (Fill t) = 1 + size t
1327 size (TFail ts) = 1 + size ts
1330 size (CaseTac x) = 1 + size x
1331 size (Equiv t) = 1 + size t
1332 size (Claim x y) = 1 + size x + size y
1334 size (MatchRefine x) = 1 + size x
1335 size (LetTacTy x y z) = 1 + size x + size y + size z
1338type PTactic = PTactic' PTerm
1340data PDo' t = DoExp FC t
1341 | DoBind FC Name FC t -- ^ second FC is precise name location
1342 | DoBindP FC t t [(t,t)]
1343 | DoLet FC Name FC t t -- ^ second FC is precise name location
1345 deriving (Eq, Functor, Data, Typeable)
1347deriving instance Binary PDo'
1348deriving instance NFData PDo'
1351instance Sized a => Sized (PDo' a) where
1352 size (DoExp fc t) = 1 + size fc + size t
1353 size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t
1354 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
1355 size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r
1356 size (DoLetP fc l r) = 1 + size fc + size l + size r
1358type PDo = PDo' PTerm
1360-- The priority gives a hint as to elaboration order. Best to elaborate
1361-- things early which will help give a more concrete type to other
1362-- variables, e.g. a before (interpTy a).
1364data PArg' t = PImp { priority :: Int
1365 , machine_inf :: Bool -- ^ true if the machine inferred it
1366 , argopts :: [ArgOpt]
1370 | PExp { priority :: Int
1371 , argopts :: [ArgOpt]
1375 | PConstraint { priority :: Int
1376 , argopts :: [ArgOpt]
1380 | PTacImplicit { priority :: Int
1381 , argopts :: [ArgOpt]
1386 deriving (Show, Eq, Functor, Data, Typeable)
1388data ArgOpt = AlwaysShow
1392 deriving (Show, Eq, Data, Typeable)
1394instance Sized a => Sized (PArg' a) where
1395 size (PImp p _ l nm trm) = 1 + size nm + size trm
1396 size (PExp p l nm trm) = 1 + size nm + size trm
1397 size (PConstraint p l nm trm) = 1 + size nm + size nm + size trm
1398 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
1401deriving instance Binary PArg'
1402deriving instance NFData PArg'
1405pimp n t mach = PImp 1 mach [] n t
1406pexp t = PExp 1 [] (sMN 0 "arg") t
1407pconst t = PConstraint 1 [] (sMN 0 "carg") t
1408ptacimp n s t = PTacImplicit 2 [] n s t
1410type PArg = PArg' PTerm
1412-- | Get the highest FC in a term, if one exists
1413highestFC :: PTerm -> Maybe FC
1414highestFC (PQuote _) = Nothing
1415highestFC (PRef fc _ _) = Just fc
1416highestFC (PInferRef fc _ _) = Just fc
1417highestFC (PPatvar fc _) = Just fc
1418highestFC (PLam fc _ _ _ _) = Just fc
1419highestFC (PPi _ _ _ _ _) = Nothing
1420highestFC (PLet fc _ _ _ _ _) = Just fc
1421highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty
1422highestFC (PApp fc _ _) = Just fc
1423highestFC (PAppBind fc _ _) = Just fc
1424highestFC (PMatchApp fc _) = Just fc
1425highestFC (PCase fc _ _) = Just fc
1426highestFC (PIfThenElse fc _ _ _) = Just fc
1427highestFC (PTrue fc _) = Just fc
1428highestFC (PResolveTC fc) = Just fc
1429highestFC (PRewrite fc _ _ _ _) = Just fc
1430highestFC (PPair fc _ _ _ _) = Just fc
1431highestFC (PDPair fc _ _ _ _ _) = Just fc
1432highestFC (PAs fc _ _) = Just fc
1433highestFC (PAlternative _ _ args) =
1434 case mapMaybe highestFC args of
1437highestFC (PHidden _) = Nothing
1438highestFC (PType fc) = Just fc
1439highestFC (PUniverse _) = Nothing
1440highestFC (PGoal fc _ _ _) = Just fc
1441highestFC (PConstant fc _) = Just fc
1442highestFC Placeholder = Nothing
1443highestFC (PDoBlock lines) =
1444 case map getDoFC lines of
1448 getDoFC (DoExp fc t) = fc
1449 getDoFC (DoBind fc nm nfc t) = fc
1450 getDoFC (DoBindP fc l r alts) = fc
1451 getDoFC (DoLet fc nm nfc l r) = fc
1452 getDoFC (DoLetP fc l r) = fc
1454highestFC (PIdiom fc _) = Just fc
1455highestFC (PReturn fc) = Just fc
1456highestFC (PMetavar fc _) = Just fc
1457highestFC (PProof _) = Nothing
1458highestFC (PTactics _) = Nothing
1459highestFC (PElabError _) = Nothing
1460highestFC PImpossible = Nothing
1461highestFC (PCoerced tm) = highestFC tm
1462highestFC (PDisamb _ opts) = highestFC opts
1463highestFC (PUnifyLog tm) = highestFC tm
1464highestFC (PNoImplicits tm) = highestFC tm
1465highestFC (PQuasiquote _ _) = Nothing
1466highestFC (PUnquote tm) = highestFC tm
1467highestFC (PQuoteName _ _ fc) = Just fc
1468highestFC (PRunElab fc _ _) = Just fc
1469highestFC (PConstSugar fc _) = Just fc
1470highestFC (PAppImpl t _) = highestFC t
1474data ClassInfo = CI {
1475 instanceCtorName :: Name
1476 , class_methods :: [(Name, (Bool, FnOpts, PTerm))] -- ^ flag whether it's a "data" method
1477 , class_defaults :: [(Name, (Name, PDecl))] -- ^ method name -> default impl
1478 , class_default_superclasses :: [PDecl]
1479 , class_params :: [Name]
1480 , class_instances :: [(Name, Bool)] -- ^ the Bool is whether to include in instance search, so named instances are excluded
1481 , class_determiners :: [Int]
1484deriving instance Binary ClassInfo
1485deriving instance NFData ClassInfo
1489data RecordInfo = RI {
1490 record_parameters :: [(Name,PTerm)]
1491 , record_constructor :: Name
1492 , record_projections :: [Name]
1495-- Type inference data
1497data TIData = TIPartial -- ^ a function with a partially defined type
1498 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
1501-- | Miscellaneous information about functions
1502data FnInfo = FnInfo { fn_params :: [Int] }
1505deriving instance Binary FnInfo
1506deriving instance NFData FnInfo
1509data OptInfo = Optimise {
1510 inaccessible :: [(Int,Name)] -- includes names for error reporting
1511 , detaggable :: Bool
1514deriving instance Binary OptInfo
1515deriving instance NFData OptInfo
1518-- | Syntactic sugar info
1524 , dsl_var :: Maybe t
1525 , index_first :: Maybe t
1526 , index_next :: Maybe t
1527 , dsl_lambda :: Maybe t
1528 , dsl_let :: Maybe t
1530 } deriving (Show, Functor)
1532deriving instance Binary DSL'
1533deriving instance NFData DSL'
1536type DSL = DSL' PTerm
1538data SynContext = PatternSyntax
1543deriving instance Binary SynContext
1544deriving instance NFData SynContext
1547data Syntax = Rule [SSymbol] PTerm SynContext
1548 | DeclRule [SSymbol] [PDecl]
1551syntaxNames :: Syntax -> [Name]
1552syntaxNames (Rule syms _ _) = mapMaybe ename syms
1553 where ename (Keyword n) = Just n
1555syntaxNames (DeclRule syms _) = mapMaybe ename syms
1556 where ename (Keyword n) = Just n
1559syntaxSymbols :: Syntax -> [SSymbol]
1560syntaxSymbols (Rule ss _ _) = ss
1561syntaxSymbols (DeclRule ss _) = ss
1563deriving instance Binary Syntax
1564deriving instance NFData Syntax
1567data SSymbol = Keyword Name
1576deriving instance Binary SSymbol
1577deriving instance NFData SSymbol
1580newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
1582emptySyntaxRules :: SyntaxRules
1583emptySyntaxRules = SyntaxRules []
1585updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
1586updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
1588 newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
1593 ruleSort (s1:ss1) (s2:ss2) =
1594 case symCompare s1 s2 of
1595 EQ -> ruleSort ss1 ss2
1598 -- Better than creating Ord instance for SSymbol since
1599 -- in general this ordering does not really make sense.
1600 symCompare (Keyword n1) (Keyword n2) = compare n1 n2
1601 symCompare (Keyword _) _ = LT
1602 symCompare (Symbol _) (Keyword _) = GT
1603 symCompare (Symbol s1) (Symbol s2) = compare s1 s2
1604 symCompare (Symbol _) _ = LT
1605 symCompare (Binding _) (Keyword _) = GT
1606 symCompare (Binding _) (Symbol _) = GT
1607 symCompare (Binding b1) (Binding b2) = compare b1 b2
1608 symCompare (Binding _) _ = LT
1609 symCompare (Expr _) (Keyword _) = GT
1610 symCompare (Expr _) (Symbol _) = GT
1611 symCompare (Expr _) (Binding _) = GT
1612 symCompare (Expr e1) (Expr e2) = compare e1 e2
1613 symCompare (Expr _) _ = LT
1614 symCompare (SimpleExpr _) (Keyword _) = GT
1615 symCompare (SimpleExpr _) (Symbol _) = GT
1616 symCompare (SimpleExpr _) (Binding _) = GT
1617 symCompare (SimpleExpr _) (Expr _) = GT
1618 symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
1620initDSL = DSL (PRef f [] (sUN ">>="))
1621 (PRef f [] (sUN "return"))
1622 (PRef f [] (sUN "<*>"))
1623 (PRef f [] (sUN "pure"))
1630 where f = fileFC "(builtin)"
1632data Using = UImplicit Name PTerm
1633 | UConstraint Name [Name]
1634 deriving (Show, Eq, Data, Typeable)
1636deriving instance Binary Using
1637deriving instance NFData Using
1640data SyntaxInfo = Syn {
1642 , syn_params :: [(Name, PTerm)]
1643 , syn_namespace :: [String]
1645 , imp_methods :: [Name]
1646 -- ^ class methods. When expanding implicits, these should be
1647 -- expanded even under binders
1648 , decoration :: Name -> Name
1650 , implicitAllowed :: Bool
1651 , constraintAllowed :: Bool
1652 , maxline :: Maybe Int
1653 , mut_nesting :: Int
1655 , syn_in_quasiquote :: Int
1656 , syn_toplevel :: Bool
1657 , withAppAllowed :: Bool
1660deriving instance NFData SyntaxInfo
1661deriving instance Binary SyntaxInfo
1664defaultSyntax = Syn [] [] [] [] [] id False False False Nothing 0 initDSL 0 True True
1666expandNS :: SyntaxInfo -> Name -> Name
1667expandNS syn n@(NS _ _) = n
1668expandNS syn n = case syn_namespace syn of
1673-- For inferring types of things
1675bi = fileFC "builtin"
1676primfc = fileFC "(primitive)"
1678inferTy = sMN 0 "__Infer"
1679inferCon = sMN 0 "__infer"
1680inferDecl = PDatadecl inferTy primfc
1682 [(emptyDocstring, [], inferCon, primfc, PPi impl (sMN 0 "iType") primfc (PType bi) (
1683 PPi expl (sMN 0 "ival") primfc (PRef bi [] (sMN 0 "iType"))
1684 (PRef bi [] inferTy)), bi, [])]
1687infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
1688infP = P (TCon 6 0) inferTy (TType (UVal 0))
1690getInferTerm, getInferType :: Term -> Term
1691getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
1692getInferTerm (App _ (App _ _ _) tm) = tm
1693getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1695getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1696 where toTy (Lam t) = Pi Nothing t (TType (UVar [] 0))
1697 toTy (PVar t) = PVTy t
1699getInferType (App _ (App _ _ ty) _) = ty
1703-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
1705primNames = [inferTy, inferCon]
1708unitCon = sUN "MkUnit"
1710falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
1711 "The empty type, also known as the trivially false proposition." ++
1713 "Use `void` or `absurd` to prove anything if you have a variable " ++
1714 "of type `Void` in scope."
1717pairTy = sNS (sUN "Pair") ["Builtins"]
1718pairCon = sNS (sUN "MkPair") ["Builtins"]
1720upairTy = sNS (sUN "UPair") ["Builtins"]
1721upairCon = sNS (sUN "MkUPair") ["Builtins"]
1725eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
1726 "The propositional equality type. A proof that `x` = `y`." ++
1728 "To use such a proof, pattern-match on it, and the two equal things will " ++
1729 "then need to be the _same_ pattern." ++
1731 "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
1732 "is possible to state equalities between values of potentially different " ++
1733 "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
1735 "You may need to use `(~=~)` to explicitly request heterogeneous equality."
1737eqDecl = PDatadecl eqTy primfc (piBindp impl [(n "A", PType bi), (n "B", PType bi)]
1738 (piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))]
1740 [(reflDoc, reflParamDoc,
1741 eqCon, primfc, PPi impl (n "A") primfc (PType bi) (
1742 PPi impl (n "x") primfc (PRef bi [] (n "A"))
1743 (PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False,
1744 pimp (n "B") Placeholder False,
1745 pexp (PRef bi [] (n "x")),
1746 pexp (PRef bi [] (n "x"))])), bi, [])]
1748 reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
1749 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1750 "shown that both sides are in fact equal."
1751 reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
1752 (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1754eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
1755 (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
1761-- | The special name to be used in the module documentation context -
1762-- not for use in the main definition context. The namespace around it
1763-- will determine the module to which the docs adhere.
1765modDocName = sMN 0 "ModuleDocs"
1767-- Defined in builtins.idr
1768sigmaTy = sNS (sUN "DPair") ["Builtins"]
1769sigmaCon = sNS (sUN "MkDPair") ["Builtins"]
1771piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1772piBind = piBindp expl
1774piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1776piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t)
1779-- Pretty-printing declarations and terms
1781-- These "show" instances render to an absurdly wide screen because inserted line breaks
1782-- could interfere with interactive editing, which calls "show".
1784instance Show PTerm where
1785 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1787instance Show PDecl where
1788 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
1790instance Show PClause where
1791 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1793instance Show PData where
1794 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1796instance Pretty PTerm OutputAnnotation where
1797 pretty = prettyImp defaultPPOption
1799-- | Colourise annotations according to an Idris state. It ignores the
1800-- names in the annotation, as there's no good way to show extended
1801-- information on a terminal.
1802annotationColour :: IState -> OutputAnnotation -> Maybe IdrisColour
1803annotationColour ist _ | not (idris_colourRepl ist) = Nothing
1804annotationColour ist (AnnConst c) =
1805 let theme = idris_colourTheme ist
1806 in Just $ if constIsType c
1807 then typeColour theme
1808 else dataColour theme
1809annotationColour ist (AnnData _ _) = Just $ dataColour (idris_colourTheme ist)
1810annotationColour ist (AnnType _ _) = Just $ typeColour (idris_colourTheme ist)
1811annotationColour ist (AnnBoundName _ True) = Just $ implicitColour (idris_colourTheme ist)
1812annotationColour ist (AnnBoundName _ False) = Just $ boundVarColour (idris_colourTheme ist)
1813annotationColour ist AnnKeyword = Just $ keywordColour (idris_colourTheme ist)
1814annotationColour ist (AnnName n _ _ _) =
1815 let ctxt = tt_ctxt ist
1816 theme = idris_colourTheme ist
1818 _ | isDConName n ctxt -> Just $ dataColour theme
1819 _ | isFnName n ctxt -> Just $ functionColour theme
1820 _ | isTConName n ctxt -> Just $ typeColour theme
1821 _ | isPostulateName n ist -> Just $ postulateColour theme
1822 _ | otherwise -> Nothing -- don't colourise unknown names
1823annotationColour ist (AnnTextFmt fmt) = Just (colour fmt)
1824 where colour BoldText = IdrisColour Nothing True False True False
1825 colour UnderlineText = IdrisColour Nothing True True False False
1826 colour ItalicText = IdrisColour Nothing True False False True
1827annotationColour ist _ = Nothing
1830-- | Colourise annotations according to an Idris state. It ignores the
1831-- names in the annotation, as there's no good way to show extended
1832-- information on a terminal. Note that strings produced this way will
1833-- not be coloured on Windows, so the use of the colour rendering
1834-- functions in Idris.Output is to be preferred.
1835consoleDecorate :: IState -> OutputAnnotation -> String -> String
1836consoleDecorate ist ann = maybe id colourise (annotationColour ist ann)
1838isPostulateName :: Name -> IState -> Bool
1839isPostulateName n ist = S.member n (idris_postulates ist)
1841-- | Pretty-print a high-level closed Idris term with no information
1842-- about precedence/associativity
1843prettyImp :: PPOption -- ^ pretty printing options
1844 -> PTerm -- ^ the term to pretty-print
1845 -> Doc OutputAnnotation
1846prettyImp impl = pprintPTerm impl [] [] []
1848-- | Serialise something to base64 using its Binary instance.
1850-- | Do the right thing for rendering a term in an IState
1851prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1852prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1854-- | Pretty-print a high-level Idris term in some bindings context
1856pprintPTerm :: PPOption -- ^ pretty printing options
1857 -> [(Name, Bool)] -- ^ the currently-bound names and whether they are implicit
1858 -> [Name] -- ^ names to always show in pi, even if not used
1859 -> [FixDecl] -- ^ Fixity declarations
1860 -> PTerm -- ^ the term to pretty-print
1861 -> Doc OutputAnnotation
1862pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1867 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1868 prettySe d p bnd (PQuote r) =
1869 text "![" <> pretty r <> text "]"
1870 prettySe d p bnd (PPatvar fc n) = pretty n
1872 | Just str <- slist d p bnd e = depth d $ str
1873 | Just n <- snat ppo d p e = depth d $ annotate (AnnData "Nat" "") (text (show n))
1874 prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n
1875 prettySe d p bnd (PLam fc n nfc ty sc) =
1876 depth d . bracket p startPrec . group . align . hang 2 $
1877 text "\\" <> prettyBindingOf n False <+> text "=>" <$>
1878 prettySe (decD d) startPrec ((n, False):bnd) sc
1879 prettySe d p bnd (PLet fc n nfc ty v sc) =
1880 depth d . bracket p startPrec . group . align $
1881 kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
1882 kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
1883 prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
1884 | n `elem` allNamesIn sc || ppopt_impl ppo && uname n || n `elem` docArgs
1885 || ppopt_pinames ppo && uname n =
1886 depth d . bracket p startPrec . group $
1887 enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
1888 st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
1890 depth d . bracket p startPrec . group $
1891 group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$>
1892 group (prettySe (decD d) startPrec ((n, False):bnd) sc)
1894 uname (UN n) = case str n of
1901 Static -> text "%static" <> space
1903 prettySe d p bnd (PPi (Imp l s _ fa _) n _ ty sc)
1905 depth d . bracket p startPrec $
1906 lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
1907 st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1908 | otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
1912 Static -> text "%static" <> space
1914 prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
1915 depth d . bracket p startPrec $
1916 prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1917 prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch{}])) n _ ty sc) =
1918 lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1919 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1920 prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
1921 depth d . bracket p startPrec $
1922 lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1923 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1924 prettySe d p bnd (PApp _ (PRef _ _ neg) [_, _, val])
1925 | basename neg == sUN "negate" =
1926 lparen <> text "-" <> prettySe d funcAppPrec bnd (getTm val) <> rparen
1927 -- This case preserves the behavior of the former constructor PEq.
1928 -- It should be removed if feasible when the pretty-printing of infix
1929 -- operators in general is improved.
1930 prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r])
1931 | n == eqTy, ppopt_impl ppo =
1932 depth d . bracket p eqPrec $
1933 enclose lparen rparen eq <+>
1934 align (group (vsep (map (prettyArgS (decD d) bnd)
1937 depth d . bracket p eqPrec . align . group $
1938 prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r))
1939 where eq = annName eqTy (text "=")
1941 prettyTerm = prettySe (decD d) (eqPrec + 1) bnd
1942 prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args
1943 | UN nm <- basename f
1944 , not (ppopt_impl ppo) && null (getShowArgs args) =
1945 prettyName True (ppopt_impl ppo) bnd f
1946 prettySe d p bnd (PAppBind _ (PRef _ _ f) [])
1947 | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
1948 prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators
1949 | UN nm <- basename op
1951 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1952 case getShowArgs args of
1954 [x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x)))
1955 [l,r] -> let precedence = maybe (startPrec - 1) prec f
1956 in depth d . bracket p precedence $ inFix (getTm l) (getTm r)
1957 (l@(PExp{}) : r@(PExp{}) : rest) ->
1958 depth d . bracket p funcAppPrec $
1959 enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
1960 align (group (vsep (map (prettyArgS d bnd) rest)))
1961 as -> opName True <+> align (vsep (map (prettyArgS d bnd) as))
1962 where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
1963 f = getFixity (opStr op)
1965 Nothing -> funcAppPrec + 1
1966 Just (Infixl p') -> p'
1967 Just f' -> prec f' + 1
1969 Nothing -> funcAppPrec + 1
1970 Just (Infixr p') -> p'
1971 Just f' -> prec f' + 1
1972 inFix l r = align . group $
1973 (prettySe (decD d) left bnd l <+> opName False) <$>
1974 group (prettySe (decD d) right bnd r)
1975 prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo
1976 | PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm,
1977 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1978 char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str))
1979 prettySe d p bnd (PApp _ f as) = -- Normal prefix applications
1980 let args = getShowArgs as
1981 fp = prettySe (decD d) (startPrec + 1) bnd f
1982 shownArgs = if ppopt_impl ppo then as else args
1984 depth d . bracket p funcAppPrec . group $
1987 else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs))
1988 prettySe d p bnd (PWithApp _ f a) = prettySe d p bnd f <+> text "|" <+> prettySe d p bnd a
1989 prettySe d p bnd (PCase _ scr cases) =
1990 align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$>
1991 depth d (indent 2 (vsep (map ppcase cases)))
1993 ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec
1994 ([(n, False) | n <- vars l] ++ bnd)
1995 in nest nestingSize $
1996 prettyCase l <+> text "=>" <+> prettyCase r
1997 -- Warning: this is a bit of a hack. At this stage, we don't have the
1998 -- global context, so we can't determine which names are constructors,
1999 -- which are types, and which are pattern variables on the LHS of the
2000 -- case pattern. We use the heuristic that names without a namespace
2001 -- are patvars, because right now case blocks in PTerms are always
2002 -- delaborated from TT before being sent to the pretty-printer. If they
2003 -- start getting printed directly, THIS WILL BREAK.
2004 -- Potential solution: add a list of known patvars to the cases in
2005 -- PCase, and have the delaborator fill it out, kind of like the pun
2006 -- disambiguation on PDPair.
2007 vars tm = filter noNS (allNamesIn tm)
2008 noNS (NS _ _) = False
2011 prettySe d p bnd (PIfThenElse _ c t f) =
2012 depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $
2013 [ kwd "if" <+> prettySe (decD d) startPrec bnd c
2014 , kwd "then" <+> prettySe (decD d) startPrec bnd t
2015 , kwd "else" <+> prettySe (decD d) startPrec bnd f
2017 prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
2018 prettySe d p bnd (PResolveTC _) = kwd "%instance"
2019 prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
2020 prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
2021 prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
2022 prettySe d p bnd (PRewrite _ by l r _) =
2023 depth d . bracket p startPrec $
2024 text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l
2027 Just fn -> text "using" <+>
2028 prettyName True (ppopt_impl ppo) bnd fn) <+>
2029 text "in" <+> prettySe (decD d) startPrec bnd r
2030 prettySe d p bnd (PTyped l r) =
2031 lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen
2032 prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser
2033 | Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) .
2034 align . group . vsep . punctuate (ann comma) $
2035 map (prettySe (decD d) startPrec bnd) elts
2036 where ann = case pun of
2038 IsType -> annName pairTy
2039 IsTerm -> annName pairCon
2040 prettySe d p bnd dpair@(PDPair _ _ pun l t r)
2041 | Just elts <- dPairElts dpair
2042 = depth d . enclose (annotated lparen) (annotated rparen) .
2043 align . group . vsep . punctuate (space <> annotated (text "**")) $
2049 annotated (text "**") <+>
2050 prettySe (decD d) startPrec (addBinding bnd) r <>
2052 where annotated = case pun of
2053 IsType -> annName sigmaTy
2054 IsTerm -> annName sigmaCon
2057 (left, addBinding) = case (l, pun) of
2058 (PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :))
2059 _ -> (prettySe (decD d) startPrec bnd l, id)
2062 ppElts [(_, v)] bs = [prettySe (decD d) startPrec bs v]
2063 ppElts ((PRef _ _ n, t):rs) bs
2065 = (bindingOf n False <+> colon <+>
2066 prettySe (decD d) startPrec bs t) : ppElts rs ((n, False):bs)
2067 ppElts ((l, t):rs) bs
2068 = (prettySe (decD d) startPrec bs l) : ppElts rs bs
2069 prettySe d p bnd (PAlternative ns a as) =
2070 lparen <> text "|" <> prettyAs <> text "|" <> rparen
2073 foldr ((\ l r -> l <+> text "," <+> r) .
2074 depth d . prettySe (decD d) startPrec bnd)
2076 prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type"
2077 prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
2078 prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c))
2079 -- XXX: add pretty for tactics
2080 prettySe d p bnd (PProof ts) =
2081 kwd "proof" <+> lbrace <> ellipsis <> rbrace
2082 prettySe d p bnd (PTactics ts) =
2083 kwd "tactics" <+> lbrace <> ellipsis <> rbrace
2084 prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n
2085 prettySe d p bnd (PReturn f) = kwd "return"
2086 prettySe d p bnd PImpossible = kwd "impossible"
2087 prettySe d p bnd Placeholder = text "_"
2088 prettySe d p bnd (PDoBlock dos) =
2089 bracket p startPrec $
2090 kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos)))
2091 where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos
2092 ppdo bnd (DoBind _ bn _ tm : dos) =
2093 (prettyBindingOf bn False <+> text "<-" <+>
2094 group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) :
2095 ppdo ((bn, False):bnd) dos
2096 ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab
2097 text "no pretty printer for pattern-matching do binding" :
2099 ppdo bnd (DoLet _ ln _ ty v : dos) =
2100 (kwd "let" <+> prettyBindingOf ln False <+>
2101 (if ty /= Placeholder
2102 then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="
2104 group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :
2105 ppdo ((ln, False):bnd) dos
2106 ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab
2107 text "no pretty printer for pattern-matching do binding" :
2110 prettySe d p bnd (PCoerced t) = prettySe d p bnd t
2111 prettySe d p bnd (PElabError s) = pretty s
2112 -- Quasiquote pprinting ignores bound vars
2113 prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")"
2114 prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")"
2115 prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t
2116 prettySe d p bnd (PQuoteName n res _) = text start <> prettyName True (ppopt_impl ppo) bnd n <> text end
2117 where start = if res then "`{" else "`{{"
2118 end = if res then "}" else "}}"
2119 prettySe d p bnd (PRunElab _ tm _) =
2120 bracket p funcAppPrec . group . align . hang 2 $
2122 prettySe (decD d) funcAppPrec bnd tm
2123 prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
2124 prettySe d p bnd _ = text "missing pretty-printer for term"
2126 prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
2127 prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
2128 where display (UN n) = T.unpack n
2129 display (MN _ n) = T.unpack n
2130 -- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
2131 display (NS n ns) = (intercalate "." . map T.unpack . reverse) ns ++ "." ++ display n
2134 prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm)
2135 prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm
2136 prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm
2137 prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm)
2139 prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg
2140 prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
2141 prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace
2142 prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
2144 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
2145 annName n = annotate (AnnName n Nothing Nothing Nothing)
2147 opStr :: Name -> String
2148 opStr (NS n _) = opStr n
2149 opStr (UN n) = T.unpack n
2151 slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation]
2152 slist' (Just d) _ _ _ | d <= 0 = Nothing
2154 | containsHole e = Nothing
2155 slist' d p bnd (PApp _ (PRef _ _ nil) _)
2156 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
2157 slist' d p bnd (PRef _ _ nil)
2158 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
2159 slist' d p bnd (PApp _ (PRef _ _ cons) args)
2160 | nsroot cons == sUN "::",
2161 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
2163 Just tl' <- slist' (decD d) p bnd tl
2164 = Just (prettySe d startPrec bnd hd : tl')
2166 isImp (PImp {}) = True
2168 slist' _ _ _ tm = Nothing
2170 slist d p bnd e | Just es <- slist' d p bnd e = Just $
2172 [] -> annotate (AnnData "" "") $ text "[]"
2173 [x] -> enclose left right . group $ x
2174 xs -> enclose left right .
2175 align . group . vsep .
2176 punctuate comma $ xs
2177 where left = (annotate (AnnData "" "") (text "["))
2178 right = (annotate (AnnData "" "") (text "]"))
2179 comma = (annotate (AnnData "" "") (text ","))
2180 slist _ _ _ _ = Nothing
2182 pairElts :: PTerm -> Maybe [PTerm]
2183 pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts)
2184 | otherwise = Just [x, y]
2185 pairElts _ = Nothing
2187 dPairElts :: PTerm -> Maybe [(PTerm, PTerm)]
2188 dPairElts (PDPair _ _ _ l t r) | Just elts <- dPairElts r = Just ((l, t):elts)
2189 | otherwise = Just [(l, t), (Placeholder, r)]
2190 dPairElts _ = Nothing
2192 natns = "Prelude.Nat."
2194 snat :: PPOption -> Maybe Int -> Int -> PTerm -> Maybe Integer
2196 | ppopt_desugarnats ppo = Nothing
2197 | otherwise = snat' d p e
2199 snat' :: Maybe Int -> Int -> PTerm -> Maybe Integer
2200 snat' (Just x) _ _ | x <= 0 = Nothing
2201 snat' d p (PRef _ _ z)
2202 | show z == (natns++"Z") || show z == "Z" = Just 0
2203 snat' d p (PApp _ s [PExp {getTm=n}])
2204 | show s == (natns++"S") || show s == "S",
2205 Just n' <- snat' (decD d) p n
2207 snat' _ _ _ = Nothing
2209 bracket outer inner doc
2210 | outer > inner = lparen <> doc <> rparen
2213 ellipsis = text "..."
2216 depth (Just d) = if d <= 0 then const ellipsis else id
2218 decD = fmap (\x -> x - 1)
2220 kwd = annotate AnnKeyword . text
2222 fixities :: M.Map String Fixity
2223 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
2225 getFixity :: String -> Maybe Fixity
2226 getFixity = flip M.lookup fixities
2228-- | Strip away namespace information
2229basename :: Name -> Name
2230basename (NS n _) = basename n
2233-- | Determine whether a name was the one inserted for a hole or guess
2234-- by the delaborator
2235isHoleName :: Name -> Bool
2236isHoleName (UN n) = n == T.pack "[__]"
2239-- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess
2240containsHole :: PTerm -> Bool
2241containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm]
2243-- | Pretty-printer helper for names that attaches the correct annotations
2244prettyName :: Bool -- ^ whether the name should be parenthesised if it is an infix operator
2245 -> Bool -- ^ whether to show namespaces
2246 -> [(Name, Bool)] -- ^ the current bound variables and whether they are implicit
2247 -> Name -- ^ the name to pprint
2248 -> Doc OutputAnnotation
2249prettyName infixParen showNS bnd n
2250 | (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_"
2251 | (UN n') <- n, T.unpack n' == "_" = text "_"
2252 | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
2253 | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
2254 where fullName = text nameSpace <> parenthesise (text (baseName n))
2255 baseName (UN n) = T.unpack n
2256 baseName (NS n ns) = baseName n
2257 baseName (MN i s) = T.unpack s
2258 baseName other = show other
2259 nameSpace = case n of
2260 (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
2262 isInfix = case baseName n of
2264 (c : _) -> not (isAlpha c)
2265 parenthesise = if isInfix && infixParen then enclose lparen rparen else id
2268showCImp :: PPOption -> PClause -> Doc OutputAnnotation
2269showCImp ppo (PClause _ n l ws r w)
2270 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
2271 <+> text "where" <+> text (show w)
2274 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2275showCImp ppo (PWith _ n l ws r pn w)
2276 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
2277 <+> braces (text (show w))
2280 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2283showDImp :: PPOption -> PData -> Doc OutputAnnotation
2284showDImp ppo (PDatadecl n nfc ty cons)
2285 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
2286 (indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
2288showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
2289showDecls o ds = vsep (map (showDeclImp o) ds)
2291showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
2292showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
2293showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
2294 indent 2 (vsep (map (showCImp o) cs))
2295showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
2296showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
2297showDeclImp o (POpenInterfaces _ ns ps) = text "open" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
2298showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
2299showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
2300showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _)
2301 = text "interface" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
2302showDeclImp o (PInstance _ _ _ _ cs _ acc _ n _ _ _ t _ ds)
2303 = text "implementation" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
2304showDeclImp _ _ = text "..."
2305-- showDeclImp (PImport o) = "import " ++ o
2307getImps :: [PArg] -> [(Name, PTerm)]
2309getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
2310getImps (_ : xs) = getImps xs
2312getExps :: [PArg] -> [PTerm]
2314getExps (PExp _ _ _ tm : xs) = tm : getExps xs
2315getExps (_ : xs) = getExps xs
2317getShowArgs :: [PArg] -> [PArg]
2319getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
2320getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
2321 | PImp _ _ _ _ tm <- e
2322 , containsHole tm = e : getShowArgs xs
2323getShowArgs (_ : xs) = getShowArgs xs
2325getConsts :: [PArg] -> [PTerm]
2327getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
2328getConsts (_ : xs) = getConsts xs
2330getAll :: [PArg] -> [PTerm]
2335showName :: Maybe IState -- ^ the Idris state, for information about names and colours
2336 -> [(Name, Bool)] -- ^ the bound variables and whether they're implicit
2337 -> PPOption -- ^ pretty printing options
2338 -> Bool -- ^ whether to colourise
2339 -> Name -- ^ the term to show
2341showName ist bnd ppo colour n = case ist of
2342 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
2343 Nothing -> showbasic n
2344 where name = if ppopt_impl ppo then show n else showbasic n
2345 showbasic n@(UN _) = showCG n
2346 showbasic (MN i s) = str s
2347 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
2348 showbasic (SN s) = show s
2350 colourise n t = let ctxt' = fmap tt_ctxt ist in
2353 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
2354 else colouriseBound t name
2355 | isDConName n ctxt -> colouriseData t name
2356 | isFnName n ctxt -> colouriseFun t name
2357 | isTConName n ctxt -> colouriseType t name
2358 -- The assumption is that if a name is not bound and does not exist in the
2359 -- global context, then we're somewhere in which implicit info has been lost
2360 -- (like error messages). Thus, unknown vars are colourised as implicits.
2361 | otherwise -> colouriseImplicit t name
2363showTm :: IState -- ^ the Idris state, for information about identifiers and colours
2364 -> PTerm -- ^ the term to show
2366showTm ist = displayDecorated (consoleDecorate ist) .
2367 renderPretty 0.8 100000 .
2368 prettyImp (ppOptionIst ist)
2370-- | Show a term with implicits, no colours
2371showTmImpls :: PTerm -> String
2372showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
2374-- | Show a term with specific options
2375showTmOpts :: PPOption -> PTerm -> String
2376showTmOpts opt = flip (displayS . renderPretty 1.0 10000000 . prettyImp opt) ""
2379instance Sized PTerm where
2380 size (PQuote rawTerm) = size rawTerm
2381 size (PRef fc _ name) = size name
2382 size (PLam fc name _ ty bdy) = 1 + size ty + size bdy
2383 size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy
2384 size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy
2385 size (PTyped trm ty) = 1 + size trm + size ty
2386 size (PApp fc name args) = 1 + size args
2387 size (PAppBind fc name args) = 1 + size args
2388 size (PCase fc trm bdy) = 1 + size trm + size bdy
2389 size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f])
2390 size (PTrue fc _) = 1
2391 size (PResolveTC fc) = 1
2392 size (PRewrite fc by left right _) = 1 + size left + size right
2393 size (PPair fc _ _ left right) = 1 + size left + size right
2394 size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right
2395 size (PAlternative _ a alts) = 1 + size alts
2396 size (PHidden hidden) = size hidden
2397 size (PUnifyLog tm) = size tm
2398 size (PDisamb _ tm) = size tm
2399 size (PNoImplicits tm) = size tm
2401 size (PUniverse _) = 1
2402 size (PConstant fc const) = 1 + size fc + size const
2403 size Placeholder = 1
2404 size (PDoBlock dos) = 1 + size dos
2405 size (PIdiom fc term) = 1 + size term
2406 size (PReturn fc) = 1
2407 size (PMetavar _ name) = 1
2408 size (PProof tactics) = size tactics
2409 size (PElabError err) = size err
2410 size PImpossible = 1
2413getPArity :: PTerm -> Int
2414getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc
2417-- Return all names, free or globally bound, in the given term.
2419allNamesIn :: PTerm -> [Name]
2420allNamesIn tm = nub $ ni 0 [] tm
2421 where -- TODO THINK added niTacImp, but is it right?
2422 ni 0 env (PRef _ _ n)
2423 | not (n `elem` env) = [n]
2424 ni 0 env (PPatvar _ n) = [n]
2425 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2426 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2427 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env . snd) os
2428 ni 0 env (PIfThenElse _ c t f) = ni 0 env c ++ ni 0 env t ++ ni 0 env f
2429 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2430 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2431 ni 0 env (PLet _ n _ ty val sc) = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc
2432 ni 0 env (PHidden tm) = ni 0 env tm
2433 ni 0 env (PRewrite _ _ l r _) = ni 0 env l ++ ni 0 env r
2434 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2435 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2436 ni 0 env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : 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 ls) = map snd ns ++ concatMap (ni 0 env) ls
2440 ni 0 env (PUnifyLog tm) = ni 0 env tm
2441 ni 0 env (PDisamb _ tm) = ni 0 env tm
2442 ni 0 env (PNoImplicits tm) = ni 0 env tm
2444 ni i env (PQuasiquote tm ty) = ni (i+1) env tm ++ maybe [] (ni i env) ty
2445 ni i env (PUnquote tm) = ni (i - 1) env tm
2446 ni i env tm = concatMap (ni i env) (children tm)
2448 niTacImp i env (TacImp _ _ scr) = ni i env scr
2452-- Return all names defined in binders in the given term
2453boundNamesIn :: PTerm -> [Name]
2454boundNamesIn tm = S.toList (ni 0 S.empty tm)
2455 where -- TODO THINK Added niTacImp, but is it right?
2456 ni :: Int -> S.Set Name -> PTerm -> S.Set Name
2457 ni 0 set (PApp _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2458 ni 0 set (PAppBind _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2459 ni 0 set (PCase _ c os) = niTms 0 (ni 0 set c) (map snd os)
2460 ni 0 set (PIfThenElse _ c t f) = niTms 0 set [c, t, f]
2461 ni 0 set (PLam fc n _ ty sc) = S.insert n $ ni 0 (ni 0 set ty) sc
2462 ni 0 set (PLet fc n nfc ty val sc) = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc
2463 ni 0 set (PPi p n _ ty sc) = niTacImp 0 (S.insert n $ ni 0 (ni 0 set ty) sc) p
2464 ni 0 set (PRewrite _ _ l r _) = ni 0 (ni 0 set l) r
2465 ni 0 set (PTyped l r) = ni 0 (ni 0 set l) r
2466 ni 0 set (PPair _ _ _ l r) = ni 0 (ni 0 set l) r
2467 ni 0 set (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 (ni 0 set t) r
2468 ni 0 set (PDPair _ _ _ l t r) = ni 0 (ni 0 (ni 0 set l) t) r
2469 ni 0 set (PAlternative ns a as) = niTms 0 set as
2470 ni 0 set (PHidden tm) = ni 0 set tm
2471 ni 0 set (PUnifyLog tm) = ni 0 set tm
2472 ni 0 set (PDisamb _ tm) = ni 0 set tm
2473 ni 0 set (PNoImplicits tm) = ni 0 set tm
2475 ni i set (PQuasiquote tm ty) = ni (i + 1) set tm `S.union` maybe S.empty (ni i set) ty
2476 ni i set (PUnquote tm) = ni (i - 1) set tm
2478 ni i set tm = foldr (S.union . ni i set) set (children tm)
2480 niTms :: Int -> S.Set Name -> [PTerm] -> S.Set Name
2481 niTms i set [] = set
2482 niTms i set (x : xs) = niTms i (ni i set x) xs
2484 niTacImp i set (TacImp _ _ scr) = ni i set scr
2485 niTacImp i set _ = set
2487-- Return names which are valid implicits in the given term (type).
2488implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
2489implicitNamesIn uvars ist tm
2490 = let (imps, fns) = execState (ni 0 [] tm) ([], []) in
2493 addImp n = do (imps, fns) <- get
2495 addFn n = do (imps, fns) <- get
2499 notCAF (PExp _ _ _ _ : _) = True
2500 notCAF (_ : xs) = notCAF xs
2502 notHidden (n, _) = case getAccessibility n of
2508 = case lookupDefAccExact n False (tt_ctxt ist) of
2512 ni 0 env (PRef _ _ n@(NS _ _))
2513 | not (n `elem` env)
2514 -- Never implicitly bind if there's a namespace
2516 ni 0 env (PRef _ _ n)
2517 | not (n `elem` env) && implicitable n || n `elem` uvars = addImp n
2518 ni 0 env (PApp _ f@(PRef _ _ n) as)
2519 | n `elem` uvars = do ni 0 env f
2520 mapM_ (ni 0 env . getTm) as
2521 | otherwise = do case lookupTy n (tt_ctxt ist) of
2524 mapM_ (ni 0 env . getTm) as
2525 ni 0 env (PApp _ f as) = do ni 0 env f
2526 mapM_ (ni 0 env . getTm) as
2527 ni 0 env (PAppBind _ f as) = do ni 0 env f
2528 mapM_ (ni 0 env . getTm) as
2529 ni 0 env (PCase _ c os) = do ni 0 env c
2530 -- names in 'os', not counting the names bound in the cases
2531 mapM_ (ni 0 env . snd) os
2534 mapM_ (ni 0 env . fst) os
2536 put (nub imps \\ nub impsfst, fns)
2537 ni 0 env (PIfThenElse _ c t f) = mapM_ (ni 0 env) [c, t, f]
2538 ni 0 env (PLam fc n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2539 ni 0 env (PPi p n _ ty sc) = do ni 0 env ty; ni 0 (n:env) sc
2540 ni 0 env (PRewrite _ _ l r _) = do ni 0 env l; ni 0 env r
2541 ni 0 env (PTyped l r) = do ni 0 env l; ni 0 env r
2542 ni 0 env (PPair _ _ _ l r) = do ni 0 env l; ni 0 env r
2543 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = do ni 0 env t; ni 0 (n:env) r
2544 ni 0 env (PDPair _ _ _ l t r) = do ni 0 env l
2547 ni 0 env (PAlternative ns a as) = mapM_ (ni 0 env) as
2548 ni 0 env (PHidden tm) = ni 0 env tm
2549 ni 0 env (PUnifyLog tm) = ni 0 env tm
2550 ni 0 env (PDisamb _ tm) = ni 0 env tm
2551 ni 0 env (PNoImplicits tm) = ni 0 env tm
2553 ni i env (PQuasiquote tm ty) = do ni (i + 1) env tm
2554 maybe (return ()) (ni i env) ty
2555 ni i env (PUnquote tm) = ni (i - 1) env tm
2557 ni i env tm = mapM_ (ni i env) (children tm)
2559-- Return names which are free in the given term.
2560namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
2561namesIn uvars ist tm = nub $ ni 0 [] tm
2563 ni 0 env (PRef _ _ n)
2564 | not (n `elem` env)
2565 = case lookupTy n (tt_ctxt ist) of
2567 _ -> [n | n `elem` (map fst uvars)]
2568 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2569 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2570 ni 0 env (PCase _ c os) = ni 0 env c ++
2571 -- names in 'os', not counting the names bound in the cases
2572 (nub (concatMap (ni 0 env . snd) os)
2573 \\ nub (concatMap (ni 0 env . fst) os))
2574 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2575 ni 0 env (PLam fc n nfc ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2576 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2577 ni 0 env (PRewrite _ _ l r _) = ni 0 env l ++ ni 0 env r
2578 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2579 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2580 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2581 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2582 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2583 ni 0 env (PHidden tm) = ni 0 env tm
2584 ni 0 env (PUnifyLog tm) = ni 0 env tm
2585 ni 0 env (PDisamb _ tm) = ni 0 env tm
2586 ni 0 env (PNoImplicits tm) = ni 0 env tm
2588 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2589 ni i env (PUnquote tm) = ni (i - 1) env tm
2591 ni i env tm = concatMap (ni i env) (children tm)
2593 niTacImp i env (TacImp _ _ scr) = ni i env scr
2596-- Return which of the given names are used in the given term.
2598usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
2599usedNamesIn vars ist tm = nub $ ni 0 [] tm
2600 where -- TODO THINK added niTacImp, but is it right?
2601 ni 0 env (PRef _ _ n)
2602 | n `elem` vars && not (n `elem` env)
2603 = case lookupDefExact n (tt_ctxt ist) of
2606 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2607 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env . getTm) as
2608 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env . snd) os
2609 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2610 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2611 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2612 ni 0 env (PRewrite _ _ l r _) = ni 0 env l ++ ni 0 env r
2613 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2614 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2615 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2616 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2617 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2618 ni 0 env (PHidden tm) = ni 0 env tm
2619 ni 0 env (PUnifyLog tm) = ni 0 env tm
2620 ni 0 env (PDisamb _ tm) = ni 0 env tm
2621 ni 0 env (PNoImplicits tm) = ni 0 env tm
2623 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2624 ni i env (PUnquote tm) = ni (i - 1) env tm
2626 ni i env tm = concatMap (ni i env) (children tm)
2628 niTacImp i env (TacImp _ _ scr) = ni i env scr
2631-- Return the list of inaccessible (= dotted) positions for a name.
2632getErasureInfo :: IState -> Name -> [Int]
2633getErasureInfo ist n =
2634 case lookupCtxtExact n (idris_optimisation ist) of
2635 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