on 77ea792 help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1698 lines 68 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntaxTree where
6import Idris.Core.TT
7import Idris.Core.Evaluate
8import Idris.Core.Elaborate hiding (Tactic(..))
9import Idris.Core.Typecheck
10import Idris.Docstrings
11import IRTS.Lang
12import IRTS.CodegenCommon
13import Util.Pretty
14import Util.DynamicLinker
16import Idris.Colours
18import Paths_idris
20import System.Console.Haskeline
21import System.IO
23import Control.Monad.Trans.State.Strict
24import Control.Monad.Trans.Error
26import Data.List hiding (group)
27import Data.Char
28import qualified Data.Map as M
29import qualified Data.Text as T
30import qualified Data.Map as M
31import Data.Either
32import qualified Data.Set as S
33import Data.Word (Word)
34import Data.Maybe (fromMaybe)
36import Debug.Trace
38import Text.PrettyPrint.Annotated.Leijen
40-- Data to pass to recursively called elaborators; e.g. for where blocks,
41-- paramaterised declarations, etc.
43data ElabInfo = EInfo { params :: [(Name, PTerm)],
44 inblock :: Ctxt [Name], -- names in the block, and their params
45 liftname :: Name -> Name,
46 namespace :: Maybe [String] }
48toplevel = EInfo [] emptyContext id Nothing
50eInfoNames :: ElabInfo -> [Name]
51eInfoNames info = map fst (params info) ++ M.keys (inblock info)
53data IOption = IOption { opt_logLevel :: Int,
54 opt_typecase :: Bool,
55 opt_typeintype :: Bool,
56 opt_coverage :: Bool,
57 opt_showimp :: Bool, -- ^^ show implicits
58 opt_errContext :: Bool,
59 opt_repl :: Bool,
60 opt_verbose :: Bool,
61 opt_nobanner :: Bool,
62 opt_quiet :: Bool,
63 opt_codegen :: Codegen,
64 opt_outputTy :: OutputType,
65 opt_ibcsubdir :: FilePath,
66 opt_importdirs :: [FilePath],
67 opt_triple :: String,
68 opt_cpu :: String,
69 opt_optLevel :: Word,
70 opt_cmdline :: [Opt], -- remember whole command line
71 opt_origerr :: Bool,
72 opt_autoSolve :: Bool -- ^ automatically apply "solve" tactic in prover
73 }
74 deriving (Show, Eq)
76defaultOpts = IOption { opt_logLevel = 0
77 , opt_typecase = False
78 , opt_typeintype = False
79 , opt_coverage = True
80 , opt_showimp = False
81 , opt_errContext = False
82 , opt_repl = True
83 , opt_verbose = True
84 , opt_nobanner = False
85 , opt_quiet = False
86 , opt_codegen = ViaC
87 , opt_outputTy = Executable
88 , opt_ibcsubdir = ""
89 , opt_importdirs = []
90 , opt_triple = ""
91 , opt_cpu = ""
92 , opt_optLevel = 2
93 , opt_cmdline = []
94 , opt_origerr = False
95 , opt_autoSolve = True
96 }
98data PPOption = PPOption {
99 ppopt_impl :: Bool -- ^^ whether to show implicits
100} deriving (Show)
102-- | Pretty printing options with default verbosity.
103defaultPPOption :: PPOption
104defaultPPOption = PPOption { ppopt_impl = False }
106-- | Pretty printing options with the most verbosity.
107verbosePPOption :: PPOption
108verbosePPOption = PPOption { ppopt_impl = True }
110-- | Get pretty printing options from the big options record.
111ppOption :: IOption -> PPOption
112ppOption opt = PPOption {
113 ppopt_impl = opt_showimp opt
116-- | Get pretty printing options from an idris state record.
117ppOptionIst :: IState -> PPOption
118ppOptionIst = ppOption . idris_options
120data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
122-- | The output mode in use
123data OutputMode = RawOutput | IdeSlave Integer deriving Show
125-- | How wide is the console?
126data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
127 | ColsWide Int -- ^ Manually specified - must be positive
128 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
130-- | The global state used in the Idris monad
131data IState = IState {
132 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
133 idris_constraints :: [(UConstraint, FC)],
134 -- ^ A list of universe constraints and their corresponding source locations
135 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
136 idris_implicits :: Ctxt [PArg],
137 idris_statics :: Ctxt [Bool],
138 idris_classes :: Ctxt ClassInfo,
139 idris_dsls :: Ctxt DSL,
140 idris_optimisation :: Ctxt OptInfo,
141 idris_datatypes :: Ctxt TypeInfo,
142 idris_namehints :: Ctxt [Name],
143 idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
144 -- ^ list of lhs/rhs, and a list of missing clauses
145 idris_flags :: Ctxt [FnOpt],
146 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
147 idris_calledgraph :: Ctxt [Name],
148 idris_docstrings :: Ctxt (Docstring, [(Name, Docstring)]),
149 idris_tyinfodata :: Ctxt TIData,
150 idris_totcheck :: [(FC, Name)], -- names to check totality on
151 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
152 idris_totcheckfail :: [(FC, String)],
153 idris_options :: IOption,
154 idris_name :: Int,
155 idris_lineapps :: [((FilePath, Int), PTerm)],
156 -- ^ Full application LHS on source line
157 idris_metavars :: [(Name, (Maybe Name, Int, Bool))], -- ^ The currently defined but not proven metavariables
158 idris_coercions :: [Name],
159 idris_transforms :: [(Term, Term)],
160 idris_errRev :: [(Term, Term)],
161 syntax_rules :: [Syntax],
162 syntax_keywords :: [String],
163 imported :: [FilePath], -- ^ The imported modules
164 idris_scprims :: [(Name, (Int, PrimFn))],
165 idris_objs :: [(Codegen, FilePath)],
166 idris_libs :: [(Codegen, String)],
167 idris_cgflags :: [(Codegen, String)],
168 idris_hdrs :: [(Codegen, String)],
169 idris_imported :: [FilePath], -- ^ Imported ibc file names
170 proof_list :: [(Name, [String])],
171 errSpan :: Maybe FC,
172 parserWarnings :: [(FC, Err)],
173 lastParse :: Maybe Name,
174 indent_stack :: [Int],
175 brace_stack :: [Maybe Int],
176 lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
177 idris_parsedSpan :: Maybe FC,
178 hide_list :: [(Name, Maybe Accessibility)],
179 default_access :: Accessibility,
180 default_total :: Bool,
181 ibc_write :: [IBCWrite],
182 compiled_so :: Maybe String,
183 idris_dynamic_libs :: [DynamicLib],
184 idris_language_extensions :: [LanguageExt],
185 idris_outputmode :: OutputMode,
186 idris_colourRepl :: Bool,
187 idris_colourTheme :: ColourTheme,
188 idris_outh :: Handle,
189 idris_errorhandlers :: [Name], -- ^ Global error handlers
190 idris_nameIdx :: (Int, Ctxt (Int, Name)),
191 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
192 module_aliases :: M.Map [T.Text] [T.Text],
193 idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
194 idris_postulates :: S.Set Name,
195 idris_whocalls :: Maybe (M.Map Name [Name]),
196 idris_callswho :: Maybe (M.Map Name [Name])
197 }
199data SizeChange = Smaller | Same | Bigger | Unknown
200 deriving (Show, Eq)
201{-!
202deriving instance Binary SizeChange
203deriving instance NFData SizeChange
204!-}
206type SCGEntry = (Name, [Maybe (Int, SizeChange)])
207type UsageReason = (Name, Int) -- fn_name, its_arg_number
209data CGInfo = CGInfo { argsdef :: [Name],
210 calls :: [(Name, [[Name]])],
211 scg :: [SCGEntry],
212 argsused :: [Name],
213 usedpos :: [(Int, [UsageReason])] }
214 deriving Show
215{-!
216deriving instance Binary CGInfo
217deriving instance NFData CGInfo
218!-}
220primDefs = [sUN "unsafePerformPrimIO",
221 sUN "mkLazyForeignPrim",
222 sUN "mkForeignPrim",
223 sUN "FalseElim"]
225-- information that needs writing for the current module's .ibc file
226data IBCWrite = IBCFix FixDecl
227 | IBCImp Name
228 | IBCStatic Name
229 | IBCClass Name
230 | IBCInstance Bool Name Name
231 | IBCDSL Name
232 | IBCData Name
233 | IBCOpt Name
234 | IBCMetavar Name
235 | IBCSyntax Syntax
236 | IBCKeyword String
237 | IBCImport FilePath
238 | IBCObj Codegen FilePath
239 | IBCLib Codegen String
240 | IBCCGFlag Codegen String
241 | IBCDyLib String
242 | IBCHeader Codegen String
243 | IBCAccess Name Accessibility
244 | IBCMetaInformation Name MetaInformation
245 | IBCTotal Name Totality
246 | IBCFlags Name [FnOpt]
247 | IBCTrans (Term, Term)
248 | IBCErrRev (Term, Term)
249 | IBCCG Name
250 | IBCDoc Name
251 | IBCCoercion Name
252 | IBCDef Name -- i.e. main context
253 | IBCNameHint (Name, Name)
254 | IBCLineApp FilePath Int PTerm
255 | IBCErrorHandler Name
256 | IBCFunctionErrorHandler Name Name Name
257 | IBCPostulate Name
258 | IBCTotCheckErr FC String
259 | IBCParsedRegion FC
260 deriving Show
262-- | The initial state for the compiler
263idrisInit :: IState
264idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
265 emptyContext emptyContext emptyContext emptyContext
266 emptyContext emptyContext emptyContext emptyContext
267 emptyContext emptyContext
268 [] [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
269 [] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] [] RawOutput
270 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
271 AutomaticWidth S.empty Nothing Nothing
273-- | The monad for the main REPL - reading and processing files and updating
274-- global state (hence the IO inner monad).
275--type Idris = WriterT [Either String (IO ())] (State IState a))
276type Idris = StateT IState (ErrorT Err IO)
278-- Commands in the REPL
280data Codegen = ViaC
281 | ViaJava
282 | ViaNode
283 | ViaJavaScript
284 | ViaLLVM
285 | Bytecode
286 deriving (Show, Eq)
288-- | REPL commands
289data Command = Quit
290 | Help
291 | Eval PTerm
292 | Check PTerm
293 | DocStr (Either Name Const)
294 | TotCheck Name
295 | Reload
296 | Load FilePath (Maybe Int) -- up to maximum line number
297 | ChangeDirectory FilePath
298 | ModImport String
299 | Edit
300 | Compile Codegen String
301 | Execute
302 | ExecVal PTerm
303 | Metavars
304 | Prove Name
305 | AddProof (Maybe Name)
306 | RmProof Name
307 | ShowProof Name
308 | Proofs
309 | Universes
310 | LogLvl Int
311 | Spec PTerm
312 | HNF PTerm
313 | TestInline PTerm
314 | Defn Name
315 | Missing Name
316 | DynamicLink FilePath
317 | ListDynamic
318 | Pattelab PTerm
319 | DebugInfo Name
320 | Search PTerm
321 | CaseSplitAt Bool Int Name
322 | AddClauseFrom Bool Int Name
323 | AddProofClauseFrom Bool Int Name
324 | AddMissing Bool Int Name
325 | MakeWith Bool Int Name
326 | MakeLemma Bool Int Name
327 | DoProofSearch Bool Bool Int Name [Name]
328 -- ^ the first bool is whether to update,
329 -- the second is whether to search recursively (i.e. for the arguments)
330 | SetOpt Opt
331 | UnsetOpt Opt
332 | NOP
333 | SetColour ColourType IdrisColour
334 | ColourOn
335 | ColourOff
336 | ListErrorHandlers
337 | SetConsoleWidth ConsoleWidth
338 | Apropos String
339 | WhoCalls Name
340 | CallsWho Name
341 | MakeDoc String -- IdrisDoc
344data Opt = Filename String
345 | Quiet
346 | NoBanner
347 | ColourREPL Bool
348 | Ideslave
349 | ShowLibs
350 | ShowLibdir
351 | ShowIncs
352 | NoBasePkgs
353 | NoPrelude
354 | NoBuiltins -- only for the really primitive stuff!
355 | NoREPL
356 | OLogging Int
357 | Output String
358 | TypeCase
359 | TypeInType
360 | DefaultTotal
361 | DefaultPartial
362 | WarnPartial
363 | WarnReach
364 | NoCoverage
365 | ErrContext
366 | ShowImpl
367 | Verbose
368 | IBCSubDir String
369 | ImportDir String
370 | PkgBuild String
371 | PkgInstall String
372 | PkgClean String
373 | PkgCheck String
374 | PkgREPL String
375 | PkgMkDoc String -- IdrisDoc
376 | WarnOnly
377 | Pkg String
378 | BCAsm String
379 | DumpDefun String
380 | DumpCases String
381 | UseCodegen Codegen
382 | OutputTy OutputType
383 | Extension LanguageExt
384 | InterpretScript String
385 | EvalExpr String
386 | TargetTriple String
387 | TargetCPU String
388 | OptLevel Word
389 | Client String
390 | ShowOrigErr
391 | AutoWidth -- ^ Automatically adjust terminal width
392 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
393 deriving (Show, Eq)
395-- Parsed declarations
397data Fixity = Infixl { prec :: Int }
398 | Infixr { prec :: Int }
399 | InfixN { prec :: Int }
400 | PrefixN { prec :: Int }
401 deriving Eq
402{-!
403deriving instance Binary Fixity
404deriving instance NFData Fixity
405!-}
407instance Show Fixity where
408 show (Infixl i) = "infixl " ++ show i
409 show (Infixr i) = "infixr " ++ show i
410 show (InfixN i) = "infix " ++ show i
411 show (PrefixN i) = "prefix " ++ show i
413data FixDecl = Fix Fixity String
414 deriving Eq
416instance Show FixDecl where
417 show (Fix f s) = show f ++ " " ++ s
419{-!
420deriving instance Binary FixDecl
421deriving instance NFData FixDecl
422!-}
424instance Ord FixDecl where
425 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
428data Static = Static | Dynamic
429 deriving (Show, Eq)
430{-!
431deriving instance Binary Static
432deriving instance NFData Static
433!-}
435-- Mark bindings with their explicitness, and laziness
436data Plicity = Imp { pargopts :: [ArgOpt],
437 pstatic :: Static,
438 pparam :: Bool }
439 | Exp { pargopts :: [ArgOpt],
440 pstatic :: Static,
441 pparam :: Bool } -- this is a param (rather than index)
442 | Constraint { pargopts :: [ArgOpt],
443 pstatic :: Static }
444 | TacImp { pargopts :: [ArgOpt],
445 pstatic :: Static,
446 pscript :: PTerm }
447 deriving (Show, Eq)
449{-!
450deriving instance Binary Plicity
451deriving instance NFData Plicity
452!-}
454impl = Imp [] Dynamic False
455expl = Exp [] Dynamic False
456expl_param = Exp [] Dynamic True
457constraint = Constraint [] Dynamic
458tacimpl t = TacImp [] Dynamic t
460data FnOpt = Inlinable -- always evaluate when simplifying
461 | TotalFn | PartialFn | CoveringFn
462 | Coinductive | AssertTotal
463 | Dictionary -- type class dictionary, eval only when
464 -- a function argument, and further evaluation resutls
465 | Implicit -- implicit coercion
466 | CExport String -- export, with a C name
467 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
468 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
469 | Reflection -- a reflecting function, compile-time only
470 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
471 deriving (Show, Eq)
472{-!
473deriving instance Binary FnOpt
474deriving instance NFData FnOpt
475!-}
477type FnOpts = [FnOpt]
479inlinable :: FnOpts -> Bool
480inlinable = elem Inlinable
482dictionary :: FnOpts -> Bool
483dictionary = elem Dictionary
486-- | Data declaration options
487data DataOpt = Codata -- Set if the the data-type is coinductive
488 | DefaultEliminator -- Set if an eliminator should be generated for data type
489 | DataErrRev
490 deriving (Show, Eq)
492type DataOpts = [DataOpt]
494-- | Type provider - what to provide
495data ProvideWhat = ProvTerm -- ^ only allow providing terms
496 | ProvPostulate -- ^ only allow postulates
497 | ProvAny -- ^ either is ok
498 deriving (Show, Eq)
500-- | Top-level declarations such as compiler directives, definitions,
501-- datatypes and typeclasses.
502data PDecl' t
503 = PFix FC Fixity [String] -- ^ Fixity declaration
504 | PTy Docstring [(Name, Docstring)] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
505 | PPostulate Docstring SyntaxInfo FC FnOpts Name t -- ^ Postulate
506 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
507 | PCAF FC Name t -- ^ Top level constant
508 | PData Docstring [(Name, Docstring)] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
509 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
510 | PNamespace String [PDecl' t] -- ^ New namespace
511 | PRecord Docstring SyntaxInfo FC Name t DataOpts Docstring Name t -- ^ Record declaration
512 | PClass Docstring SyntaxInfo FC
513 [t] -- constraints
514 Name
515 [(Name, t)] -- parameters
516 [(Name, Docstring)] -- parameter docstrings
517 [PDecl' t] -- declarations
518 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
519 -- class name, parameters, method declarations
520 | PInstance SyntaxInfo FC [t] -- constraints
521 Name -- class
522 [t] -- parameters
523 t -- full instance type
524 (Maybe Name) -- explicit name
525 [PDecl' t]
526 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
527 -- class name, parameters, full instance type, optional explicit name, and definitions
528 | PDSL Name (DSL' t) -- ^ DSL declaration
529 | PSyntax FC Syntax -- ^ Syntax definition
530 | PMutual FC [PDecl' t] -- ^ Mutual block
531 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
532 | PProvider SyntaxInfo FC ProvideWhat Name t t -- ^ Type provider. The first t is the type, the second is the term
533 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
534 -- bool is True, lhs and rhs must be convertible
535 deriving Functor
536{-!
537deriving instance Binary PDecl'
538deriving instance NFData PDecl'
539!-}
541-- For elaborator state
542type ElabD a = Elab' [PDecl] a
544-- | One clause of a top-level definition. Term arguments to constructors are:
545--
546-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
547--
548-- 2. The list of extra 'with' patterns
549--
550-- 3. The right-hand side
551--
552-- 4. The where block (PDecl' t)
554data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
555 | PWith FC Name t [t] t [PDecl' t]
556 | PClauseR FC [t] t [PDecl' t]
557 | PWithR FC [t] t [PDecl' t]
558 deriving Functor
559{-!
560deriving instance Binary PClause'
561deriving instance NFData PClause'
562!-}
564-- | Data declaration
565data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
566 d_tcon :: t, -- ^ Type constructor
567 d_cons :: [(Docstring, [(Name, Docstring)], Name, t, FC, [Name])] -- ^ Constructors
568 }
569 -- ^ Data declaration
570 | PLaterdecl { d_name :: Name, d_tcon :: t }
571 -- ^ "Placeholder" for data whose constructors are defined later
572 deriving Functor
573{-!
574deriving instance Binary PData'
575deriving instance NFData PData'
576!-}
578-- Handy to get a free function for applying PTerm -> PTerm functions
579-- across a program, by deriving Functor
581type PDecl = PDecl' PTerm
582type PData = PData' PTerm
583type PClause = PClause' PTerm
585-- get all the names declared in a decl
587declared :: PDecl -> [Name]
588declared (PFix _ _ _) = []
589declared (PTy _ _ _ _ _ n t) = [n]
590declared (PPostulate _ _ _ _ n t) = [n]
591declared (PClauses _ _ n _) = [] -- not a declaration
592declared (PCAF _ n _) = [n]
593declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
594 where fstt (_, _, a, _, _, _) = a
595declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
596declared (PParams _ _ ds) = concatMap declared ds
597declared (PNamespace _ ds) = concatMap declared ds
598declared (PRecord _ _ _ n _ _ _ c _) = [n, c]
599declared (PClass _ _ _ _ n _ _ ms) = n : concatMap declared ms
600declared (PInstance _ _ _ _ _ _ _ _) = []
601declared (PDSL n _) = [n]
602declared (PSyntax _ _) = []
603declared (PMutual _ ds) = concatMap declared ds
604declared (PDirective _) = []
606-- get the names declared, not counting nested parameter blocks
607tldeclared :: PDecl -> [Name]
608tldeclared (PFix _ _ _) = []
609tldeclared (PTy _ _ _ _ _ n t) = [n]
610tldeclared (PPostulate _ _ _ _ n t) = [n]
611tldeclared (PClauses _ _ n _) = [] -- not a declaration
612tldeclared (PRecord _ _ _ n _ _ _ c _) = [n, c]
613tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
614 where fstt (_, _, a, _, _, _) = a
615tldeclared (PParams _ _ ds) = []
616tldeclared (PMutual _ ds) = concatMap tldeclared ds
617tldeclared (PNamespace _ ds) = concatMap tldeclared ds
618tldeclared (PClass _ _ _ _ n _ _ ms) = concatMap tldeclared ms
619tldeclared (PInstance _ _ _ _ _ _ _ _) = []
620tldeclared _ = []
622defined :: PDecl -> [Name]
623defined (PFix _ _ _) = []
624defined (PTy _ _ _ _ _ n t) = []
625defined (PPostulate _ _ _ _ n t) = []
626defined (PClauses _ _ n _) = [n] -- not a declaration
627defined (PCAF _ n _) = [n]
628defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
629 where fstt (_, _, a, _, _, _) = a
630defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
631defined (PParams _ _ ds) = concatMap defined ds
632defined (PNamespace _ ds) = concatMap defined ds
633defined (PRecord _ _ _ n _ _ _ c _) = [n, c]
634defined (PClass _ _ _ _ n _ _ ms) = n : concatMap defined ms
635defined (PInstance _ _ _ _ _ _ _ _) = []
636defined (PDSL n _) = [n]
637defined (PSyntax _ _) = []
638defined (PMutual _ ds) = concatMap defined ds
639defined (PDirective _) = []
640--defined _ = []
642updateN :: [(Name, Name)] -> Name -> Name
643updateN ns n | Just n' <- lookup n ns = n'
644updateN _ n = n
646updateNs :: [(Name, Name)] -> PTerm -> PTerm
647updateNs [] t = t
648updateNs ns t = mapPT updateRef t
649 where updateRef (PRef fc f) = PRef fc (updateN ns f)
650 updateRef t = t
652-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
653-- updateDNs [] t = t
654-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
655-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
656-- where updateCNs ns (PClause n l ts r ds)
657-- = PClause (updateN ns n) (fmap (updateNs ns) l)
658-- (map (fmap (updateNs ns)) ts)
659-- (fmap (updateNs ns) r)
660-- (map (updateDNs ns) ds)
661-- updateDNs ns c = c
663data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
665-- | High level language terms
666data PTerm = PQuote Raw
667 | PRef FC Name
668 | PInferRef FC Name -- ^ A name to be defined later
669 | PPatvar FC Name
670 | PLam Name PTerm PTerm
671 | PPi Plicity Name PTerm PTerm -- ^ (n : t1) -> t2
672 | PLet Name PTerm PTerm PTerm
673 | PTyped PTerm PTerm -- ^ Term with explicit type
674 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
675 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
676 | PMatchApp FC Name -- ^ Make an application by type matching
677 | PCase FC PTerm [(PTerm, PTerm)]
678 | PTrue FC PunInfo -- ^ Unit type..?
679 | PFalse FC -- ^ _|_
680 | PRefl FC PTerm
681 | PResolveTC FC
682 | PEq FC PTerm PTerm -- ^ Equality type: A = B
683 | PRewrite FC PTerm PTerm (Maybe PTerm)
684 | PPair FC PunInfo PTerm PTerm
685 | PDPair FC PunInfo PTerm PTerm PTerm
686 | PAlternative Bool [PTerm] -- True if only one may work
687 | PHidden PTerm -- ^ Irrelevant or hidden pattern
688 | PType -- ^ 'Type' type
689 | PGoal FC PTerm Name PTerm
690 | PConstant Const -- ^ Builtin types
691 | Placeholder
692 | PDoBlock [PDo]
693 | PIdiom FC PTerm
694 | PReturn FC
695 | PMetavar Name
696 | PProof [PTactic] -- ^ Proof script
697 | PTactics [PTactic] -- ^ As PProof, but no auto solving
698 | PElabError Err -- ^ Error to report on elaboration
699 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
700 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
701 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
702 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
703 | PNoImplicits PTerm -- ^ never run implicit converions on the term
704 deriving Eq
707{-!
708deriving instance Binary PTerm
709deriving instance NFData PTerm
710!-}
712mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
713mapPT f t = f (mpt t) where
714 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
715 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
716 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
717 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
718 (fmap (mapPT f) g)
719 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
720 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
721 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
722 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
723 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
724 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
725 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
726 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
727 mpt (PHidden t) = PHidden (mapPT f t)
728 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
729 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
730 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
731 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
732 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
733 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
734 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
735 mpt x = x
738data PTactic' t = Intro [Name] | Intros | Focus Name
739 | Refine Name [Bool] | Rewrite t | DoUnify
740 | Induction Name
741 | Equiv t
742 | MatchRefine Name
743 | LetTac Name t | LetTacTy Name t t
744 | Exact t | Compute | Trivial | TCInstance
745 | ProofSearch Bool Bool Int (Maybe Name) [Name]
746 -- ^ the bool is whether to search recursively
747 | Solve
748 | Attack
749 | ProofState | ProofTerm | Undo
750 | Try (PTactic' t) (PTactic' t)
751 | TSeq (PTactic' t) (PTactic' t)
752 | ApplyTactic t -- see Language.Reflection module
753 | ByReflection t
754 | Reflect t
755 | Fill t
756 | GoalType String (PTactic' t)
757 | TCheck t
758 | TEval t
759 | Qed | Abandon
760 deriving (Show, Eq, Functor)
761{-!
762deriving instance Binary PTactic'
763deriving instance NFData PTactic'
764!-}
765instance Sized a => Sized (PTactic' a) where
766 size (Intro nms) = 1 + size nms
767 size Intros = 1
768 size (Focus nm) = 1 + size nm
769 size (Refine nm bs) = 1 + size nm + length bs
770 size (Rewrite t) = 1 + size t
771 size (Induction t) = 1 + size t
772 size (LetTac nm t) = 1 + size nm + size t
773 size (Exact t) = 1 + size t
774 size Compute = 1
775 size Trivial = 1
776 size Solve = 1
777 size Attack = 1
778 size ProofState = 1
779 size ProofTerm = 1
780 size Undo = 1
781 size (Try l r) = 1 + size l + size r
782 size (TSeq l r) = 1 + size l + size r
783 size (ApplyTactic t) = 1 + size t
784 size (Reflect t) = 1 + size t
785 size (Fill t) = 1 + size t
786 size Qed = 1
787 size Abandon = 1
789type PTactic = PTactic' PTerm
791data PDo' t = DoExp FC t
792 | DoBind FC Name t
793 | DoBindP FC t t [(t,t)]
794 | DoLet FC Name t t
795 | DoLetP FC t t
796 deriving (Eq, Functor)
797{-!
798deriving instance Binary PDo'
799deriving instance NFData PDo'
800!-}
802instance Sized a => Sized (PDo' a) where
803 size (DoExp fc t) = 1 + size fc + size t
804 size (DoBind fc nm t) = 1 + size fc + size nm + size t
805 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
806 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
807 size (DoLetP fc l r) = 1 + size fc + size l + size r
809type PDo = PDo' PTerm
811-- The priority gives a hint as to elaboration order. Best to elaborate
812-- things early which will help give a more concrete type to other
813-- variables, e.g. a before (interpTy a).
815data PArg' t = PImp { priority :: Int,
816 machine_inf :: Bool, -- true if the machine inferred it
817 argopts :: [ArgOpt],
818 pname :: Name, getTm :: t }
819 | PExp { priority :: Int,
820 argopts :: [ArgOpt],
821 pname :: Name,
822 getTm :: t }
823 | PConstraint { priority :: Int,
824 argopts :: [ArgOpt],
825 pname :: Name,
826 getTm :: t }
827 | PTacImplicit { priority :: Int,
828 argopts :: [ArgOpt],
829 pname :: Name,
830 getScript :: t,
831 getTm :: t }
832 deriving (Show, Eq, Functor)
834data ArgOpt = HideDisplay | InaccessibleArg
835 deriving (Show, Eq)
837instance Sized a => Sized (PArg' a) where
838 size (PImp p _ l nm trm) = 1 + size nm + size trm
839 size (PExp p l nm trm) = 1 + size nm + size trm
840 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
841 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
843{-!
844deriving instance Binary PArg'
845deriving instance NFData PArg'
846!-}
848pimp n t mach = PImp 1 mach [] n t
849pexp t = PExp 1 [] (sMN 0 "arg") t
850pconst t = PConstraint 1 [] (sMN 0 "carg") t
851ptacimp n s t = PTacImplicit 2 [] n s t
853type PArg = PArg' PTerm
855-- Type class data
857data ClassInfo = CI { instanceName :: Name,
858 class_methods :: [(Name, (FnOpts, PTerm))],
859 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
860 class_default_superclasses :: [PDecl],
861 class_params :: [Name],
862 class_instances :: [Name] }
863 deriving Show
864{-!
865deriving instance Binary ClassInfo
866deriving instance NFData ClassInfo
867!-}
869-- Type inference data
871data TIData = TIPartial -- ^ a function with a partially defined type
872 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
873 deriving Show
875data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
876 detaggable :: Bool }
877 deriving Show
878{-!
879deriving instance Binary OptInfo
880deriving instance NFData OptInfo
881!-}
884data TypeInfo = TI { con_names :: [Name],
885 codata :: Bool,
886 data_opts :: DataOpts,
887 param_pos :: [Int] }
888 deriving Show
889{-!
890deriving instance Binary TypeInfo
891deriving instance NFData TypeInfo
892!-}
894-- Syntactic sugar info
896data DSL' t = DSL { dsl_bind :: t,
897 dsl_return :: t,
898 dsl_apply :: t,
899 dsl_pure :: t,
900 dsl_var :: Maybe t,
901 index_first :: Maybe t,
902 index_next :: Maybe t,
903 dsl_lambda :: Maybe t,
904 dsl_let :: Maybe t
905 }
906 deriving (Show, Functor)
907{-!
908deriving instance Binary DSL'
909deriving instance NFData DSL'
910!-}
912type DSL = DSL' PTerm
914data SynContext = PatternSyntax | TermSyntax | AnySyntax
915 deriving Show
916{-!
917deriving instance Binary SynContext
918deriving instance NFData SynContext
919!-}
921data Syntax = Rule [SSymbol] PTerm SynContext
922 deriving Show
923{-!
924deriving instance Binary Syntax
925deriving instance NFData Syntax
926!-}
928data SSymbol = Keyword Name
929 | Symbol String
930 | Binding Name
931 | Expr Name
932 | SimpleExpr Name
933 deriving Show
934{-!
935deriving instance Binary SSymbol
936deriving instance NFData SSymbol
937!-}
939initDSL = DSL (PRef f (sUN ">>="))
940 (PRef f (sUN "return"))
941 (PRef f (sUN "<$>"))
942 (PRef f (sUN "pure"))
943 Nothing
944 Nothing
945 Nothing
946 Nothing
947 Nothing
948 where f = fileFC "(builtin)"
950data Using = UImplicit Name PTerm
951 | UConstraint Name [Name]
952 deriving (Show, Eq)
953{-!
954deriving instance Binary Using
955deriving instance NFData Using
956!-}
958data SyntaxInfo = Syn { using :: [Using],
959 syn_params :: [(Name, PTerm)],
960 syn_namespace :: [String],
961 no_imp :: [Name],
962 decoration :: Name -> Name,
963 inPattern :: Bool,
964 implicitAllowed :: Bool,
965 maxline :: Maybe Int,
966 dsl_info :: DSL }
967 deriving Show
968{-!
969deriving instance NFData SyntaxInfo
970deriving instance Binary SyntaxInfo
971!-}
973defaultSyntax = Syn [] [] [] [] id False False Nothing initDSL
975expandNS :: SyntaxInfo -> Name -> Name
976expandNS syn n@(NS _ _) = n
977expandNS syn n = case syn_namespace syn of
978 [] -> n
979 xs -> sNS n xs
982-- For inferring types of things
984bi = fileFC "builtin"
986inferTy = sMN 0 "__Infer"
987inferCon = sMN 0 "__infer"
988inferDecl = PDatadecl inferTy
989 PType
990 [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType (
991 PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType"))
992 (PRef bi inferTy)), bi, [])]
993inferOpts = []
995infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
996infP = P (TCon 6 0) inferTy (TType (UVal 0))
998getInferTerm, getInferType :: Term -> Term
999getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
1000getInferTerm (App (App _ _) tm) = tm
1001getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1003getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1004 where toTy (Lam t) = Pi t
1005 toTy (PVar t) = PVTy t
1006 toTy b = b
1007getInferType (App (App _ ty) _) = ty
1011-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign, Elim type class
1013primNames = [unitTy, unitCon,
1014 falseTy, pairTy, pairCon,
1015 eqTy, eqCon, inferTy, inferCon]
1017unitDoc = parseDocstring . T.pack $ "The canonical single-element type, also known as the trivially true proposition."
1018unitTy = sMN 0 "__Unit"
1019unitCon = sMN 0 "__II"
1020unitDecl = PDatadecl unitTy PType
1021 [(parseDocstring . T.pack $ "The trivial constructor for `()`. ", [], unitCon, PRef bi unitTy, bi, [])]
1022unitOpts = [DefaultEliminator]
1024falseDoc = parseDocstring . T.pack $
1025 "The empty type, also known as the trivially false proposition." ++
1026 "\n\n" ++
1027 "Use `FalseElim` or `absurd` to prove anything if you have a variable " ++
1028 "of type `_|_` in scope."
1029falseTy = sMN 0 "__False"
1030falseDecl = PDatadecl falseTy PType []
1031falseOpts = []
1033pairDoc = parseDocstring . T.pack $ "The non-dependent pair type, also known as conjunction."
1034pairTy = sMN 0 "__Pair"
1035pairCon = sMN 0 "__MkPair"
1036pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
1037 [(pairConDoc, pairConParamDoc,
1038 pairCon, PPi impl (n "A") PType (
1039 PPi impl (n "B") PType (
1040 PPi expl (n "a") (PRef bi (n "A")) (
1041 PPi expl (n "b") (PRef bi (n "B"))
1042 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
1043 pexp (PRef bi (n "B"))])))), bi, [])]
1044 where n a = sMN 0 a
1045 pairConDoc = parseDocstring . T.pack $ "A pair of elements"
1046 pairConParamDoc = [(n "a", parseDocstring . T.pack $ "the left element of the pair"),
1047 (n "b", parseDocstring . T.pack $ "the right element of the pair")]
1048pairOpts = []
1049pairParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left elements in the pair"),
1050 (n "B", parseDocstring . T.pack $ "the type of the left elements in the pair")]
1051 where n a = sMN 0 a
1053eqTy = sUN "="
1054eqCon = sUN "refl"
1055eqDoc = parseDocstring . T.pack $
1056 "The propositional equality type. A proof that `x` = `y`." ++
1057 "\n\n" ++
1058 "To use such a proof, pattern-match on it, and the two equal things will " ++
1059 "then need to be the _same_ pattern." ++
1060 "\n\n" ++
1061 "**Note**: Idris's equality type is _heterogeneous_, which means that it " ++
1062 "is possible to state equalities between values of potentially different " ++
1063 "types. This is sometimes referred to in the literature as \"John Major\" " ++
1064 "equality." ++
1065 "\n\n" ++
1066 "Thus, if Idris can't infer the type of one side of the equality, then " ++
1067 "you may need to annotate it. See the function `the`."
1069eqDecl = PDatadecl eqTy (piBind [(n "A", PType), (n "B", PType),
1070 (n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))]
1071 PType)
1072 [(reflDoc, reflParamDoc,
1073 eqCon, PPi impl (n "A") PType (
1074 PPi impl (n "x") (PRef bi (n "A"))
1075 (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False,
1076 pimp (n "B") Placeholder False,
1077 pexp (PRef bi (n "x")),
1078 pexp (PRef bi (n "x"))])), bi, [])]
1079 where n a = sMN 0 a
1080 reflDoc = parseDocstring . T.pack $
1081 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1082 "shown that both sides are in fact equal."
1083 reflParamDoc = [(n "A", parseDocstring . T.pack $ "the type at which the equality is proven"),
1084 (n "x", parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1086eqParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left side of the equality"),
1087 (n "B", parseDocstring . T.pack $ "the type of the right side of the equality")
1089 where n a = sMN 0 a
1091eqOpts = []
1093elimName = sUN "__Elim"
1094elimMethElimTy = sUN "__elimTy"
1095elimMethElim = sUN "elim"
1096elimDecl = PClass (parseDocstring . T.pack $ "Type class for eliminators") defaultSyntax bi [] elimName [(sUN "scrutineeType", PType)] []
1097 [PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElimTy PType,
1098 PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElim (PRef bi elimMethElimTy)]
1100-- Defined in builtins.idr
1101sigmaTy = sUN "Pair"
1102existsCon = sUN "pair"
1104piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1105piBind = piBindp expl
1107piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1108piBindp p [] t = t
1109piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t)
1112-- Pretty-printing declarations and terms
1114-- These "show" instances render to an absurdly wide screen because inserted line breaks
1115-- could interfere with interactive editing, which calls "show".
1117instance Show PTerm where
1118 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1120instance Show PDecl where
1121 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp defaultPPOption) d
1123instance Show PClause where
1124 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1126instance Show PData where
1127 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1129instance Pretty PTerm OutputAnnotation where
1130 pretty = prettyImp defaultPPOption
1132-- | Colourise annotations according to an Idris state. It ignores the names
1133-- in the annotation, as there's no good way to show extended information on a
1134-- terminal.
1135consoleDecorate :: IState -> OutputAnnotation -> String -> String
1136consoleDecorate ist _ | not (idris_colourRepl ist) = id
1137consoleDecorate ist (AnnConst c) = let theme = idris_colourTheme ist
1138 in if constIsType c
1139 then colouriseType theme
1140 else colouriseData theme
1141consoleDecorate ist (AnnData _ _) = colouriseData (idris_colourTheme ist)
1142consoleDecorate ist (AnnType _ _) = colouriseType (idris_colourTheme ist)
1143consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
1144consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
1145consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1146consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1147 theme = idris_colourTheme ist
1148 in case () of
1149 _ | isDConName n ctxt -> colouriseData theme
1150 _ | isFnName n ctxt -> colouriseFun theme
1151 _ | isTConName n ctxt -> colouriseType theme
1152 _ | otherwise -> id -- don't colourise unknown names
1153consoleDecorate ist (AnnFC _) = id
1154consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
1155 where colour BoldText = IdrisColour Nothing True False True False
1156 colour UnderlineText = IdrisColour Nothing True True False False
1157 colour ItalicText = IdrisColour Nothing True False False True
1159-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1160prettyImp :: PPOption -- ^^ pretty printing options
1161 -> PTerm -- ^^ the term to pretty-print
1162 -> Doc OutputAnnotation
1163prettyImp impl = pprintPTerm impl [] [] []
1165-- | Do the right thing for rendering a term in an IState
1166prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1167prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1169-- | Pretty-print a high-level Idris term in some bindings context with infix info
1170pprintPTerm :: PPOption -- ^^ pretty printing options
1171 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1172 -> [Name] -- ^^ names to always show in pi, even if not used
1173 -> [FixDecl] -- ^^ Fixity declarations
1174 -> PTerm -- ^^ the term to pretty-print
1175 -> Doc OutputAnnotation
1176pprintPTerm ppo bnd docArgs infixes = prettySe 10 bnd
1177 where
1178 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1179 prettySe p bnd (PQuote r) =
1180 text "![" <> pretty r <> text "]"
1181 prettySe p bnd (PPatvar fc n) = pretty n
1182 prettySe p bnd e
1183 | Just str <- slist p bnd e = str
1184 | Just n <- snat p e = annotate (AnnData "Nat" "") (text (show n))
1185 prettySe p bnd (PRef fc n) = prettyName (ppopt_impl ppo) bnd n
1186 prettySe p bnd (PLam n ty sc) =
1187 bracket p 2 . group . align . hang 2 $
1188 text "\\" <> bindingOf n False <+> text "=>" <$>
1189 prettySe 10 ((n, False):bnd) sc
1190 prettySe p bnd (PLet n ty v sc) =
1191 bracket p 2 $
1192 kwd "let" <+> bindingOf n False <+> text "=" </>
1193 prettySe 10 bnd v <+> kwd "in" </>
1194 prettySe 10 ((n, False):bnd) sc
1195 prettySe p bnd (PPi (Exp l s _) n ty sc)
1196 | n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs =
1197 bracket p 2 . group $
1198 enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1199 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1200 | otherwise =
1201 bracket p 2 . group $
1202 group (prettySe 1 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1203 where
1204 st =
1205 case s of
1206 Static -> text "[static]" <> space
1207 _ -> empty
1208 prettySe p bnd (PPi (Imp l s _) n ty sc)
1209 | ppopt_impl ppo =
1210 bracket p 2 $
1211 lbrace <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1212 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1213 | otherwise = prettySe 10 ((n, True):bnd) sc
1214 where
1215 st =
1216 case s of
1217 Static -> text "[static]" <> space
1218 _ -> empty
1219 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1220 bracket p 2 $
1221 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1222 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1223 bracket p 2 $
1224 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1225 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1226 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1227 | UN nm <- basename f
1228 , not (ppopt_impl ppo) && null (getExps args) =
1229 if isAlpha (thead nm)
1230 then prettyName (ppopt_impl ppo) bnd f
1231 else enclose lparen rparen $ prettyName (ppopt_impl ppo) bnd f
1232 prettySe p bnd (PAppBind _ (PRef _ f) [])
1233 | not (ppopt_impl ppo) = text "!" <> prettyName (ppopt_impl ppo) bnd f
1234 prettySe p bnd (PApp _ (PRef _ op) args) -- infix operators
1235 | UN nm <- basename op
1236 , not (tnull nm) &&
1237 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1238 case getExps args of
1239 [] -> enclose lparen rparen opName
1240 [x] -> group (enclose lparen rparen opName <$> group (prettySe 0 bnd x))
1241 [l,r] -> let precedence = fromMaybe 20 (fmap prec f)
1242 in bracket p precedence $ inFix l r
1243 (l:r:rest) -> bracket p 1 $
1244 enclose lparen rparen (inFix l r) <+>
1245 align (group (vsep (map (prettyArgSe bnd) rest)))
1246 where opName = prettyName (ppopt_impl ppo) bnd op
1247 f = getFixity (opStr op)
1248 left l = case f of
1249 Nothing -> prettySe (-1) bnd l
1250 Just (Infixl p') -> prettySe p' bnd l
1251 Just f' -> prettySe (prec f'-1) bnd l
1252 right r = case f of
1253 Nothing -> prettySe (-1) bnd r
1254 Just (Infixr p') -> prettySe p' bnd r
1255 Just f' -> prettySe (prec f'-1) bnd r
1256 inFix l r = align . group $
1257 (left l <+> opName) <$> group (right r)
1258 prettySe p bnd (PApp _ hd@(PRef fc f) [tm]) -- symbols, like 'foo
1259 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1260 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1261 char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1262 prettySe p bnd (PApp _ f as) = -- Normal prefix applications
1263 let args = getExps as
1264 fp = prettySe 1 bnd f
1265 in
1266 bracket p 1 . group $
1267 if ppopt_impl ppo
1268 then if null as
1269 then fp
1270 else fp <+> align (vsep (map (prettyArgS bnd) as))
1271 else if null args
1272 then fp
1273 else fp <+> align (vsep (map (prettyArgSe bnd) args))
1274 prettySe p bnd (PCase _ scr opts) =
1275 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1276 where
1277 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1279 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1280 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1281 prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
1282 prettySe p bnd (PResolveTC _) = text "resolvetc"
1283 prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1284 prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1285 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1286 prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
1287 prettySe p bnd (PEq _ l r) =
1288 bracket p 2 . align . group $
1289 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1290 where eq = annName eqTy (text "=")
1291 prettySe p bnd (PRewrite _ l r _) =
1292 bracket p 2 $
1293 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1294 prettySe p bnd (PTyped l r) =
1295 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1296 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1297 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1298 align . group . vsep . punctuate (ann comma) $
1299 map (prettySe 10 bnd) elts
1300 where ann = case pun of
1301 TypeOrTerm -> id
1302 IsType -> annName pairTy
1303 IsTerm -> annName pairCon
1304 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1305 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1306 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1307 annName sigmaTy lparen <>
1308 bindingOf n False <+>
1309 annName sigmaTy (text "**") <+>
1310 prettySe 10 ((n, False):bnd) r <>
1311 annName sigmaTy rparen
1312 prettySe p bnd (PDPair _ IsType l t r) =
1313 annName sigmaTy lparen <>
1314 prettySe 10 bnd l <+>
1315 annName sigmaTy (text "**") <+>
1316 prettySe 10 bnd r <>
1317 annName sigmaTy rparen
1318 prettySe p bnd (PDPair _ IsTerm l t r) =
1319 annName existsCon lparen <>
1320 prettySe 10 bnd l <+>
1321 annName existsCon (text "**") <+>
1322 prettySe 10 bnd r <>
1323 annName existsCon rparen
1324 prettySe p bnd (PAlternative a as) =
1325 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1326 where
1327 prettyAs =
1328 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1329 prettySe p bnd PType = annotate (AnnType "Type" "The type of types") $ text "Type"
1330 prettySe p bnd (PConstant c) = annotate (AnnConst c) (text (show c))
1331 -- XXX: add pretty for tactics
1332 prettySe p bnd (PProof ts) =
1333 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1334 prettySe p bnd (PTactics ts) =
1335 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1336 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1337 prettySe p bnd (PReturn f) = kwd "return"
1338 prettySe p bnd PImpossible = kwd "impossible"
1339 prettySe p bnd Placeholder = text "_"
1340 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1341 prettySe p bnd (PCoerced t) = prettySe p bnd t
1342 prettySe p bnd (PElabError s) = pretty s
1344 prettySe p bnd _ = text "test"
1346 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1347 prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm
1348 prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm
1349 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1351 prettyArgSe bnd arg = prettySe 0 bnd arg
1352 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1353 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1354 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1356 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1357 annName n = annotate (AnnName n Nothing Nothing Nothing)
1359 opStr :: Name -> String
1360 opStr (NS n _) = opStr n
1361 opStr (UN n) = T.unpack n
1363 basename :: Name -> Name
1364 basename (NS n _) = basename n
1365 basename n = n
1367 slist' p bnd (PApp _ (PRef _ nil) _)
1368 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1369 slist' p bnd (PRef _ nil)
1370 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1371 slist' p bnd (PApp _ (PRef _ cons) args)
1372 | nsroot cons == sUN "::",
1373 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1374 all isImp imps,
1375 Just tl' <- slist' p bnd tl
1376 = Just (hd:tl')
1377 where
1378 isImp (PImp {}) = True
1379 isImp _ = False
1380 slist' _ _ tm = Nothing
1382 slist p bnd e | Just es <- slist' p bnd e = Just $
1383 case es of [] -> annotate (AnnData "" "") $ text "[]"
1384 [x] -> enclose left right . group $
1385 prettySe p bnd x
1386 xs -> (enclose left right .
1387 align . group . vsep .
1388 punctuate comma .
1389 map (prettySe p bnd)) xs
1390 where left = (annotate (AnnData "" "") (text "["))
1391 right = (annotate (AnnData "" "") (text "]"))
1392 comma = (annotate (AnnData "" "") (text ","))
1393 slist _ _ _ = Nothing
1395 pairElts :: PTerm -> Maybe [PTerm]
1396 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1397 | otherwise = Just [x, y]
1398 pairElts _ = Nothing
1400 natns = "Prelude.Nat."
1402 snat p (PRef _ z)
1403 | show z == (natns++"Z") || show z == "Z" = Just 0
1404 snat p (PApp _ s [PExp {getTm=n}])
1405 | show s == (natns++"S") || show s == "S",
1406 Just n' <- snat p n
1407 = Just $ 1 + n'
1408 snat _ _ = Nothing
1410 bracket outer inner doc
1411 | inner > outer = lparen <> doc <> rparen
1412 | otherwise = doc
1414 kwd = annotate AnnKeyword . text
1416 fixities :: M.Map String Fixity
1417 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
1419 getFixity :: String -> Maybe Fixity
1420 getFixity = flip M.lookup fixities
1422-- | Pretty-printer helper for the binding site of a name
1423bindingOf :: Name -- ^^ the bound name
1424 -> Bool -- ^^ whether the name is implicit
1425 -> Doc OutputAnnotation
1426bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1428-- | Pretty-printer helper for names that attaches the correct annotations
1429prettyName :: Bool -- ^^ whether to show namespaces
1430 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1431 -> Name -- ^^ the name to pprint
1432 -> Doc OutputAnnotation
1433prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1434 | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
1435 where strName (UN n) = T.unpack n
1436 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1437 | otherwise = strName n
1438 strName n | n == falseTy = "_|_"
1439 strName (MN i s) = T.unpack s
1440 strName other = show other
1443showCImp :: PPOption -> PClause -> Doc OutputAnnotation
1444showCImp ppo (PClause _ n l ws r w)
1445 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
1446 <+> text "where" <+> text (show w)
1447 where
1448 showWs [] = empty
1449 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
1450showCImp ppo (PWith _ n l ws r w)
1451 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
1452 <+> braces (text (show w))
1453 where
1454 showWs [] = empty
1455 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
1458showDImp :: PPOption -> PData -> Doc OutputAnnotation
1459showDImp ppo (PDatadecl n ty cons)
1460 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
1461 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp ppo t) cons))
1463showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
1464showDecls o ds = vsep (map (showDeclImp o) ds)
1466showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1467showDeclImp o (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
1468showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1469 indent 2 (vsep (map (showCImp o) cs))
1470showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
1471showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
1472showDeclImp o (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
1473showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1474showDeclImp o (PClass _ _ _ cs n ps _ ds)
1475 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
1476showDeclImp o (PInstance _ _ cs n _ t _ ds)
1477 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
1478showDeclImp _ _ = text "..."
1479-- showDeclImp (PImport o) = "import " ++ o
1481instance Show (Doc OutputAnnotation) where
1482 show = flip (displayS . renderCompact) ""
1484getImps :: [PArg] -> [(Name, PTerm)]
1485getImps [] = []
1486getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1487getImps (_ : xs) = getImps xs
1489getExps :: [PArg] -> [PTerm]
1490getExps [] = []
1491getExps (PExp _ _ _ tm : xs) = tm : getExps xs
1492getExps (_ : xs) = getExps xs
1494getConsts :: [PArg] -> [PTerm]
1495getConsts [] = []
1496getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
1497getConsts (_ : xs) = getConsts xs
1499getAll :: [PArg] -> [PTerm]
1500getAll = map getTm
1503-- | Show Idris name
1504showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1505 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1506 -> PPOption -- ^^ pretty printing options
1507 -> Bool -- ^^ whether to colourise
1508 -> Name -- ^^ the term to show
1509 -> String
1510showName ist bnd ppo colour n = case ist of
1511 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1512 Nothing -> showbasic n
1513 where name = if ppopt_impl ppo then show n else showbasic n
1514 showbasic n@(UN _) = showCG n
1515 showbasic (MN _ s) = str s
1516 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1517 showbasic (SN s) = show s
1518 fst3 (x, _, _) = x
1519 colourise n t = let ctxt' = fmap tt_ctxt ist in
1520 case ctxt' of
1521 Nothing -> name
1522 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1523 else colouriseBound t name
1524 | isDConName n ctxt -> colouriseData t name
1525 | isFnName n ctxt -> colouriseFun t name
1526 | isTConName n ctxt -> colouriseType t name
1527 -- The assumption is that if a name is not bound and does not exist in the
1528 -- global context, then we're somewhere in which implicit info has been lost
1529 -- (like error messages). Thus, unknown vars are colourised as implicits.
1530 | otherwise -> colouriseImplicit t name
1532showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1533 -> PTerm -- ^^ the term to show
1534 -> String
1535showTm ist = displayDecorated (consoleDecorate ist) .
1536 renderPretty 0.8 100000 .
1537 prettyImp (ppOptionIst ist)
1539-- | Show a term with implicits, no colours
1540showTmImpls :: PTerm -> String
1541showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
1545instance Sized PTerm where
1546 size (PQuote rawTerm) = size rawTerm
1547 size (PRef fc name) = size name
1548 size (PLam name ty bdy) = 1 + size ty + size bdy
1549 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1550 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1551 size (PTyped trm ty) = 1 + size trm + size ty
1552 size (PApp fc name args) = 1 + size args
1553 size (PAppBind fc name args) = 1 + size args
1554 size (PCase fc trm bdy) = 1 + size trm + size bdy
1555 size (PTrue fc _) = 1
1556 size (PFalse fc) = 1
1557 size (PRefl fc _) = 1
1558 size (PResolveTC fc) = 1
1559 size (PEq fc left right) = 1 + size left + size right
1560 size (PRewrite fc left right _) = 1 + size left + size right
1561 size (PPair fc _ left right) = 1 + size left + size right
1562 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1563 size (PAlternative a alts) = 1 + size alts
1564 size (PHidden hidden) = size hidden
1565 size (PUnifyLog tm) = size tm
1566 size (PDisamb _ tm) = size tm
1567 size (PNoImplicits tm) = size tm
1568 size PType = 1
1569 size (PConstant const) = 1 + size const
1570 size Placeholder = 1
1571 size (PDoBlock dos) = 1 + size dos
1572 size (PIdiom fc term) = 1 + size term
1573 size (PReturn fc) = 1
1574 size (PMetavar name) = 1
1575 size (PProof tactics) = size tactics
1576 size (PElabError err) = size err
1577 size PImpossible = 1
1579getPArity :: PTerm -> Int
1580getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1581getPArity _ = 0
1583-- Return all names, free or globally bound, in the given term.
1585allNamesIn :: PTerm -> [Name]
1586allNamesIn tm = nub $ ni [] tm
1587 where -- TODO THINK added niTacImp, but is it right?
1588 ni env (PRef _ n)
1589 | not (n `elem` env) = [n]
1590 ni env (PPatvar _ n) = [n]
1591 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1592 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1593 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1594 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1595 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1596 ni env (PHidden tm) = ni env tm
1597 ni env (PEq _ l r) = ni env l ++ ni env r
1598 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1599 ni env (PTyped l r) = ni env l ++ ni env r
1600 ni env (PPair _ _ l r) = ni env l ++ ni env r
1601 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1602 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1603 ni env (PAlternative a ls) = concatMap (ni env) ls
1604 ni env (PUnifyLog tm) = ni env tm
1605 ni env (PDisamb _ tm) = ni env tm
1606 ni env (PNoImplicits tm) = ni env tm
1607 ni env _ = []
1609 niTacImp env (TacImp _ _ scr) = ni env scr
1610 niTacImp _ _ = []
1612-- Return all names defined in binders in the given term
1613boundNamesIn :: PTerm -> [Name]
1614boundNamesIn tm = nub $ ni tm
1615 where -- TODO THINK Added niTacImp, but is it right?
1616 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1617 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1618 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1619 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1620 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1621 ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc))
1622 ni (PEq _ l r) = ni l ++ ni r
1623 ni (PRewrite _ l r _) = ni l ++ ni r
1624 ni (PTyped l r) = ni l ++ ni r
1625 ni (PPair _ _ l r) = ni l ++ ni r
1626 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1627 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1628 ni (PAlternative a as) = concatMap (ni) as
1629 ni (PHidden tm) = ni tm
1630 ni (PUnifyLog tm) = ni tm
1631 ni (PDisamb _ tm) = ni tm
1632 ni (PNoImplicits tm) = ni tm
1633 ni _ = []
1635 niTacImp (TacImp _ _ scr) = ni scr
1636 niTacImp _ = []
1638-- Return names which are free in the given term.
1639namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1640namesIn uvars ist tm = nub $ ni [] tm
1641 where
1642 ni env (PRef _ n)
1643 | not (n `elem` env)
1644 = case lookupTy n (tt_ctxt ist) of
1645 [] -> [n]
1646 _ -> if n `elem` (map fst uvars) then [n] else []
1647 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1648 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1649 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1650 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1651 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1652 ni env (PEq _ l r) = ni env l ++ ni env r
1653 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1654 ni env (PTyped l r) = ni env l ++ ni env r
1655 ni env (PPair _ _ l r) = ni env l ++ ni env r
1656 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1657 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1658 ni env (PAlternative a as) = concatMap (ni env) as
1659 ni env (PHidden tm) = ni env tm
1660 ni env (PUnifyLog tm) = ni env tm
1661 ni env (PDisamb _ tm) = ni env tm
1662 ni env (PNoImplicits tm) = ni env tm
1663 ni env _ = []
1665 niTacImp env (TacImp _ _ scr) = ni env scr
1666 niTacImp _ _ = []
1668-- Return which of the given names are used in the given term.
1670usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1671usedNamesIn vars ist tm = nub $ ni [] tm
1672 where -- TODO THINK added niTacImp, but is it right?
1673 ni env (PRef _ n)
1674 | n `elem` vars && not (n `elem` env)
1675 = case lookupDefExact n (tt_ctxt ist) of
1676 Nothing -> [n]
1677 _ -> []
1678 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1679 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1680 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1681 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1682 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1683 ni env (PEq _ l r) = ni env l ++ ni env r
1684 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1685 ni env (PTyped l r) = ni env l ++ ni env r
1686 ni env (PPair _ _ l r) = ni env l ++ ni env r
1687 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1688 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1689 ni env (PAlternative a as) = concatMap (ni env) as
1690 ni env (PHidden tm) = ni env tm
1691 ni env (PUnifyLog tm) = ni env tm
1692 ni env (PDisamb _ tm) = ni env tm
1693 ni env (PNoImplicits tm) = ni env tm
1694 ni env _ = []
1696 niTacImp env (TacImp _ _ scr) = ni env scr
1697 niTacImp _ _ = []