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