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)
34import Data.Maybe (fromMaybe)
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,
55 opt_typeintype :: Bool,
57 opt_showimp :: Bool, -- ^^ show implicits
58 opt_errContext :: Bool,
63 opt_codegen :: Codegen,
64 opt_outputTy :: OutputType,
65 opt_ibcsubdir :: FilePath,
66 opt_importdirs :: [FilePath],
70 opt_cmdline :: [Opt], -- remember whole command line
72 opt_autoSolve :: Bool -- ^ automatically apply "solve" tactic in prover
76defaultOpts = IOption { opt_logLevel = 0
77 , opt_typecase = False
78 , opt_typeintype = False
81 , opt_errContext = False
84 , opt_nobanner = False
87 , opt_outputTy = Executable
95 , opt_autoSolve = True
98data PPOption = PPOption {
99 ppopt_impl :: Bool -- ^^ whether to show implicits
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,
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])],
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 hide_list :: [(Name, Maybe Accessibility)],
178 default_access :: Accessibility,
179 default_total :: Bool,
180 ibc_write :: [IBCWrite],
181 compiled_so :: Maybe String,
182 idris_dynamic_libs :: [DynamicLib],
183 idris_language_extensions :: [LanguageExt],
184 idris_outputmode :: OutputMode,
185 idris_colourRepl :: Bool,
186 idris_colourTheme :: ColourTheme,
187 idris_outh :: Handle,
188 idris_errorhandlers :: [Name], -- ^ Global error handlers
189 idris_nameIdx :: (Int, Ctxt (Int, Name)),
190 idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers
191 module_aliases :: M.Map [T.Text] [T.Text],
192 idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console?
193 idris_postulates :: S.Set Name,
194 idris_whocalls :: Maybe (M.Map Name [Name]),
195 idris_callswho :: Maybe (M.Map Name [Name])
198data SizeChange = Smaller | Same | Bigger | Unknown
201deriving instance Binary SizeChange
202deriving instance NFData SizeChange
205type SCGEntry = (Name, [Maybe (Int, SizeChange)])
206type UsageReason = (Name, Int) -- fn_name, its_arg_number
208data CGInfo = CGInfo { argsdef :: [Name],
209 calls :: [(Name, [[Name]])],
212 usedpos :: [(Int, [UsageReason])] }
215deriving instance Binary CGInfo
216deriving instance NFData CGInfo
219primDefs = [sUN "unsafePerformPrimIO",
220 sUN "mkLazyForeignPrim",
224-- information that needs writing for the current module's .ibc file
225data IBCWrite = IBCFix FixDecl
229 | IBCInstance Bool Name Name
237 | IBCObj Codegen FilePath
238 | IBCLib Codegen String
239 | IBCCGFlag Codegen String
241 | IBCHeader Codegen String
242 | IBCAccess Name Accessibility
243 | IBCMetaInformation Name MetaInformation
244 | IBCTotal Name Totality
245 | IBCFlags Name [FnOpt]
246 | IBCTrans (Term, Term)
247 | IBCErrRev (Term, Term)
251 | IBCDef Name -- i.e. main context
252 | IBCNameHint (Name, Name)
253 | IBCLineApp FilePath Int PTerm
254 | IBCErrorHandler Name
255 | IBCFunctionErrorHandler Name Name Name
257 | IBCTotCheckErr FC String
260-- | The initial state for the compiler
262idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
263 emptyContext emptyContext emptyContext emptyContext
264 emptyContext emptyContext emptyContext emptyContext
265 emptyContext emptyContext
266 [] [] [] defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] [] []
267 [] [] Nothing [] Nothing [] [] Nothing [] Hidden False [] Nothing [] [] RawOutput
268 True defaultTheme stdout [] (0, emptyContext) emptyContext M.empty
269 AutomaticWidth S.empty Nothing Nothing
271-- | The monad for the main REPL - reading and processing files and updating
272-- global state (hence the IO inner monad).
273--type Idris = WriterT [Either String (IO ())] (State IState a))
274type Idris = StateT IState (ErrorT Err IO)
276-- Commands in the REPL
291 | DocStr (Either Name Const)
295 | ChangeDirectory FilePath
298 | Compile Codegen String
303 | AddProof (Maybe Name)
314 | DynamicLink FilePath
319 | CaseSplitAt Bool Int Name
320 | AddClauseFrom Bool Int Name
321 | AddProofClauseFrom Bool Int Name
322 | AddMissing Bool Int Name
323 | MakeWith Bool Int Name
324 | MakeLemma Bool Int Name
325 | DoProofSearch Bool Bool Int Name [Name]
326 -- ^ the first bool is whether to update,
327 -- the second is whether to search recursively (i.e. for the arguments)
331 | SetColour ColourType IdrisColour
335 | SetConsoleWidth ConsoleWidth
339 | MakeDoc String -- IdrisDoc
342data Opt = Filename String
352 | NoBuiltins -- only for the really primitive stuff!
373 | PkgMkDoc String -- IdrisDoc
380 | OutputTy OutputType
381 | Extension LanguageExt
382 | InterpretScript String
384 | TargetTriple String
389 | AutoWidth -- ^ Automatically adjust terminal width
390 | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover
393-- Parsed declarations
395data Fixity = Infixl { prec :: Int }
396 | Infixr { prec :: Int }
397 | InfixN { prec :: Int }
398 | PrefixN { prec :: Int }
401deriving instance Binary Fixity
402deriving instance NFData Fixity
405instance Show Fixity where
406 show (Infixl i) = "infixl " ++ show i
407 show (Infixr i) = "infixr " ++ show i
408 show (InfixN i) = "infix " ++ show i
409 show (PrefixN i) = "prefix " ++ show i
411data FixDecl = Fix Fixity String
414instance Show FixDecl where
415 show (Fix f s) = show f ++ " " ++ s
418deriving instance Binary FixDecl
419deriving instance NFData FixDecl
422instance Ord FixDecl where
423 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
426data Static = Static | Dynamic
429deriving instance Binary Static
430deriving instance NFData Static
433-- Mark bindings with their explicitness, and laziness
434data Plicity = Imp { pargopts :: [ArgOpt],
437 | Exp { pargopts :: [ArgOpt],
439 pparam :: Bool } -- this is a param (rather than index)
440 | Constraint { pargopts :: [ArgOpt],
442 | TacImp { pargopts :: [ArgOpt],
448deriving instance Binary Plicity
449deriving instance NFData Plicity
452impl = Imp [] Dynamic False
453expl = Exp [] Dynamic False
454expl_param = Exp [] Dynamic True
455constraint = Constraint [] Dynamic
456tacimpl t = TacImp [] Dynamic t
458data FnOpt = Inlinable -- always evaluate when simplifying
459 | TotalFn | PartialFn | CoveringFn
460 | Coinductive | AssertTotal
461 | Dictionary -- type class dictionary, eval only when
462 -- a function argument, and further evaluation resutls
463 | Implicit -- implicit coercion
464 | CExport String -- export, with a C name
465 | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension
466 | ErrorReverse -- ^^ attempt to reverse normalise before showing in error
467 | Reflection -- a reflecting function, compile-time only
468 | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names
471deriving instance Binary FnOpt
472deriving instance NFData FnOpt
477inlinable :: FnOpts -> Bool
478inlinable = elem Inlinable
480dictionary :: FnOpts -> Bool
481dictionary = elem Dictionary
484-- | Data declaration options
485data DataOpt = Codata -- Set if the the data-type is coinductive
486 | DefaultEliminator -- Set if an eliminator should be generated for data type
490type DataOpts = [DataOpt]
492-- | Type provider - what to provide
493data ProvideWhat = ProvTerm -- ^ only allow providing terms
494 | ProvPostulate -- ^ only allow postulates
495 | ProvAny -- ^ either is ok
498-- | Top-level declarations such as compiler directives, definitions,
499-- datatypes and typeclasses.
501 = PFix FC Fixity [String] -- ^ Fixity declaration
502 | PTy Docstring [(Name, Docstring)] SyntaxInfo FC FnOpts Name t -- ^ Type declaration
503 | PPostulate Docstring SyntaxInfo FC FnOpts Name t -- ^ Postulate
504 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
505 | PCAF FC Name t -- ^ Top level constant
506 | PData Docstring [(Name, Docstring)] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration.
507 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
508 | PNamespace String [PDecl' t] -- ^ New namespace
509 | PRecord Docstring SyntaxInfo FC Name t DataOpts Docstring Name t -- ^ Record declaration
510 | PClass Docstring SyntaxInfo FC
513 [(Name, t)] -- parameters
514 [(Name, Docstring)] -- parameter docstrings
515 [PDecl' t] -- declarations
516 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
517 -- class name, parameters, method declarations
518 | PInstance SyntaxInfo FC [t] -- constraints
521 t -- full instance type
522 (Maybe Name) -- explicit name
524 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
525 -- class name, parameters, full instance type, optional explicit name, and definitions
526 | PDSL Name (DSL' t) -- ^ DSL declaration
527 | PSyntax FC Syntax -- ^ Syntax definition
528 | PMutual FC [PDecl' t] -- ^ Mutual block
529 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
530 | PProvider SyntaxInfo FC ProvideWhat Name t t -- ^ Type provider. The first t is the type, the second is the term
531 | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If
532 -- bool is True, lhs and rhs must be convertible
535deriving instance Binary PDecl'
536deriving instance NFData PDecl'
539-- For elaborator state
540type ElabD a = Elab' [PDecl] a
542-- | One clause of a top-level definition. Term arguments to constructors are:
544-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
546-- 2. The list of extra 'with' patterns
548-- 3. The right-hand side
550-- 4. The where block (PDecl' t)
552data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
553 | PWith FC Name t [t] t [PDecl' t]
554 | PClauseR FC [t] t [PDecl' t]
555 | PWithR FC [t] t [PDecl' t]
558deriving instance Binary PClause'
559deriving instance NFData PClause'
563data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
564 d_tcon :: t, -- ^ Type constructor
565 d_cons :: [(Docstring, [(Name, Docstring)], Name, t, FC, [Name])] -- ^ Constructors
567 -- ^ Data declaration
568 | PLaterdecl { d_name :: Name, d_tcon :: t }
569 -- ^ "Placeholder" for data whose constructors are defined later
572deriving instance Binary PData'
573deriving instance NFData PData'
576-- Handy to get a free function for applying PTerm -> PTerm functions
577-- across a program, by deriving Functor
579type PDecl = PDecl' PTerm
580type PData = PData' PTerm
581type PClause = PClause' PTerm
583-- get all the names declared in a decl
585declared :: PDecl -> [Name]
586declared (PFix _ _ _) = []
587declared (PTy _ _ _ _ _ n t) = [n]
588declared (PPostulate _ _ _ _ n t) = [n]
589declared (PClauses _ _ n _) = [] -- not a declaration
590declared (PCAF _ n _) = [n]
591declared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
592 where fstt (_, _, a, _, _, _) = a
593declared (PData _ _ _ _ _ (PLaterdecl n _)) = [n]
594declared (PParams _ _ ds) = concatMap declared ds
595declared (PNamespace _ ds) = concatMap declared ds
596declared (PRecord _ _ _ n _ _ _ c _) = [n, c]
597declared (PClass _ _ _ _ n _ _ ms) = n : concatMap declared ms
598declared (PInstance _ _ _ _ _ _ _ _) = []
599declared (PDSL n _) = [n]
600declared (PSyntax _ _) = []
601declared (PMutual _ ds) = concatMap declared ds
602declared (PDirective _) = []
604-- get the names declared, not counting nested parameter blocks
605tldeclared :: PDecl -> [Name]
606tldeclared (PFix _ _ _) = []
607tldeclared (PTy _ _ _ _ _ n t) = [n]
608tldeclared (PPostulate _ _ _ _ n t) = [n]
609tldeclared (PClauses _ _ n _) = [] -- not a declaration
610tldeclared (PRecord _ _ _ n _ _ _ c _) = [n, c]
611tldeclared (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
612 where fstt (_, _, a, _, _, _) = a
613tldeclared (PParams _ _ ds) = []
614tldeclared (PMutual _ ds) = concatMap tldeclared ds
615tldeclared (PNamespace _ ds) = concatMap tldeclared ds
616tldeclared (PClass _ _ _ _ n _ _ ms) = concatMap tldeclared ms
617tldeclared (PInstance _ _ _ _ _ _ _ _) = []
620defined :: PDecl -> [Name]
621defined (PFix _ _ _) = []
622defined (PTy _ _ _ _ _ n t) = []
623defined (PPostulate _ _ _ _ n t) = []
624defined (PClauses _ _ n _) = [n] -- not a declaration
625defined (PCAF _ n _) = [n]
626defined (PData _ _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
627 where fstt (_, _, a, _, _, _) = a
628defined (PData _ _ _ _ _ (PLaterdecl n _)) = []
629defined (PParams _ _ ds) = concatMap defined ds
630defined (PNamespace _ ds) = concatMap defined ds
631defined (PRecord _ _ _ n _ _ _ c _) = [n, c]
632defined (PClass _ _ _ _ n _ _ ms) = n : concatMap defined ms
633defined (PInstance _ _ _ _ _ _ _ _) = []
634defined (PDSL n _) = [n]
635defined (PSyntax _ _) = []
636defined (PMutual _ ds) = concatMap defined ds
637defined (PDirective _) = []
640updateN :: [(Name, Name)] -> Name -> Name
641updateN ns n | Just n' <- lookup n ns = n'
644updateNs :: [(Name, Name)] -> PTerm -> PTerm
646updateNs ns t = mapPT updateRef t
647 where updateRef (PRef fc f) = PRef fc (updateN ns f)
650-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
652-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
653-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
654-- where updateCNs ns (PClause n l ts r ds)
655-- = PClause (updateN ns n) (fmap (updateNs ns) l)
656-- (map (fmap (updateNs ns)) ts)
657-- (fmap (updateNs ns) r)
658-- (map (updateDNs ns) ds)
661data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show)
663-- | High level language terms
664data PTerm = PQuote Raw
666 | PInferRef FC Name -- ^ A name to be defined later
668 | PLam Name PTerm PTerm
669 | PPi Plicity Name PTerm PTerm -- ^ (n : t1) -> t2
670 | PLet Name PTerm PTerm PTerm
671 | PTyped PTerm PTerm -- ^ Term with explicit type
672 | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x
673 | PAppBind FC PTerm [PArg] -- ^ implicitly bound application
674 | PMatchApp FC Name -- ^ Make an application by type matching
675 | PCase FC PTerm [(PTerm, PTerm)]
676 | PTrue FC PunInfo -- ^ Unit type..?
680 | PEq FC PTerm PTerm -- ^ Equality type: A = B
681 | PRewrite FC PTerm PTerm (Maybe PTerm)
682 | PPair FC PunInfo PTerm PTerm
683 | PDPair FC PunInfo PTerm PTerm PTerm
684 | PAlternative Bool [PTerm] -- True if only one may work
685 | PHidden PTerm -- ^ Irrelevant or hidden pattern
686 | PType -- ^ 'Type' type
687 | PGoal FC PTerm Name PTerm
688 | PConstant Const -- ^ Builtin types
694 | PProof [PTactic] -- ^ Proof script
695 | PTactics [PTactic] -- ^ As PProof, but no auto solving
696 | PElabError Err -- ^ Error to report on elaboration
697 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
698 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
699 | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces
700 | PUnifyLog PTerm -- ^ dump a trace of unifications when building term
701 | PNoImplicits PTerm -- ^ never run implicit converions on the term
706deriving instance Binary PTerm
707deriving instance NFData PTerm
710mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
711mapPT f t = f (mpt t) where
712 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
713 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
714 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
715 mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s)
717 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
718 mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as)
719 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
720 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
721 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
722 mpt (PPair fc p l r) = PPair fc p (mapPT f l) (mapPT f r)
723 mpt (PDPair fc p l t r) = PDPair fc p (mapPT f l) (mapPT f t) (mapPT f r)
724 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
725 mpt (PHidden t) = PHidden (mapPT f t)
726 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
727 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
728 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
729 mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm)
730 mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm)
731 mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm)
732 mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc)
736data PTactic' t = Intro [Name] | Intros | Focus Name
737 | Refine Name [Bool] | Rewrite t | DoUnify
741 | LetTac Name t | LetTacTy Name t t
742 | Exact t | Compute | Trivial | TCInstance
743 | ProofSearch Bool Bool (Maybe Name) [Name]
744 -- ^ the bool is whether to search recursively
747 | ProofState | ProofTerm | Undo
748 | Try (PTactic' t) (PTactic' t)
749 | TSeq (PTactic' t) (PTactic' t)
750 | ApplyTactic t -- see Language.Reflection module
754 | GoalType String (PTactic' t)
758 deriving (Show, Eq, Functor)
760deriving instance Binary PTactic'
761deriving instance NFData PTactic'
763instance Sized a => Sized (PTactic' a) where
764 size (Intro nms) = 1 + size nms
766 size (Focus nm) = 1 + size nm
767 size (Refine nm bs) = 1 + size nm + length bs
768 size (Rewrite t) = 1 + size t
769 size (Induction t) = 1 + size t
770 size (LetTac nm t) = 1 + size nm + size t
771 size (Exact t) = 1 + size t
779 size (Try l r) = 1 + size l + size r
780 size (TSeq l r) = 1 + size l + size r
781 size (ApplyTactic t) = 1 + size t
782 size (Reflect t) = 1 + size t
783 size (Fill t) = 1 + size t
787type PTactic = PTactic' PTerm
789data PDo' t = DoExp FC t
791 | DoBindP FC t t [(t,t)]
794 deriving (Eq, Functor)
796deriving instance Binary PDo'
797deriving instance NFData PDo'
800instance Sized a => Sized (PDo' a) where
801 size (DoExp fc t) = 1 + size fc + size t
802 size (DoBind fc nm t) = 1 + size fc + size nm + size t
803 size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts
804 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
805 size (DoLetP fc l r) = 1 + size fc + size l + size r
809-- The priority gives a hint as to elaboration order. Best to elaborate
810-- things early which will help give a more concrete type to other
811-- variables, e.g. a before (interpTy a).
813data PArg' t = PImp { priority :: Int,
814 machine_inf :: Bool, -- true if the machine inferred it
816 pname :: Name, getTm :: t }
817 | PExp { priority :: Int,
821 | PConstraint { priority :: Int,
825 | PTacImplicit { priority :: Int,
830 deriving (Show, Eq, Functor)
832data ArgOpt = HideDisplay | InaccessibleArg
835instance Sized a => Sized (PArg' a) where
836 size (PImp p _ l nm trm) = 1 + size nm + size trm
837 size (PExp p l nm trm) = 1 + size nm + size trm
838 size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm
839 size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm
842deriving instance Binary PArg'
843deriving instance NFData PArg'
846pimp n t mach = PImp 1 mach [] n t
847pexp t = PExp 1 [] (sMN 0 "arg") t
848pconst t = PConstraint 1 [] (sMN 0 "carg") t
849ptacimp n s t = PTacImplicit 2 [] n s t
851type PArg = PArg' PTerm
855data ClassInfo = CI { instanceName :: Name,
856 class_methods :: [(Name, (FnOpts, PTerm))],
857 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
858 class_default_superclasses :: [PDecl],
859 class_params :: [Name],
860 class_instances :: [Name] }
863deriving instance Binary ClassInfo
864deriving instance NFData ClassInfo
867-- Type inference data
869data TIData = TIPartial -- ^ a function with a partially defined type
870 | TISolution [Term] -- ^ possible solutions to a metavariable in a type
873data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting
877deriving instance Binary OptInfo
878deriving instance NFData OptInfo
882data TypeInfo = TI { con_names :: [Name],
884 data_opts :: DataOpts,
888deriving instance Binary TypeInfo
889deriving instance NFData TypeInfo
892-- Syntactic sugar info
894data DSL' t = DSL { dsl_bind :: t,
899 index_first :: Maybe t,
900 index_next :: Maybe t,
901 dsl_lambda :: Maybe t,
904 deriving (Show, Functor)
906deriving instance Binary DSL'
907deriving instance NFData DSL'
912data SynContext = PatternSyntax | TermSyntax | AnySyntax
915deriving instance Binary SynContext
916deriving instance NFData SynContext
919data Syntax = Rule [SSymbol] PTerm SynContext
922deriving instance Binary Syntax
923deriving instance NFData Syntax
926data SSymbol = Keyword Name
933deriving instance Binary SSymbol
934deriving instance NFData SSymbol
937initDSL = DSL (PRef f (sUN ">>="))
938 (PRef f (sUN "return"))
940 (PRef f (sUN "pure"))
946 where f = fileFC "(builtin)"
948data Using = UImplicit Name PTerm
949 | UConstraint Name [Name]
952deriving instance Binary Using
953deriving instance NFData Using
956data SyntaxInfo = Syn { using :: [Using],
957 syn_params :: [(Name, PTerm)],
958 syn_namespace :: [String],
960 decoration :: Name -> Name,
962 implicitAllowed :: Bool,
966deriving instance NFData SyntaxInfo
967deriving instance Binary SyntaxInfo
970defaultSyntax = Syn [] [] [] [] id False False initDSL
972expandNS :: SyntaxInfo -> Name -> Name
973expandNS syn n@(NS _ _) = n
974expandNS syn n = case syn_namespace syn of
979-- For inferring types of things
983inferTy = sMN 0 "__Infer"
984inferCon = sMN 0 "__infer"
985inferDecl = PDatadecl inferTy
987 [(emptyDocstring, [], inferCon, PPi impl (sMN 0 "iType") PType (
988 PPi expl (sMN 0 "ival") (PRef bi (sMN 0 "iType"))
989 (PRef bi inferTy)), bi, [])]
992infTerm t = PApp bi (PRef bi inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t]
993infP = P (TCon 6 0) inferTy (TType (UVal 0))
995getInferTerm, getInferType :: Term -> Term
996getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc
997getInferTerm (App (App _ _) tm) = tm
998getInferTerm tm = tm -- error ("getInferTerm " ++ show tm)
1000getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc
1001 where toTy (Lam t) = Pi t
1002 toTy (PVar t) = PVTy t
1004getInferType (App (App _ ty) _) = ty
1008-- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign, Elim type class
1010primNames = [unitTy, unitCon,
1011 falseTy, pairTy, pairCon,
1012 eqTy, eqCon, inferTy, inferCon]
1014unitDoc = parseDocstring . T.pack $ "The canonical single-element type, also known as the trivially true proposition."
1015unitTy = sMN 0 "__Unit"
1016unitCon = sMN 0 "__II"
1017unitDecl = PDatadecl unitTy PType
1018 [(parseDocstring . T.pack $ "The trivial constructor for `()`. ", [], unitCon, PRef bi unitTy, bi, [])]
1019unitOpts = [DefaultEliminator]
1021falseDoc = parseDocstring . T.pack $
1022 "The empty type, also known as the trivially false proposition." ++
1024 "Use `FalseElim` or `absurd` to prove anything if you have a variable " ++
1025 "of type `_|_` in scope."
1026falseTy = sMN 0 "__False"
1027falseDecl = PDatadecl falseTy PType []
1030pairDoc = parseDocstring . T.pack $ "The non-dependent pair type, also known as conjunction."
1031pairTy = sMN 0 "__Pair"
1032pairCon = sMN 0 "__MkPair"
1033pairDecl = PDatadecl pairTy (piBind [(n "A", PType), (n "B", PType)] PType)
1034 [(pairConDoc, pairConParamDoc,
1035 pairCon, PPi impl (n "A") PType (
1036 PPi impl (n "B") PType (
1037 PPi expl (n "a") (PRef bi (n "A")) (
1038 PPi expl (n "b") (PRef bi (n "B"))
1039 (PApp bi (PRef bi pairTy) [pexp (PRef bi (n "A")),
1040 pexp (PRef bi (n "B"))])))), bi, [])]
1042 pairConDoc = parseDocstring . T.pack $ "A pair of elements"
1043 pairConParamDoc = [(n "a", parseDocstring . T.pack $ "the left element of the pair"),
1044 (n "b", parseDocstring . T.pack $ "the right element of the pair")]
1046pairParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left elements in the pair"),
1047 (n "B", parseDocstring . T.pack $ "the type of the left elements in the pair")]
1052eqDoc = parseDocstring . T.pack $
1053 "The propositional equality type. A proof that `x` = `y`." ++
1055 "To use such a proof, pattern-match on it, and the two equal things will " ++
1056 "then need to be the _same_ pattern." ++
1058 "**Note**: Idris's equality type is _heterogeneous_, which means that it " ++
1059 "is possible to state equalities between values of potentially different " ++
1060 "types. This is sometimes referred to in the literature as \"John Major\" " ++
1063 "Thus, if Idris can't infer the type of one side of the equality, then " ++
1064 "you may need to annotate it. See the function `the`."
1066eqDecl = PDatadecl eqTy (piBind [(n "A", PType), (n "B", PType),
1067 (n "x", PRef bi (n "A")), (n "y", PRef bi (n "B"))]
1069 [(reflDoc, reflParamDoc,
1070 eqCon, PPi impl (n "A") PType (
1071 PPi impl (n "x") (PRef bi (n "A"))
1072 (PApp bi (PRef bi eqTy) [pimp (n "A") Placeholder False,
1073 pimp (n "B") Placeholder False,
1074 pexp (PRef bi (n "x")),
1075 pexp (PRef bi (n "x"))])), bi, [])]
1077 reflDoc = parseDocstring . T.pack $
1078 "A proof that `x` in fact equals `x`. To construct this, you must have already " ++
1079 "shown that both sides are in fact equal."
1080 reflParamDoc = [(n "A", parseDocstring . T.pack $ "the type at which the equality is proven"),
1081 (n "x", parseDocstring . T.pack $ "the element shown to be equal to itself.")]
1083eqParamDoc = [(n "A", parseDocstring . T.pack $ "the type of the left side of the equality"),
1084 (n "B", parseDocstring . T.pack $ "the type of the right side of the equality")
1090elimName = sUN "__Elim"
1091elimMethElimTy = sUN "__elimTy"
1092elimMethElim = sUN "elim"
1093elimDecl = PClass (parseDocstring . T.pack $ "Type class for eliminators") defaultSyntax bi [] elimName [(sUN "scrutineeType", PType)] []
1094 [PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElimTy PType,
1095 PTy emptyDocstring [] defaultSyntax bi [TotalFn] elimMethElim (PRef bi elimMethElimTy)]
1097-- Defined in builtins.idr
1098sigmaTy = sUN "Exists"
1099existsCon = sUN "Ex_intro"
1101piBind :: [(Name, PTerm)] -> PTerm -> PTerm
1102piBind = piBindp expl
1104piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm
1106piBindp p ((n, ty):ns) t = PPi p n ty (piBindp p ns t)
1109-- Pretty-printing declarations and terms
1111-- These "show" instances render to an absurdly wide screen because inserted line breaks
1112-- could interfere with interactive editing, which calls "show".
1114instance Show PTerm where
1115 showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm
1117instance Show PDecl where
1118 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp defaultPPOption) d
1120instance Show PClause where
1121 showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c
1123instance Show PData where
1124 showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d
1126instance Pretty PTerm OutputAnnotation where
1127 pretty = prettyImp defaultPPOption
1129-- | Colourise annotations according to an Idris state. It ignores the names
1130-- in the annotation, as there's no good way to show extended information on a
1132consoleDecorate :: IState -> OutputAnnotation -> String -> String
1133consoleDecorate ist _ | not (idris_colourRepl ist) = id
1134consoleDecorate ist (AnnConst c) = let theme = idris_colourTheme ist
1136 then colouriseType theme
1137 else colouriseData theme
1138consoleDecorate ist (AnnData _ _) = colouriseData (idris_colourTheme ist)
1139consoleDecorate ist (AnnType _ _) = colouriseType (idris_colourTheme ist)
1140consoleDecorate ist (AnnBoundName _ True) = colouriseImplicit (idris_colourTheme ist)
1141consoleDecorate ist (AnnBoundName _ False) = colouriseBound (idris_colourTheme ist)
1142consoleDecorate ist AnnKeyword = colouriseKeyword (idris_colourTheme ist)
1143consoleDecorate ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist
1144 theme = idris_colourTheme ist
1146 _ | isDConName n ctxt -> colouriseData theme
1147 _ | isFnName n ctxt -> colouriseFun theme
1148 _ | isTConName n ctxt -> colouriseType theme
1149 _ | otherwise -> id -- don't colourise unknown names
1150consoleDecorate ist (AnnFC _) = id
1151consoleDecorate ist (AnnTextFmt fmt) = Idris.Colours.colourise (colour fmt)
1152 where colour BoldText = IdrisColour Nothing True False True False
1153 colour UnderlineText = IdrisColour Nothing True True False False
1154 colour ItalicText = IdrisColour Nothing True False False True
1156-- | Pretty-print a high-level closed Idris term with no information about precedence/associativity
1157prettyImp :: PPOption -- ^^ pretty printing options
1158 -> PTerm -- ^^ the term to pretty-print
1159 -> Doc OutputAnnotation
1160prettyImp impl = pprintPTerm impl [] [] []
1162-- | Do the right thing for rendering a term in an IState
1163prettyIst :: IState -> PTerm -> Doc OutputAnnotation
1164prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist)
1166-- | Pretty-print a high-level Idris term in some bindings context with infix info
1167pprintPTerm :: PPOption -- ^^ pretty printing options
1168 -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit
1169 -> [Name] -- ^^ names to always show in pi, even if not used
1170 -> [FixDecl] -- ^^ Fixity declarations
1171 -> PTerm -- ^^ the term to pretty-print
1172 -> Doc OutputAnnotation
1173pprintPTerm ppo bnd docArgs infixes = prettySe 10 bnd
1175 prettySe :: Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation
1176 prettySe p bnd (PQuote r) =
1177 text "![" <> pretty r <> text "]"
1178 prettySe p bnd (PPatvar fc n) = pretty n
1180 | Just str <- slist p bnd e = str
1181 | Just n <- snat p e = annotate (AnnData "Nat" "") (text (show n))
1182 prettySe p bnd (PRef fc n) = prettyName (ppopt_impl ppo) bnd n
1183 prettySe p bnd (PLam n ty sc) =
1184 bracket p 2 . group . align . hang 2 $
1185 text "\\" <> bindingOf n False <+> text "=>" <$>
1186 prettySe 10 ((n, False):bnd) sc
1187 prettySe p bnd (PLet n ty v sc) =
1189 kwd "let" <+> bindingOf n False <+> text "=" </>
1190 prettySe 10 bnd v <+> kwd "in" </>
1191 prettySe 10 ((n, False):bnd) sc
1192 prettySe p bnd (PPi (Exp l s _) n ty sc)
1193 | n `elem` allNamesIn sc || ppopt_impl ppo || n `elem` docArgs =
1194 bracket p 2 . group $
1195 enclose lparen rparen (group . align $ bindingOf n False <+> colon <+> prettySe 10 bnd ty) <+>
1196 st <> text "->" <$> prettySe 10 ((n, False):bnd) sc
1198 bracket p 2 . group $
1199 group (prettySe 1 bnd ty <+> st) <> text "->" <$> group (prettySe 10 ((n, False):bnd) sc)
1203 Static -> text "[static]" <> space
1205 prettySe p bnd (PPi (Imp l s _) n ty sc)
1208 lbrace <> bindingOf n True <+> colon <+> prettySe 10 bnd ty <> rbrace <+>
1209 st <> text "->" </> prettySe 10 ((n, True):bnd) sc
1210 | otherwise = prettySe 10 ((n, True):bnd) sc
1214 Static -> text "[static]" <> space
1216 prettySe p bnd (PPi (Constraint _ _) n ty sc) =
1218 prettySe 10 bnd ty <+> text "=>" </> prettySe 10 ((n, True):bnd) sc
1219 prettySe p bnd (PPi (TacImp _ _ s) n ty sc) =
1221 lbrace <> kwd "tacimp" <+> pretty n <+> colon <+> prettySe 10 bnd ty <>
1222 rbrace <+> text "->" </> prettySe 10 ((n, True):bnd) sc
1223 prettySe p bnd (PApp _ (PRef _ f) args) -- normal names, no explicit args
1224 | UN nm <- basename f
1225 , not (ppopt_impl ppo) && null (getExps args) =
1226 if isAlpha (thead nm)
1227 then prettyName (ppopt_impl ppo) bnd f
1228 else enclose lparen rparen $ prettyName (ppopt_impl ppo) bnd f
1229 prettySe p bnd (PAppBind _ (PRef _ f) [])
1230 | not (ppopt_impl ppo) = text "!" <> prettyName (ppopt_impl ppo) bnd f
1231 prettySe p bnd (PApp _ (PRef _ op) args) -- infix operators
1232 | UN nm <- basename op
1234 (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) =
1235 case getExps args of
1236 [] -> enclose lparen rparen opName
1237 [x] -> group (enclose lparen rparen opName <$> group (prettySe 0 bnd x))
1238 [l,r] -> let precedence = fromMaybe 20 (fmap prec f)
1239 in bracket p precedence $ inFix l r
1240 (l:r:rest) -> bracket p 1 $
1241 enclose lparen rparen (inFix l r) <+>
1242 align (group (vsep (map (prettyArgSe bnd) rest)))
1243 where opName = prettyName (ppopt_impl ppo) bnd op
1244 f = getFixity (opStr op)
1246 Nothing -> prettySe (-1) bnd l
1247 Just (Infixl p') -> prettySe p' bnd l
1248 Just f' -> prettySe (prec f'-1) bnd l
1250 Nothing -> prettySe (-1) bnd r
1251 Just (Infixr p') -> prettySe p' bnd r
1252 Just f' -> prettySe (prec f'-1) bnd r
1253 inFix l r = align . group $
1254 (left l <+> opName) <$> group (right r)
1255 prettySe p bnd (PApp _ hd@(PRef fc f) [tm]) -- symbols, like 'foo
1256 | PConstant (Idris.Core.TT.Str str) <- getTm tm,
1257 f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $
1258 char '\'' <> prettySe 10 bnd (PRef fc (sUN str))
1259 prettySe p bnd (PApp _ f as) = -- Normal prefix applications
1260 let args = getExps as
1261 fp = prettySe 1 bnd f
1263 bracket p 1 . group $
1267 else fp <+> align (vsep (map (prettyArgS bnd) as))
1270 else fp <+> align (vsep (map (prettyArgSe bnd) args))
1271 prettySe p bnd (PCase _ scr opts) =
1272 kwd "case" <+> prettySe 10 bnd scr <+> kwd "of" <> prettyBody
1274 prettyBody = foldr (<>) empty $ intersperse (text "|") $ map sc opts
1276 sc (l, r) = nest nestingSize $ prettySe 10 bnd l <+> text "=>" <+> prettySe 10 bnd r
1277 prettySe p bnd (PHidden tm) = text "." <> prettySe 0 bnd tm
1278 prettySe p bnd (PRefl _ _) = annName eqCon $ text "refl"
1279 prettySe p bnd (PResolveTC _) = text "resolvetc"
1280 prettySe p bnd (PTrue _ IsType) = annName unitTy $ text "()"
1281 prettySe p bnd (PTrue _ IsTerm) = annName unitCon $ text "()"
1282 prettySe p bnd (PTrue _ TypeOrTerm) = text "()"
1283 prettySe p bnd (PFalse _) = annName falseTy $ text "_|_"
1284 prettySe p bnd (PEq _ l r) =
1285 bracket p 2 . align . group $
1286 prettySe 10 bnd l <+> eq <$> group (prettySe 10 bnd r)
1287 where eq = annName eqTy (text "=")
1288 prettySe p bnd (PRewrite _ l r _) =
1290 text "rewrite" <+> prettySe 10 bnd l <+> text "in" <+> prettySe 10 bnd r
1291 prettySe p bnd (PTyped l r) =
1292 lparen <> prettySe 10 bnd l <+> colon <+> prettySe 10 bnd r <> rparen
1293 prettySe p bnd pair@(PPair _ pun _ _) -- flatten tuples to the right, like parser
1294 | Just elts <- pairElts pair = enclose (ann lparen) (ann rparen) .
1295 align . group . vsep . punctuate (ann comma) $
1296 map (prettySe 10 bnd) elts
1297 where ann = case pun of
1299 IsType -> annName pairTy
1300 IsTerm -> annName pairCon
1301 prettySe p bnd (PDPair _ TypeOrTerm l t r) =
1302 lparen <> prettySe 10 bnd l <+> text "**" <+> prettySe 10 bnd r <> rparen
1303 prettySe p bnd (PDPair _ IsType (PRef _ n) t r) =
1304 annName sigmaTy lparen <>
1305 bindingOf n False <+>
1306 annName sigmaTy (text "**") <+>
1307 prettySe 10 ((n, False):bnd) r <>
1308 annName sigmaTy rparen
1309 prettySe p bnd (PDPair _ IsType l t r) =
1310 annName sigmaTy lparen <>
1311 prettySe 10 bnd l <+>
1312 annName sigmaTy (text "**") <+>
1313 prettySe 10 bnd r <>
1314 annName sigmaTy rparen
1315 prettySe p bnd (PDPair _ IsTerm l t r) =
1316 annName existsCon lparen <>
1317 prettySe 10 bnd l <+>
1318 annName existsCon (text "**") <+>
1319 prettySe 10 bnd r <>
1320 annName existsCon rparen
1321 prettySe p bnd (PAlternative a as) =
1322 lparen <> text "|" <> prettyAs <> text "|" <> rparen
1325 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10 bnd) as
1326 prettySe p bnd PType = annotate (AnnType "Type" "The type of types") $ text "Type"
1327 prettySe p bnd (PConstant c) = annotate (AnnConst c) (text (show c))
1328 -- XXX: add pretty for tactics
1329 prettySe p bnd (PProof ts) =
1330 text "proof" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1331 prettySe p bnd (PTactics ts) =
1332 text "tactics" <+> lbrace <> nest nestingSize (text . show $ ts) <> rbrace
1333 prettySe p bnd (PMetavar n) = text "?" <> pretty n
1334 prettySe p bnd (PReturn f) = kwd "return"
1335 prettySe p bnd PImpossible = kwd "impossible"
1336 prettySe p bnd Placeholder = text "_"
1337 prettySe p bnd (PDoBlock _) = text "do block pretty not implemented"
1338 prettySe p bnd (PElabError s) = pretty s
1340 prettySe p bnd _ = text "test"
1342 prettyArgS bnd (PImp _ _ _ n tm) = prettyArgSi bnd (n, tm)
1343 prettyArgS bnd (PExp _ _ _ tm) = prettyArgSe bnd tm
1344 prettyArgS bnd (PConstraint _ _ _ tm) = prettyArgSc bnd tm
1345 prettyArgS bnd (PTacImplicit _ _ n _ tm) = prettyArgSti bnd (n, tm)
1347 prettyArgSe bnd arg = prettySe 0 bnd arg
1348 prettyArgSi bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1349 prettyArgSc bnd val = lbrace <> lbrace <> prettySe 10 bnd val <> rbrace <> rbrace
1350 prettyArgSti bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe 10 bnd val <> rbrace
1352 annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation
1353 annName n = annotate (AnnName n Nothing Nothing Nothing)
1355 opStr :: Name -> String
1356 opStr (NS n _) = opStr n
1357 opStr (UN n) = T.unpack n
1359 basename :: Name -> Name
1360 basename (NS n _) = basename n
1363 slist' p bnd (PApp _ (PRef _ nil) _)
1364 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1365 slist' p bnd (PRef _ nil)
1366 | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just []
1367 slist' p bnd (PApp _ (PRef _ cons) args)
1368 | nsroot cons == sUN "::",
1369 (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args,
1371 Just tl' <- slist' p bnd tl
1374 isImp (PImp {}) = True
1376 slist' _ _ tm = Nothing
1378 slist p bnd e | Just es <- slist' p bnd e = Just $
1379 case es of [] -> annotate (AnnData "" "") $ text "[]"
1380 [x] -> enclose left right . group $
1382 xs -> (enclose left right .
1383 align . group . vsep .
1385 map (prettySe p bnd)) xs
1386 where left = (annotate (AnnData "" "") (text "["))
1387 right = (annotate (AnnData "" "") (text "]"))
1388 comma = (annotate (AnnData "" "") (text ","))
1389 slist _ _ _ = Nothing
1391 pairElts :: PTerm -> Maybe [PTerm]
1392 pairElts (PPair _ _ x y) | Just elts <- pairElts y = Just (x:elts)
1393 | otherwise = Just [x, y]
1394 pairElts _ = Nothing
1396 natns = "Prelude.Nat."
1399 | show z == (natns++"Z") || show z == "Z" = Just 0
1400 snat p (PApp _ s [PExp {getTm=n}])
1401 | show s == (natns++"S") || show s == "S",
1406 bracket outer inner doc
1407 | inner > outer = lparen <> doc <> rparen
1410 kwd = annotate AnnKeyword . text
1412 fixities :: M.Map String Fixity
1413 fixities = M.fromList [(s, f) | (Fix f s) <- infixes]
1415 getFixity :: String -> Maybe Fixity
1416 getFixity = flip M.lookup fixities
1418-- | Pretty-printer helper for the binding site of a name
1419bindingOf :: Name -- ^^ the bound name
1420 -> Bool -- ^^ whether the name is implicit
1421 -> Doc OutputAnnotation
1422bindingOf n imp = annotate (AnnBoundName n imp) (text (show n))
1424-- | Pretty-printer helper for names that attaches the correct annotations
1425prettyName :: Bool -- ^^ whether to show namespaces
1426 -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit
1427 -> Name -- ^^ the name to pprint
1428 -> Doc OutputAnnotation
1429prettyName showNS bnd n | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) (text (strName n))
1430 | otherwise = annotate (AnnName n Nothing Nothing Nothing) (text (strName n))
1431 where strName (UN n) = T.unpack n
1432 strName (NS n ns) | showNS = (concatMap (++ ".") . map T.unpack . reverse) ns ++ strName n
1433 | otherwise = strName n
1434 strName n | n == falseTy = "_|_"
1435 strName (MN i s) = T.unpack s
1436 strName other = show other
1439showCImp :: PPOption -> PClause -> Doc OutputAnnotation
1440showCImp ppo (PClause _ n l ws r w)
1441 = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r
1442 <+> text "where" <+> text (show w)
1445 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
1446showCImp ppo (PWith _ n l ws r w)
1447 = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r
1448 <+> braces (text (show w))
1451 showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs
1454showDImp :: PPOption -> PData -> Doc OutputAnnotation
1455showDImp ppo (PDatadecl n ty cons)
1456 = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$>
1457 (indent 2 $ vsep (map (\ (_, _, n, t, _, _) -> pipe <+> prettyName False [] n <+> colon <+> prettyImp ppo t) cons))
1459showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation
1460showDecls o ds = vsep (map (showDeclImp o) ds)
1462showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops))
1463showDeclImp o (PTy _ _ _ _ _ n t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t
1464showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+>
1465 indent 2 (vsep (map (showCImp o) cs))
1466showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d
1467showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line)
1468showDeclImp o (PNamespace n ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line)
1469showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn)
1470showDeclImp o (PClass _ _ _ cs n ps _ ds)
1471 = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds
1472showDeclImp o (PInstance _ _ cs n _ t _ ds)
1473 = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds
1474showDeclImp _ _ = text "..."
1475-- showDeclImp (PImport o) = "import " ++ o
1477instance Show (Doc OutputAnnotation) where
1478 show = flip (displayS . renderCompact) ""
1480getImps :: [PArg] -> [(Name, PTerm)]
1482getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs
1483getImps (_ : xs) = getImps xs
1485getExps :: [PArg] -> [PTerm]
1487getExps (PExp _ _ _ tm : xs) = tm : getExps xs
1488getExps (_ : xs) = getExps xs
1490getConsts :: [PArg] -> [PTerm]
1492getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs
1493getConsts (_ : xs) = getConsts xs
1495getAll :: [PArg] -> [PTerm]
1500showName :: Maybe IState -- ^^ the Idris state, for information about names and colours
1501 -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit
1502 -> PPOption -- ^^ pretty printing options
1503 -> Bool -- ^^ whether to colourise
1504 -> Name -- ^^ the term to show
1506showName ist bnd ppo colour n = case ist of
1507 Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n
1508 Nothing -> showbasic n
1509 where name = if ppopt_impl ppo then show n else showbasic n
1510 showbasic n@(UN _) = showCG n
1511 showbasic (MN _ s) = str s
1512 showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n
1513 showbasic (SN s) = show s
1515 colourise n t = let ctxt' = fmap tt_ctxt ist in
1518 Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name
1519 else colouriseBound t name
1520 | isDConName n ctxt -> colouriseData t name
1521 | isFnName n ctxt -> colouriseFun t name
1522 | isTConName n ctxt -> colouriseType t name
1523 -- The assumption is that if a name is not bound and does not exist in the
1524 -- global context, then we're somewhere in which implicit info has been lost
1525 -- (like error messages). Thus, unknown vars are colourised as implicits.
1526 | otherwise -> colouriseImplicit t name
1528showTm :: IState -- ^^ the Idris state, for information about identifiers and colours
1529 -> PTerm -- ^^ the term to show
1531showTm ist = displayDecorated (consoleDecorate ist) .
1532 renderPretty 0.8 100000 .
1533 prettyImp (ppOptionIst ist)
1535-- | Show a term with implicits, no colours
1536showTmImpls :: PTerm -> String
1537showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) ""
1541instance Sized PTerm where
1542 size (PQuote rawTerm) = size rawTerm
1543 size (PRef fc name) = size name
1544 size (PLam name ty bdy) = 1 + size ty + size bdy
1545 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1546 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1547 size (PTyped trm ty) = 1 + size trm + size ty
1548 size (PApp fc name args) = 1 + size args
1549 size (PAppBind fc name args) = 1 + size args
1550 size (PCase fc trm bdy) = 1 + size trm + size bdy
1551 size (PTrue fc _) = 1
1552 size (PFalse fc) = 1
1553 size (PRefl fc _) = 1
1554 size (PResolveTC fc) = 1
1555 size (PEq fc left right) = 1 + size left + size right
1556 size (PRewrite fc left right _) = 1 + size left + size right
1557 size (PPair fc _ left right) = 1 + size left + size right
1558 size (PDPair fs _ left ty right) = 1 + size left + size ty + size right
1559 size (PAlternative a alts) = 1 + size alts
1560 size (PHidden hidden) = size hidden
1561 size (PUnifyLog tm) = size tm
1562 size (PDisamb _ tm) = size tm
1563 size (PNoImplicits tm) = size tm
1565 size (PConstant const) = 1 + size const
1566 size Placeholder = 1
1567 size (PDoBlock dos) = 1 + size dos
1568 size (PIdiom fc term) = 1 + size term
1569 size (PReturn fc) = 1
1570 size (PMetavar name) = 1
1571 size (PProof tactics) = size tactics
1572 size (PElabError err) = size err
1573 size PImpossible = 1
1575getPArity :: PTerm -> Int
1576getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1579-- Return all names, free or globally bound, in the given term.
1581allNamesIn :: PTerm -> [Name]
1582allNamesIn tm = nub $ ni [] tm
1583 where -- TODO THINK added niTacImp, but is it right?
1585 | not (n `elem` env) = [n]
1586 ni env (PPatvar _ n) = [n]
1587 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1588 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1589 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1590 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1591 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1592 ni env (PHidden tm) = ni env tm
1593 ni env (PEq _ l r) = ni env l ++ ni env r
1594 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1595 ni env (PTyped l r) = ni env l ++ ni env r
1596 ni env (PPair _ _ l r) = ni env l ++ ni env r
1597 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1598 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1599 ni env (PAlternative a ls) = concatMap (ni env) ls
1600 ni env (PUnifyLog tm) = ni env tm
1601 ni env (PDisamb _ tm) = ni env tm
1602 ni env (PNoImplicits tm) = ni env tm
1605 niTacImp env (TacImp _ _ scr) = ni env scr
1608-- Return all names defined in binders in the given term
1609boundNamesIn :: PTerm -> [Name]
1610boundNamesIn tm = nub $ ni tm
1611 where -- TODO THINK Added niTacImp, but is it right?
1612 ni (PApp _ f as) = ni f ++ concatMap (ni) (map getTm as)
1613 ni (PAppBind _ f as) = ni f ++ concatMap (ni) (map getTm as)
1614 ni (PCase _ c os) = ni c ++ concatMap (ni) (map snd os)
1615 ni (PLam n ty sc) = n : (ni ty ++ ni sc)
1616 ni (PLet n ty val sc) = n : (ni ty ++ ni val ++ ni sc)
1617 ni (PPi p n ty sc) = niTacImp p ++ (n : (ni ty ++ ni sc))
1618 ni (PEq _ l r) = ni l ++ ni r
1619 ni (PRewrite _ l r _) = ni l ++ ni r
1620 ni (PTyped l r) = ni l ++ ni r
1621 ni (PPair _ _ l r) = ni l ++ ni r
1622 ni (PDPair _ _ (PRef _ n) t r) = ni t ++ ni r
1623 ni (PDPair _ _ l t r) = ni l ++ ni t ++ ni r
1624 ni (PAlternative a as) = concatMap (ni) as
1625 ni (PHidden tm) = ni tm
1626 ni (PUnifyLog tm) = ni tm
1627 ni (PDisamb _ tm) = ni tm
1628 ni (PNoImplicits tm) = ni tm
1631 niTacImp (TacImp _ _ scr) = ni scr
1634-- Return names which are free in the given term.
1635namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1636namesIn uvars ist tm = nub $ ni [] tm
1639 | not (n `elem` env)
1640 = case lookupTy n (tt_ctxt ist) of
1642 _ -> if n `elem` (map fst uvars) then [n] else []
1643 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1644 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1645 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1646 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1647 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1648 ni env (PEq _ l r) = ni env l ++ ni env r
1649 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1650 ni env (PTyped l r) = ni env l ++ ni env r
1651 ni env (PPair _ _ l r) = ni env l ++ ni env r
1652 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1653 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1654 ni env (PAlternative a as) = concatMap (ni env) as
1655 ni env (PHidden tm) = ni env tm
1656 ni env (PUnifyLog tm) = ni env tm
1657 ni env (PDisamb _ tm) = ni env tm
1658 ni env (PNoImplicits tm) = ni env tm
1661 niTacImp env (TacImp _ _ scr) = ni env scr
1664-- Return which of the given names are used in the given term.
1666usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1667usedNamesIn vars ist tm = nub $ ni [] tm
1668 where -- TODO THINK added niTacImp, but is it right?
1670 | n `elem` vars && not (n `elem` env)
1671 = case lookupDefExact n (tt_ctxt ist) of
1674 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1675 ni env (PAppBind _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1676 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1677 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1678 ni env (PPi p n ty sc) = niTacImp env p ++ ni env ty ++ ni (n:env) sc
1679 ni env (PEq _ l r) = ni env l ++ ni env r
1680 ni env (PRewrite _ l r _) = ni env l ++ ni env r
1681 ni env (PTyped l r) = ni env l ++ ni env r
1682 ni env (PPair _ _ l r) = ni env l ++ ni env r
1683 ni env (PDPair _ _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1684 ni env (PDPair _ _ l t r) = ni env l ++ ni env t ++ ni env r
1685 ni env (PAlternative a as) = concatMap (ni env) as
1686 ni env (PHidden tm) = ni env tm
1687 ni env (PUnifyLog tm) = ni env tm
1688 ni env (PDisamb _ tm) = ni env tm
1689 ni env (PNoImplicits tm) = ni env tm
1692 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