on 50878fa help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
2363 lines 104 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 interactive prover
510 | UseConsoleWidth ConsoleWidth
511 | DumpHighlights
512 | DesugarNats
513 deriving (Show, Eq)
515data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm
516 | EEval PTerm | ECheck PTerm | ESearch PTerm
517 | EDocStr (Either Name Const)
518 deriving (Show, Eq)
520-- Parsed declarations
522data Fixity = Infixl { prec :: Int }
523 | Infixr { prec :: Int }
524 | InfixN { prec :: Int }
525 | PrefixN { prec :: Int }
526 deriving Eq
527{-!
528deriving instance Binary Fixity
529deriving instance NFData Fixity
530!-}
532instance Show Fixity where
533 show (Infixl i) = "infixl " ++ show i
534 show (Infixr i) = "infixr " ++ show i
535 show (InfixN i) = "infix " ++ show i
536 show (PrefixN i) = "prefix " ++ show i
538data FixDecl = Fix Fixity String
539 deriving Eq
541instance Show FixDecl where
542 show (Fix f s) = show f ++ " " ++ s
544{-!
545deriving instance Binary FixDecl
546deriving instance NFData FixDecl
547!-}
549instance Ord FixDecl where
550 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
553data Static = Static | Dynamic
554 deriving (Show, Eq, Data, Typeable)
555{-!
556deriving instance Binary Static
557deriving instance NFData Static
558!-}
560-- Mark bindings with their explicitness, and laziness
561data Plicity = Imp { pargopts :: [ArgOpt],
562 pstatic :: Static,
563 pparam :: Bool,
564 pscoped :: Maybe ImplicitInfo -- Nothing, if top level
565 }
566 | Exp { pargopts :: [ArgOpt],
567 pstatic :: Static,
568 pparam :: Bool } -- this is a param (rather than index)
569 | Constraint { pargopts :: [ArgOpt],
570 pstatic :: Static }
571 | TacImp { pargopts :: [ArgOpt],
572 pstatic :: Static,
573 pscript :: PTerm }
574 deriving (Show, Eq, Data, Typeable)
576{-!
577deriving instance Binary Plicity
578deriving instance NFData Plicity
579!-}
581is_scoped :: Plicity -> Maybe ImplicitInfo
582is_scoped (Imp _ _ _ s) = s
583is_scoped _ = Nothing
585impl = Imp [] Dynamic False Nothing
586forall_imp = Imp [] Dynamic False (Just (Impl False))
587forall_constraint = Imp [] Dynamic False (Just (Impl True))
588expl = Exp [] Dynamic False
589expl_param = Exp [] Dynamic True
590constraint = Constraint [] Static
591tacimpl t = TacImp [] Dynamic t
593data FnOpt = Inlinable -- always evaluate when simplifying
594 | TotalFn | PartialFn | CoveringFn
595 | Coinductive | AssertTotal
596 | Dictionary -- type class dictionary, eval only when
597 -- a function argument, and further evaluation resutls
598 | Implicit -- implicit coercion
599 | NoImplicit -- do not apply implicit coercions
600 | CExport String -- export, with a C name
601 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
602 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
603 | Reflection -- a reflecting function, compile-time only
604 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
605 | Constructor -- Data constructor type
606 | AutoHint -- use in auto implicit search
607 | PEGenerated -- generated by partial evaluator
608 deriving (Show, Eq)
609{-!
610deriving instance Binary FnOpt
611deriving instance NFData FnOpt
612!-}
614type FnOpts = [FnOpt]
616inlinable :: FnOpts -> Bool
617inlinable = elem Inlinable
619dictionary :: FnOpts -> Bool
620dictionary = elem Dictionary
623-- | Type provider - what to provide
624data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
625 | ProvPostulate t -- ^ goal type must be Type, so only term
626 deriving (Show, Eq, Functor)
628type ProvideWhat = ProvideWhat' PTerm
630-- | Top-level declarations such as compiler directives, definitions,
631-- datatypes and typeclasses.
632data PDecl' t
633 = PFix FC Fixity [String] -- ^ Fixity declaration
634 | PTy (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location)
635 | PPostulate Bool -- external def if true
636 (Docstring (Either Err t)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location
637 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
638 | PCAF FC Name t -- ^ Top level constant
639 | PData (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
640 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
641 | PNamespace String FC [PDecl' t]
642 -- ^ New namespace, where FC is accurate location of the
643 -- namespace in the file
644 | PRecord (Docstring (Either Err t)) SyntaxInfo FC DataOpts
645 Name -- Record name
646 FC -- Record name precise location
647 [(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span
648 [(Name, Docstring (Either Err t))] -- Param Docs
649 [((Maybe (Name, FC)), Plicity, t, Maybe (Docstring (Either Err t)))] -- Fields
650 (Maybe (Name, FC)) -- Optional constructor name and location
651 (Docstring (Either Err t)) -- Constructor doc
652 SyntaxInfo -- Constructor SyntaxInfo
653 -- ^ Record declaration
654 | PClass (Docstring (Either Err t)) SyntaxInfo FC
655 [(Name, t)] -- constraints
656 Name -- class name
657 FC -- accurate location of class name
658 [(Name, FC, t)] -- parameters and precise locations
659 [(Name, Docstring (Either Err t))] -- parameter docstrings
660 [(Name, FC)] -- determining parameters and precise locations
661 [PDecl' t] -- declarations
662 (Maybe (Name, FC)) -- instance constructor name and location
663 (Docstring (Either Err t)) -- instance constructor docs
664 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
665 -- class name, class name location, parameters, method declarations, optional constructor name
666 | PInstance
667 (Docstring (Either Err t)) -- Instance docs
668 [(Name, Docstring (Either Err t))] -- Parameter docs
669 SyntaxInfo
670 FC [(Name, t)] -- constraints
671 Name -- class
672 FC -- precise location of class
673 [t] -- parameters
674 t -- full instance type
675 (Maybe Name) -- explicit name
676 [PDecl' t]
677 -- ^ Instance declaration: arguments are documentation, syntax info, source
678 -- location, constraints, class name, parameters, full instance
679 -- type, optional explicit name, and definitions
680 | PDSL Name (DSL' t) -- ^ DSL declaration
681 | PSyntax FC Syntax -- ^ Syntax definition
682 | PMutual FC [PDecl' t] -- ^ Mutual block
683 | PDirective Directive -- ^ Compiler directive.
684 | 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.
685 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
686 -- bool is True, lhs and rhs must be convertible
687 | PRunElabDecl FC t [String] -- ^ FC is decl-level, for errors, and
688 -- Strings represent the namespace
689 deriving Functor
690{-!
691deriving instance Binary PDecl'
692deriving instance NFData PDecl'
693!-}
695-- | The set of source directives
696data Directive = DLib Codegen String |
697 DLink Codegen String |
698 DFlag Codegen String |
699 DInclude Codegen String |
700 DHide Name |
701 DFreeze Name |
702 DAccess Accessibility |
703 DDefault Bool |
704 DLogging Integer |
705 DDynamicLibs [String] |
706 DNameHint Name FC [(Name, FC)] |
707 DErrorHandlers Name FC Name FC [(Name, FC)] |
708 DLanguage LanguageExt |
709 DUsed FC Name Name
711-- | A set of instructions for things that need to happen in IState
712-- after a term elaboration when there's been reflected elaboration.
713data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type
714 | RClausesInstrs Name [([Name], Term, Term)]
715 | RAddInstance Name Name
717-- | For elaborator state
718data EState = EState {
719 case_decls :: [(Name, PDecl)],
720 delayed_elab :: [(Int, Elab' EState ())],
721 new_tyDecls :: [RDeclInstructions],
722 highlighting :: [(FC, OutputAnnotation)]
723 }
725initEState :: EState
726initEState = EState [] [] [] []
728type ElabD a = Elab' EState a
730highlightSource :: FC -> OutputAnnotation -> ElabD ()
731highlightSource fc annot =
732 updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux })
734-- | One clause of a top-level definition. Term arguments to constructors are:
735--
736-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
737--
738-- 2. The list of extra 'with' patterns
739--
740-- 3. The right-hand side
741--
742-- 4. The where block (PDecl' t)
744data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
745 | PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t]
746 | PClauseR FC [t] t [PDecl' t]
747 | PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t]
748 deriving Functor
749{-!
750deriving instance Binary PClause'
751deriving instance NFData PClause'
752!-}
754-- | Data declaration
755data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
756 d_name_fc :: FC, -- ^ The precise location of the type constructor name
757 d_tcon :: t, -- ^ Type constructor
758 d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors
759 }
760 -- ^ Data declaration
761 | PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t }
762 -- ^ "Placeholder" for data whose constructors are defined later
763 deriving Functor
765-- | Transform the FCs in a PData and its associated terms. The first
766-- function transforms the general-purpose FCs, and the second transforms
767-- those that are used for semantic source highlighting, so they can be
768-- treated specially.
769mapPDataFC :: (FC -> FC) -> (FC -> FC) -> PData -> PData
770mapPDataFC f g (PDatadecl n nfc tycon ctors) =
771 PDatadecl n (g nfc) (mapPTermFC f g tycon) (map ctorFC ctors)
772 where ctorFC (doc, argDocs, n, nfc, ty, fc, ns) =
773 (doc, argDocs, n, g nfc, mapPTermFC f g ty, f fc, ns)
774mapPDataFC f g (PLaterdecl n nfc tycon) =
775 PLaterdecl n (g nfc) (mapPTermFC f g tycon)
776{-!
777deriving instance Binary PData'
778deriving instance NFData PData'
779!-}
781-- Handy to get a free function for applying PTerm -> PTerm functions
782-- across a program, by deriving Functor
784type PDecl = PDecl' PTerm
785type PData = PData' PTerm
786type PClause = PClause' PTerm
788-- | Transform the FCs in a PTerm. The first function transforms the
789-- general-purpose FCs, and the second transforms those that are used
790-- for semantic source highlighting, so they can be treated specially.
791mapPDeclFC :: (FC -> FC) -> (FC -> FC) -> PDecl -> PDecl
792mapPDeclFC f g (PFix fc fixity ops) =
793 PFix (f fc) fixity ops
794mapPDeclFC f g (PTy doc argdocs syn fc opts n nfc ty) =
795 PTy doc argdocs syn (f fc) opts n (g nfc) (mapPTermFC f g ty)
796mapPDeclFC f g (PPostulate ext doc syn fc nfc opts n ty) =
797 PPostulate ext doc syn (f fc) (g nfc) opts n (mapPTermFC f g ty)
799mapPDeclFC f g (PClauses fc opts n clauses) =
800 PClauses (f fc) opts n (map (fmap (mapPTermFC f g)) clauses)
801mapPDeclFC f g (PCAF fc n tm) = PCAF (f fc) n (mapPTermFC f g tm)
802mapPDeclFC f g (PData doc argdocs syn fc opts dat) =
803 PData doc argdocs syn (f fc) opts (mapPDataFC f g dat)
804mapPDeclFC f g (PParams fc params decls) =
805 PParams (f fc)
806 (map (\(n, ty) -> (n, mapPTermFC f g ty)) params)
807 (map (mapPDeclFC f g) decls)
808mapPDeclFC f g (PNamespace ns fc decls) =
809 PNamespace ns (f fc) (map (mapPDeclFC f g) decls)
810mapPDeclFC f g (PRecord doc syn fc opts n nfc params paramdocs fields ctor ctorDoc syn') =
811 PRecord doc syn (f fc) opts n (g nfc)
812 (map (\(pn, pnfc, plic, ty) -> (pn, g pnfc, plic, mapPTermFC f g ty)) params)
813 paramdocs
814 (map (\(fn, plic, ty, fdoc) -> (fmap (\(fn', fnfc) -> (fn', g fnfc)) fn,
815 plic, mapPTermFC f g ty, fdoc))
816 fields)
817 (fmap (\(ctorN, ctorNFC) -> (ctorN, g ctorNFC)) ctor)
818 ctorDoc
819 syn'
820mapPDeclFC f g (PClass doc syn fc constrs n nfc params paramDocs det body ctor ctorDoc) =
821 PClass doc syn (f fc)
822 (map (\(constrn, constr) -> (constrn, mapPTermFC f g constr)) constrs)
823 n (g nfc) (map (\(n, nfc, pty) -> (n, g nfc, mapPTermFC f g pty)) params)
824 paramDocs (map (\(dn, dnfc) -> (dn, g dnfc)) det)
825 (map (mapPDeclFC f g) body)
826 (fmap (\(n, nfc) -> (n, g nfc)) ctor)
827 ctorDoc
828mapPDeclFC f g (PInstance doc paramDocs syn fc constrs cn cnfc params instTy instN body) =
829 PInstance doc paramDocs syn (f fc)
830 (map (\(constrN, constrT) -> (constrN, mapPTermFC f g constrT)) constrs)
831 cn (g cnfc) (map (mapPTermFC f g) params)
832 (mapPTermFC f g instTy)
833 instN
834 (map (mapPDeclFC f g) body)
835mapPDeclFC f g (PDSL n dsl) = PDSL n (fmap (mapPTermFC f g) dsl)
836mapPDeclFC f g (PSyntax fc syn) = PSyntax (f fc) $
837 case syn of
838 Rule syms tm ctxt -> Rule syms (mapPTermFC f g tm) ctxt
839 DeclRule syms decls -> DeclRule syms (map (mapPDeclFC f g) decls)
840mapPDeclFC f g (PMutual fc decls) =
841 PMutual (f fc) (map (mapPDeclFC f g) decls)
842mapPDeclFC f g (PDirective d) =
843 PDirective $
844 case d of
845 DNameHint n nfc ns ->
846 DNameHint n (g nfc) (map (\(hn, hnfc) -> (hn, g hnfc)) ns)
847 DErrorHandlers n nfc n' nfc' ns ->
848 DErrorHandlers n (g nfc) n' (g nfc') $
849 map (\(an, anfc) -> (an, g anfc)) ns
850mapPDeclFC f g (PProvider doc syn fc nfc what n) =
851 PProvider doc syn (f fc) (g nfc) (fmap (mapPTermFC f g) what) n
852mapPDeclFC f g (PTransform fc safe l r) =
853 PTransform (f fc) safe (mapPTermFC f g l) (mapPTermFC f g r)
854mapPDeclFC f g (PRunElabDecl fc script ns) =
855 PRunElabDecl (f fc) (mapPTermFC f g script) ns
857-- | Get all the names declared in a declaration
858declared :: PDecl -> [Name]
859declared (PFix _ _ _) = []
860declared (PTy _ _ _ _ _ n fc t) = [n]
861declared (PPostulate _ _ _ _ _ _ n t) = [n]
862declared (PClauses _ _ n _) = [] -- not a declaration
863declared (PCAF _ n _) = [n]
864declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
865 where fstt (_, _, a, _, _, _, _) = a
866declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n]
867declared (PParams _ _ ds) = concatMap declared ds
868declared (PNamespace _ _ ds) = concatMap declared ds
869declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
870declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms)
871declared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
872declared (PDSL n _) = [n]
873declared (PSyntax _ _) = []
874declared (PMutual _ ds) = concatMap declared ds
875declared (PDirective _) = []
876declared _ = []
878-- get the names declared, not counting nested parameter blocks
879tldeclared :: PDecl -> [Name]
880tldeclared (PFix _ _ _) = []
881tldeclared (PTy _ _ _ _ _ n _ t) = [n]
882tldeclared (PPostulate _ _ _ _ _ _ n t) = [n]
883tldeclared (PClauses _ _ n _) = [] -- not a declaration
884tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
885tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
886 where fstt (_, _, a, _, _, _, _) = a
887tldeclared (PParams _ _ ds) = []
888tldeclared (PMutual _ ds) = concatMap tldeclared ds
889tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds
890tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms)
891tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
892tldeclared _ = []
894defined :: PDecl -> [Name]
895defined (PFix _ _ _) = []
896defined (PTy _ _ _ _ _ n _ t) = []
897defined (PPostulate _ _ _ _ _ _ n t) = []
898defined (PClauses _ _ n _) = [n] -- not a declaration
899defined (PCAF _ n _) = [n]
900defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts
901 where fstt (_, _, a, _, _, _, _) = a
902defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = []
903defined (PParams _ _ ds) = concatMap defined ds
904defined (PNamespace _ _ ds) = concatMap defined ds
905defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn)
906defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms)
907defined (PInstance _ _ _ _ _ _ _ _ _ _ _) = []
908defined (PDSL n _) = [n]
909defined (PSyntax _ _) = []
910defined (PMutual _ ds) = concatMap defined ds
911defined (PDirective _) = []
912defined _ = []
914updateN :: [(Name, Name)] -> Name -> Name
915updateN ns n | Just n' <- lookup n ns = n'
916updateN _ n = n
918updateNs :: [(Name, Name)] -> PTerm -> PTerm
919updateNs [] t = t
920updateNs ns t = mapPT updateRef t
921 where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f)
922 updateRef t = t
924-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
925-- updateDNs [] t = t
926-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
927-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
928-- where updateCNs ns (PClause n l ts r ds)
929-- = PClause (updateN ns n) (fmap (updateNs ns) l)
930-- (map (fmap (updateNs ns)) ts)
931-- (fmap (updateNs ns) r)
932-- (map (updateDNs ns) ds)
933-- updateDNs ns c = c
935data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable)
937-- | High level language terms
938data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language
939 | 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.
940 | PInferRef FC [FC] Name -- ^ A name to be defined later
941 | PPatvar FC Name -- ^ A pattern variable
942 | PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span.
943 | PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable
944 | PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location)
945 | PTyped PTerm PTerm -- ^ Term with explicit type
946 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
947 | PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only)
948 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
949 | PMatchApp FC Name -- ^ Make an application by type matching
950 | PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse
951 | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs
952 | PTrue FC PunInfo -- ^ Unit type..?
953 | PResolveTC FC -- ^ Solve this dictionary by type class resolution
954 | PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type
955 | 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.
956 | 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.
957 | PAs FC Name PTerm -- ^ @-pattern, valid LHS only
958 | PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames.
959 | PHidden PTerm -- ^ Irrelevant or hidden pattern
960 | PType FC -- ^ 'Type' type
961 | PUniverse Universe -- ^ Some universe
962 | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions
963 | PConstant FC Const -- ^ Builtin types
964 | Placeholder -- ^ Underscore
965 | PDoBlock [PDo] -- ^ Do notation
966 | PIdiom FC PTerm -- ^ Idiom brackets
967 | PReturn FC
968 | PMetavar FC Name -- ^ A metavariable, ?name, and its precise location
969 | PProof [PTactic] -- ^ Proof script
970 | PTactics [PTactic] -- ^ As PProof, but no auto solving
971 | PElabError Err -- ^ Error to report on elaboration
972 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
973 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
974 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
975 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
976 | PNoImplicits PTerm -- ^ never run implicit converions on the term
977 | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term])
978 | PUnquote PTerm -- ^ ~Term
979 | 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.
980 | PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace.
981 | PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later.
982 deriving (Eq, Data, Typeable)
984data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed
985 | FirstSuccess
986 | TryImplicit
987 deriving (Eq, Data, Typeable)
989-- | Transform the FCs in a PTerm. The first function transforms the
990-- general-purpose FCs, and the second transforms those that are used
991-- for semantic source highlighting, so they can be treated specially.
992mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm
993mapPTermFC f g (PQuote q) = PQuote q
994mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n
995mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n
996mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n
997mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2)
998mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
999mapPTermFC 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)
1000mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2)
1001mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1002mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls
1003mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args)
1004mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n
1005mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3)
1006mapPTermFC 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)
1007mapPTermFC f g (PTrue fc info) = PTrue (f fc) info
1008mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc)
1009mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3)
1010mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2)
1011mapPTermFC 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)
1012mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t)
1013mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts)
1014mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t)
1015mapPTermFC f g (PType fc) = PType (f fc)
1016mapPTermFC f g (PUniverse u) = PUniverse u
1017mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2)
1018mapPTermFC f g (PConstant fc c) = PConstant (f fc) c
1019mapPTermFC f g Placeholder = Placeholder
1020mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos)
1021 where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t)
1022 mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t)
1023 mapPDoFC (DoBindP fc t1 t2 alts) =
1024 DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts)
1025 mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1026 mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2)
1027mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t)
1028mapPTermFC f g (PReturn fc) = PReturn (f fc)
1029mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n
1030mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs)
1031mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs)
1032mapPTermFC f g (PElabError err) = PElabError err
1033mapPTermFC f g PImpossible = PImpossible
1034mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t)
1035mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t)
1036mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t)
1037mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t)
1038mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2)
1039mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t)
1040mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns
1041mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm)
1042mapPTermFC f g (PQuoteName n x fc) = PQuoteName n x (g fc)
1044{-!
1045dg instance Binary PTerm
1046deriving instance NFData PTerm
1047!-}
1049mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
1050mapPT f t = f (mpt t) where
1051 mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s)
1052 mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s)
1053 mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s)
1054 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
1055 (fmap (mapPT f) g)
1056 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
1057 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
1058 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
1059 mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e)
1060 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
1061 mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r)
1062 mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r)
1063 mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as)
1064 mpt (PHidden t) = PHidden (mapPT f t)
1065 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
1066 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
1067 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
1068 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
1069 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
1070 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
1071 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
1072 mpt x = x
1075data PTactic' t = Intro [Name] | Intros | Focus Name
1076 | Refine Name [Bool] | Rewrite t | DoUnify
1077 | Induction t
1078 | CaseTac t
1079 | Equiv t
1080 | Claim Name t
1081 | Unfocus
1082 | MatchRefine Name
1083 | LetTac Name t | LetTacTy Name t t
1084 | Exact t | Compute | Trivial | TCInstance
1085 | ProofSearch Bool Bool Int (Maybe Name)
1086 [Name] -- allowed local names
1087 [Name] -- hints
1088 -- ^ the bool is whether to search recursively
1089 | Solve
1090 | Attack
1091 | ProofState | ProofTerm | Undo
1092 | Try (PTactic' t) (PTactic' t)
1093 | TSeq (PTactic' t) (PTactic' t)
1094 | ApplyTactic t -- see Language.Reflection module
1095 | ByReflection t
1096 | Reflect t
1097 | Fill t
1098 | GoalType String (PTactic' t)
1099 | TCheck t
1100 | TEval t
1101 | TDocStr (Either Name Const)
1102 | TSearch t
1103 | Skip
1104 | TFail [ErrorReportPart]
1105 | Qed | Abandon
1106 | SourceFC
1107 deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable)
1108{-!
1109deriving instance Binary PTactic'
1110deriving instance NFData PTactic'
1111!-}
1112instance Sized a => Sized (PTactic' a) where
1113 size (Intro nms) = 1 + size nms
1114 size Intros = 1
1115 size (Focus nm) = 1 + size nm
1116 size (Refine nm bs) = 1 + size nm + length bs
1117 size (Rewrite t) = 1 + size t
1118 size (Induction t) = 1 + size t
1119 size (LetTac nm t) = 1 + size nm + size t
1120 size (Exact t) = 1 + size t
1121 size Compute = 1
1122 size Trivial = 1
1123 size Solve = 1
1124 size Attack = 1
1125 size ProofState = 1
1126 size ProofTerm = 1
1127 size Undo = 1
1128 size (Try l r) = 1 + size l + size r
1129 size (TSeq l r) = 1 + size l + size r
1130 size (ApplyTactic t) = 1 + size t
1131 size (Reflect t) = 1 + size t
1132 size (Fill t) = 1 + size t
1133 size Qed = 1
1134 size Abandon = 1
1135 size Skip = 1
1136 size (TFail ts) = 1 + size ts
1137 size SourceFC = 1
1138 size DoUnify = 1
1139 size (CaseTac x) = 1 + size x
1140 size (Equiv t) = 1 + size t
1141 size (Claim x y) = 1 + size x + size y
1142 size Unfocus = 1
1143 size (MatchRefine x) = 1 + size x
1144 size (LetTacTy x y z) = 1 + size x + size y + size z
1145 size TCInstance = 1
1147type PTactic = PTactic' PTerm
1149data PDo' t = DoExp FC t
1150 | DoBind FC Name FC t -- ^ second FC is precise name location
1151 | DoBindP FC t t [(t,t)]
1152 | DoLet FC Name FC t t -- ^ second FC is precise name location
1153 | DoLetP FC t t
1154 deriving (Eq, Functor, Data, Typeable)
1155{-!
1156deriving instance Binary PDo'
1157deriving instance NFData PDo'
1158!-}
1160instance Sized a => Sized (PDo' a) where
1161 size (DoExp fc t) = 1 + size fc + size t
1162 size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t
1163 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
1164 size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r
1165 size (DoLetP fc l r) = 1 + size fc + size l + size r
1167type PDo = PDo' PTerm
1169-- The priority gives a hint as to elaboration order. Best to elaborate
1170-- things early which will help give a more concrete type to other
1171-- variables, e.g. a before (interpTy a).
1173data PArg' t = PImp { priority :: Int,
1174 machine_inf :: Bool, -- true if the machine inferred it
1175 argopts :: [ArgOpt],
1176 pname :: Name,
1177 getTm :: t }
1178 | PExp { priority :: Int,
1179 argopts :: [ArgOpt],
1180 pname :: Name,
1181 getTm :: t }
1182 | PConstraint { priority :: Int,
1183 argopts :: [ArgOpt],
1184 pname :: Name,
1185 getTm :: t }
1186 | PTacImplicit { priority :: Int,
1187 argopts :: [ArgOpt],
1188 pname :: Name,
1189 getScript :: t,
1190 getTm :: t }
1191 deriving (Show, Eq, Functor, Data, Typeable)
1193data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp
1194 deriving (Show, Eq, Data, Typeable)
1196instance Sized a => Sized (PArg' a) where
1197 size (PImp p _ l nm trm) = 1 + size nm + size trm
1198 size (PExp p l nm trm) = 1 + size nm + size trm
1199 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
1200 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
1202{-!
1203deriving instance Binary PArg'
1204deriving instance NFData PArg'
1205!-}
1207pimp n t mach = PImp 1 mach [] n t
1208pexp t = PExp 1 [] (sMN 0 "arg") t
1209pconst t = PConstraint 1 [] (sMN 0 "carg") t
1210ptacimp n s t = PTacImplicit 2 [] n s t
1212type PArg = PArg' PTerm
1214-- | Get the highest FC in a term, if one exists
1215highestFC :: PTerm -> Maybe FC
1216highestFC (PQuote _) = Nothing
1217highestFC (PRef fc _ _) = Just fc
1218highestFC (PInferRef fc _ _) = Just fc
1219highestFC (PPatvar fc _) = Just fc
1220highestFC (PLam fc _ _ _ _) = Just fc
1221highestFC (PPi _ _ _ _ _) = Nothing
1222highestFC (PLet fc _ _ _ _ _) = Just fc
1223highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty
1224highestFC (PApp fc _ _) = Just fc
1225highestFC (PAppBind fc _ _) = Just fc
1226highestFC (PMatchApp fc _) = Just fc
1227highestFC (PCase fc _ _) = Just fc
1228highestFC (PIfThenElse fc _ _ _) = Just fc
1229highestFC (PTrue fc _) = Just fc
1230highestFC (PResolveTC fc) = Just fc
1231highestFC (PRewrite fc _ _ _) = Just fc
1232highestFC (PPair fc _ _ _ _) = Just fc
1233highestFC (PDPair fc _ _ _ _ _) = Just fc
1234highestFC (PAs fc _ _) = Just fc
1235highestFC (PAlternative _ _ args) =
1236 case mapMaybe highestFC args of
1237 [] -> Nothing
1238 (fc:_) -> Just fc
1239highestFC (PHidden _) = Nothing
1240highestFC (PType fc) = Just fc
1241highestFC (PUniverse _) = Nothing
1242highestFC (PGoal fc _ _ _) = Just fc
1243highestFC (PConstant fc _) = Just fc
1244highestFC Placeholder = Nothing
1245highestFC (PDoBlock lines) =
1246 case map getDoFC lines of
1247 [] -> Nothing
1248 (fc:_) -> Just fc
1249 where
1250 getDoFC (DoExp fc t) = fc
1251 getDoFC (DoBind fc nm nfc t) = fc
1252 getDoFC (DoBindP fc l r alts) = fc
1253 getDoFC (DoLet fc nm nfc l r) = fc
1254 getDoFC (DoLetP fc l r) = fc
1256highestFC (PIdiom fc _) = Just fc
1257highestFC (PReturn fc) = Just fc
1258highestFC (PMetavar fc _) = Just fc
1259highestFC (PProof _) = Nothing
1260highestFC (PTactics _) = Nothing
1261highestFC (PElabError _) = Nothing
1262highestFC PImpossible = Nothing
1263highestFC (PCoerced tm) = highestFC tm
1264highestFC (PDisamb _ opts) = highestFC opts
1265highestFC (PUnifyLog tm) = highestFC tm
1266highestFC (PNoImplicits tm) = highestFC tm
1267highestFC (PQuasiquote _ _) = Nothing
1268highestFC (PUnquote tm) = highestFC tm
1269highestFC (PQuoteName _ _ fc) = Just fc
1270highestFC (PRunElab fc _ _) = Just fc
1271highestFC (PConstSugar fc _) = Just fc
1272highestFC (PAppImpl t _) = highestFC t
1274-- Type class data
1276data ClassInfo = CI { instanceCtorName :: Name,
1277 class_methods :: [(Name, (FnOpts, PTerm))],
1278 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
1279 class_default_superclasses :: [PDecl],
1280 class_params :: [Name],
1281 class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded
1282 class_determiners :: [Int] }
1283 deriving Show
1284{-!
1285deriving instance Binary ClassInfo
1286deriving instance NFData ClassInfo
1287!-}
1289-- Record data
1290data RecordInfo = RI { record_parameters :: [(Name,PTerm)],
1291 record_constructor :: Name,
1292 record_projections :: [Name] }
1293 deriving Show
1295-- Type inference data
1297data TIData = TIPartial -- ^ a function with a partially defined type
1298 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
1299 deriving Show
1301-- | Miscellaneous information about functions
1302data FnInfo = FnInfo { fn_params :: [Int] }
1303 deriving Show
1304{-!
1305deriving instance Binary FnInfo
1306deriving instance NFData FnInfo
1307!-}
1309data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
1310 detaggable :: Bool }
1311 deriving Show
1312{-!
1313deriving instance Binary OptInfo
1314deriving instance NFData OptInfo
1315!-}
1317-- | Syntactic sugar info
1318data DSL' t = DSL { dsl_bind :: t,
1319 dsl_return :: t,
1320 dsl_apply :: t,
1321 dsl_pure :: t,
1322 dsl_var :: Maybe t,
1323 index_first :: Maybe t,
1324 index_next :: Maybe t,
1325 dsl_lambda :: Maybe t,
1326 dsl_let :: Maybe t,
1327 dsl_pi :: Maybe t
1329 deriving (Show, Functor)
1330{-!
1331deriving instance Binary DSL'
1332deriving instance NFData DSL'
1333!-}
1335type DSL = DSL' PTerm
1337data SynContext = PatternSyntax | TermSyntax | AnySyntax
1338 deriving Show
1339{-!
1340deriving instance Binary SynContext
1341deriving instance NFData SynContext
1342!-}
1344data Syntax = Rule [SSymbol] PTerm SynContext
1345 | DeclRule [SSymbol] [PDecl]
1346 deriving Show
1348syntaxNames :: Syntax -> [Name]
1349syntaxNames (Rule syms _ _) = mapMaybe ename syms
1350 where ename (Keyword n) = Just n
1351 ename _ = Nothing
1352syntaxNames (DeclRule syms _) = mapMaybe ename syms
1353 where ename (Keyword n) = Just n
1354 ename _ = Nothing
1356syntaxSymbols :: Syntax -> [SSymbol]
1357syntaxSymbols (Rule ss _ _) = ss
1358syntaxSymbols (DeclRule ss _) = ss
1359{-!
1360deriving instance Binary Syntax
1361deriving instance NFData Syntax
1362!-}
1364data SSymbol = Keyword Name
1365 | Symbol String
1366 | Binding Name
1367 | Expr Name
1368 | SimpleExpr Name
1369 deriving (Show, Eq)
1372{-!
1373deriving instance Binary SSymbol
1374deriving instance NFData SSymbol
1375!-}
1377newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] }
1379emptySyntaxRules :: SyntaxRules
1380emptySyntaxRules = SyntaxRules []
1382updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules
1383updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules
1384 where
1385 newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr)
1387 ruleSort [] [] = EQ
1388 ruleSort [] _ = LT
1389 ruleSort _ [] = GT
1390 ruleSort (s1:ss1) (s2:ss2) =
1391 case symCompare s1 s2 of
1392 EQ -> ruleSort ss1 ss2
1393 r -> r
1395 -- Better than creating Ord instance for SSymbol since
1396 -- in general this ordering does not really make sense.
1397 symCompare (Keyword n1) (Keyword n2) = compare n1 n2
1398 symCompare (Keyword _) _ = LT
1399 symCompare (Symbol _) (Keyword _) = GT
1400 symCompare (Symbol s1) (Symbol s2) = compare s1 s2
1401 symCompare (Symbol _) _ = LT
1402 symCompare (Binding _) (Keyword _) = GT
1403 symCompare (Binding _) (Symbol _) = GT
1404 symCompare (Binding b1) (Binding b2) = compare b1 b2
1405 symCompare (Binding _) _ = LT
1406 symCompare (Expr _) (Keyword _) = GT
1407 symCompare (Expr _) (Symbol _) = GT
1408 symCompare (Expr _) (Binding _) = GT
1409 symCompare (Expr e1) (Expr e2) = compare e1 e2
1410 symCompare (Expr _) _ = LT
1411 symCompare (SimpleExpr _) (Keyword _) = GT
1412 symCompare (SimpleExpr _) (Symbol _) = GT
1413 symCompare (SimpleExpr _) (Binding _) = GT
1414 symCompare (SimpleExpr _) (Expr _) = GT
1415 symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2
1417initDSL = DSL (PRef f [] (sUN ">>="))
1418 (PRef f [] (sUN "return"))
1419 (PRef f [] (sUN "<*>"))
1420 (PRef f [] (sUN "pure"))
1421 Nothing
1422 Nothing
1423 Nothing
1424 Nothing
1425 Nothing
1426 Nothing
1427 where f = fileFC "(builtin)"
1429data Using = UImplicit Name PTerm
1430 | UConstraint Name [Name]
1431 deriving (Show, Eq, Data, Typeable)
1432{-!
1433deriving instance Binary Using
1434deriving instance NFData Using
1435!-}
1437data SyntaxInfo = Syn { using :: [Using],
1438 syn_params :: [(Name, PTerm)],
1439 syn_namespace :: [String],
1440 no_imp :: [Name],
1441 imp_methods :: [Name], -- class methods. When expanding
1442 -- implicits, these should be expanded even under
1443 -- binders
1444 decoration :: Name -> Name,
1445 inPattern :: Bool,
1446 implicitAllowed :: Bool,
1447 maxline :: Maybe Int,
1448 mut_nesting :: Int,
1449 dsl_info :: DSL,
1450 syn_in_quasiquote :: Int }
1451 deriving Show
1452{-!
1453deriving instance NFData SyntaxInfo
1454deriving instance Binary SyntaxInfo
1455!-}
1457defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0
1459expandNS :: SyntaxInfo -> Name -> Name
1460expandNS syn n@(NS _ _) = n
1461expandNS syn n = case syn_namespace syn of
1462 [] -> n
1463 xs -> sNS n xs
1466-- For inferring types of things
1468bi = fileFC "builtin"
1470inferTy = sMN 0 "__Infer"
1471inferCon = sMN 0 "__infer"
1472inferDecl = PDatadecl inferTy NoFC
1473 (PType bi)
1474 [(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) (
1475 PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType"))
1476 (PRef bi [] inferTy)), bi, [])]
1477inferOpts = []
1479infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
1480infP = P (TCon 6 0) inferTy (TType (UVal 0))
1482getInferTerm, getInferType :: Term -> Term
1483getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
1484getInferTerm (App _ (App _ _ _) tm) = tm
1485getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1487getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1488 where toTy (Lam t) = Pi Nothing t (TType (UVar 0))
1489 toTy (PVar t) = PVTy t
1490 toTy b = b
1491getInferType (App _ (App _ _ ty) _) = ty
1495-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign
1497primNames = [inferTy, inferCon]
1499unitTy = sUN "Unit"
1500unitCon = sUN "MkUnit"
1502falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $
1503 "The empty type, also known as the trivially false proposition." ++
1504 "\n\n" ++
1505 "Use `void` or `absurd` to prove anything if you have a variable " ++
1506 "of type `Void` in scope."
1507falseTy = sUN "Void"
1509pairTy = sNS (sUN "Pair") ["Builtins"]
1510pairCon = sNS (sUN "MkPair") ["Builtins"]
1512upairTy = sNS (sUN "UPair") ["Builtins"]
1513upairCon = sNS (sUN "MkUPair") ["Builtins"]
1515eqTy = sUN "="
1516eqCon = sUN "Refl"
1517eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $
1518 "The propositional equality type. A proof that `x` = `y`." ++
1519 "\n\n" ++
1520 "To use such a proof, pattern-match on it, and the two equal things will " ++
1521 "then need to be the _same_ pattern." ++
1522 "\n\n" ++
1523 "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++
1524 "is possible to state equalities between values of potentially different " ++
1525 "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++
1526 "\n\n" ++
1527 "You may need to use `(~=~)` to explicitly request heterogeneous equality."
1529eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)]
1530 (piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))]
1531 (PType bi)))
1532 [(reflDoc, reflParamDoc,
1533 eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) (
1534 PPi impl (n "x") NoFC (PRef bi [] (n "A"))
1535 (PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False,
1536 pimp (n "B") Placeholder False,
1537 pexp (PRef bi [] (n "x")),
1538 pexp (PRef bi [] (n "x"))])), bi, [])]
1539 where n a = sUN a
1540 reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $
1541 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1542 "shown that both sides are in fact equal."
1543 reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"),
1544 (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1546eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"),
1547 (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality")
1549 where n a = sUN a
1551eqOpts = []
1553-- | The special name to be used in the module documentation context -
1554-- not for use in the main definition context. The namespace around it
1555-- will determine the module to which the docs adhere.
1556modDocName :: Name
1557modDocName = sMN 0 "ModuleDocs"
1559-- Defined in builtins.idr
1560sigmaTy = sNS (sUN "Sigma") ["Builtins"]
1561sigmaCon = sNS (sUN "MkSigma") ["Builtins"]
1563piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1564piBind = piBindp expl
1566piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1567piBindp p [] t = t
1568piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t)
1571-- Pretty-printing declarations and terms
1573-- These "show" instances render to an absurdly wide screen because inserted line breaks
1574-- could interfere with interactive editing, which calls "show".
1576instance Show PTerm where
1577 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1579instance Show PDecl where
1580 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d
1582instance Show PClause where
1583 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1585instance Show PData where
1586 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1588instance Pretty PTerm OutputAnnotation where
1589 pretty = prettyImp defaultPPOption
1591-- | Colourise annotations according to an Idris state. It ignores the names
1592-- in the annotation, as there's no good way to show extended information on a
1593-- terminal.
1594annotationColour :: IState -> OutputAnnotation -> Maybe IdrisColour
1595annotationColour ist _ | not (idris_colourRepl ist) = Nothing
1596annotationColour ist (AnnConst c) =
1597 let theme = idris_colourTheme ist
1598 in Just $ if constIsType c
1599 then typeColour theme
1600 else dataColour theme
1601annotationColour ist (AnnData _ _) = Just $ dataColour (idris_colourTheme ist)
1602annotationColour ist (AnnType _ _) = Just $ typeColour (idris_colourTheme ist)
1603annotationColour ist (AnnBoundName _ True) = Just $ implicitColour (idris_colourTheme ist)
1604annotationColour ist (AnnBoundName _ False) = Just $ boundVarColour (idris_colourTheme ist)
1605annotationColour ist AnnKeyword = Just $ keywordColour (idris_colourTheme ist)
1606annotationColour ist (AnnName n _ _ _) =
1607 let ctxt = tt_ctxt ist
1608 theme = idris_colourTheme ist
1609 in case () of
1610 _ | isDConName n ctxt -> Just $ dataColour theme
1611 _ | isFnName n ctxt -> Just $ functionColour theme
1612 _ | isTConName n ctxt -> Just $ typeColour theme
1613 _ | isPostulateName n ist -> Just $ postulateColour theme
1614 _ | otherwise -> Nothing -- don't colourise unknown names
1615annotationColour ist (AnnTextFmt fmt) = Just (colour fmt)
1616 where colour BoldText = IdrisColour Nothing True False True False
1617 colour UnderlineText = IdrisColour Nothing True True False False
1618 colour ItalicText = IdrisColour Nothing True False False True
1619annotationColour ist _ = Nothing
1622-- | Colourise annotations according to an Idris state. It ignores the names
1623-- in the annotation, as there's no good way to show extended
1624-- information on a terminal. Note that strings produced this way will
1625-- not be coloured on Windows, so the use of the colour rendering
1626-- functions in Idris.Output is to be preferred.
1627consoleDecorate :: IState -> OutputAnnotation -> String -> String
1628consoleDecorate ist ann = maybe id colourise (annotationColour ist ann)
1630isPostulateName :: Name -> IState -> Bool
1631isPostulateName n ist = S.member n (idris_postulates ist)
1633-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1634prettyImp :: PPOption -- ^^ pretty printing options
1635 -> PTerm -- ^^ the term to pretty-print
1636 -> Doc OutputAnnotation
1637prettyImp impl = pprintPTerm impl [] [] []
1639-- | Serialise something to base64 using its Binary instance.
1641-- | Do the right thing for rendering a term in an IState
1642prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1643prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1645-- | Pretty-print a high-level Idris term in some bindings context with infix info
1646pprintPTerm :: PPOption -- ^^ pretty printing options
1647 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1648 -> [Name] -- ^^ names to always show in pi, even if not used
1649 -> [FixDecl] -- ^^ Fixity declarations
1650 -> PTerm -- ^^ the term to pretty-print
1651 -> Doc OutputAnnotation
1652pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd
1653 where
1654 startPrec = 0
1655 funcAppPrec = 10
1657 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1658 prettySe d p bnd (PQuote r) =
1659 text "![" <> pretty r <> text "]"
1660 prettySe d p bnd (PPatvar fc n) = pretty n
1661 prettySe d p bnd e
1662 | Just str <- slist d p bnd e = depth d $ str
1663 | Just n <- snat ppo d p e = depth d $ annotate (AnnData "Nat" "") (text (show n))
1664 prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n
1665 prettySe d p bnd (PLam fc n nfc ty sc) =
1666 depth d . bracket p startPrec . group . align . hang 2 $
1667 text "\\" <> prettyBindingOf n False <+> text "=>" <$>
1668 prettySe (decD d) startPrec ((n, False):bnd) sc
1669 prettySe d p bnd (PLet fc n nfc ty v sc) =
1670 depth d . bracket p startPrec . group . align $
1671 kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </>
1672 kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc)
1673 prettySe d p bnd (PPi (Exp l s _) n _ ty sc)
1674 | n `elem` allNamesIn sc || ppopt_impl ppo && uname n || n `elem` docArgs
1675 || ppopt_pinames ppo && uname n =
1676 depth d . bracket p startPrec . group $
1677 enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+>
1678 st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc
1679 | otherwise =
1680 depth d . bracket p startPrec . group $
1681 group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$>
1682 group (prettySe (decD d) startPrec ((n, False):bnd) sc)
1683 where
1684 uname (UN n) = case str n of
1685 ('_':_) -> False
1686 _ -> True
1687 uname _ = False
1689 st =
1690 case s of
1691 Static -> text "[static]" <> space
1692 _ -> empty
1693 prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc)
1694 | ppopt_impl ppo =
1695 depth d . bracket p startPrec $
1696 lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+>
1697 st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1698 | otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc
1699 where
1700 st =
1701 case s of
1702 Static -> text "[static]" <> space
1703 _ -> empty
1704 prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) =
1705 depth d . bracket p startPrec $
1706 prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1707 prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch _ _ _ _ _ _])) n _ ty sc) =
1708 lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1709 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1710 prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) =
1711 depth d . bracket p startPrec $
1712 lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <>
1713 rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc
1714 -- This case preserves the behavior of the former constructor PEq.
1715 -- It should be removed if feasible when the pretty-printing of infix
1716 -- operators in general is improved.
1717 prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r])
1718 | n == eqTy, ppopt_impl ppo =
1719 depth d . bracket p eqPrec $
1720 enclose lparen rparen eq <+>
1721 align (group (vsep (map (prettyArgS (decD d) bnd)
1722 [lt, rt, l, r])))
1723 | n == eqTy =
1724 depth d . bracket p eqPrec . align . group $
1725 prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r))
1726 where eq = annName eqTy (text "=")
1727 eqPrec = startPrec
1728 prettyTerm = prettySe (decD d) (eqPrec + 1) bnd
1729 prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args
1730 | UN nm <- basename f
1731 , not (ppopt_impl ppo) && null (getShowArgs args) =
1732 prettyName True (ppopt_impl ppo) bnd f
1733 prettySe d p bnd (PAppBind _ (PRef _ _ f) [])
1734 | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f
1735 prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators
1736 | UN nm <- basename op
1737 , not (tnull nm) &&
1738 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1739 case getShowArgs args of
1740 [] -> opName True
1741 [x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x)))
1742 [l,r] -> let precedence = maybe (startPrec - 1) prec f
1743 in depth d . bracket p precedence $ inFix (getTm l) (getTm r)
1744 (l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) ->
1745 depth d . bracket p funcAppPrec $
1746 enclose lparen rparen (inFix (getTm l) (getTm r)) <+>
1747 align (group (vsep (map (prettyArgS d bnd) rest)))
1748 as -> opName True <+> align (vsep (map (prettyArgS d bnd) as))
1749 where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op
1750 f = getFixity (opStr op)
1751 left = case f of
1752 Nothing -> funcAppPrec + 1
1753 Just (Infixl p') -> p'
1754 Just f' -> prec f' + 1
1755 right = case f of
1756 Nothing -> funcAppPrec + 1
1757 Just (Infixr p') -> p'
1758 Just f' -> prec f' + 1
1759 inFix l r = align . group $
1760 (prettySe (decD d) left bnd l <+> opName False) <$>
1761 group (prettySe (decD d) right bnd r)
1762 prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo
1763 | PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm,
1764 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1765 char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str))
1766 prettySe d p bnd (PApp _ f as) = -- Normal prefix applications
1767 let args = getShowArgs as
1768 fp = prettySe (decD d) (startPrec + 1) bnd f
1769 shownArgs = if ppopt_impl ppo then as else args
1770 in
1771 depth d . bracket p funcAppPrec . group $
1772 if null shownArgs
1773 then fp
1774 else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs))
1775 prettySe d p bnd (PCase _ scr cases) =
1776 align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$>
1777 depth d (indent 2 (vsep (map ppcase cases)))
1778 where
1779 ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec
1780 ([(n, False) | n <- vars l] ++ bnd)
1781 in nest nestingSize $
1782 prettyCase l <+> text "=>" <+> prettyCase r
1783 -- Warning: this is a bit of a hack. At this stage, we don't have the
1784 -- global context, so we can't determine which names are constructors,
1785 -- which are types, and which are pattern variables on the LHS of the
1786 -- case pattern. We use the heuristic that names without a namespace
1787 -- are patvars, because right now case blocks in PTerms are always
1788 -- delaborated from TT before being sent to the pretty-printer. If they
1789 -- start getting printed directly, THIS WILL BREAK.
1790 -- Potential solution: add a list of known patvars to the cases in
1791 -- PCase, and have the delaborator fill it out, kind of like the pun
1792 -- disambiguation on PDPair.
1793 vars tm = filter noNS (allNamesIn tm)
1794 noNS (NS _ _) = False
1795 noNS _ = True
1797 prettySe d p bnd (PIfThenElse _ c t f) =
1798 depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $
1799 [ kwd "if" <+> prettySe (decD d) startPrec bnd c
1800 , kwd "then" <+> prettySe (decD d) startPrec bnd t
1801 , kwd "else" <+> prettySe (decD d) startPrec bnd f
1803 prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm
1804 prettySe d p bnd (PResolveTC _) = kwd "%instance"
1805 prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1806 prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1807 prettySe d p bnd (PTrue _ TypeOrTerm) = text "()"
1808 prettySe d p bnd (PRewrite _ l r _) =
1809 depth d . bracket p startPrec $
1810 text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r
1811 prettySe d p bnd (PTyped l r) =
1812 lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen
1813 prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser
1814 | Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) .
1815 align . group . vsep . punctuate (ann comma) $
1816 map (prettySe (decD d) startPrec bnd) elts
1817 where ann = case pun of
1818 TypeOrTerm -> id
1819 IsType -> annName pairTy
1820 IsTerm -> annName pairCon
1821 prettySe d p bnd (PDPair _ _ pun l t r) =
1822 depth d $
1823 annotated lparen <>
1824 left <+>
1825 annotated (text "**") <+>
1826 prettySe (decD d) startPrec (addBinding bnd) r <>
1827 annotated rparen
1828 where annotated = case pun of
1829 IsType -> annName sigmaTy
1830 IsTerm -> annName sigmaCon
1831 TypeOrTerm -> id
1832 (left, addBinding) = case (l, pun) of
1833 (PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :))
1834 _ -> (prettySe (decD d) startPrec bnd l, id)
1835 prettySe d p bnd (PAlternative ns a as) =
1836 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1837 where
1838 prettyAs =
1839 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (depth d . prettySe (decD d) startPrec bnd) as
1840 prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type"
1841 prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u)
1842 prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c))
1843 -- XXX: add pretty for tactics
1844 prettySe d p bnd (PProof ts) =
1845 kwd "proof" <+> lbrace <> ellipsis <> rbrace
1846 prettySe d p bnd (PTactics ts) =
1847 kwd "tactics" <+> lbrace <> ellipsis <> rbrace
1848 prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n
1849 prettySe d p bnd (PReturn f) = kwd "return"
1850 prettySe d p bnd PImpossible = kwd "impossible"
1851 prettySe d p bnd Placeholder = text "_"
1852 prettySe d p bnd (PDoBlock dos) =
1853 bracket p startPrec $
1854 kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos)))
1855 where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos
1856 ppdo bnd (DoBind _ bn _ tm : dos) =
1857 (prettyBindingOf bn False <+> text "<-" <+>
1858 group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) :
1859 ppdo ((bn, False):bnd) dos
1860 ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab
1861 text "no pretty printer for pattern-matching do binding" :
1862 ppdo bnd dos
1863 ppdo bnd (DoLet _ ln _ ty v : dos) =
1864 (kwd "let" <+> prettyBindingOf ln False <+>
1865 (if ty /= Placeholder
1866 then colon <+> prettySe (decD d) startPrec bnd ty <+> text "="
1867 else text "=") <+>
1868 group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) :
1869 ppdo ((ln, False):bnd) dos
1870 ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab
1871 text "no pretty printer for pattern-matching do binding" :
1872 ppdo bnd dos
1873 ppdo _ [] = []
1874 prettySe d p bnd (PCoerced t) = prettySe d p bnd t
1875 prettySe d p bnd (PElabError s) = pretty s
1876 -- Quasiquote pprinting ignores bound vars
1877 prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")"
1878 prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")"
1879 prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t
1880 prettySe d p bnd (PQuoteName n res _) = text start <> prettyName True (ppopt_impl ppo) bnd n <> text end
1881 where start = if res then "`{" else "`{{"
1882 end = if res then "}" else "}}"
1883 prettySe d p bnd (PRunElab _ tm _) =
1884 bracket p funcAppPrec . group . align . hang 2 $
1885 text "%runElab" <$>
1886 prettySe (decD d) funcAppPrec bnd tm
1887 prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless
1889 prettySe d p bnd _ = text "missing pretty-printer for term"
1891 prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation
1892 prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n))
1893 where display (UN n) = T.unpack n
1894 display (MN _ n) = T.unpack n
1895 -- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings
1896 display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n
1897 display n = show n
1899 prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm)
1900 prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm
1901 prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm
1902 prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm)
1904 prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg
1905 prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
1906 prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace
1907 prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace
1909 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1910 annName n = annotate (AnnName n Nothing Nothing Nothing)
1912 opStr :: Name -> String
1913 opStr (NS n _) = opStr n
1914 opStr (UN n) = T.unpack n
1916 slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation]
1917 slist' (Just d) _ _ _ | d <= 0 = Nothing
1918 slist' d _ _ e
1919 | containsHole e = Nothing
1920 slist' d p bnd (PApp _ (PRef _ _ nil) _)
1921 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1922 slist' d p bnd (PRef _ _ nil)
1923 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1924 slist' d p bnd (PApp _ (PRef _ _ cons) args)
1925 | nsroot cons == sUN "::",
1926 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1927 all isImp imps,
1928 Just tl' <- slist' (decD d) p bnd tl
1929 = Just (prettySe d startPrec bnd hd : tl')
1930 where
1931 isImp (PImp {}) = True
1932 isImp _ = False
1933 slist' _ _ _ tm = Nothing
1935 slist d p bnd e | Just es <- slist' d p bnd e = Just $
1936 case es of
1937 [] -> annotate (AnnData "" "") $ text "[]"
1938 [x] -> enclose left right . group $ x
1939 xs -> enclose left right .
1940 align . group . vsep .
1941 punctuate comma $ xs
1942 where left = (annotate (AnnData "" "") (text "["))
1943 right = (annotate (AnnData "" "") (text "]"))
1944 comma = (annotate (AnnData "" "") (text ","))
1945 slist _ _ _ _ = Nothing
1947 pairElts :: PTerm -> Maybe [PTerm]
1948 pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1949 | otherwise = Just [x, y]
1950 pairElts _ = Nothing
1952 natns = "Prelude.Nat."
1954 snat :: PPOption -> Maybe Int -> Int -> PTerm -> Maybe Integer
1955 snat ppo d p e
1956 | ppopt_desugarnats ppo = Nothing
1957 | otherwise = snat' d p e
1958 where
1959 snat' :: Maybe Int -> Int -> PTerm -> Maybe Integer
1960 snat' (Just x) _ _ | x <= 0 = Nothing
1961 snat' d p (PRef _ _ z)
1962 | show z == (natns++"Z") || show z == "Z" = Just 0
1963 snat' d p (PApp _ s [PExp {getTm=n}])
1964 | show s == (natns++"S") || show s == "S",
1965 Just n' <- snat' (decD d) p n
1966 = Just $ 1 + n'
1967 snat' _ _ _ = Nothing
1969 bracket outer inner doc
1970 | outer > inner = lparen <> doc <> rparen
1971 | otherwise = doc
1973 ellipsis = text "..."
1975 depth Nothing = id
1976 depth (Just d) = if d <= 0 then const (ellipsis) else id
1978 decD = fmap (\x -> x - 1)
1980 kwd = annotate AnnKeyword . text
1982 fixities :: M.Map String Fixity
1983 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
1985 getFixity :: String -> Maybe Fixity
1986 getFixity = flip M.lookup fixities
1988-- | Strip away namespace information
1989basename :: Name -> Name
1990basename (NS n _) = basename n
1991basename n = n
1993-- | Determine whether a name was the one inserted for a hole or
1994-- guess by the delaborator
1995isHoleName :: Name -> Bool
1996isHoleName (UN n) = n == T.pack "[__]"
1997isHoleName _ = False
1999-- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess
2000containsHole :: PTerm -> Bool
2001containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm]
2003-- | Pretty-printer helper for names that attaches the correct annotations
2004prettyName
2005 :: Bool -- ^^ whether the name should be parenthesised if it is an infix operator
2006 -> Bool -- ^^ whether to show namespaces
2007 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
2008 -> Name -- ^^ the name to pprint
2009 -> Doc OutputAnnotation
2010prettyName infixParen showNS bnd n
2011 | (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_"
2012 | (UN n') <- n, T.unpack n' == "_" = text "_"
2013 | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName
2014 | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName
2015 where fullName = text nameSpace <> parenthesise (text (baseName n))
2016 baseName (UN n) = T.unpack n
2017 baseName (NS n ns) = baseName n
2018 baseName (MN i s) = T.unpack s
2019 baseName other = show other
2020 nameSpace = case n of
2021 (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else ""
2022 _ -> ""
2023 isInfix = case baseName n of
2024 "" -> False
2025 (c : _) -> not (isAlpha c)
2026 parenthesise = if isInfix && infixParen then enclose lparen rparen else id
2029showCImp :: PPOption -> PClause -> Doc OutputAnnotation
2030showCImp ppo (PClause _ n l ws r w)
2031 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
2032 <+> text "where" <+> text (show w)
2033 where
2034 showWs [] = empty
2035 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2036showCImp ppo (PWith _ n l ws r pn w)
2037 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
2038 <+> braces (text (show w))
2039 where
2040 showWs [] = empty
2041 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
2044showDImp :: PPOption -> PData -> Doc OutputAnnotation
2045showDImp ppo (PDatadecl n nfc ty cons)
2046 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
2047 (indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons))
2049showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
2050showDecls o ds = vsep (map (showDeclImp o) ds)
2052showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
2053showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
2054showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
2055 indent 2 (vsep (map (showCImp o) cs))
2056showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
2057showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
2058showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
2059showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
2060showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _)
2061 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
2062showDeclImp o (PInstance _ _ _ _ cs n _ _ t _ ds)
2063 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
2064showDeclImp _ _ = text "..."
2065-- showDeclImp (PImport o) = "import " ++ o
2067getImps :: [PArg] -> [(Name, PTerm)]
2068getImps [] = []
2069getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
2070getImps (_ : xs) = getImps xs
2072getExps :: [PArg] -> [PTerm]
2073getExps [] = []
2074getExps (PExp _ _ _ tm : xs) = tm : getExps xs
2075getExps (_ : xs) = getExps xs
2077getShowArgs :: [PArg] -> [PArg]
2078getShowArgs [] = []
2079getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs
2080getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs
2081 | PImp _ _ _ _ tm <- e
2082 , containsHole tm = e : getShowArgs xs
2083getShowArgs (_ : xs) = getShowArgs xs
2085getConsts :: [PArg] -> [PTerm]
2086getConsts [] = []
2087getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
2088getConsts (_ : xs) = getConsts xs
2090getAll :: [PArg] -> [PTerm]
2091getAll = map getTm
2094-- | Show Idris name
2095showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
2096 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
2097 -> PPOption -- ^^ pretty printing options
2098 -> Bool -- ^^ whether to colourise
2099 -> Name -- ^^ the term to show
2100 -> String
2101showName ist bnd ppo colour n = case ist of
2102 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
2103 Nothing -> showbasic n
2104 where name = if ppopt_impl ppo then show n else showbasic n
2105 showbasic n@(UN _) = showCG n
2106 showbasic (MN i s) = str s
2107 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
2108 showbasic (SN s) = show s
2109 fst3 (x, _, _) = x
2110 colourise n t = let ctxt' = fmap tt_ctxt ist in
2111 case ctxt' of
2112 Nothing -> name
2113 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
2114 else colouriseBound t name
2115 | isDConName n ctxt -> colouriseData t name
2116 | isFnName n ctxt -> colouriseFun t name
2117 | isTConName n ctxt -> colouriseType t name
2118 -- The assumption is that if a name is not bound and does not exist in the
2119 -- global context, then we're somewhere in which implicit info has been lost
2120 -- (like error messages). Thus, unknown vars are colourised as implicits.
2121 | otherwise -> colouriseImplicit t name
2123showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
2124 -> PTerm -- ^^ the term to show
2125 -> String
2126showTm ist = displayDecorated (consoleDecorate ist) .
2127 renderPretty 0.8 100000 .
2128 prettyImp (ppOptionIst ist)
2130-- | Show a term with implicits, no colours
2131showTmImpls :: PTerm -> String
2132showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
2134-- | Show a term with specific options
2135showTmOpts :: PPOption -> PTerm -> String
2136showTmOpts opt = flip (displayS . renderPretty 1.0 10000000 . prettyImp opt) ""
2139instance Sized PTerm where
2140 size (PQuote rawTerm) = size rawTerm
2141 size (PRef fc _ name) = size name
2142 size (PLam fc name _ ty bdy) = 1 + size ty + size bdy
2143 size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy
2144 size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy
2145 size (PTyped trm ty) = 1 + size trm + size ty
2146 size (PApp fc name args) = 1 + size args
2147 size (PAppBind fc name args) = 1 + size args
2148 size (PCase fc trm bdy) = 1 + size trm + size bdy
2149 size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f])
2150 size (PTrue fc _) = 1
2151 size (PResolveTC fc) = 1
2152 size (PRewrite fc left right _) = 1 + size left + size right
2153 size (PPair fc _ _ left right) = 1 + size left + size right
2154 size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right
2155 size (PAlternative _ a alts) = 1 + size alts
2156 size (PHidden hidden) = size hidden
2157 size (PUnifyLog tm) = size tm
2158 size (PDisamb _ tm) = size tm
2159 size (PNoImplicits tm) = size tm
2160 size (PType _) = 1
2161 size (PUniverse _) = 1
2162 size (PConstant fc const) = 1 + size fc + size const
2163 size Placeholder = 1
2164 size (PDoBlock dos) = 1 + size dos
2165 size (PIdiom fc term) = 1 + size term
2166 size (PReturn fc) = 1
2167 size (PMetavar _ name) = 1
2168 size (PProof tactics) = size tactics
2169 size (PElabError err) = size err
2170 size PImpossible = 1
2171 size _ = 0
2173getPArity :: PTerm -> Int
2174getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc
2175getPArity _ = 0
2177-- Return all names, free or globally bound, in the given term.
2179allNamesIn :: PTerm -> [Name]
2180allNamesIn tm = nub $ ni 0 [] tm
2181 where -- TODO THINK added niTacImp, but is it right?
2182 ni 0 env (PRef _ _ n)
2183 | not (n `elem` env) = [n]
2184 ni 0 env (PPatvar _ n) = [n]
2185 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2186 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2187 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os)
2188 ni 0 env (PIfThenElse _ c t f) = ni 0 env c ++ ni 0 env t ++ ni 0 env f
2189 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2190 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2191 ni 0 env (PLet _ n _ ty val sc) = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc
2192 ni 0 env (PHidden tm) = ni 0 env tm
2193 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2194 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2195 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2196 ni 0 env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni 0 env r
2197 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2198 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2199 ni 0 env (PAlternative ns a ls) = concatMap (ni 0 env) ls
2200 ni 0 env (PUnifyLog tm) = ni 0 env tm
2201 ni 0 env (PDisamb _ tm) = ni 0 env tm
2202 ni 0 env (PNoImplicits tm) = ni 0 env tm
2204 ni i env (PQuasiquote tm ty) = ni (i+1) env tm ++ maybe [] (ni i env) ty
2205 ni i env (PUnquote tm) = ni (i - 1) env tm
2207 ni i env tm = concatMap (ni i env) (children tm)
2209 niTacImp i env (TacImp _ _ scr) = ni i env scr
2210 niTacImp _ _ _ = []
2213-- Return all names defined in binders in the given term
2214boundNamesIn :: PTerm -> [Name]
2215boundNamesIn tm = S.toList (ni 0 S.empty tm)
2216 where -- TODO THINK Added niTacImp, but is it right?
2217 ni :: Int -> S.Set Name -> PTerm -> S.Set Name
2218 ni 0 set (PApp _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2219 ni 0 set (PAppBind _ f as) = niTms 0 (ni 0 set f) (map getTm as)
2220 ni 0 set (PCase _ c os) = niTms 0 (ni 0 set c) (map snd os)
2221 ni 0 set (PIfThenElse _ c t f) = niTms 0 set [c, t, f]
2222 ni 0 set (PLam fc n _ ty sc) = S.insert n $ ni 0 (ni 0 set ty) sc
2223 ni 0 set (PLet fc n nfc ty val sc) = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc
2224 ni 0 set (PPi p n _ ty sc) = niTacImp 0 (S.insert n $ ni 0 (ni 0 set ty) sc) p
2225 ni 0 set (PRewrite _ l r _) = ni 0 (ni 0 set l) r
2226 ni 0 set (PTyped l r) = ni 0 (ni 0 set l) r
2227 ni 0 set (PPair _ _ _ l r) = ni 0 (ni 0 set l) r
2228 ni 0 set (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 (ni 0 set t) r
2229 ni 0 set (PDPair _ _ _ l t r) = ni 0 (ni 0 (ni 0 set l) t) r
2230 ni 0 set (PAlternative ns a as) = niTms 0 set as
2231 ni 0 set (PHidden tm) = ni 0 set tm
2232 ni 0 set (PUnifyLog tm) = ni 0 set tm
2233 ni 0 set (PDisamb _ tm) = ni 0 set tm
2234 ni 0 set (PNoImplicits tm) = ni 0 set tm
2236 ni i set (PQuasiquote tm ty) = ni (i + 1) set tm `S.union` maybe S.empty (ni i set) ty
2237 ni i set (PUnquote tm) = ni (i - 1) set tm
2239 ni i set tm = foldr S.union set (map (ni i set) (children tm))
2241 niTms :: Int -> S.Set Name -> [PTerm] -> S.Set Name
2242 niTms i set [] = set
2243 niTms i set (x : xs) = niTms i (ni i set x) xs
2245 niTacImp i set (TacImp _ _ scr) = ni i set scr
2246 niTacImp i set _ = set
2248-- Return names which are valid implicits in the given term (type).
2249implicitNamesIn :: [Name] -> IState -> PTerm -> [Name]
2250implicitNamesIn uvars ist tm = nub $ ni 0 [] tm
2251 where
2252 ni 0 env (PRef _ _ n)
2253 | not (n `elem` env)
2254 = case lookupTy n (tt_ctxt ist) of
2255 [] -> [n]
2256 _ -> if n `elem` uvars then [n] else []
2257 ni 0 env (PApp _ f@(PRef _ _ n) as)
2258 | n `elem` uvars = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2259 | otherwise = concatMap (ni 0 env) (map getTm as)
2260 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2261 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2262 ni 0 env (PCase _ c os) = ni 0 env c ++
2263 -- names in 'os', not counting the names bound in the cases
2264 (nub (concatMap (ni 0 env) (map snd os))
2265 \\ nub (concatMap (ni 0 env) (map fst os)))
2266 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2267 ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2268 ni 0 env (PPi p n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2269 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2270 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2271 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2272 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2273 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2274 ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as
2275 ni 0 env (PHidden tm) = ni 0 env tm
2276 ni 0 env (PUnifyLog tm) = ni 0 env tm
2277 ni 0 env (PDisamb _ tm) = ni 0 env tm
2278 ni 0 env (PNoImplicits tm) = ni 0 env tm
2280 ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++
2281 maybe [] (ni i env) ty
2282 ni i env (PUnquote tm) = ni (i - 1) env tm
2284 ni i env tm = concatMap (ni i env) (children tm)
2286-- Return names which are free in the given term.
2287namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
2288namesIn uvars ist tm = nub $ ni 0 [] tm
2289 where
2290 ni 0 env (PRef _ _ n)
2291 | not (n `elem` env)
2292 = case lookupTy n (tt_ctxt ist) of
2293 [] -> [n]
2294 _ -> if n `elem` (map fst uvars) then [n] else []
2295 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2296 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2297 ni 0 env (PCase _ c os) = ni 0 env c ++
2298 -- names in 'os', not counting the names bound in the cases
2299 (nub (concatMap (ni 0 env) (map snd os))
2300 \\ nub (concatMap (ni 0 env) (map fst os)))
2301 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2302 ni 0 env (PLam fc n nfc ty sc) = ni 0 env ty ++ ni 0 (n:env) sc
2303 ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc
2304 ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r
2305 ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r
2306 ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r
2307 ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r
2308 ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r
2309 ni 0 env (PAlternative ns a as) = concatMap (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) = ni (i + 1) env tm ++ maybe [] (ni i env) ty
2316 ni i env (PUnquote tm) = ni (i - 1) env tm
2318 ni i env tm = concatMap (ni i env) (children tm)
2320 niTacImp i env (TacImp _ _ scr) = ni i env scr
2321 niTacImp _ _ _ = []
2323-- Return which of the given names are used in the given term.
2325usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
2326usedNamesIn vars ist tm = nub $ ni 0 [] tm
2327 where -- TODO THINK added niTacImp, but is it right?
2328 ni 0 env (PRef _ _ n)
2329 | n `elem` vars && not (n `elem` env)
2330 = case lookupDefExact n (tt_ctxt ist) of
2331 Nothing -> [n]
2332 _ -> []
2333 ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2334 ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as)
2335 ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os)
2336 ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f]
2337 ni 0 env (PLam fc n _ 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 the list of inaccessible (= dotted) positions for a name.
2359getErasureInfo :: IState -> Name -> [Int]
2360getErasureInfo ist n =
2361 case lookupCtxtExact n (idris_optimisation ist) of
2362 Just (Optimise inacc detagg) -> map fst inacc
2363 Nothing -> []