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