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