on fca147b help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1710 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
342 | Warranty
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 | PkgTest String
377 | WarnOnly
378 | Pkg String
379 | BCAsm String
380 | DumpDefun String
381 | DumpCases String
382 | UseCodegen Codegen
383 | OutputTy OutputType
384 | Extension LanguageExt
385 | InterpretScript String
386 | EvalExpr String
387 | TargetTriple String
388 | TargetCPU String
389 | OptLevel Word
390 | Client String
391 | ShowOrigErr
392 | AutoWidth -- ^ Automatically adjust terminal width
393 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
394 deriving (Show, Eq)
396-- Parsed declarations
398data Fixity = Infixl { prec :: Int }
399 | Infixr { prec :: Int }
400 | InfixN { prec :: Int }
401 | PrefixN { prec :: Int }
402 deriving Eq
403{-!
404deriving instance Binary Fixity
405deriving instance NFData Fixity
406!-}
408instance Show Fixity where
409 show (Infixl i) = "infixl " ++ show i
410 show (Infixr i) = "infixr " ++ show i
411 show (InfixN i) = "infix " ++ show i
412 show (PrefixN i) = "prefix " ++ show i
414data FixDecl = Fix Fixity String
415 deriving Eq
417instance Show FixDecl where
418 show (Fix f s) = show f ++ " " ++ s
420{-!
421deriving instance Binary FixDecl
422deriving instance NFData FixDecl
423!-}
425instance Ord FixDecl where
426 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
429data Static = Static | Dynamic
430 deriving (Show, Eq)
431{-!
432deriving instance Binary Static
433deriving instance NFData Static
434!-}
436-- Mark bindings with their explicitness, and laziness
437data Plicity = Imp { pargopts :: [ArgOpt],
438 pstatic :: Static,
439 pparam :: Bool }
440 | Exp { pargopts :: [ArgOpt],
441 pstatic :: Static,
442 pparam :: Bool } -- this is a param (rather than index)
443 | Constraint { pargopts :: [ArgOpt],
444 pstatic :: Static }
445 | TacImp { pargopts :: [ArgOpt],
446 pstatic :: Static,
447 pscript :: PTerm }
448 deriving (Show, Eq)
450{-!
451deriving instance Binary Plicity
452deriving instance NFData Plicity
453!-}
455impl = Imp [] Dynamic False
456expl = Exp [] Dynamic False
457expl_param = Exp [] Dynamic True
458constraint = Constraint [] Dynamic
459tacimpl t = TacImp [] Dynamic t
461data FnOpt = Inlinable -- always evaluate when simplifying
462 | TotalFn | PartialFn | CoveringFn
463 | Coinductive | AssertTotal
464 | Dictionary -- type class dictionary, eval only when
465 -- a function argument, and further evaluation resutls
466 | Implicit -- implicit coercion
467 | CExport String -- export, with a C name
468 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
469 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
470 | Reflection -- a reflecting function, compile-time only
471 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
472 deriving (Show, Eq)
473{-!
474deriving instance Binary FnOpt
475deriving instance NFData FnOpt
476!-}
478type FnOpts = [FnOpt]
480inlinable :: FnOpts -> Bool
481inlinable = elem Inlinable
483dictionary :: FnOpts -> Bool
484dictionary = elem Dictionary
487-- | Data declaration options
488data DataOpt = Codata -- Set if the the data-type is coinductive
489 | DefaultEliminator -- Set if an eliminator should be generated for data type
490 | DataErrRev
491 deriving (Show, Eq)
493type DataOpts = [DataOpt]
495-- | Type provider - what to provide
496data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term
497 | ProvPostulate t -- ^ goal type must be Type, so only term
498 deriving (Show, Eq, Functor)
500type ProvideWhat = ProvideWhat' PTerm
502-- | Top-level declarations such as compiler directives, definitions,
503-- datatypes and typeclasses.
504data PDecl' t
505 = PFix FC Fixity [String] -- ^ Fixity declaration
506 | PTy Docstring [(Name, Docstring)] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
507 | PPostulate Docstring SyntaxInfo FC FnOpts Name t -- ^ Postulate
508 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
509 | PCAF FC Name t -- ^ Top level constant
510 | PData Docstring [(Name, Docstring)] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
511 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
512 | PNamespace String [PDecl' t] -- ^ New namespace
513 | PRecord Docstring SyntaxInfo FC Name t DataOpts Docstring Name t -- ^ Record declaration
514 | PClass Docstring SyntaxInfo FC
515 [t] -- constraints
516 Name
517 [(Name, t)] -- parameters
518 [(Name, Docstring)] -- parameter docstrings
519 [PDecl' t] -- declarations
520 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
521 -- class name, parameters, method declarations
522 | PInstance SyntaxInfo FC [t] -- constraints
523 Name -- class
524 [t] -- parameters
525 t -- full instance type
526 (Maybe Name) -- explicit name
527 [PDecl' t]
528 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
529 -- class name, parameters, full instance type, optional explicit name, and definitions
530 | PDSL Name (DSL' t) -- ^ DSL declaration
531 | PSyntax FC Syntax -- ^ Syntax definition
532 | PMutual FC [PDecl' t] -- ^ Mutual block
533 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
534 | PProvider SyntaxInfo FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term
535 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
536 -- bool is True, lhs and rhs must be convertible
537 deriving Functor
538{-!
539deriving instance Binary PDecl'
540deriving instance NFData PDecl'
541!-}
543-- For elaborator state
544type ElabD a = Elab' [PDecl] a
546-- | One clause of a top-level definition. Term arguments to constructors are:
547--
548-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
549--
550-- 2. The list of extra 'with' patterns
551--
552-- 3. The right-hand side
553--
554-- 4. The where block (PDecl' t)
556data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
557 | PWith FC Name t [t] t [PDecl' t]
558 | PClauseR FC [t] t [PDecl' t]
559 | PWithR FC [t] t [PDecl' t]
560 deriving Functor
561{-!
562deriving instance Binary PClause'
563deriving instance NFData PClause'
564!-}
566-- | Data declaration
567data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
568 d_tcon :: t, -- ^ Type constructor
569 d_cons :: [(Docstring, [(Name, Docstring)], Name, t, FC, [Name])] -- ^ Constructors
570 }
571 -- ^ Data declaration
572 | PLaterdecl { d_name :: Name, d_tcon :: t }
573 -- ^ "Placeholder" for data whose constructors are defined later
574 deriving Functor
575{-!
576deriving instance Binary PData'
577deriving instance NFData PData'
578!-}
580-- Handy to get a free function for applying PTerm -> PTerm functions
581-- across a program, by deriving Functor
583type PDecl = PDecl' PTerm
584type PData = PData' PTerm
585type PClause = PClause' PTerm
587-- get all the names declared in a decl
589declared :: PDecl -> [Name]
590declared (PFix _ _ _) = []
591declared (PTy _ _ _ _ _ n t) = [n]
592declared (PPostulate _ _ _ _ n t) = [n]
593declared (PClauses _ _ n _) = [] -- not a declaration
594declared (PCAF _ n _) = [n]
595declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
596 where fstt (_, _, a, _, _, _) = a
597declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
598declared (PParams _ _ ds) = concatMap declared ds
599declared (PNamespace _ ds) = concatMap declared ds
600declared (PRecord _ _ _ n _ _ _ c _) = [n, c]
601declared (PClass _ _ _ _ n _ _ ms) = n : concatMap declared ms
602declared (PInstance _ _ _ _ _ _ _ _) = []
603declared (PDSL n _) = [n]
604declared (PSyntax _ _) = []
605declared (PMutual _ ds) = concatMap declared ds
606declared (PDirective _) = []
608-- get the names declared, not counting nested parameter blocks
609tldeclared :: PDecl -> [Name]
610tldeclared (PFix _ _ _) = []
611tldeclared (PTy _ _ _ _ _ n t) = [n]
612tldeclared (PPostulate _ _ _ _ n t) = [n]
613tldeclared (PClauses _ _ n _) = [] -- not a declaration
614tldeclared (PRecord _ _ _ n _ _ _ c _) = [n, c]
615tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
616 where fstt (_, _, a, _, _, _) = a
617tldeclared (PParams _ _ ds) = []
618tldeclared (PMutual _ ds) = concatMap tldeclared ds
619tldeclared (PNamespace _ ds) = concatMap tldeclared ds
620tldeclared (PClass _ _ _ _ n _ _ ms) = concatMap tldeclared ms
621tldeclared (PInstance _ _ _ _ _ _ _ _) = []
622tldeclared _ = []
624defined :: PDecl -> [Name]
625defined (PFix _ _ _) = []
626defined (PTy _ _ _ _ _ n t) = []
627defined (PPostulate _ _ _ _ n t) = []
628defined (PClauses _ _ n _) = [n] -- not a declaration
629defined (PCAF _ n _) = [n]
630defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
631 where fstt (_, _, a, _, _, _) = a
632defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
633defined (PParams _ _ ds) = concatMap defined ds
634defined (PNamespace _ ds) = concatMap defined ds
635defined (PRecord _ _ _ n _ _ _ c _) = [n, c]
636defined (PClass _ _ _ _ n _ _ ms) = n : concatMap defined ms
637defined (PInstance _ _ _ _ _ _ _ _) = []
638defined (PDSL n _) = [n]
639defined (PSyntax _ _) = []
640defined (PMutual _ ds) = concatMap defined ds
641defined (PDirective _) = []
642--defined _ = []
644updateN :: [(Name, Name)] -> Name -> Name
645updateN ns n | Just n' <- lookup n ns = n'
646updateN _ n = n
648updateNs :: [(Name, Name)] -> PTerm -> PTerm
649updateNs [] t = t
650updateNs ns t = mapPT updateRef t
651 where updateRef (PRef fc f) = PRef fc (updateN ns f)
652 updateRef t = t
654-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
655-- updateDNs [] t = t
656-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
657-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
658-- where updateCNs ns (PClause n l ts r ds)
659-- = PClause (updateN ns n) (fmap (updateNs ns) l)
660-- (map (fmap (updateNs ns)) ts)
661-- (fmap (updateNs ns) r)
662-- (map (updateDNs ns) ds)
663-- updateDNs ns c = c
665data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
667-- | High level language terms
668data PTerm = PQuote Raw
669 | PRef FC Name
670 | PInferRef FC Name -- ^ A name to be defined later
671 | PPatvar FC Name
672 | PLam Name PTerm PTerm
673 | PPi Plicity Name PTerm PTerm -- ^ (n : t1) -> t2
674 | PLet Name PTerm PTerm PTerm
675 | PTyped PTerm PTerm -- ^ Term with explicit type
676 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
677 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
678 | PMatchApp FC Name -- ^ Make an application by type matching
679 | PCase FC PTerm [(PTerm, PTerm)]
680 | PTrue FC PunInfo -- ^ Unit type..?
681 | PFalse FC -- ^ _|_
682 | PRefl FC PTerm
683 | PResolveTC FC
684 | PEq FC PTerm PTerm -- ^ Equality type: A = B
685 | PRewrite FC PTerm PTerm (Maybe PTerm)
686 | PPair FC PunInfo PTerm PTerm
687 | PDPair FC PunInfo PTerm PTerm PTerm
688 | PAlternative Bool [PTerm] -- True if only one may work
689 | PHidden PTerm -- ^ Irrelevant or hidden pattern
690 | PType -- ^ 'Type' type
691 | PGoal FC PTerm Name PTerm
692 | PConstant Const -- ^ Builtin types
693 | Placeholder
694 | PDoBlock [PDo]
695 | PIdiom FC PTerm
696 | PReturn FC
697 | PMetavar Name
698 | PProof [PTactic] -- ^ Proof script
699 | PTactics [PTactic] -- ^ As PProof, but no auto solving
700 | PElabError Err -- ^ Error to report on elaboration
701 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
702 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
703 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
704 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
705 | PNoImplicits PTerm -- ^ never run implicit converions on the term
706 deriving Eq
709{-!
710deriving instance Binary PTerm
711deriving instance NFData PTerm
712!-}
714mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
715mapPT f t = f (mpt t) where
716 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
717 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
718 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
719 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
720 (fmap (mapPT f) g)
721 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
722 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
723 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
724 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
725 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
726 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
727 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
728 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
729 mpt (PHidden t) = PHidden (mapPT f t)
730 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
731 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
732 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
733 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
734 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
735 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
736 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
737 mpt x = x
740data PTactic' t = Intro [Name] | Intros | Focus Name
741 | Refine Name [Bool] | Rewrite t | DoUnify
742 | Induction Name
743 | Equiv t
744 | MatchRefine Name
745 | LetTac Name t | LetTacTy Name t t
746 | Exact t | Compute | Trivial | TCInstance
747 | ProofSearch Bool Bool Int (Maybe Name) [Name]
748 -- ^ the bool is whether to search recursively
749 | Solve
750 | Attack
751 | ProofState | ProofTerm | Undo
752 | Try (PTactic' t) (PTactic' t)
753 | TSeq (PTactic' t) (PTactic' t)
754 | ApplyTactic t -- see Language.Reflection module
755 | ByReflection t
756 | Reflect t
757 | Fill t
758 | GoalType String (PTactic' t)
759 | TCheck t
760 | TEval t
761 | Qed | Abandon
762 deriving (Show, Eq, Functor)
763{-!
764deriving instance Binary PTactic'
765deriving instance NFData PTactic'
766!-}
767instance Sized a => Sized (PTactic' a) where
768 size (Intro nms) = 1 + size nms
769 size Intros = 1
770 size (Focus nm) = 1 + size nm
771 size (Refine nm bs) = 1 + size nm + length bs
772 size (Rewrite t) = 1 + size t
773 size (Induction t) = 1 + size t
774 size (LetTac nm t) = 1 + size nm + size t
775 size (Exact t) = 1 + size t
776 size Compute = 1
777 size Trivial = 1
778 size Solve = 1
779 size Attack = 1
780 size ProofState = 1
781 size ProofTerm = 1
782 size Undo = 1
783 size (Try l r) = 1 + size l + size r
784 size (TSeq l r) = 1 + size l + size r
785 size (ApplyTactic t) = 1 + size t
786 size (Reflect t) = 1 + size t
787 size (Fill t) = 1 + size t
788 size Qed = 1
789 size Abandon = 1
791type PTactic = PTactic' PTerm
793data PDo' t = DoExp FC t
794 | DoBind FC Name t
795 | DoBindP FC t t [(t,t)]
796 | DoLet FC Name t t
797 | DoLetP FC t t
798 deriving (Eq, Functor)
799{-!
800deriving instance Binary PDo'
801deriving instance NFData PDo'
802!-}
804instance Sized a => Sized (PDo' a) where
805 size (DoExp fc t) = 1 + size fc + size t
806 size (DoBind fc nm t) = 1 + size fc + size nm + size t
807 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
808 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
809 size (DoLetP fc l r) = 1 + size fc + size l + size r
811type PDo = PDo' PTerm
813-- The priority gives a hint as to elaboration order. Best to elaborate
814-- things early which will help give a more concrete type to other
815-- variables, e.g. a before (interpTy a).
817data PArg' t = PImp { priority :: Int,
818 machine_inf :: Bool, -- true if the machine inferred it
819 argopts :: [ArgOpt],
820 pname :: Name, getTm :: t }
821 | PExp { priority :: Int,
822 argopts :: [ArgOpt],
823 pname :: Name,
824 getTm :: t }
825 | PConstraint { priority :: Int,
826 argopts :: [ArgOpt],
827 pname :: Name,
828 getTm :: t }
829 | PTacImplicit { priority :: Int,
830 argopts :: [ArgOpt],
831 pname :: Name,
832 getScript :: t,
833 getTm :: t }
834 deriving (Show, Eq, Functor)
836data ArgOpt = HideDisplay | InaccessibleArg
837 deriving (Show, Eq)
839instance Sized a => Sized (PArg' a) where
840 size (PImp p _ l nm trm) = 1 + size nm + size trm
841 size (PExp p l nm trm) = 1 + size nm + size trm
842 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
843 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
845{-!
846deriving instance Binary PArg'
847deriving instance NFData PArg'
848!-}
850pimp n t mach = PImp 1 mach [] n t
851pexp t = PExp 1 [] (sMN 0 "arg") t
852pconst t = PConstraint 1 [] (sMN 0 "carg") t
853ptacimp n s t = PTacImplicit 2 [] n s t
855type PArg = PArg' PTerm
857-- Type class data
859data ClassInfo = CI { instanceName :: Name,
860 class_methods :: [(Name, (FnOpts, PTerm))],
861 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
862 class_default_superclasses :: [PDecl],
863 class_params :: [Name],
864 class_instances :: [Name] }
865 deriving Show
866{-!
867deriving instance Binary ClassInfo
868deriving instance NFData ClassInfo
869!-}
871-- Type inference data
873data TIData = TIPartial -- ^ a function with a partially defined type
874 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
875 deriving Show
877data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
878 detaggable :: Bool }
879 deriving Show
880{-!
881deriving instance Binary OptInfo
882deriving instance NFData OptInfo
883!-}
886data TypeInfo = TI { con_names :: [Name],
887 codata :: Bool,
888 data_opts :: DataOpts,
889 param_pos :: [Int],
890 mutual_types :: [Name] }
891 deriving Show
892{-!
893deriving instance Binary TypeInfo
894deriving instance NFData TypeInfo
895!-}
897-- Syntactic sugar info
899data DSL' t = DSL { dsl_bind :: t,
900 dsl_return :: t,
901 dsl_apply :: t,
902 dsl_pure :: t,
903 dsl_var :: Maybe t,
904 index_first :: Maybe t,
905 index_next :: Maybe t,
906 dsl_lambda :: Maybe t,
907 dsl_let :: Maybe t
908 }
909 deriving (Show, Functor)
910{-!
911deriving instance Binary DSL'
912deriving instance NFData DSL'
913!-}
915type DSL = DSL' PTerm
917data SynContext = PatternSyntax | TermSyntax | AnySyntax
918 deriving Show
919{-!
920deriving instance Binary SynContext
921deriving instance NFData SynContext
922!-}
924data Syntax = Rule [SSymbol] PTerm SynContext
925 deriving Show
926{-!
927deriving instance Binary Syntax
928deriving instance NFData Syntax
929!-}
931data SSymbol = Keyword Name
932 | Symbol String
933 | Binding Name
934 | Expr Name
935 | SimpleExpr Name
936 deriving Show
937{-!
938deriving instance Binary SSymbol
939deriving instance NFData SSymbol
940!-}
942initDSL = DSL (PRef f (sUN ">>="))
943 (PRef f (sUN "return"))
944 (PRef f (sUN "<$>"))
945 (PRef f (sUN "pure"))
946 Nothing
947 Nothing
948 Nothing
949 Nothing
950 Nothing
951 where f = fileFC "(builtin)"
953data Using = UImplicit Name PTerm
954 | UConstraint Name [Name]
955 deriving (Show, Eq)
956{-!
957deriving instance Binary Using
958deriving instance NFData Using
959!-}
961data SyntaxInfo = Syn { using :: [Using],
962 syn_params :: [(Name, PTerm)],
963 syn_namespace :: [String],
964 no_imp :: [Name],
965 decoration :: Name -> Name,
966 inPattern :: Bool,
967 implicitAllowed :: Bool,
968 maxline :: Maybe Int,
969 mut_nesting :: Int,
970 dsl_info :: DSL }
971 deriving Show
972{-!
973deriving instance NFData SyntaxInfo
974deriving instance Binary SyntaxInfo
975!-}
977defaultSyntax = Syn [] [] [] [] id False False Nothing 0 initDSL
979expandNS :: SyntaxInfo -> Name -> Name
980expandNS syn n@(NS _ _) = n
981expandNS syn n = case syn_namespace syn of
982 [] -> n
983 xs -> sNS n xs
986-- For inferring types of things
988bi = fileFC "builtin"
990inferTy = sMN 0 "__Infer"
991inferCon = sMN 0 "__infer"
992inferDecl = PDatadecl inferTy
993 PType
994 [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType (
995 PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType"))
996 (PRef bi inferTy)), bi, [])]
997inferOpts = []
999infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
1000infP = P (TCon 6 0) inferTy (TType (UVal 0))
1002getInferTerm, getInferType :: Term -> Term
1003getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
1004getInferTerm (App (App _ _) tm) = tm
1005getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1007getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1008 where toTy (Lam t) = Pi t
1009 toTy (PVar t) = PVTy t
1010 toTy b = b
1011getInferType (App (App _ ty) _) = ty
1015-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign, Elim type class
1017primNames = [unitTy, unitCon,
1018 falseTy, pairTy, pairCon,
1019 eqTy, eqCon, inferTy, inferCon]
1021unitDoc = parseDocstring . T.pack $ "The canonical single-element type, also known as the trivially true proposition."
1022unitTy = sMN 0 "__Unit"
1023unitCon = sMN 0 "__II"
1024unitDecl = PDatadecl unitTy PType
1025 [(parseDocstring . T.pack $ "The trivial constructor for `()`. ", [], unitCon, PRef bi unitTy, bi, [])]
1026unitOpts = [DefaultEliminator]
1028falseDoc = parseDocstring . T.pack $
1029 "The empty type, also known as the trivially false proposition." ++
1030 "\n\n" ++
1031 "Use `FalseElim` or `absurd` to prove anything if you have a variable " ++
1032 "of type `_|_` in scope."
1033falseTy = sMN 0 "__False"
1034falseDecl = PDatadecl falseTy PType []
1035falseOpts = []
1037pairDoc = parseDocstring . T.pack $ "The non-dependent pair type, also known as conjunction."
1038pairTy = sMN 0 "__Pair"
1039pairCon = sMN 0 "__MkPair"
1040pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
1041 [(pairConDoc, pairConParamDoc,
1042 pairCon, PPi impl (n "A") PType (
1043 PPi impl (n "B") PType (
1044 PPi expl (n "a") (PRef bi (n "A")) (
1045 PPi expl (n "b") (PRef bi (n "B"))
1046 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
1047 pexp (PRef bi (n "B"))])))), bi, [])]
1048 where n a = sMN 0 a
1049 pairConDoc = parseDocstring . T.pack $ "A pair of elements"
1050 pairConParamDoc = [(n "a", parseDocstring . T.pack $ "the left element of the pair"),
1051 (n "b", parseDocstring . T.pack $ "the right element of the pair")]
1052pairOpts = []
1053pairParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left elements in the pair"),
1054 (n "B", parseDocstring . T.pack $ "the type of the left elements in the pair")]
1055 where n a = sMN 0 a
1057eqTy = sUN "="
1058eqCon = sUN "refl"
1059eqDoc = parseDocstring . T.pack $
1060 "The propositional equality type. A proof that `x` = `y`." ++
1061 "\n\n" ++
1062 "To use such a proof, pattern-match on it, and the two equal things will " ++
1063 "then need to be the _same_ pattern." ++
1064 "\n\n" ++
1065 "**Note**: Idris's equality type is _heterogeneous_, which means that it " ++
1066 "is possible to state equalities between values of potentially different " ++
1067 "types. This is sometimes referred to in the literature as \"John Major\" " ++
1068 "equality." ++
1069 "\n\n" ++
1070 "Thus, if Idris can't infer the type of one side of the equality, then " ++
1071 "you may need to annotate it. See the function `the`."
1073eqDecl = PDatadecl eqTy (piBind [(n "A", PType), (n "B", PType),
1074 (n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))]
1075 PType)
1076 [(reflDoc, reflParamDoc,
1077 eqCon, PPi impl (n "A") PType (
1078 PPi impl (n "x") (PRef bi (n "A"))
1079 (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False,
1080 pimp (n "B") Placeholder False,
1081 pexp (PRef bi (n "x")),
1082 pexp (PRef bi (n "x"))])), bi, [])]
1083 where n a = sMN 0 a
1084 reflDoc = parseDocstring . T.pack $
1085 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1086 "shown that both sides are in fact equal."
1087 reflParamDoc = [(n "A", parseDocstring . T.pack $ "the type at which the equality is proven"),
1088 (n "x", parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1090eqParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left side of the equality"),
1091 (n "B", parseDocstring . T.pack $ "the type of the right side of the equality")
1093 where n a = sMN 0 a
1095eqOpts = []
1097elimName = sUN "__Elim"
1098elimMethElimTy = sUN "__elimTy"
1099elimMethElim = sUN "elim"
1100elimDecl = PClass (parseDocstring . T.pack $ "Type class for eliminators") defaultSyntax bi [] elimName [(sUN "scrutineeType", PType)] []
1101 [PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElimTy PType,
1102 PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElim (PRef bi elimMethElimTy)]
1104-- Defined in builtins.idr
1105sigmaTy = sUN "Sigma"
1106existsCon = sUN "Sg_intro"
1108piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1109piBind = piBindp expl
1111piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1112piBindp p [] t = t
1113piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t)
1116-- Pretty-printing declarations and terms
1118-- These "show" instances render to an absurdly wide screen because inserted line breaks
1119-- could interfere with interactive editing, which calls "show".
1121instance Show PTerm where
1122 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1124instance Show PDecl where
1125 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp defaultPPOption) d
1127instance Show PClause where
1128 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1130instance Show PData where
1131 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1133instance Pretty PTerm OutputAnnotation where
1134 pretty = prettyImp defaultPPOption
1136-- | Colourise annotations according to an Idris state. It ignores the names
1137-- in the annotation, as there's no good way to show extended information on a
1138-- terminal.
1139consoleDecorate :: IState -> OutputAnnotation -> String -> String
1140consoleDecorate ist _ | not (idris_colourRepl ist) = id
1141consoleDecorate ist (AnnConst c) = let theme = idris_colourTheme ist
1142 in if constIsType c
1143 then colouriseType theme
1144 else colouriseData theme
1145consoleDecorate ist (AnnData _ _) = colouriseData (idris_colourTheme ist)
1146consoleDecorate ist (AnnType _ _) = colouriseType (idris_colourTheme ist)
1147consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
1148consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
1149consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1150consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1151 theme = idris_colourTheme ist
1152 in case () of
1153 _ | isDConName n ctxt -> colouriseData theme
1154 _ | isFnName n ctxt -> colouriseFun theme
1155 _ | isTConName n ctxt -> colouriseType theme
1156 _ | isPostulateName n ist -> colourisePostulate theme
1157 _ | otherwise -> id -- don't colourise unknown names
1158consoleDecorate ist (AnnFC _) = id
1159consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
1160 where colour BoldText = IdrisColour Nothing True False True False
1161 colour UnderlineText = IdrisColour Nothing True True False False
1162 colour ItalicText = IdrisColour Nothing True False False True
1164isPostulateName :: Name -> IState -> Bool
1165isPostulateName n ist = S.member n (idris_postulates ist)
1167-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1168prettyImp :: PPOption -- ^^ pretty printing options
1169 -> PTerm -- ^^ the term to pretty-print
1170 -> Doc OutputAnnotation
1171prettyImp impl = pprintPTerm impl [] [] []
1173-- | Do the right thing for rendering a term in an IState
1174prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1175prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1177-- | Pretty-print a high-level Idris term in some bindings context with infix info
1178pprintPTerm :: PPOption -- ^^ pretty printing options
1179 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1180 -> [Name] -- ^^ names to always show in pi, even if not used
1181 -> [FixDecl] -- ^^ Fixity declarations
1182 -> PTerm -- ^^ the term to pretty-print
1183 -> Doc OutputAnnotation
1184pprintPTerm ppo bnd docArgs infixes = prettySe 10 bnd
1185 where
1186 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1187 prettySe p bnd (PQuote r) =
1188 text "![" <> pretty r <> text "]"
1189 prettySe p bnd (PPatvar fc n) = pretty n
1190 prettySe p bnd e
1191 | Just str <- slist p bnd e = str
1192 | Just n <- snat p e = annotate (AnnData "Nat" "") (text (show n))
1193 prettySe p bnd (PRef fc n) = prettyName (ppopt_impl ppo) bnd n
1194 prettySe p bnd (PLam n ty sc) =
1195 bracket p 2 . group . align . hang 2 $
1196 text "\\" <> bindingOf n False <+> text "=>" <$>
1197 prettySe 10 ((n, False):bnd) sc
1198 prettySe p bnd (PLet n ty v sc) =
1199 bracket p 2 $
1200 kwd "let" <+> bindingOf n False <+> text "=" </>
1201 prettySe 10 bnd v <+> kwd "in" </>
1202 prettySe 10 ((n, False):bnd) sc
1203 prettySe p bnd (PPi (Exp l s _) n ty sc)
1204 | n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs =
1205 bracket p 2 . group $
1206 enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1207 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1208 | otherwise =
1209 bracket p 2 . group $
1210 group (prettySe 1 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1211 where
1212 st =
1213 case s of
1214 Static -> text "[static]" <> space
1215 _ -> empty
1216 prettySe p bnd (PPi (Imp l s _) n ty sc)
1217 | ppopt_impl ppo =
1218 bracket p 2 $
1219 lbrace <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1220 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1221 | otherwise = prettySe 10 ((n, True):bnd) sc
1222 where
1223 st =
1224 case s of
1225 Static -> text "[static]" <> space
1226 _ -> empty
1227 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1228 bracket p 2 $
1229 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1230 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1231 bracket p 2 $
1232 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1233 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1234 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1235 | UN nm <- basename f
1236 , not (ppopt_impl ppo) && null (getExps args) =
1237 if isAlpha (thead nm)
1238 then prettyName (ppopt_impl ppo) bnd f
1239 else enclose lparen rparen $ prettyName (ppopt_impl ppo) bnd f
1240 prettySe p bnd (PAppBind _ (PRef _ f) [])
1241 | not (ppopt_impl ppo) = text "!" <> prettyName (ppopt_impl ppo) bnd f
1242 prettySe p bnd (PApp _ (PRef _ op) args) -- infix operators
1243 | UN nm <- basename op
1244 , not (tnull nm) &&
1245 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1246 case getExps args of
1247 [] -> enclose lparen rparen opName
1248 [x] -> group (enclose lparen rparen opName <$> group (prettySe 0 bnd x))
1249 [l,r] -> let precedence = fromMaybe 20 (fmap prec f)
1250 in bracket p precedence $ inFix l r
1251 (l:r:rest) -> bracket p 1 $
1252 enclose lparen rparen (inFix l r) <+>
1253 align (group (vsep (map (prettyArgSe bnd) rest)))
1254 where opName = prettyName (ppopt_impl ppo) bnd op
1255 f = getFixity (opStr op)
1256 left l = case f of
1257 Nothing -> prettySe (-1) bnd l
1258 Just (Infixl p') -> prettySe p' bnd l
1259 Just f' -> prettySe (prec f'-1) bnd l
1260 right r = case f of
1261 Nothing -> prettySe (-1) bnd r
1262 Just (Infixr p') -> prettySe p' bnd r
1263 Just f' -> prettySe (prec f'-1) bnd r
1264 inFix l r = align . group $
1265 (left l <+> opName) <$> group (right r)
1266 prettySe p bnd (PApp _ hd@(PRef fc f) [tm]) -- symbols, like 'foo
1267 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1268 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1269 char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1270 prettySe p bnd (PApp _ f as) = -- Normal prefix applications
1271 let args = getExps as
1272 fp = prettySe 1 bnd f
1273 in
1274 bracket p 1 . group $
1275 if ppopt_impl ppo
1276 then if null as
1277 then fp
1278 else fp <+> align (vsep (map (prettyArgS bnd) as))
1279 else if null args
1280 then fp
1281 else fp <+> align (vsep (map (prettyArgSe bnd) args))
1282 prettySe p bnd (PCase _ scr opts) =
1283 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1284 where
1285 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1287 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1288 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1289 prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
1290 prettySe p bnd (PResolveTC _) = text "resolvetc"
1291 prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1292 prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1293 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1294 prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
1295 prettySe p bnd (PEq _ l r) =
1296 bracket p 2 . align . group $
1297 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1298 where eq = annName eqTy (text "=")
1299 prettySe p bnd (PRewrite _ l r _) =
1300 bracket p 2 $
1301 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1302 prettySe p bnd (PTyped l r) =
1303 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1304 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1305 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1306 align . group . vsep . punctuate (ann comma) $
1307 map (prettySe 10 bnd) elts
1308 where ann = case pun of
1309 TypeOrTerm -> id
1310 IsType -> annName pairTy
1311 IsTerm -> annName pairCon
1312 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1313 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1314 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1315 annName sigmaTy lparen <>
1316 bindingOf n False <+>
1317 annName sigmaTy (text "**") <+>
1318 prettySe 10 ((n, False):bnd) r <>
1319 annName sigmaTy rparen
1320 prettySe p bnd (PDPair _ IsType l t r) =
1321 annName sigmaTy lparen <>
1322 prettySe 10 bnd l <+>
1323 annName sigmaTy (text "**") <+>
1324 prettySe 10 bnd r <>
1325 annName sigmaTy rparen
1326 prettySe p bnd (PDPair _ IsTerm l t r) =
1327 annName existsCon lparen <>
1328 prettySe 10 bnd l <+>
1329 annName existsCon (text "**") <+>
1330 prettySe 10 bnd r <>
1331 annName existsCon rparen
1332 prettySe p bnd (PAlternative a as) =
1333 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1334 where
1335 prettyAs =
1336 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1337 prettySe p bnd PType = annotate (AnnType "Type" "The type of types") $ text "Type"
1338 prettySe p bnd (PConstant c) = annotate (AnnConst c) (text (show c))
1339 -- XXX: add pretty for tactics
1340 prettySe p bnd (PProof ts) =
1341 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1342 prettySe p bnd (PTactics ts) =
1343 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1344 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1345 prettySe p bnd (PReturn f) = kwd "return"
1346 prettySe p bnd PImpossible = kwd "impossible"
1347 prettySe p bnd Placeholder = text "_"
1348 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1349 prettySe p bnd (PCoerced t) = prettySe p bnd t
1350 prettySe p bnd (PElabError s) = pretty s
1352 prettySe p bnd _ = text "test"
1354 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1355 prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm
1356 prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm
1357 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1359 prettyArgSe bnd arg = prettySe 0 bnd arg
1360 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1361 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1362 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1364 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1365 annName n = annotate (AnnName n Nothing Nothing Nothing)
1367 opStr :: Name -> String
1368 opStr (NS n _) = opStr n
1369 opStr (UN n) = T.unpack n
1371 basename :: Name -> Name
1372 basename (NS n _) = basename n
1373 basename n = n
1375 slist' p bnd (PApp _ (PRef _ nil) _)
1376 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1377 slist' p bnd (PRef _ nil)
1378 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1379 slist' p bnd (PApp _ (PRef _ cons) args)
1380 | nsroot cons == sUN "::",
1381 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1382 all isImp imps,
1383 Just tl' <- slist' p bnd tl
1384 = Just (hd:tl')
1385 where
1386 isImp (PImp {}) = True
1387 isImp _ = False
1388 slist' _ _ tm = Nothing
1390 slist p bnd e | Just es <- slist' p bnd e = Just $
1391 case es of [] -> annotate (AnnData "" "") $ text "[]"
1392 [x] -> enclose left right . group $
1393 prettySe p bnd x
1394 xs -> (enclose left right .
1395 align . group . vsep .
1396 punctuate comma .
1397 map (prettySe p bnd)) xs
1398 where left = (annotate (AnnData "" "") (text "["))
1399 right = (annotate (AnnData "" "") (text "]"))
1400 comma = (annotate (AnnData "" "") (text ","))
1401 slist _ _ _ = Nothing
1403 pairElts :: PTerm -> Maybe [PTerm]
1404 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1405 | otherwise = Just [x, y]
1406 pairElts _ = Nothing
1408 natns = "Prelude.Nat."
1410 snat p (PRef _ z)
1411 | show z == (natns++"Z") || show z == "Z" = Just 0
1412 snat p (PApp _ s [PExp {getTm=n}])
1413 | show s == (natns++"S") || show s == "S",
1414 Just n' <- snat p n
1415 = Just $ 1 + n'
1416 snat _ _ = Nothing
1418 bracket outer inner doc
1419 | inner > outer = lparen <> doc <> rparen
1420 | otherwise = doc
1422 kwd = annotate AnnKeyword . text
1424 fixities :: M.Map String Fixity
1425 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
1427 getFixity :: String -> Maybe Fixity
1428 getFixity = flip M.lookup fixities
1430prettyDocumentedIst :: IState -> (Name, PTerm, Maybe Docstring) -> Doc OutputAnnotation
1431prettyDocumentedIst ist (name, ty, docs) =
1432 prettyName True [] name <+> colon <+> align (prettyIst ist ty) <$>
1433 fromMaybe empty (fmap (\d -> renderDocstring d <> line) docs)
1435-- | Pretty-printer helper for the binding site of a name
1436bindingOf :: Name -- ^^ the bound name
1437 -> Bool -- ^^ whether the name is implicit
1438 -> Doc OutputAnnotation
1439bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1441-- | Pretty-printer helper for names that attaches the correct annotations
1442prettyName :: Bool -- ^^ whether to show namespaces
1443 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1444 -> Name -- ^^ the name to pprint
1445 -> Doc OutputAnnotation
1446prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1447 | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
1448 where strName (UN n) = T.unpack n
1449 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1450 | otherwise = strName n
1451 strName n | n == falseTy = "_|_"
1452 strName (MN i s) = T.unpack s
1453 strName other = show other
1456showCImp :: PPOption -> PClause -> Doc OutputAnnotation
1457showCImp ppo (PClause _ n l ws r w)
1458 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
1459 <+> text "where" <+> text (show w)
1460 where
1461 showWs [] = empty
1462 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
1463showCImp ppo (PWith _ n l ws r w)
1464 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
1465 <+> braces (text (show w))
1466 where
1467 showWs [] = empty
1468 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
1471showDImp :: PPOption -> PData -> Doc OutputAnnotation
1472showDImp ppo (PDatadecl n ty cons)
1473 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
1474 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp ppo t) cons))
1476showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
1477showDecls o ds = vsep (map (showDeclImp o) ds)
1479showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1480showDeclImp o (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
1481showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1482 indent 2 (vsep (map (showCImp o) cs))
1483showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
1484showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
1485showDeclImp o (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
1486showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1487showDeclImp o (PClass _ _ _ cs n ps _ ds)
1488 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
1489showDeclImp o (PInstance _ _ cs n _ t _ ds)
1490 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
1491showDeclImp _ _ = text "..."
1492-- showDeclImp (PImport o) = "import " ++ o
1494instance Show (Doc OutputAnnotation) where
1495 show = flip (displayS . renderCompact) ""
1497getImps :: [PArg] -> [(Name, PTerm)]
1498getImps [] = []
1499getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1500getImps (_ : xs) = getImps xs
1502getExps :: [PArg] -> [PTerm]
1503getExps [] = []
1504getExps (PExp _ _ _ tm : xs) = tm : getExps xs
1505getExps (_ : xs) = getExps xs
1507getConsts :: [PArg] -> [PTerm]
1508getConsts [] = []
1509getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
1510getConsts (_ : xs) = getConsts xs
1512getAll :: [PArg] -> [PTerm]
1513getAll = map getTm
1516-- | Show Idris name
1517showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1518 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1519 -> PPOption -- ^^ pretty printing options
1520 -> Bool -- ^^ whether to colourise
1521 -> Name -- ^^ the term to show
1522 -> String
1523showName ist bnd ppo colour n = case ist of
1524 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1525 Nothing -> showbasic n
1526 where name = if ppopt_impl ppo then show n else showbasic n
1527 showbasic n@(UN _) = showCG n
1528 showbasic (MN _ s) = str s
1529 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1530 showbasic (SN s) = show s
1531 fst3 (x, _, _) = x
1532 colourise n t = let ctxt' = fmap tt_ctxt ist in
1533 case ctxt' of
1534 Nothing -> name
1535 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1536 else colouriseBound t name
1537 | isDConName n ctxt -> colouriseData t name
1538 | isFnName n ctxt -> colouriseFun t name
1539 | isTConName n ctxt -> colouriseType t name
1540 -- The assumption is that if a name is not bound and does not exist in the
1541 -- global context, then we're somewhere in which implicit info has been lost
1542 -- (like error messages). Thus, unknown vars are colourised as implicits.
1543 | otherwise -> colouriseImplicit t name
1545showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1546 -> PTerm -- ^^ the term to show
1547 -> String
1548showTm ist = displayDecorated (consoleDecorate ist) .
1549 renderPretty 0.8 100000 .
1550 prettyImp (ppOptionIst ist)
1552-- | Show a term with implicits, no colours
1553showTmImpls :: PTerm -> String
1554showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
1558instance Sized PTerm where
1559 size (PQuote rawTerm) = size rawTerm
1560 size (PRef fc name) = size name
1561 size (PLam name ty bdy) = 1 + size ty + size bdy
1562 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1563 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1564 size (PTyped trm ty) = 1 + size trm + size ty
1565 size (PApp fc name args) = 1 + size args
1566 size (PAppBind fc name args) = 1 + size args
1567 size (PCase fc trm bdy) = 1 + size trm + size bdy
1568 size (PTrue fc _) = 1
1569 size (PFalse fc) = 1
1570 size (PRefl fc _) = 1
1571 size (PResolveTC fc) = 1
1572 size (PEq fc left right) = 1 + size left + size right
1573 size (PRewrite fc left right _) = 1 + size left + size right
1574 size (PPair fc _ left right) = 1 + size left + size right
1575 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1576 size (PAlternative a alts) = 1 + size alts
1577 size (PHidden hidden) = size hidden
1578 size (PUnifyLog tm) = size tm
1579 size (PDisamb _ tm) = size tm
1580 size (PNoImplicits tm) = size tm
1581 size PType = 1
1582 size (PConstant const) = 1 + size const
1583 size Placeholder = 1
1584 size (PDoBlock dos) = 1 + size dos
1585 size (PIdiom fc term) = 1 + size term
1586 size (PReturn fc) = 1
1587 size (PMetavar name) = 1
1588 size (PProof tactics) = size tactics
1589 size (PElabError err) = size err
1590 size PImpossible = 1
1592getPArity :: PTerm -> Int
1593getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1594getPArity _ = 0
1596-- Return all names, free or globally bound, in the given term.
1598allNamesIn :: PTerm -> [Name]
1599allNamesIn tm = nub $ ni [] tm
1600 where -- TODO THINK added niTacImp, but is it right?
1601 ni env (PRef _ n)
1602 | not (n `elem` env) = [n]
1603 ni env (PPatvar _ n) = [n]
1604 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1605 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1606 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1607 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1608 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1609 ni env (PHidden tm) = ni env tm
1610 ni env (PEq _ l r) = ni env l ++ ni env r
1611 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1612 ni env (PTyped l r) = ni env l ++ ni env r
1613 ni env (PPair _ _ l r) = ni env l ++ ni env r
1614 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1615 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1616 ni env (PAlternative a ls) = concatMap (ni env) ls
1617 ni env (PUnifyLog tm) = ni env tm
1618 ni env (PDisamb _ tm) = ni env tm
1619 ni env (PNoImplicits tm) = ni env tm
1620 ni env _ = []
1622 niTacImp env (TacImp _ _ scr) = ni env scr
1623 niTacImp _ _ = []
1625-- Return all names defined in binders in the given term
1626boundNamesIn :: PTerm -> [Name]
1627boundNamesIn tm = nub $ ni tm
1628 where -- TODO THINK Added niTacImp, but is it right?
1629 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1630 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1631 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1632 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1633 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1634 ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc))
1635 ni (PEq _ l r) = ni l ++ ni r
1636 ni (PRewrite _ l r _) = ni l ++ ni r
1637 ni (PTyped l r) = ni l ++ ni r
1638 ni (PPair _ _ l r) = ni l ++ ni r
1639 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1640 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1641 ni (PAlternative a as) = concatMap (ni) as
1642 ni (PHidden tm) = ni tm
1643 ni (PUnifyLog tm) = ni tm
1644 ni (PDisamb _ tm) = ni tm
1645 ni (PNoImplicits tm) = ni tm
1646 ni _ = []
1648 niTacImp (TacImp _ _ scr) = ni scr
1649 niTacImp _ = []
1651-- Return names which are free in the given term.
1652namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1653namesIn uvars ist tm = nub $ ni [] tm
1654 where
1655 ni env (PRef _ n)
1656 | not (n `elem` env)
1657 = case lookupTy n (tt_ctxt ist) of
1658 [] -> [n]
1659 _ -> if n `elem` (map fst uvars) then [n] else []
1660 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1661 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1662 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1663 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1664 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1665 ni env (PEq _ l r) = ni env l ++ ni env r
1666 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1667 ni env (PTyped l r) = ni env l ++ ni env r
1668 ni env (PPair _ _ l r) = ni env l ++ ni env r
1669 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1670 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1671 ni env (PAlternative a as) = concatMap (ni env) as
1672 ni env (PHidden tm) = ni env tm
1673 ni env (PUnifyLog tm) = ni env tm
1674 ni env (PDisamb _ tm) = ni env tm
1675 ni env (PNoImplicits tm) = ni env tm
1676 ni env _ = []
1678 niTacImp env (TacImp _ _ scr) = ni env scr
1679 niTacImp _ _ = []
1681-- Return which of the given names are used in the given term.
1683usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1684usedNamesIn vars ist tm = nub $ ni [] tm
1685 where -- TODO THINK added niTacImp, but is it right?
1686 ni env (PRef _ n)
1687 | n `elem` vars && not (n `elem` env)
1688 = case lookupDefExact n (tt_ctxt ist) of
1689 Nothing -> [n]
1690 _ -> []
1691 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1692 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1693 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1694 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1695 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1696 ni env (PEq _ l r) = ni env l ++ ni env r
1697 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1698 ni env (PTyped l r) = ni env l ++ ni env r
1699 ni env (PPair _ _ l r) = ni env l ++ ni env r
1700 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1701 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1702 ni env (PAlternative a as) = concatMap (ni env) as
1703 ni env (PHidden tm) = ni env tm
1704 ni env (PUnifyLog tm) = ni env tm
1705 ni env (PDisamb _ tm) = ni env tm
1706 ni env (PNoImplicits tm) = ni env tm
1707 ni env _ = []
1709 niTacImp env (TacImp _ _ scr) = ni env scr
1710 niTacImp _ _ = []