1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntaxTree where
7import Idris.Core.Evaluate
8import Idris.Core.Elaborate hiding (Tactic(..))
9import Idris.Core.Typecheck
10import Idris.Docstrings
12import IRTS.CodegenCommon
14import Util.DynamicLinker
20import System.Console.Haskeline
23import Control.Monad.Trans.State.Strict
24import Control.Monad.Trans.Error
26import Data.List hiding (group)
28import qualified Data.Map as M
29import qualified Data.Text as T
30import qualified Data.Map as M
32import qualified Data.Set as S
33import Data.Word (Word)
37import Text.PrettyPrint.Annotated.Leijen
39-- Data to pass to recursively called elaborators; e.g. for where blocks,
40-- paramaterised declarations, etc.
42data ElabInfo = EInfo { params :: [(Name, PTerm)],
43 inblock :: Ctxt [Name], -- names in the block, and their params
44 liftname :: Name -> Name,
45 namespace :: Maybe [String] }
47toplevel = EInfo [] emptyContext id Nothing
49eInfoNames :: ElabInfo -> [Name]
50eInfoNames info = map fst (params info) ++ M.keys (inblock info)
52data IOption = IOption { opt_logLevel :: Int,
54 opt_typeintype :: Bool,
56 opt_showimp :: Bool, -- ^^ show implicits
57 opt_errContext :: Bool,
62 opt_codegen :: Codegen,
63 opt_outputTy :: OutputType,
64 opt_ibcsubdir :: FilePath,
65 opt_importdirs :: [FilePath],
69 opt_cmdline :: [Opt], -- remember whole command line
71 opt_autoSolve :: Bool -- ^ automatically apply "solve" tactic in prover
75defaultOpts = IOption { opt_logLevel = 0
76 , opt_typecase = False
77 , opt_typeintype = False
80 , opt_errContext = False
83 , opt_nobanner = False
86 , opt_outputTy = Executable
94 , opt_autoSolve = True
97data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord)
99-- | The output mode in use
100data OutputMode = RawOutput | IdeSlave Integer deriving Show
102-- | How wide is the console?
103data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken
104 | ColsWide Int -- ^ Manually specified - must be positive
105 | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise
107-- | The global state used in the Idris monad
108data IState = IState {
109 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
110 idris_constraints :: [(UConstraint, FC)],
111 -- ^ A list of universe constraints and their corresponding source locations
112 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
113 idris_implicits :: Ctxt [PArg],
114 idris_statics :: Ctxt [Bool],
115 idris_classes :: Ctxt ClassInfo,
116 idris_dsls :: Ctxt DSL,
117 idris_optimisation :: Ctxt OptInfo,
118 idris_datatypes :: Ctxt TypeInfo,
119 idris_namehints :: Ctxt [Name],
120 idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported
121 -- ^ list of lhs/rhs, and a list of missing clauses
122 idris_flags :: Ctxt [FnOpt],
123 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
124 idris_calledgraph :: Ctxt [Name],
125 idris_docstrings :: Ctxt (Docstring, [(Name, Docstring)]),
126 idris_tyinfodata :: Ctxt TIData,
127 idris_totcheck :: [(FC, Name)], -- names to check totality on
128 idris_defertotcheck :: [(FC, Name)], -- names to check at the end
129 idris_options :: IOption,
131 idris_lineapps :: [((FilePath, Int), PTerm)],
132 -- ^ Full application LHS on source line
133 idris_metavars :: [(Name, (Maybe Name, Int, Bool))], -- ^ The currently defined but not proven metavariables
134 idris_coercions :: [Name],
135 idris_transforms :: [(Term, Term)],
136 idris_errRev :: [(Term, Term)],
137 syntax_rules :: [Syntax],
138 syntax_keywords :: [String],
139 imported :: [FilePath], -- ^ The imported modules
140 idris_scprims :: [(Name, (Int, PrimFn))],
141 idris_objs :: [(Codegen, FilePath)],
142 idris_libs :: [(Codegen, String)],
143 idris_cgflags :: [(Codegen, String)],
144 idris_hdrs :: [(Codegen, String)],
145 idris_imported :: [FilePath], -- ^ Imported ibc file names
146 proof_list :: [(Name, [String])],
148 parserWarnings :: [(FC, Err)],
149 lastParse :: Maybe Name,
150 indent_stack :: [Int],
151 brace_stack :: [Maybe Int],
152 lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed?
153 hide_list :: [(Name, Maybe Accessibility)],
154 default_access :: Accessibility,
155 default_total :: Bool,
156 ibc_write :: [IBCWrite],
157 compiled_so :: Maybe String,
158 idris_dynamic_libs :: [DynamicLib],
159 idris_language_extensions :: [LanguageExt],
160 idris_outputmode :: OutputMode,
161 idris_colourRepl :: Bool,
162 idris_colourTheme :: ColourTheme,
163 idris_outh :: Handle,
164 idris_errorhandlers :: [Name], -- ^ Global error handlers
165 idris_nameIdx :: (Int, Ctxt (Int, Name)),
166 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
167 module_aliases :: M.Map [T.Text] [T.Text],
168 idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
169 idris_postulates :: S.Set Name,
170 idris_whocalls :: Maybe (M.Map Name [Name]),
171 idris_callswho :: Maybe (M.Map Name [Name])
174data SizeChange = Smaller | Same | Bigger | Unknown
177deriving instance Binary SizeChange
178deriving instance NFData SizeChange
181type SCGEntry = (Name, [Maybe (Int, SizeChange)])
182type UsageReason = (Name, Int) -- fn_name, its_arg_number
184data CGInfo = CGInfo { argsdef :: [Name],
185 calls :: [(Name, [[Name]])],
188 usedpos :: [(Int, [UsageReason])] }
191deriving instance Binary CGInfo
192deriving instance NFData CGInfo
195primDefs = [sUN "unsafePerformPrimIO",
196 sUN "mkLazyForeignPrim",
200-- information that needs writing for the current module's .ibc file
201data IBCWrite = IBCFix FixDecl
205 | IBCInstance Bool Name Name
213 | IBCObj Codegen FilePath
214 | IBCLib Codegen String
215 | IBCCGFlag Codegen String
217 | IBCHeader Codegen String
218 | IBCAccess Name Accessibility
219 | IBCMetaInformation Name MetaInformation
220 | IBCTotal Name Totality
221 | IBCFlags Name [FnOpt]
222 | IBCTrans (Term, Term)
223 | IBCErrRev (Term, Term)
227 | IBCDef Name -- i.e. main context
228 | IBCNameHint (Name, Name)
229 | IBCLineApp FilePath Int PTerm
230 | IBCErrorHandler Name
231 | IBCFunctionErrorHandler Name Name Name
235-- | The initial state for the compiler
237idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
238 emptyContext emptyContext emptyContext emptyContext
239 emptyContext emptyContext emptyContext emptyContext
240 emptyContext emptyContext
241 [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
242 [] [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
243 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
244 AutomaticWidth S.empty Nothing Nothing
246-- | The monad for the main REPL - reading and processing files and updating
247-- global state (hence the IO inner monad).
248--type Idris = WriterT [Either String (IO ())] (State IState a))
249type Idris = StateT IState (ErrorT Err IO)
251-- Commands in the REPL
270 | ChangeDirectory FilePath
273 | Compile Codegen String
278 | AddProof (Maybe Name)
289 | DynamicLink FilePath
294 | CaseSplitAt Bool Int Name
295 | AddClauseFrom Bool Int Name
296 | AddProofClauseFrom Bool Int Name
297 | AddMissing Bool Int Name
298 | MakeWith Bool Int Name
299 | DoProofSearch Bool -- ^ update
300 Bool -- ^ recursive (i.e. do arguments too)
305 | SetColour ColourType IdrisColour
309 | SetConsoleWidth ConsoleWidth
313 | MakeDoc String -- IdrisDoc
316data Opt = Filename String
328 | NoBuiltins -- only for the really primitive stuff!
349 | PkgMkDoc String -- IdrisDoc
356 | OutputTy OutputType
357 | Extension LanguageExt
358 | InterpretScript String
360 | TargetTriple String
365 | AutoWidth -- ^ Automatically adjust terminal width
366 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
369-- Parsed declarations
371data Fixity = Infixl { prec :: Int }
372 | Infixr { prec :: Int }
373 | InfixN { prec :: Int }
374 | PrefixN { prec :: Int }
377deriving instance Binary Fixity
378deriving instance NFData Fixity
381instance Show Fixity where
382 show (Infixl i) = "infixl " ++ show i
383 show (Infixr i) = "infixr " ++ show i
384 show (InfixN i) = "infix " ++ show i
385 show (PrefixN i) = "prefix " ++ show i
387data FixDecl = Fix Fixity String
390instance Show FixDecl where
391 show (Fix f s) = show f ++ " " ++ s
394deriving instance Binary FixDecl
395deriving instance NFData FixDecl
398instance Ord FixDecl where
399 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
402data Static = Static | Dynamic
405deriving instance Binary Static
406deriving instance NFData Static
409-- Mark bindings with their explicitness, and laziness
410data Plicity = Imp { pargopts :: [ArgOpt],
413 | Exp { pargopts :: [ArgOpt],
415 pparam :: Bool } -- this is a param (rather than index)
416 | Constraint { pargopts :: [ArgOpt],
418 | TacImp { pargopts :: [ArgOpt],
424deriving instance Binary Plicity
425deriving instance NFData Plicity
428impl = Imp [] Dynamic False
429expl = Exp [] Dynamic False
430expl_param = Exp [] Dynamic True
431constraint = Constraint [] Dynamic
432tacimpl t = TacImp [] Dynamic t
434data FnOpt = Inlinable -- always evaluate when simplifying
435 | TotalFn | PartialFn | CoveringFn
436 | Coinductive | AssertTotal
437 | Dictionary -- type class dictionary, eval only when
438 -- a function argument, and further evaluation resutls
439 | Implicit -- implicit coercion
440 | CExport String -- export, with a C name
441 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
442 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
443 | Reflection -- a reflecting function, compile-time only
444 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
447deriving instance Binary FnOpt
448deriving instance NFData FnOpt
453inlinable :: FnOpts -> Bool
454inlinable = elem Inlinable
456dictionary :: FnOpts -> Bool
457dictionary = elem Dictionary
460-- | Data declaration options
461data DataOpt = Codata -- Set if the the data-type is coinductive
462 | DefaultEliminator -- Set if an eliminator should be generated for data type
466type DataOpts = [DataOpt]
468-- | Type provider - what to provide
469data ProvideWhat = ProvTerm -- ^ only allow providing terms
470 | ProvPostulate -- ^ only allow postulates
471 | ProvAny -- ^ either is ok
474-- | Top-level declarations such as compiler directives, definitions,
475-- datatypes and typeclasses.
477 = PFix FC Fixity [String] -- ^ Fixity declaration
478 | PTy Docstring [(Name, Docstring)] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
479 | PPostulate Docstring SyntaxInfo FC FnOpts Name t -- ^ Postulate
480 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
481 | PCAF FC Name t -- ^ Top level constant
482 | PData Docstring [(Name, Docstring)] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
483 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
484 | PNamespace String [PDecl' t] -- ^ New namespace
485 | PRecord Docstring SyntaxInfo FC Name t DataOpts Docstring Name t -- ^ Record declaration
486 | PClass Docstring SyntaxInfo FC
489 [(Name, t)] -- parameters
490 [PDecl' t] -- declarations
491 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
492 -- class name, parameters, method declarations
493 | PInstance SyntaxInfo FC [t] -- constraints
496 t -- full instance type
497 (Maybe Name) -- explicit name
499 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
500 -- class name, parameters, full instance type, optional explicit name, and definitions
501 | PDSL Name (DSL' t) -- ^ DSL declaration
502 | PSyntax FC Syntax -- ^ Syntax definition
503 | PMutual FC [PDecl' t] -- ^ Mutual block
504 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
505 | PProvider SyntaxInfo FC ProvideWhat Name t t -- ^ Type provider. The first t is the type, the second is the term
506 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
507 -- bool is True, lhs and rhs must be convertible
510deriving instance Binary PDecl'
511deriving instance NFData PDecl'
514-- For elaborator state
515type ElabD a = Elab' [PDecl] a
517-- | One clause of a top-level definition. Term arguments to constructors are:
519-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
521-- 2. The list of extra 'with' patterns
523-- 3. The right-hand side
525-- 4. The where block (PDecl' t)
527data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
528 | PWith FC Name t [t] t [PDecl' t]
529 | PClauseR FC [t] t [PDecl' t]
530 | PWithR FC [t] t [PDecl' t]
533deriving instance Binary PClause'
534deriving instance NFData PClause'
538data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
539 d_tcon :: t, -- ^ Type constructor
540 d_cons :: [(Docstring, [(Name, Docstring)], Name, t, FC, [Name])] -- ^ Constructors
542 -- ^ Data declaration
543 | PLaterdecl { d_name :: Name, d_tcon :: t }
544 -- ^ "Placeholder" for data whose constructors are defined later
547deriving instance Binary PData'
548deriving instance NFData PData'
551-- Handy to get a free function for applying PTerm -> PTerm functions
552-- across a program, by deriving Functor
554type PDecl = PDecl' PTerm
555type PData = PData' PTerm
556type PClause = PClause' PTerm
558-- get all the names declared in a decl
560declared :: PDecl -> [Name]
561declared (PFix _ _ _) = []
562declared (PTy _ _ _ _ _ n t) = [n]
563declared (PPostulate _ _ _ _ n t) = [n]
564declared (PClauses _ _ n _) = [] -- not a declaration
565declared (PCAF _ n _) = [n]
566declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
567 where fstt (_, _, a, _, _, _) = a
568declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
569declared (PParams _ _ ds) = concatMap declared ds
570declared (PNamespace _ ds) = concatMap declared ds
571declared (PRecord _ _ _ n _ _ _ c _) = [n, c]
572declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
573declared (PInstance _ _ _ _ _ _ _ _) = []
574declared (PDSL n _) = [n]
575declared (PSyntax _ _) = []
576declared (PMutual _ ds) = concatMap declared ds
577declared (PDirective _) = []
579-- get the names declared, not counting nested parameter blocks
580tldeclared :: PDecl -> [Name]
581tldeclared (PFix _ _ _) = []
582tldeclared (PTy _ _ _ _ _ n t) = [n]
583tldeclared (PPostulate _ _ _ _ n t) = [n]
584tldeclared (PClauses _ _ n _) = [] -- not a declaration
585tldeclared (PRecord _ _ _ n _ _ _ c _) = [n, c]
586tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
587 where fstt (_, _, a, _, _, _) = a
588tldeclared (PParams _ _ ds) = []
589tldeclared (PMutual _ ds) = concatMap tldeclared ds
590tldeclared (PNamespace _ ds) = concatMap tldeclared ds
591tldeclared (PClass _ _ _ _ n _ ms) = concatMap tldeclared ms
592tldeclared (PInstance _ _ _ _ _ _ _ _) = []
595defined :: PDecl -> [Name]
596defined (PFix _ _ _) = []
597defined (PTy _ _ _ _ _ n t) = []
598defined (PPostulate _ _ _ _ n t) = []
599defined (PClauses _ _ n _) = [n] -- not a declaration
600defined (PCAF _ n _) = [n]
601defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
602 where fstt (_, _, a, _, _, _) = a
603defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
604defined (PParams _ _ ds) = concatMap defined ds
605defined (PNamespace _ ds) = concatMap defined ds
606defined (PRecord _ _ _ n _ _ _ c _) = [n, c]
607defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
608defined (PInstance _ _ _ _ _ _ _ _) = []
609defined (PDSL n _) = [n]
610defined (PSyntax _ _) = []
611defined (PMutual _ ds) = concatMap defined ds
612defined (PDirective _) = []
615updateN :: [(Name, Name)] -> Name -> Name
616updateN ns n | Just n' <- lookup n ns = n'
619updateNs :: [(Name, Name)] -> PTerm -> PTerm
621updateNs ns t = mapPT updateRef t
622 where updateRef (PRef fc f) = PRef fc (updateN ns f)
625-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
627-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
628-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
629-- where updateCNs ns (PClause n l ts r ds)
630-- = PClause (updateN ns n) (fmap (updateNs ns) l)
631-- (map (fmap (updateNs ns)) ts)
632-- (fmap (updateNs ns) r)
633-- (map (updateDNs ns) ds)
636data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
638-- | High level language terms
639data PTerm = PQuote Raw
641 | PInferRef FC Name -- ^ A name to be defined later
643 | PLam Name PTerm PTerm
644 | PPi Plicity Name PTerm PTerm -- ^ (n : t1) -> t2
645 | PLet Name PTerm PTerm PTerm
646 | PTyped PTerm PTerm -- ^ Term with explicit type
647 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
648 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
649 | PMatchApp FC Name -- ^ Make an application by type matching
650 | PCase FC PTerm [(PTerm, PTerm)]
651 | PTrue FC PunInfo -- ^ Unit type..?
655 | PEq FC PTerm PTerm -- ^ Equality type: A = B
656 | PRewrite FC PTerm PTerm (Maybe PTerm)
657 | PPair FC PunInfo PTerm PTerm
658 | PDPair FC PunInfo PTerm PTerm PTerm
659 | PAlternative Bool [PTerm] -- True if only one may work
660 | PHidden PTerm -- ^ Irrelevant or hidden pattern
661 | PType -- ^ 'Type' type
662 | PGoal FC PTerm Name PTerm
663 | PConstant Const -- ^ Builtin types
669 | PProof [PTactic] -- ^ Proof script
670 | PTactics [PTactic] -- ^ As PProof, but no auto solving
671 | PElabError Err -- ^ Error to report on elaboration
672 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
673 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
674 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
675 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
676 | PNoImplicits PTerm -- ^ never run implicit converions on the term
681deriving instance Binary PTerm
682deriving instance NFData PTerm
685mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
686mapPT f t = f (mpt t) where
687 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
688 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
689 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
690 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
692 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
693 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
694 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
695 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
696 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
697 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
698 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
699 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
700 mpt (PHidden t) = PHidden (mapPT f t)
701 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
702 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
703 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
704 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
705 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
706 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
707 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
711data PTactic' t = Intro [Name] | Intros | Focus Name
712 | Refine Name [Bool] | Rewrite t | DoUnify
716 | LetTac Name t | LetTacTy Name t t
717 | Exact t | Compute | Trivial | TCInstance
718 | ProofSearch Bool -- ^ recursive
722 | ProofState | ProofTerm | Undo
723 | Try (PTactic' t) (PTactic' t)
724 | TSeq (PTactic' t) (PTactic' t)
725 | ApplyTactic t -- see Language.Reflection module
729 | GoalType String (PTactic' t)
733 deriving (Show, Eq, Functor)
735deriving instance Binary PTactic'
736deriving instance NFData PTactic'
738instance Sized a => Sized (PTactic' a) where
739 size (Intro nms) = 1 + size nms
741 size (Focus nm) = 1 + size nm
742 size (Refine nm bs) = 1 + size nm + length bs
743 size (Rewrite t) = 1 + size t
744 size (Induction t) = 1 + size t
745 size (LetTac nm t) = 1 + size nm + size t
746 size (Exact t) = 1 + size t
754 size (Try l r) = 1 + size l + size r
755 size (TSeq l r) = 1 + size l + size r
756 size (ApplyTactic t) = 1 + size t
757 size (Reflect t) = 1 + size t
758 size (Fill t) = 1 + size t
762type PTactic = PTactic' PTerm
764data PDo' t = DoExp FC t
766 | DoBindP FC t t [(t,t)]
769 deriving (Eq, Functor)
771deriving instance Binary PDo'
772deriving instance NFData PDo'
775instance Sized a => Sized (PDo' a) where
776 size (DoExp fc t) = 1 + size fc + size t
777 size (DoBind fc nm t) = 1 + size fc + size nm + size t
778 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
779 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
780 size (DoLetP fc l r) = 1 + size fc + size l + size r
784-- The priority gives a hint as to elaboration order. Best to elaborate
785-- things early which will help give a more concrete type to other
786-- variables, e.g. a before (interpTy a).
788data PArg' t = PImp { priority :: Int,
789 machine_inf :: Bool, -- true if the machine inferred it
791 pname :: Name, getTm :: t }
792 | PExp { priority :: Int,
796 | PConstraint { priority :: Int,
800 | PTacImplicit { priority :: Int,
805 deriving (Show, Eq, Functor)
807data ArgOpt = HideDisplay | InaccessibleArg
810instance Sized a => Sized (PArg' a) where
811 size (PImp p _ l nm trm) = 1 + size nm + size trm
812 size (PExp p l nm trm) = 1 + size nm + size trm
813 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
814 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
817deriving instance Binary PArg'
818deriving instance NFData PArg'
821pimp n t mach = PImp 1 mach [] n t
822pexp t = PExp 1 [] (sMN 0 "arg") t
823pconst t = PConstraint 1 [] (sMN 0 "carg") t
824ptacimp n s t = PTacImplicit 2 [] n s t
826type PArg = PArg' PTerm
830data ClassInfo = CI { instanceName :: Name,
831 class_methods :: [(Name, (FnOpts, PTerm))],
832 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
833 class_default_superclasses :: [PDecl],
834 class_params :: [Name],
835 class_instances :: [Name] }
838deriving instance Binary ClassInfo
839deriving instance NFData ClassInfo
842-- Type inference data
844data TIData = TIPartial -- ^ a function with a partially defined type
845 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
848data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
852deriving instance Binary OptInfo
853deriving instance NFData OptInfo
857data TypeInfo = TI { con_names :: [Name],
859 data_opts :: DataOpts,
863deriving instance Binary TypeInfo
864deriving instance NFData TypeInfo
867-- Syntactic sugar info
869data DSL' t = DSL { dsl_bind :: t,
874 index_first :: Maybe t,
875 index_next :: Maybe t,
876 dsl_lambda :: Maybe t,
879 deriving (Show, Functor)
881deriving instance Binary DSL'
882deriving instance NFData DSL'
887data SynContext = PatternSyntax | TermSyntax | AnySyntax
890deriving instance Binary SynContext
891deriving instance NFData SynContext
894data Syntax = Rule [SSymbol] PTerm SynContext
897deriving instance Binary Syntax
898deriving instance NFData Syntax
901data SSymbol = Keyword Name
908deriving instance Binary SSymbol
909deriving instance NFData SSymbol
912initDSL = DSL (PRef f (sUN ">>="))
913 (PRef f (sUN "return"))
915 (PRef f (sUN "pure"))
921 where f = fileFC "(builtin)"
923data Using = UImplicit Name PTerm
924 | UConstraint Name [Name]
927deriving instance Binary Using
928deriving instance NFData Using
931data SyntaxInfo = Syn { using :: [Using],
932 syn_params :: [(Name, PTerm)],
933 syn_namespace :: [String],
935 decoration :: Name -> Name,
937 implicitAllowed :: Bool,
941deriving instance NFData SyntaxInfo
942deriving instance Binary SyntaxInfo
945defaultSyntax = Syn [] [] [] [] id False False initDSL
947expandNS :: SyntaxInfo -> Name -> Name
948expandNS syn n@(NS _ _) = n
949expandNS syn n = case syn_namespace syn of
954-- For inferring types of things
958inferTy = sMN 0 "__Infer"
959inferCon = sMN 0 "__infer"
960inferDecl = PDatadecl inferTy
962 [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType (
963 PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType"))
964 (PRef bi inferTy)), bi, [])]
967infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
968infP = P (TCon 6 0) inferTy (TType (UVal 0))
970getInferTerm, getInferType :: Term -> Term
971getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
972getInferTerm (App (App _ _) tm) = tm
973getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
975getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
976 where toTy (Lam t) = Pi t
977 toTy (PVar t) = PVTy t
979getInferType (App (App _ ty) _) = ty
983-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign, Elim type class
985primNames = [unitTy, unitCon,
986 falseTy, pairTy, pairCon,
987 eqTy, eqCon, inferTy, inferCon]
989unitDoc = parseDocstring . T.pack $ "The canonical single-element type, also known as the trivially true proposition."
990unitTy = sMN 0 "__Unit"
991unitCon = sMN 0 "__II"
992unitDecl = PDatadecl unitTy PType
993 [(parseDocstring . T.pack $ "The trivial constructor for `()`. ", [], unitCon, PRef bi unitTy, bi, [])]
994unitOpts = [DefaultEliminator]
996falseDoc = parseDocstring . T.pack $
997 "The empty type, also known as the trivially false proposition." ++
999 "Use `FalseElim` or `absurd` to prove anything if you have a variable " ++
1000 "of type `_|_` in scope."
1001falseTy = sMN 0 "__False"
1002falseDecl = PDatadecl falseTy PType []
1005pairDoc = parseDocstring . T.pack $ "The non-dependent pair type, also known as conjunction."
1006pairTy = sMN 0 "__Pair"
1007pairCon = sMN 0 "__MkPair"
1008pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
1009 [(pairConDoc, pairConParamDoc,
1010 pairCon, PPi impl (n "A") PType (
1011 PPi impl (n "B") PType (
1012 PPi expl (n "a") (PRef bi (n "A")) (
1013 PPi expl (n "b") (PRef bi (n "B"))
1014 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
1015 pexp (PRef bi (n "B"))])))), bi, [])]
1017 pairConDoc = parseDocstring . T.pack $ "A pair of elements"
1018 pairConParamDoc = [(n "a", parseDocstring . T.pack $ "the left element of the pair"),
1019 (n "b", parseDocstring . T.pack $ "the right element of the pair")]
1021pairParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left elements in the pair"),
1022 (n "B", parseDocstring . T.pack $ "the type of the left elements in the pair")]
1027eqDoc = parseDocstring . T.pack $
1028 "The propositional equality type. A proof that `x` = `y`." ++
1030 "To use such a proof, pattern-match on it, and the two equal things will " ++
1031 "then need to be the _same_ pattern." ++
1033 "**Note**: Idris's equality type is _heterogeneous_, which means that it " ++
1034 "is possible to state equalities between values of potentially different " ++
1035 "types. This is sometimes referred to in the literature as \"John Major\" " ++
1038 "Thus, if Idris can't infer the type of one side of the equality, then " ++
1039 "you may need to annotate it. See the function `the`."
1041eqDecl = PDatadecl eqTy (piBind [(n "A", PType), (n "B", PType),
1042 (n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))]
1044 [(reflDoc, reflParamDoc,
1045 eqCon, PPi impl (n "A") PType (
1046 PPi impl (n "x") (PRef bi (n "A"))
1047 (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False,
1048 pimp (n "B") Placeholder False,
1049 pexp (PRef bi (n "x")),
1050 pexp (PRef bi (n "x"))])), bi, [])]
1052 reflDoc = parseDocstring . T.pack $
1053 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1054 "shown that both sides are in fact equal."
1055 reflParamDoc = [(n "A", parseDocstring . T.pack $ "the type at which the equality is proven"),
1056 (n "x", parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1058eqParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left side of the equality"),
1059 (n "B", parseDocstring . T.pack $ "the type of the right side of the equality")
1065elimName = sUN "__Elim"
1066elimMethElimTy = sUN "__elimTy"
1067elimMethElim = sUN "elim"
1068elimDecl = PClass (parseDocstring . T.pack $ "Type class for eliminators") defaultSyntax bi [] elimName [(sUN "scrutineeType", PType)]
1069 [PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElimTy PType,
1070 PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElim (PRef bi elimMethElimTy)]
1072-- Defined in builtins.idr
1073sigmaTy = sUN "Exists"
1074existsCon = sUN "Ex_intro"
1076piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1077piBind = piBindp expl
1079piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1081piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t)
1084-- Pretty-printing declarations and terms
1086-- These "show" instances render to an absurdly wide screen because inserted line breaks
1087-- could interfere with interactive editing, which calls "show".
1089instance Show PTerm where
1090 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp False) tm
1092instance Show PDecl where
1093 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp False) d
1095instance Show PClause where
1096 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp True) c
1098instance Show PData where
1099 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp False) d
1101instance Pretty PTerm OutputAnnotation where
1102 pretty = prettyImp False
1104-- | Colourise annotations according to an Idris state. It ignores the names
1105-- in the annotation, as there's no good way to show extended information on a
1107consoleDecorate :: IState -> OutputAnnotation -> String -> String
1108consoleDecorate ist _ | not (idris_colourRepl ist) = id
1109consoleDecorate ist AnnConstData = let theme = idris_colourTheme ist
1110 in colouriseData theme
1111consoleDecorate ist AnnConstType = let theme = idris_colourTheme ist
1112 in colouriseType theme
1113consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
1114consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
1115consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1116consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1117 theme = idris_colourTheme ist
1119 _ | isDConName n ctxt -> colouriseData theme
1120 _ | isFnName n ctxt -> colouriseFun theme
1121 _ | isTConName n ctxt -> colouriseType theme
1122 _ | otherwise -> id -- don't colourise unknown names
1123consoleDecorate ist (AnnFC _) = id
1124consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
1125 where colour BoldText = IdrisColour Nothing True False True False
1126 colour UnderlineText = IdrisColour Nothing True True False False
1127 colour ItalicText = IdrisColour Nothing True False False True
1129-- | Pretty-print a high-level closed Idris term
1130prettyImp :: Bool -- ^^ whether to show implicits
1131 -> PTerm -- ^^ the term to pretty-print
1132 -> Doc OutputAnnotation
1133prettyImp impl = pprintPTerm impl [] []
1135-- | Pretty-print a high-level Idris term in some bindings context
1136pprintPTerm :: Bool -- ^^ whether to show implicits
1137 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1138 -> [Name] -- ^^ names to always show in pi, even if not used
1139 -> PTerm -- ^^ the term to pretty-print
1140 -> Doc OutputAnnotation
1141pprintPTerm impl bnd docArgs = prettySe 10 bnd
1143 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1144 prettySe p bnd (PQuote r) =
1145 text "![" <> pretty r <> text "]"
1146 prettySe p bnd (PPatvar fc n) = pretty n
1148 | Just str <- slist p bnd e = str
1149 | Just n <- snat p e = annotate AnnConstData (text (show n))
1150 prettySe p bnd (PRef fc n) = prettyName impl bnd n
1151 prettySe p bnd (PLam n ty sc) =
1152 bracket p 2 . group . align . hang 2 $
1153 text "\\" <> bindingOf n False <+> text "=>" <$>
1154 prettySe 10 ((n, False):bnd) sc
1155 prettySe p bnd (PLet n ty v sc) =
1157 kwd "let" <+> bindingOf n False <+> text "=" </>
1158 prettySe 10 bnd v <+> kwd "in" </>
1159 prettySe 10 ((n, False):bnd) sc
1160 prettySe p bnd (PPi (Exp l s _) n ty sc)
1161 | n `elem` allNamesIn sc || impl || n `elem` docArgs =
1162 bracket p 2 . group $
1163 enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1164 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1166 bracket p 2 . group $
1167 group (prettySe 0 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1171 Static -> text "[static]" <> space
1173 prettySe p bnd (PPi (Imp l s _) n ty sc)
1176 lbrace <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1177 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1178 | otherwise = prettySe 10 ((n, True):bnd) sc
1182 Static -> text "[static]" <> space
1184 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1186 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1187 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1189 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1190 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1191 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1192 | UN nm <- basename f
1193 , not impl && null (getExps args) = if isAlpha (thead nm)
1194 then prettyName impl bnd f
1195 else enclose lparen rparen $
1196 prettyName impl bnd f
1197 prettySe p bnd (PAppBind _ (PRef _ f) [])
1198 | not impl = text "!" <> prettyName impl bnd f
1199 prettySe p bnd (PApp _ (PRef _ op) args)
1200 | UN nm <- basename op
1202 (not impl) && (not $ isAlpha (thead nm)) =
1203 case getExps args of
1204 [] -> enclose lparen rparen opName
1205 [x] -> group (enclose lparen rparen opName <$> group (prettySe 0 bnd x))
1206 [l,r] -> bracket p 1 $ inFix l r
1207 (l:r:rest) -> bracket p 1 $
1208 enclose lparen rparen (inFix l r) <+>
1209 align (group (vsep (map (prettyArgSe bnd) rest)))
1210 where opName = prettyName impl bnd op
1211 inFix l r = align . group $
1212 (prettySe 1 bnd l <+> opName) <$> group (prettySe 0 bnd r)
1213 prettySe p bnd (PApp _ hd@(PRef fc f) [tm])
1214 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1215 f == sUN "Symbol_" = char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1216 prettySe p bnd (PApp _ f as) =
1217 let args = getExps as
1218 fp = prettySe 1 bnd f
1220 bracket p 1 . group $
1224 else fp <+> align (vsep (map (prettyArgS bnd) as))
1227 else fp <+> align (vsep (map (prettyArgSe bnd) args))
1228 prettySe p bnd (PCase _ scr opts) =
1229 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1231 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1233 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1234 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1235 prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
1236 prettySe p bnd (PResolveTC _) = text "resolvetc"
1237 prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1238 prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1239 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1240 prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
1241 prettySe p bnd (PEq _ l r) =
1242 bracket p 2 . align . group $
1243 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1244 where eq = annName eqTy (text "=")
1245 prettySe p bnd (PRewrite _ l r _) =
1247 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1248 prettySe p bnd (PTyped l r) =
1249 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1250 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1251 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1252 align . group . vsep . punctuate (ann comma) $
1253 map (prettySe 10 bnd) elts
1254 where ann = case pun of
1256 IsType -> annName pairTy
1257 IsTerm -> annName pairCon
1258 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1259 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1260 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1261 annName sigmaTy lparen <>
1262 bindingOf n False <+>
1263 annName sigmaTy (text "**") <+>
1264 prettySe 10 ((n, False):bnd) r <>
1265 annName sigmaTy rparen
1266 prettySe p bnd (PDPair _ IsType l t r) =
1267 annName sigmaTy lparen <>
1268 prettySe 10 bnd l <+>
1269 annName sigmaTy (text "**") <+>
1270 prettySe 10 bnd r <>
1271 annName sigmaTy rparen
1272 prettySe p bnd (PDPair _ IsTerm l t r) =
1273 annName existsCon lparen <>
1274 prettySe 10 bnd l <+>
1275 annName existsCon (text "**") <+>
1276 prettySe 10 bnd r <>
1277 annName existsCon rparen
1278 prettySe p bnd (PAlternative a as) =
1279 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1282 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1283 prettySe p bnd PType = annotate AnnConstType $ text "Type"
1284 prettySe p bnd (PConstant c) = annotate (annot c) (text (show c))
1285 where annot (AType _) = AnnConstType
1286 annot StrType = AnnConstType
1287 annot PtrType = AnnConstType
1288 annot VoidType = AnnConstType
1289 annot _ = AnnConstData
1290 -- XXX: add pretty for tactics
1291 prettySe p bnd (PProof ts) =
1292 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1293 prettySe p bnd (PTactics ts) =
1294 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1295 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1296 prettySe p bnd (PReturn f) = kwd "return"
1297 prettySe p bnd PImpossible = kwd "impossible"
1298 prettySe p bnd Placeholder = text "_"
1299 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1300 prettySe p bnd (PElabError s) = pretty s
1302 prettySe p bnd _ = text "test"
1304 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1305 prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm
1306 prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm
1307 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1309 prettyArgSe bnd arg = prettySe 0 bnd arg
1310 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1311 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1312 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1314 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1315 annName n = annotate (AnnName n Nothing Nothing Nothing)
1317 basename :: Name -> Name
1318 basename (NS n _) = basename n
1321 slist' p bnd (PApp _ (PRef _ nil) _)
1322 | not impl && nsroot nil == sUN "Nil" = Just []
1323 slist' p bnd (PRef _ nil)
1324 | not impl && nsroot nil == sUN "Nil" = Just []
1325 slist' p bnd (PApp _ (PRef _ cons) args)
1326 | nsroot cons == sUN "::",
1327 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1329 Just tl' <- slist' p bnd tl
1332 isImp (PImp {}) = True
1334 slist' _ _ tm = Nothing
1336 slist p bnd e | Just es <- slist' p bnd e = Just $
1337 case es of [] -> annotate AnnConstData $ text "[]"
1338 [x] -> enclose left right . group $
1340 xs -> (enclose left right .
1341 align . group . vsep .
1343 map (prettySe p bnd)) xs
1344 where left = (annotate AnnConstData (text "["))
1345 right = (annotate AnnConstData (text "]"))
1346 comma = (annotate AnnConstData (text ","))
1347 slist _ _ _ = Nothing
1349 pairElts :: PTerm -> Maybe [PTerm]
1350 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1351 | otherwise = Just [x, y]
1352 pairElts _ = Nothing
1354 natns = "Prelude.Nat."
1357 | show z == (natns++"Z") || show z == "Z" = Just 0
1358 snat p (PApp _ s [PExp {getTm=n}])
1359 | show s == (natns++"S") || show s == "S",
1364 bracket outer inner doc
1365 | inner > outer = lparen <> doc <> rparen
1368 kwd = annotate AnnKeyword . text
1370-- | Pretty-printer helper for the binding site of a name
1371bindingOf :: Name -- ^^ the bound name
1372 -> Bool -- ^^ whether the name is implicit
1373 -> Doc OutputAnnotation
1374bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1376-- | Pretty-printer helper for names that attaches the correct annotations
1377prettyName :: Bool -- ^^ whether to show namespaces
1378 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1379 -> Name -- ^^ the name to pprint
1380 -> Doc OutputAnnotation
1381prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1382 | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
1383 where strName (UN n) = T.unpack n
1384 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1385 | otherwise = strName n
1386 strName n | n == falseTy = "_|_"
1387 strName (MN i s) = T.unpack s
1388 strName other = show other
1391showCImp :: Bool -> PClause -> Doc OutputAnnotation
1392showCImp impl (PClause _ n l ws r w)
1393 = prettyImp impl l <+> showWs ws <+> text "=" <+> prettyImp impl r
1394 <+> text "where" <+> text (show w)
1397 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1398showCImp impl (PWith _ n l ws r w)
1399 = prettyImp impl l <+> showWs ws <+> text "with" <+> prettyImp impl r
1400 <+> braces (text (show w))
1403 showWs (x : xs) = text "|" <+> prettyImp impl x <+> showWs xs
1406showDImp :: Bool -> PData -> Doc OutputAnnotation
1407showDImp impl (PDatadecl n ty cons)
1408 = text "data" <+> text (show n) <+> colon <+> prettyImp impl ty <+> text "where" <$>
1409 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp impl t) cons))
1411showDecls :: Bool -> [PDecl] -> Doc OutputAnnotation
1412showDecls i ds = vsep (map (showDeclImp i) ds)
1414showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1415showDeclImp i (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp i t
1416showDeclImp i (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1417 indent 2 (vsep (map (showCImp i) cs))
1418showDeclImp _ (PData _ _ _ _ _ d) = showDImp True d
1419showDeclImp i (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls i ps <> line)
1420showDeclImp i (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls i ps <> line)
1421showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1422showDeclImp i (PClass _ _ _ cs n ps ds)
1423 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls i ds
1424showDeclImp i (PInstance _ _ cs n _ t _ ds)
1425 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp i t <> line <> showDecls i ds
1426showDeclImp _ _ = text "..."
1427-- showDeclImp (PImport i) = "import " ++ i
1429instance Show (Doc OutputAnnotation) where
1430 show = flip (displayS . renderCompact) ""
1432getImps :: [PArg] -> [(Name, PTerm)]
1434getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1435getImps (_ : xs) = getImps xs
1437getExps :: [PArg] -> [PTerm]
1439getExps (PExp _ _ _ tm : xs) = tm : getExps xs
1440getExps (_ : xs) = getExps xs
1442getConsts :: [PArg] -> [PTerm]
1444getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
1445getConsts (_ : xs) = getConsts xs
1447getAll :: [PArg] -> [PTerm]
1452showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1453 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1454 -> Bool -- ^^ whether to show implicits
1455 -> Bool -- ^^ whether to colourise
1456 -> Name -- ^^ the term to show
1458showName ist bnd impl colour n = case ist of
1459 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1460 Nothing -> showbasic n
1461 where name = if impl then show n else showbasic n
1462 showbasic n@(UN _) = showCG n
1463 showbasic (MN _ s) = str s
1464 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1465 showbasic (SN s) = show s
1467 colourise n t = let ctxt' = fmap tt_ctxt ist in
1470 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1471 else colouriseBound t name
1472 | isDConName n ctxt -> colouriseData t name
1473 | isFnName n ctxt -> colouriseFun t name
1474 | isTConName n ctxt -> colouriseType t name
1475 -- The assumption is that if a name is not bound and does not exist in the
1476 -- global context, then we're somewhere in which implicit info has been lost
1477 -- (like error messages). Thus, unknown vars are colourised as implicits.
1478 | otherwise -> colouriseImplicit t name
1480showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1481 -> PTerm -- ^^ the term to show
1483showTm ist = displayDecorated (consoleDecorate ist) .
1484 renderPretty 0.8 100000 .
1485 prettyImp (opt_showimp (idris_options ist))
1487-- | Show a term with implicits, no colours
1488showTmImpls :: PTerm -> String
1489showTmImpls = flip (displayS . renderCompact . prettyImp True) ""
1492instance Sized PTerm where
1493 size (PQuote rawTerm) = size rawTerm
1494 size (PRef fc name) = size name
1495 size (PLam name ty bdy) = 1 + size ty + size bdy
1496 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1497 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1498 size (PTyped trm ty) = 1 + size trm + size ty
1499 size (PApp fc name args) = 1 + size args
1500 size (PAppBind fc name args) = 1 + size args
1501 size (PCase fc trm bdy) = 1 + size trm + size bdy
1502 size (PTrue fc _) = 1
1503 size (PFalse fc) = 1
1504 size (PRefl fc _) = 1
1505 size (PResolveTC fc) = 1
1506 size (PEq fc left right) = 1 + size left + size right
1507 size (PRewrite fc left right _) = 1 + size left + size right
1508 size (PPair fc _ left right) = 1 + size left + size right
1509 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1510 size (PAlternative a alts) = 1 + size alts
1511 size (PHidden hidden) = size hidden
1512 size (PUnifyLog tm) = size tm
1513 size (PDisamb _ tm) = size tm
1514 size (PNoImplicits tm) = size tm
1516 size (PConstant const) = 1 + size const
1517 size Placeholder = 1
1518 size (PDoBlock dos) = 1 + size dos
1519 size (PIdiom fc term) = 1 + size term
1520 size (PReturn fc) = 1
1521 size (PMetavar name) = 1
1522 size (PProof tactics) = size tactics
1523 size (PElabError err) = size err
1524 size PImpossible = 1
1526getPArity :: PTerm -> Int
1527getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1530-- Return all names, free or globally bound, in the given term.
1532allNamesIn :: PTerm -> [Name]
1533allNamesIn tm = nub $ ni [] tm
1534 where -- TODO THINK added niTacImp, but is it right?
1536 | not (n `elem` env) = [n]
1537 ni env (PPatvar _ n) = [n]
1538 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1539 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1540 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1541 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1542 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1543 ni env (PHidden tm) = ni env tm
1544 ni env (PEq _ l r) = ni env l ++ ni env r
1545 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1546 ni env (PTyped l r) = ni env l ++ ni env r
1547 ni env (PPair _ _ l r) = ni env l ++ ni env r
1548 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1549 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1550 ni env (PAlternative a ls) = concatMap (ni env) ls
1551 ni env (PUnifyLog tm) = ni env tm
1552 ni env (PDisamb _ tm) = ni env tm
1553 ni env (PNoImplicits tm) = ni env tm
1556 niTacImp env (TacImp _ _ scr) = ni env scr
1559-- Return all names defined in binders in the given term
1560boundNamesIn :: PTerm -> [Name]
1561boundNamesIn tm = nub $ ni tm
1562 where -- TODO THINK Added niTacImp, but is it right?
1563 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1564 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1565 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1566 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1567 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1568 ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc))
1569 ni (PEq _ l r) = ni l ++ ni r
1570 ni (PRewrite _ l r _) = ni l ++ ni r
1571 ni (PTyped l r) = ni l ++ ni r
1572 ni (PPair _ _ l r) = ni l ++ ni r
1573 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1574 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1575 ni (PAlternative a as) = concatMap (ni) as
1576 ni (PHidden tm) = ni tm
1577 ni (PUnifyLog tm) = ni tm
1578 ni (PDisamb _ tm) = ni tm
1579 ni (PNoImplicits tm) = ni tm
1582 niTacImp (TacImp _ _ scr) = ni scr
1585-- Return names which are free in the given term.
1586namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1587namesIn uvars ist tm = nub $ ni [] tm
1590 | not (n `elem` env)
1591 = case lookupTy n (tt_ctxt ist) of
1593 _ -> if n `elem` (map fst uvars) then [n] else []
1594 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1595 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1596 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1597 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1598 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1599 ni env (PEq _ l r) = ni env l ++ ni env r
1600 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1601 ni env (PTyped l r) = ni env l ++ ni env r
1602 ni env (PPair _ _ l r) = ni env l ++ ni env r
1603 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1604 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1605 ni env (PAlternative a as) = concatMap (ni env) as
1606 ni env (PHidden tm) = ni env tm
1607 ni env (PUnifyLog tm) = ni env tm
1608 ni env (PDisamb _ tm) = ni env tm
1609 ni env (PNoImplicits tm) = ni env tm
1612 niTacImp env (TacImp _ _ scr) = ni env scr
1615-- Return which of the given names are used in the given term.
1617usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1618usedNamesIn vars ist tm = nub $ ni [] tm
1619 where -- TODO THINK added niTacImp, but is it right?
1621 | n `elem` vars && not (n `elem` env)
1622 = case lookupDefExact n (tt_ctxt ist) of
1625 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1626 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1627 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1628 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1629 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1630 ni env (PEq _ l r) = ni env l ++ ni env r
1631 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1632 ni env (PTyped l r) = ni env l ++ ni env r
1633 ni env (PPair _ _ l r) = ni env l ++ ni env r
1634 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1635 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1636 ni env (PAlternative a as) = concatMap (ni env) as
1637 ni env (PHidden tm) = ni env tm
1638 ni env (PUnifyLog tm) = ni env tm
1639 ni env (PDisamb _ tm) = ni env tm
1640 ni env (PNoImplicits tm) = ni env tm
1643 niTacImp env (TacImp _ _ scr) = ni env scr
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list