on d8cff54 help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1164 lines 41 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor,
2 TypeSynonymInstances, PatternGuards #-}
4module Idris.AbsSyntaxTree where
6import Core.TT
7import Core.Evaluate
8import Core.Elaborate hiding (Tactic(..))
9import Core.Typecheck
10import IRTS.Lang
11import IRTS.CodegenCommon
12import Util.Pretty
13import Util.DynamicLinker
15import Paths_idris
17import System.Console.Haskeline
19import Control.Monad.Trans.State.Strict
21import Data.List
22import Data.Char
23import Data.Either
25import Debug.Trace
27data IOption = IOption { opt_logLevel :: Int,
28 opt_typecase :: Bool,
29 opt_typeintype :: Bool,
30 opt_coverage :: Bool,
31 opt_showimp :: Bool,
32 opt_errContext :: Bool,
33 opt_repl :: Bool,
34 opt_verbose :: Bool,
35 opt_quiet :: Bool,
36 opt_target :: Target,
37 opt_outputTy :: OutputType,
38 opt_ibcsubdir :: FilePath,
39 opt_importdirs :: [FilePath],
40 opt_cmdline :: [Opt] -- remember whole command line
41 }
42 deriving (Show, Eq)
44defaultOpts = IOption 0 False False True False False True True False ViaC Executable "" [] []
46data LanguageExt = TypeProviders deriving (Show, Eq, Read, Ord)
48-- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e
49-- without typechecking).
50-- This will include all the functions and data declarations, plus fixity declarations
51-- and syntax macros.
53-- | The global state used in the Idris monad
54data IState = IState {
55 tt_ctxt :: Context, -- ^ All the currently defined names and their terms
56 idris_constraints :: [(UConstraint, FC)],
57 -- ^ A list of universe constraints and their corresponding source locations
58 idris_infixes :: [FixDecl], -- ^ Currently defined infix operators
59 idris_implicits :: Ctxt [PArg],
60 idris_statics :: Ctxt [Bool],
61 idris_classes :: Ctxt ClassInfo,
62 idris_dsls :: Ctxt DSL,
63 idris_optimisation :: Ctxt OptInfo,
64 idris_datatypes :: Ctxt TypeInfo,
65 idris_patdefs :: Ctxt [([Name], Term, Term)], -- not exported
66 idris_flags :: Ctxt [FnOpt],
67 idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos
68 idris_calledgraph :: Ctxt [Name],
69 idris_docstrings :: Ctxt String,
70 idris_totcheck :: [(FC, Name)],
71 idris_log :: String,
72 idris_options :: IOption,
73 idris_name :: Int,
74 idris_metavars :: [Name], -- ^ The currently defined but not proven metavariables
75 idris_coercions :: [Name],
76 syntax_rules :: [Syntax],
77 syntax_keywords :: [String],
78 imported :: [FilePath], -- ^ The imported modules
79 idris_scprims :: [(Name, (Int, PrimFn))],
80 idris_objs :: [FilePath],
81 idris_libs :: [String],
82 idris_hdrs :: [String],
83 proof_list :: [(Name, [String])],
84 errLine :: Maybe Int,
85 lastParse :: Maybe Name,
86 indent_stack :: [Int],
87 brace_stack :: [Maybe Int],
88 hide_list :: [(Name, Maybe Accessibility)],
89 default_access :: Accessibility,
90 default_total :: Bool,
91 ibc_write :: [IBCWrite],
92 compiled_so :: Maybe String,
93 idris_dynamic_libs :: [DynamicLib],
94 idris_language_extensions :: [LanguageExt]
95 }
97data SizeChange = Smaller | Same | Bigger | Unknown
98 deriving (Show, Eq)
99{-!
100deriving instance Binary SizeChange
101!-}
103type SCGEntry = (Name, [Maybe (Int, SizeChange)])
105data CGInfo = CGInfo { argsdef :: [Name],
106 calls :: [(Name, [[Name]])],
107 scg :: [SCGEntry],
108 argsused :: [Name],
109 unusedpos :: [Int] }
110 deriving Show
111{-!
112deriving instance Binary CGInfo
113!-}
115primDefs = [UN "unsafePerformIO", UN "mkLazyForeign", UN "mkForeign", UN "FalseElim"]
117-- information that needs writing for the current module's .ibc file
118data IBCWrite = IBCFix FixDecl
119 | IBCImp Name
120 | IBCStatic Name
121 | IBCClass Name
122 | IBCInstance Bool Name Name
123 | IBCDSL Name
124 | IBCData Name
125 | IBCOpt Name
126 | IBCSyntax Syntax
127 | IBCKeyword String
128 | IBCImport FilePath
129 | IBCObj FilePath
130 | IBCLib String
131 | IBCDyLib String
132 | IBCHeader String
133 | IBCAccess Name Accessibility
134 | IBCTotal Name Totality
135 | IBCFlags Name [FnOpt]
136 | IBCCG Name
137 | IBCDoc Name
138 | IBCCoercion Name
139 | IBCDef Name -- i.e. main context
140 deriving Show
142idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext
143 emptyContext emptyContext emptyContext emptyContext
144 emptyContext emptyContext emptyContext emptyContext
145 [] "" defaultOpts 6 [] [] [] [] [] [] [] [] []
146 [] Nothing Nothing [] [] [] Hidden False [] Nothing [] []
148-- | The monad for the main REPL - reading and processing files and updating
149-- global state (hence the IO inner monad).
150type Idris = StateT IState IO
152-- Commands in the REPL
154data Target = ViaC
155 | ViaJava
156 | ViaNode
157 | ViaJavaScript
158 | Bytecode
159 deriving (Show, Eq)
161-- | REPL commands
162data Command = Quit
163 | Help
164 | Eval PTerm
165 | Check PTerm
166 | DocStr Name
167 | TotCheck Name
168 | Reload
169 | Load FilePath
170 | ModImport String
171 | Edit
172 | Compile Target String
173 | Execute
174 | ExecVal PTerm
175 | NewCompile String
176 | Metavars
177 | Prove Name
178 | AddProof (Maybe Name)
179 | RmProof Name
180 | ShowProof Name
181 | Proofs
182 | Universes
183 | TTShell
184 | LogLvl Int
185 | Spec PTerm
186 | HNF PTerm
187 | Defn Name
188 | Info Name
189 | Missing Name
190 | DynamicLink FilePath
191 | ListDynamic
192 | Pattelab PTerm
193 | DebugInfo Name
194 | Search PTerm
195 | SetOpt Opt
196 | UnsetOpt Opt
197 | NOP
199data Opt = Filename String
200 | Ver
201 | Usage
202 | Quiet
203 | ShowLibs
204 | ShowLibdir
205 | ShowIncs
206 | NoPrelude
207 | NoREPL
208 | OLogging Int
209 | Output String
210 | NewOutput String
211 | TypeCase
212 | TypeInType
213 | DefaultTotal
214 | DefaultPartial
215 | WarnPartial
216 | NoCoverage
217 | ErrContext
218 | ShowImpl
219 | Verbose
220 | IBCSubDir String
221 | ImportDir String
222 | PkgBuild String
223 | PkgInstall String
224 | PkgClean String
225 | WarnOnly
226 | Pkg String
227 | BCAsm String
228 | DumpDefun String
229 | DumpCases String
230 | FOVM String
231 | UseTarget Target
232 | OutputTy OutputType
233 | Extension LanguageExt
234 deriving (Show, Eq)
236-- Parsed declarations
238data Fixity = Infixl { prec :: Int }
239 | Infixr { prec :: Int }
240 | InfixN { prec :: Int }
241 | PrefixN { prec :: Int }
242 deriving Eq
243{-!
244deriving instance Binary Fixity
245!-}
247instance Show Fixity where
248 show (Infixl i) = "infixl " ++ show i
249 show (Infixr i) = "infixr " ++ show i
250 show (InfixN i) = "infix " ++ show i
251 show (PrefixN i) = "prefix " ++ show i
253data FixDecl = Fix Fixity String
254 deriving Eq
256instance Show FixDecl where
257 show (Fix f s) = show f ++ " " ++ s
259{-!
260deriving instance Binary FixDecl
261!-}
263instance Ord FixDecl where
264 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
267data Static = Static | Dynamic
268 deriving (Show, Eq)
269{-!
270deriving instance Binary Static
271!-}
273-- Mark bindings with their explicitness, and laziness
274data Plicity = Imp { plazy :: Bool,
275 pstatic :: Static,
276 pdocstr :: String }
277 | Exp { plazy :: Bool,
278 pstatic :: Static,
279 pdocstr :: String }
280 | Constraint { plazy :: Bool,
281 pstatic :: Static,
282 pdocstr :: String }
283 | TacImp { plazy :: Bool,
284 pstatic :: Static,
285 pscript :: PTerm,
286 pdocstr :: String }
287 deriving (Show, Eq)
289{-!
290deriving instance Binary Plicity
291!-}
293impl = Imp False Dynamic ""
294expl = Exp False Dynamic ""
295constraint = Constraint False Dynamic ""
296tacimpl t = TacImp False Dynamic t ""
298data FnOpt = Inlinable | TotalFn | PartialFn
299 | Coinductive | AssertTotal | TCGen
300 | Implicit -- implicit coercion
301 | CExport String -- export, with a C name
302 | Specialise [Name] -- specialise it, freeze these names
303 deriving (Show, Eq)
304{-!
305deriving instance Binary FnOpt
306!-}
308type FnOpts = [FnOpt]
310inlinable :: FnOpts -> Bool
311inlinable = elem Inlinable
313-- | Top-level declarations such as compiler directives, definitions,
314-- datatypes and typeclasses.
315data PDecl' t
316 = PFix FC Fixity [String] -- ^ Fixity declaration
317 | PTy String SyntaxInfo FC FnOpts Name t -- ^ Type declaration
318 | PPostulate String SyntaxInfo FC FnOpts Name t -- ^ Postulate
319 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
320 | PCAF FC Name t -- ^ Top level constant
321 | PData String SyntaxInfo FC Bool (PData' t) -- ^ Data declaration. The Bool argument is True for codata.
322 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
323 | PNamespace String [PDecl' t] -- ^ New namespace
324 | PRecord String SyntaxInfo FC Name t String Name t -- ^ Record declaration
325 | PClass String SyntaxInfo FC
326 [t] -- constraints
327 Name
328 [(Name, t)] -- parameters
329 [PDecl' t] -- declarations
330 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
331 -- class name, parameters, method declarations
332 | PInstance SyntaxInfo FC [t] -- constraints
333 Name -- class
334 [t] -- parameters
335 t -- full instance type
336 (Maybe Name) -- explicit name
337 [PDecl' t]
338 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
339 -- class name, parameters, full instance type, optional explicit name, and definitions
340 | PDSL Name (DSL' t) -- ^ DSL declaration
341 | PSyntax FC Syntax -- ^ Syntax definition
342 | PMutual FC [PDecl' t] -- ^ Mutual block
343 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
344 | PProvider SyntaxInfo FC Name t t -- ^ Type provider. The first t is the type, the second is the term
345 deriving Functor
346{-!
347deriving instance Binary PDecl'
348!-}
350-- | One clause of a top-level definition. Term arguments to constructors are:
351--
352-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
353--
354-- 2. The list of patterns
355--
356-- 3. The right-hand side
357--
358-- 4. The where block (PDecl' t)
359data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
360 | PWith FC Name t [t] t [PDecl' t]
361 | PClauseR FC [t] t [PDecl' t]
362 | PWithR FC [t] t [PDecl' t]
363 deriving Functor
364{-!
365deriving instance Binary PClause'
366!-}
368-- | Data declaration
369data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
370 d_tcon :: t, -- ^ Type constructor
371 d_cons :: [(String, Name, t, FC)] -- ^ Constructors
372 }
373 -- ^ Data declaration
374 | PLaterdecl { d_name :: Name, d_tcon :: t }
375 -- ^ "Placeholder" for data whose constructors are defined later
376 deriving Functor
377{-!
378deriving instance Binary PData'
379!-}
381-- Handy to get a free function for applying PTerm -> PTerm functions
382-- across a program, by deriving Functor
384type PDecl = PDecl' PTerm
385type PData = PData' PTerm
386type PClause = PClause' PTerm
388-- get all the names declared in a decl
390declared :: PDecl -> [Name]
391declared (PFix _ _ _) = []
392declared (PTy _ _ _ _ n t) = [n]
393declared (PPostulate _ _ _ _ n t) = [n]
394declared (PClauses _ _ n _) = [] -- not a declaration
395declared (PCAF _ n _) = [n]
396declared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
397 where fstt (_, a, _, _) = a
398declared (PData _ _ _ _ (PLaterdecl n _)) = [n]
399declared (PParams _ _ ds) = concatMap declared ds
400declared (PNamespace _ ds) = concatMap declared ds
401declared (PRecord _ _ _ n _ _ c _) = [n, c]
402declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
403declared (PInstance _ _ _ _ _ _ _ _) = []
404declared (PDSL n _) = [n]
405declared (PSyntax _ _) = []
406declared (PMutual _ ds) = concatMap declared ds
407declared (PDirective _) = []
409-- get the names declared, not counting nested parameter blocks
410tldeclared :: PDecl -> [Name]
411tldeclared (PFix _ _ _) = []
412tldeclared (PTy _ _ _ _ n t) = [n]
413tldeclared (PPostulate _ _ _ _ n t) = [n]
414tldeclared (PClauses _ _ n _) = [] -- not a declaration
415tldeclared (PRecord _ _ _ n _ _ c _) = [n, c]
416tldeclared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
417 where fstt (_, a, _, _) = a
418tldeclared (PParams _ _ ds) = []
419tldeclared (PMutual _ ds) = concatMap tldeclared ds
420tldeclared (PNamespace _ ds) = concatMap tldeclared ds
423defined :: PDecl -> [Name]
424defined (PFix _ _ _) = []
425defined (PTy _ _ _ _ n t) = []
426defined (PPostulate _ _ _ _ n t) = []
427defined (PClauses _ _ n _) = [n] -- not a declaration
428defined (PCAF _ n _) = [n]
429defined (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
430 where fstt (_, a, _, _) = a
431defined (PData _ _ _ _ (PLaterdecl n _)) = []
432defined (PParams _ _ ds) = concatMap defined ds
433defined (PNamespace _ ds) = concatMap defined ds
434defined (PRecord _ _ _ n _ _ c _) = [n, c]
435defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
436defined (PInstance _ _ _ _ _ _ _ _) = []
437defined (PDSL n _) = [n]
438defined (PSyntax _ _) = []
439defined (PMutual _ ds) = concatMap defined ds
440defined (PDirective _) = []
441--defined _ = []
443updateN :: [(Name, Name)] -> Name -> Name
444updateN ns n | Just n' <- lookup n ns = n'
445updateN _ n = n
447updateNs :: [(Name, Name)] -> PTerm -> PTerm
448updateNs [] t = t
449updateNs ns t = mapPT updateRef t
450 where updateRef (PRef fc f) = PRef fc (updateN ns f)
451 updateRef t = t
453-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
454-- updateDNs [] t = t
455-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
456-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
457-- where updateCNs ns (PClause n l ts r ds)
458-- = PClause (updateN ns n) (fmap (updateNs ns) l)
459-- (map (fmap (updateNs ns)) ts)
460-- (fmap (updateNs ns) r)
461-- (map (updateDNs ns) ds)
462-- updateDNs ns c = c
464-- | High level language terms
465data PTerm = PQuote Raw
466 | PRef FC Name
467 | PInferRef FC Name -- ^ A name to be defined later
468 | PPatvar FC Name
469 | PLam Name PTerm PTerm
470 | PPi Plicity Name PTerm PTerm
471 | PLet Name PTerm PTerm PTerm
472 | PTyped PTerm PTerm -- ^ Term with explicit type
473 | PApp FC PTerm [PArg]
474 | PCase FC PTerm [(PTerm, PTerm)]
475 | PTrue FC
476 | PFalse FC
477 | PRefl FC PTerm
478 | PResolveTC FC
479 | PEq FC PTerm PTerm
480 | PRewrite FC PTerm PTerm
481 | PPair FC PTerm PTerm
482 | PDPair FC PTerm PTerm PTerm
483 | PAlternative Bool [PTerm] -- True if only one may work
484 | PHidden PTerm -- ^ Irrelevant or hidden pattern
485 | PType
486 | PConstant Const
487 | Placeholder
488 | PDoBlock [PDo]
489 | PIdiom FC PTerm
490 | PReturn FC
491 | PMetavar Name
492 | PProof [PTactic] -- ^ Proof script
493 | PTactics [PTactic] -- ^ As PProof, but no auto solving
494 | PElabError Err -- ^ Error to report on elaboration
495 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
496 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
497 deriving Eq
498{-!
499deriving instance Binary PTerm
500!-}
502mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
503mapPT f t = f (mpt t) where
504 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
505 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
506 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
507 mpt (PRewrite fc t s) = PRewrite fc (mapPT f t) (mapPT f s)
508 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
509 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
510 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
511 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
512 mpt (PPair fc l r) = PPair fc (mapPT f l) (mapPT f r)
513 mpt (PDPair fc l t r) = PDPair fc (mapPT f l) (mapPT f t) (mapPT f r)
514 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
515 mpt (PHidden t) = PHidden (mapPT f t)
516 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
517 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
518 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
519 mpt x = x
522data PTactic' t = Intro [Name] | Intros | Focus Name
523 | Refine Name [Bool] | Rewrite t
524 | LetTac Name t | LetTacTy Name t t
525 | Exact t | Compute | Trivial
526 | Solve
527 | Attack
528 | ProofState | ProofTerm | Undo
529 | Try (PTactic' t) (PTactic' t)
530 | TSeq (PTactic' t) (PTactic' t)
531 | ReflectTac t -- see Language.Reflection module
532 | GoalType String (PTactic' t)
533 | Qed | Abandon
534 deriving (Show, Eq, Functor)
535{-!
536deriving instance Binary PTactic'
537!-}
539instance Sized a => Sized (PTactic' a) where
540 size (Intro nms) = 1 + size nms
541 size Intros = 1
542 size (Focus nm) = 1 + size nm
543 size (Refine nm bs) = 1 + size nm + length bs
544 size (Rewrite t) = 1 + size t
545 size (LetTac nm t) = 1 + size nm + size t
546 size (Exact t) = 1 + size t
547 size Compute = 1
548 size Trivial = 1
549 size Solve = 1
550 size Attack = 1
551 size ProofState = 1
552 size ProofTerm = 1
553 size Undo = 1
554 size (Try l r) = 1 + size l + size r
555 size (TSeq l r) = 1 + size l + size r
556 size Qed = 1
557 size Abandon = 1
559type PTactic = PTactic' PTerm
561data PDo' t = DoExp FC t
562 | DoBind FC Name t
563 | DoBindP FC t t
564 | DoLet FC Name t t
565 | DoLetP FC t t
566 deriving (Eq, Functor)
567{-!
568deriving instance Binary PDo'
569!-}
571instance Sized a => Sized (PDo' a) where
572 size (DoExp fc t) = 1 + size fc + size t
573 size (DoBind fc nm t) = 1 + size fc + size nm + size t
574 size (DoBindP fc l r) = 1 + size fc + size l + size r
575 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
576 size (DoLetP fc l r) = 1 + size fc + size l + size r
578type PDo = PDo' PTerm
580-- The priority gives a hint as to elaboration order. Best to elaborate
581-- things early which will help give a more concrete type to other
582-- variables, e.g. a before (interpTy a).
583-- TODO: priority no longer serves any purpose, drop it!
585data PArg' t = PImp { priority :: Int,
586 lazyarg :: Bool, pname :: Name, getTm :: t,
587 pargdoc :: String }
588 | PExp { priority :: Int,
589 lazyarg :: Bool, getTm :: t,
590 pargdoc :: String }
591 | PConstraint { priority :: Int,
592 lazyarg :: Bool, getTm :: t,
593 pargdoc :: String }
594 | PTacImplicit { priority :: Int,
595 lazyarg :: Bool, pname :: Name,
596 getScript :: t,
597 getTm :: t,
598 pargdoc :: String }
599 deriving (Show, Eq, Functor)
601instance Sized a => Sized (PArg' a) where
602 size (PImp p l nm trm _) = 1 + size nm + size trm
603 size (PExp p l trm _) = 1 + size trm
604 size (PConstraint p l trm _) = 1 + size trm
605 size (PTacImplicit p l nm scr trm _) = 1 + size nm + size scr + size trm
607{-!
608deriving instance Binary PArg'
609!-}
611pimp n t = PImp 0 True n t ""
612pexp t = PExp 0 False t ""
613pconst t = PConstraint 0 False t ""
614ptacimp n s t = PTacImplicit 0 True n s t ""
616type PArg = PArg' PTerm
618-- Type class data
620data ClassInfo = CI { instanceName :: Name,
621 class_methods :: [(Name, (FnOpts, PTerm))],
622 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
623 class_params :: [Name],
624 class_instances :: [Name] }
625 deriving Show
626{-!
627deriving instance Binary ClassInfo
628!-}
630data OptInfo = Optimise { collapsible :: Bool,
631 forceable :: [Int], -- argument positions
632 recursive :: [Int] }
633 deriving Show
634{-!
635deriving instance Binary OptInfo
636!-}
639data TypeInfo = TI { con_names :: [Name],
640 codata :: Bool,
641 param_pos :: [Int] }
642 deriving Show
643{-!
644deriving instance Binary TypeInfo
645!-}
647-- Syntactic sugar info
649data DSL' t = DSL { dsl_bind :: t,
650 dsl_return :: t,
651 dsl_apply :: t,
652 dsl_pure :: t,
653 dsl_var :: Maybe t,
654 index_first :: Maybe t,
655 index_next :: Maybe t,
656 dsl_lambda :: Maybe t,
657 dsl_let :: Maybe t
658 }
659 deriving (Show, Functor)
660{-!
661deriving instance Binary DSL'
662!-}
664type DSL = DSL' PTerm
666data SynContext = PatternSyntax | TermSyntax | AnySyntax
667 deriving Show
668{-!
669deriving instance Binary SynContext
670!-}
672data Syntax = Rule [SSymbol] PTerm SynContext
673 deriving Show
674{-!
675deriving instance Binary Syntax
676!-}
678data SSymbol = Keyword Name
679 | Symbol String
680 | Binding Name
681 | Expr Name
682 | SimpleExpr Name
683 deriving Show
684{-!
685deriving instance Binary SSymbol
686!-}
688initDSL = DSL (PRef f (UN ">>="))
689 (PRef f (UN "return"))
690 (PRef f (UN "<$>"))
691 (PRef f (UN "pure"))
692 Nothing
693 Nothing
694 Nothing
695 Nothing
696 Nothing
697 where f = FC "(builtin)" 0
699data SyntaxInfo = Syn { using :: [(Name, PTerm)],
700 syn_params :: [(Name, PTerm)],
701 syn_namespace :: [String],
702 no_imp :: [Name],
703 decoration :: Name -> Name,
704 inPattern :: Bool,
705 implicitAllowed :: Bool,
706 dsl_info :: DSL }
707 deriving Show
708{-!
709deriving instance Binary SyntaxInfo
710!-}
712defaultSyntax = Syn [] [] [] [] id False False initDSL
714expandNS :: SyntaxInfo -> Name -> Name
715expandNS syn n@(NS _ _) = n
716expandNS syn n = case syn_namespace syn of
717 [] -> n
718 xs -> NS n xs
721--- Pretty printing declarations and terms
723instance Show PTerm where
724 show tm = showImp False tm
726instance Pretty PTerm where
727 pretty = prettyImp False
729instance Show PDecl where
730 show d = showDeclImp False d
732instance Show PClause where
733 show c = showCImp True c
735instance Show PData where
736 show d = showDImp False d
738showDeclImp _ (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
739showDeclImp t (PTy _ _ _ _ n ty) = show n ++ " : " ++ showImp t ty
740showDeclImp t (PPostulate _ _ _ _ n ty) = show n ++ " : " ++ showImp t ty
741showDeclImp _ (PClauses _ _ n c) = showSep "\n" (map show c)
742showDeclImp _ (PData _ _ _ _ d) = show d
743showDeclImp _ (PParams f ns ps) = "parameters " ++ show ns ++ "\n" ++
744 showSep "\n" (map show ps)
747showCImp :: Bool -> PClause -> String
748showCImp impl (PClause _ n l ws r w)
749 = showImp impl l ++ showWs ws ++ " = " ++ showImp impl r
750 ++ " where " ++ show w
751 where
752 showWs [] = ""
753 showWs (x : xs) = " | " ++ showImp impl x ++ showWs xs
754showCImp impl (PWith _ n l ws r w)
755 = showImp impl l ++ showWs ws ++ " with " ++ showImp impl r
756 ++ " { " ++ show w ++ " } "
757 where
758 showWs [] = ""
759 showWs (x : xs) = " | " ++ showImp impl x ++ showWs xs
762showDImp :: Bool -> PData -> String
763showDImp impl (PDatadecl n ty cons)
764 = "data " ++ show n ++ " : " ++ showImp impl ty ++ " where\n\t"
765 ++ showSep "\n\t| "
766 (map (\ (_, n, t, _) -> show n ++ " : " ++ showImp impl t) cons)
768getImps :: [PArg] -> [(Name, PTerm)]
769getImps [] = []
770getImps (PImp _ _ n tm _ : xs) = (n, tm) : getImps xs
771getImps (_ : xs) = getImps xs
773getExps :: [PArg] -> [PTerm]
774getExps [] = []
775getExps (PExp _ _ tm _ : xs) = tm : getExps xs
776getExps (_ : xs) = getExps xs
778getConsts :: [PArg] -> [PTerm]
779getConsts [] = []
780getConsts (PConstraint _ _ tm _ : xs) = tm : getConsts xs
781getConsts (_ : xs) = getConsts xs
783getAll :: [PArg] -> [PTerm]
784getAll = map getTm
786prettyImp :: Bool -> PTerm -> Doc
787prettyImp impl = prettySe 10
788 where
789 prettySe p (PQuote r) =
790 if size r > breakingSize then
791 text "![" $$ pretty r <> text "]"
792 else
793 text "![" <> pretty r <> text "]"
794 prettySe p (PPatvar fc n) = pretty n
795 prettySe p (PRef fc n) =
796 if impl then
797 pretty n
798 else
799 prettyBasic n
800 where
801 prettyBasic n@(UN _) = pretty n
802 prettyBasic (MN _ s) = text s
803 prettyBasic (NS n s) = (foldr (<>) empty (intersperse (text ".") (map text $ reverse s))) <> prettyBasic n
804 prettySe p (PLam n ty sc) =
805 bracket p 2 $
806 if size sc > breakingSize then
807 text "λ" <> pretty n <+> text "=>" $+$ pretty sc
808 else
809 text "λ" <> pretty n <+> text "=>" <+> pretty sc
810 prettySe p (PLet n ty v sc) =
811 bracket p 2 $
812 if size sc > breakingSize then
813 text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" $+$
814 nest nestingSize (prettySe 10 sc)
815 else
816 text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" <+>
817 prettySe 10 sc
818 prettySe p (PPi (Exp l s _) n ty sc)
819 | n `elem` allNamesIn sc || impl =
820 let open = if l then text "|" <> lparen else lparen in
821 bracket p 2 $
822 if size sc > breakingSize then
823 open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+>
824 st <+> text "->" $+$ prettySe 10 sc
825 else
826 open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+>
827 st <+> text "->" <+> prettySe 10 sc
828 | otherwise =
829 bracket p 2 $
830 if size sc > breakingSize then
831 prettySe 0 ty <+> st <+> text "->" $+$ prettySe 10 sc
832 else
833 prettySe 0 ty <+> st <+> text "->" <+> prettySe 10 sc
834 where
835 st =
836 case s of
837 Static -> text "[static]"
838 _ -> empty
839 prettySe p (PPi (Imp l s _) n ty sc)
840 | impl =
841 let open = if l then text "|" <> lbrace else lbrace in
842 bracket p 2 $
843 if size sc > breakingSize then
844 open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+>
845 st <+> text "->" <+> prettySe 10 sc
846 else
847 open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+>
848 st <+> text "->" <+> prettySe 10 sc
849 | otherwise = prettySe 10 sc
850 where
851 st =
852 case s of
853 Static -> text $ "[static]"
854 _ -> empty
855 prettySe p (PPi (Constraint _ _ _) n ty sc) =
856 bracket p 2 $
857 if size sc > breakingSize then
858 prettySe 10 ty <+> text "=>" <+> prettySe 10 sc
859 else
860 prettySe 10 ty <+> text "=>" $+$ prettySe 10 sc
861 prettySe p (PPi (TacImp _ _ s _) n ty sc) =
862 bracket p 2 $
863 if size sc > breakingSize then
864 lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <>
865 rbrace <+> text "->" $+$ prettySe 10 sc
866 else
867 lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <>
868 rbrace <+> text "->" <+> prettySe 10 sc
869 prettySe p (PApp _ (PRef _ f) [])
870 | not impl = pretty f
871 prettySe p (PApp _ (PRef _ op@(UN (f:_))) args)
872 | length (getExps args) == 2 && (not impl) && (not $ isAlpha f) =
873 let [l, r] = getExps args in
874 bracket p 1 $
875 if size r > breakingSize then
876 prettySe 1 l <+> pretty op $+$ prettySe 0 r
877 else
878 prettySe 1 l <+> pretty op <+> prettySe 0 r
879 prettySe p (PApp _ f as) =
880 let args = getExps as in
881 bracket p 1 $
882 prettySe 1 f <+>
883 if impl then
884 foldl fS empty as
885 -- foldr (<+>) empty $ map prettyArgS as
886 else
887 foldl fSe empty args
888 -- foldr (<+>) empty $ map prettyArgSe args
889 where
890 fS l r =
891 if size r > breakingSize then
892 l $+$ nest nestingSize (prettyArgS r)
893 else
894 l <+> prettyArgS r
896 fSe l r =
897 if size r > breakingSize then
898 l $+$ nest nestingSize (prettyArgSe r)
899 else
900 l <+> prettyArgSe r
901 prettySe p (PCase _ scr opts) =
902 text "case" <+> prettySe 10 scr <+> text "of" $+$ nest nestingSize prettyBody
903 where
904 prettyBody = foldr ($$) empty $ intersperse (text "|") $ map sc opts
906 sc (l, r) = prettySe 10 l <+> text "=>" <+> prettySe 10 r
907 prettySe p (PHidden tm) = text "." <> prettySe 0 tm
908 prettySe p (PRefl _ _) = text "refl"
909 prettySe p (PResolveTC _) = text "resolvetc"
910 prettySe p (PTrue _) = text "()"
911 prettySe p (PFalse _) = text "_|_"
912 prettySe p (PEq _ l r) =
913 bracket p 2 $
914 if size r > breakingSize then
915 prettySe 10 l <+> text "=" $$ nest nestingSize (prettySe 10 r)
916 else
917 prettySe 10 l <+> text "=" <+> prettySe 10 r
918 prettySe p (PRewrite _ l r) =
919 bracket p 2 $
920 if size r > breakingSize then
921 text "rewrite" <+> prettySe 10 l <+> text "in" $$ nest nestingSize (prettySe 10 r)
922 else
923 text "rewrite" <+> prettySe 10 l <+> text "in" <+> prettySe 10 r
924 prettySe p (PTyped l r) =
925 lparen <> prettySe 10 l <+> colon <+> prettySe 10 r <> rparen
926 prettySe p (PPair _ l r) =
927 if size r > breakingSize then
928 lparen <> prettySe 10 l <> text "," $+$
929 prettySe 10 r <> rparen
930 else
931 lparen <> prettySe 10 l <> text "," <+> prettySe 10 r <> rparen
932 prettySe p (PDPair _ l t r) =
933 if size r > breakingSize then
934 lparen <> prettySe 10 l <+> text "**" $+$
935 prettySe 10 r <> rparen
936 else
937 lparen <> prettySe 10 l <+> text "**" <+> prettySe 10 r <> rparen
938 prettySe p (PAlternative a as) =
939 lparen <> text "|" <> prettyAs <> text "|" <> rparen
940 where
941 prettyAs =
942 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10) as
943 prettySe p PType = text "Type"
944 prettySe p (PConstant c) = pretty c
945 -- XXX: add pretty for tactics
946 prettySe p (PProof ts) =
947 text "proof" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace
948 prettySe p (PTactics ts) =
949 text "tactics" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace
950 prettySe p (PMetavar n) = text "?" <> pretty n
951 prettySe p (PReturn f) = text "return"
952 prettySe p PImpossible = text "impossible"
953 prettySe p Placeholder = text "_"
954 prettySe p (PDoBlock _) = text "do block pretty not implemented"
955 prettySe p (PElabError s) = pretty s
957 prettySe p _ = text "test"
959 prettyArgS (PImp _ _ n tm _) = prettyArgSi (n, tm)
960 prettyArgS (PExp _ _ tm _) = prettyArgSe tm
961 prettyArgS (PConstraint _ _ tm _) = prettyArgSc tm
962 prettyArgS (PTacImplicit _ _ n _ tm _) = prettyArgSti (n, tm)
964 prettyArgSe arg = prettySe 0 arg
965 prettyArgSi (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 val <> rbrace
966 prettyArgSc val = lbrace <> lbrace <> prettySe 10 val <> rbrace <> rbrace
967 prettyArgSti (n, val) = lbrace <> text "auto" <+> pretty n <+> text "=" <+> prettySe 10 val <> rbrace
969 bracket outer inner doc
970 | inner > outer = lparen <> doc <> rparen
971 | otherwise = doc
973showImp :: Bool -> PTerm -> String
974showImp impl tm = se 10 tm where
975 se p (PQuote r) = "![" ++ show r ++ "]"
976 se p (PPatvar fc n) = show n
977 se p (PInferRef fc n) = "!" ++ show n -- ++ "[" ++ show fc ++ "]"
978 se p (PRef fc n) = if impl then show n -- ++ "[" ++ show fc ++ "]"
979 else showbasic n
980 where showbasic n@(UN _) = show n
981 showbasic (MN _ s) = s
982 showbasic (NS n s) = showSep "." (reverse s) ++ "." ++ showbasic n
983 se p (PLam n ty sc) = bracket p 2 $ "\\ " ++ show n ++
984 (if impl then " : " ++ se 10 ty else "") ++ " => "
985 ++ se 10 sc
986 se p (PLet n ty v sc) = bracket p 2 $ "let " ++ show n ++ " = " ++ se 10 v ++
987 " in " ++ se 10 sc
988 se p (PPi (Exp l s _) n ty sc)
989 | n `elem` allNamesIn sc || impl
990 = bracket p 2 $
991 (if l then "|(" else "(") ++
992 show n ++ " : " ++ se 10 ty ++
993 ") " ++ st ++
994 "-> " ++ se 10 sc
995 | otherwise = bracket p 2 $ se 0 ty ++ " " ++ st ++ "-> " ++ se 10 sc
996 where st = case s of
997 Static -> "[static] "
998 _ -> ""
999 se p (PPi (Imp l s _) n ty sc)
1000 | impl = bracket p 2 $ (if l then "|{" else "{") ++
1001 show n ++ " : " ++ se 10 ty ++
1002 "} " ++ st ++ "-> " ++ se 10 sc
1003 | otherwise = se 10 sc
1004 where st = case s of
1005 Static -> "[static] "
1006 _ -> ""
1007 se p (PPi (Constraint _ _ _) n ty sc)
1008 = bracket p 2 $ se 10 ty ++ " => " ++ se 10 sc
1009 se p (PPi (TacImp _ _ s _) n ty sc)
1010 = bracket p 2 $ "{tacimp " ++ show n ++ " : " ++ se 10 ty ++ "} -> " ++ se 10 sc
1011 se p (PApp _ (PRef _ f) [])
1012 | not impl = show f
1013 se p (PApp _ (PRef _ op@(UN (f:_))) args)
1014 | length (getExps args) == 2 && not impl && not (isAlpha f)
1015 = let [l, r] = getExps args in
1016 bracket p 1 $ se 1 l ++ " " ++ show op ++ " " ++ se 0 r
1017 se p (PApp _ f as)
1018 = let args = getExps as in
1019 bracket p 1 $ se 1 f ++ if impl then concatMap sArg as
1020 else concatMap seArg args
1021 se p (PCase _ scr opts) = "case " ++ se 10 scr ++ " of " ++ showSep " | " (map sc opts)
1022 where sc (l, r) = se 10 l ++ " => " ++ se 10 r
1023 se p (PHidden tm) = "." ++ se 0 tm
1024 se p (PRefl _ t)
1025 | not impl = "refl"
1026 | otherwise = "refl {" ++ se 10 t ++ "}"
1027 se p (PResolveTC _) = "resolvetc"
1028 se p (PTrue _) = "()"
1029 se p (PFalse _) = "_|_"
1030 se p (PEq _ l r) = bracket p 2 $ se 10 l ++ " = " ++ se 10 r
1031 se p (PRewrite _ l r) = bracket p 2 $ "rewrite " ++ se 10 l ++ " in " ++ se 10 r
1032 se p (PTyped l r) = "(" ++ se 10 l ++ " : " ++ se 10 r ++ ")"
1033 se p (PPair _ l r) = "(" ++ se 10 l ++ ", " ++ se 10 r ++ ")"
1034 se p (PDPair _ l t r) = "(" ++ se 10 l ++ " ** " ++ se 10 r ++ ")"
1035 se p (PAlternative a as) = "(|" ++ showSep " , " (map (se 10) as) ++ "|)"
1036 se p PType = "Type"
1037 se p (PConstant c) = show c
1038 se p (PProof ts) = "proof { " ++ show ts ++ "}"
1039 se p (PTactics ts) = "tactics { " ++ show ts ++ "}"
1040 se p (PMetavar n) = "?" ++ show n
1041 se p (PReturn f) = "return"
1042 se p PImpossible = "impossible"
1043 se p Placeholder = "_"
1044 se p (PDoBlock _) = "do block show not implemented"
1045 se p (PElabError s) = show s
1046 se p (PCoerced t) = se p t
1047-- se p x = "Not implemented"
1049 sArg (PImp _ _ n tm _) = siArg (n, tm)
1050 sArg (PExp _ _ tm _) = seArg tm
1051 sArg (PConstraint _ _ tm _) = scArg tm
1052 sArg (PTacImplicit _ _ n _ tm _) = stiArg (n, tm)
1054 seArg arg = " " ++ se 0 arg
1055 siArg (n, val) = " {" ++ show n ++ " = " ++ se 10 val ++ "}"
1056 scArg val = " {{" ++ se 10 val ++ "}}"
1057 stiArg (n, val) = " {auto " ++ show n ++ " = " ++ se 10 val ++ "}"
1059 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
1060 | otherwise = str
1063instance Sized PTerm where
1064 size (PQuote rawTerm) = size rawTerm
1065 size (PRef fc name) = size name
1066 size (PLam name ty bdy) = 1 + size ty + size bdy
1067 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1068 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1069 size (PTyped trm ty) = 1 + size trm + size ty
1070 size (PApp fc name args) = 1 + size args
1071 size (PCase fc trm bdy) = 1 + size trm + size bdy
1072 size (PTrue fc) = 1
1073 size (PFalse fc) = 1
1074 size (PRefl fc _) = 1
1075 size (PResolveTC fc) = 1
1076 size (PEq fc left right) = 1 + size left + size right
1077 size (PRewrite fc left right) = 1 + size left + size right
1078 size (PPair fc left right) = 1 + size left + size right
1079 size (PDPair fs left ty right) = 1 + size left + size ty + size right
1080 size (PAlternative a alts) = 1 + size alts
1081 size (PHidden hidden) = size hidden
1082 size PType = 1
1083 size (PConstant const) = 1 + size const
1084 size Placeholder = 1
1085 size (PDoBlock dos) = 1 + size dos
1086 size (PIdiom fc term) = 1 + size term
1087 size (PReturn fc) = 1
1088 size (PMetavar name) = 1
1089 size (PProof tactics) = size tactics
1090 size (PElabError err) = size err
1091 size PImpossible = 1
1093getPArity :: PTerm -> Int
1094getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1095getPArity _ = 0
1097-- Return all names, free or globally bound, in the given term.
1099allNamesIn :: PTerm -> [Name]
1100allNamesIn tm = nub $ ni [] tm
1101 where
1102 ni env (PRef _ n)
1103 | not (n `elem` env) = [n]
1104 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1105 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1106 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1107 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1108 ni env (PHidden tm) = ni env tm
1109 ni env (PEq _ l r) = ni env l ++ ni env r
1110 ni env (PRewrite _ l r) = ni env l ++ ni env r
1111 ni env (PTyped l r) = ni env l ++ ni env r
1112 ni env (PPair _ l r) = ni env l ++ ni env r
1113 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1114 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1115 ni env (PAlternative a ls) = concatMap (ni env) ls
1116 ni env _ = []
1118-- Return names which are free in the given term.
1120namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1121namesIn uvars ist tm = nub $ ni [] tm
1122 where
1123 ni env (PRef _ n)
1124 | not (n `elem` env)
1125 = case lookupTy Nothing n (tt_ctxt ist) of
1126 [] -> [n]
1127 _ -> if n `elem` (map fst uvars) then [n] else []
1128 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1129 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1130 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1131 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1132 ni env (PEq _ l r) = ni env l ++ ni env r
1133 ni env (PRewrite _ l r) = ni env l ++ ni env r
1134 ni env (PTyped l r) = ni env l ++ ni env r
1135 ni env (PPair _ l r) = ni env l ++ ni env r
1136 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1137 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1138 ni env (PAlternative a as) = concatMap (ni env) as
1139 ni env (PHidden tm) = ni env tm
1140 ni env _ = []
1142-- Return which of the given names are used in the given term.
1144usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1145usedNamesIn vars ist tm = nub $ ni [] tm
1146 where
1147 ni env (PRef _ n)
1148 | n `elem` vars && not (n `elem` env)
1149 = case lookupTy Nothing n (tt_ctxt ist) of
1150 [] -> [n]
1151 _ -> []
1152 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1153 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1154 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1155 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1156 ni env (PEq _ l r) = ni env l ++ ni env r
1157 ni env (PRewrite _ l r) = ni env l ++ ni env r
1158 ni env (PTyped l r) = ni env l ++ ni env r
1159 ni env (PPair _ l r) = ni env l ++ ni env r
1160 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1161 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1162 ni env (PAlternative a as) = concatMap (ni env) as
1163 ni env (PHidden tm) = ni env tm
1164 ni env _ = []