on 62be419 help sign in
Idris-dev/src/Idris/AbsSyntaxTree.hs
1166 lines 42 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 | ChangeDirectory FilePath
171 | ModImport String
172 | Edit
173 | Compile Target String
174 | Execute
175 | ExecVal PTerm
176 | NewCompile String
177 | Metavars
178 | Prove Name
179 | AddProof (Maybe Name)
180 | RmProof Name
181 | ShowProof Name
182 | Proofs
183 | Universes
184 | TTShell
185 | LogLvl Int
186 | Spec PTerm
187 | HNF PTerm
188 | Defn Name
189 | Info Name
190 | Missing Name
191 | DynamicLink FilePath
192 | ListDynamic
193 | Pattelab PTerm
194 | DebugInfo Name
195 | Search PTerm
196 | SetOpt Opt
197 | UnsetOpt Opt
198 | NOP
200data Opt = Filename String
201 | Ver
202 | Usage
203 | Quiet
204 | ShowLibs
205 | ShowLibdir
206 | ShowIncs
207 | NoPrelude
208 | NoREPL
209 | OLogging Int
210 | Output String
211 | NewOutput String
212 | TypeCase
213 | TypeInType
214 | DefaultTotal
215 | DefaultPartial
216 | WarnPartial
217 | NoCoverage
218 | ErrContext
219 | ShowImpl
220 | Verbose
221 | IBCSubDir String
222 | ImportDir String
223 | PkgBuild String
224 | PkgInstall String
225 | PkgClean String
226 | WarnOnly
227 | Pkg String
228 | BCAsm String
229 | DumpDefun String
230 | DumpCases String
231 | FOVM String
232 | UseTarget Target
233 | OutputTy OutputType
234 | Extension LanguageExt
235 | DynamicRTS FilePath
236 deriving (Show, Eq)
238-- Parsed declarations
240data Fixity = Infixl { prec :: Int }
241 | Infixr { prec :: Int }
242 | InfixN { prec :: Int }
243 | PrefixN { prec :: Int }
244 deriving Eq
245{-!
246deriving instance Binary Fixity
247!-}
249instance Show Fixity where
250 show (Infixl i) = "infixl " ++ show i
251 show (Infixr i) = "infixr " ++ show i
252 show (InfixN i) = "infix " ++ show i
253 show (PrefixN i) = "prefix " ++ show i
255data FixDecl = Fix Fixity String
256 deriving Eq
258instance Show FixDecl where
259 show (Fix f s) = show f ++ " " ++ s
261{-!
262deriving instance Binary FixDecl
263!-}
265instance Ord FixDecl where
266 compare (Fix x _) (Fix y _) = compare (prec x) (prec y)
269data Static = Static | Dynamic
270 deriving (Show, Eq)
271{-!
272deriving instance Binary Static
273!-}
275-- Mark bindings with their explicitness, and laziness
276data Plicity = Imp { plazy :: Bool,
277 pstatic :: Static,
278 pdocstr :: String }
279 | Exp { plazy :: Bool,
280 pstatic :: Static,
281 pdocstr :: String }
282 | Constraint { plazy :: Bool,
283 pstatic :: Static,
284 pdocstr :: String }
285 | TacImp { plazy :: Bool,
286 pstatic :: Static,
287 pscript :: PTerm,
288 pdocstr :: String }
289 deriving (Show, Eq)
291{-!
292deriving instance Binary Plicity
293!-}
295impl = Imp False Dynamic ""
296expl = Exp False Dynamic ""
297constraint = Constraint False Dynamic ""
298tacimpl t = TacImp False Dynamic t ""
300data FnOpt = Inlinable | TotalFn | PartialFn
301 | Coinductive | AssertTotal | TCGen
302 | Implicit -- implicit coercion
303 | CExport String -- export, with a C name
304 | Specialise [Name] -- specialise it, freeze these names
305 deriving (Show, Eq)
306{-!
307deriving instance Binary FnOpt
308!-}
310type FnOpts = [FnOpt]
312inlinable :: FnOpts -> Bool
313inlinable = elem Inlinable
315-- | Top-level declarations such as compiler directives, definitions,
316-- datatypes and typeclasses.
317data PDecl' t
318 = PFix FC Fixity [String] -- ^ Fixity declaration
319 | PTy String SyntaxInfo FC FnOpts Name t -- ^ Type declaration
320 | PPostulate String SyntaxInfo FC FnOpts Name t -- ^ Postulate
321 | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause
322 | PCAF FC Name t -- ^ Top level constant
323 | PData String SyntaxInfo FC Bool (PData' t) -- ^ Data declaration. The Bool argument is True for codata.
324 | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block
325 | PNamespace String [PDecl' t] -- ^ New namespace
326 | PRecord String SyntaxInfo FC Name t String Name t -- ^ Record declaration
327 | PClass String SyntaxInfo FC
328 [t] -- constraints
329 Name
330 [(Name, t)] -- parameters
331 [PDecl' t] -- declarations
332 -- ^ Type class: arguments are documentation, syntax info, source location, constraints,
333 -- class name, parameters, method declarations
334 | PInstance SyntaxInfo FC [t] -- constraints
335 Name -- class
336 [t] -- parameters
337 t -- full instance type
338 (Maybe Name) -- explicit name
339 [PDecl' t]
340 -- ^ Instance declaration: arguments are syntax info, source location, constraints,
341 -- class name, parameters, full instance type, optional explicit name, and definitions
342 | PDSL Name (DSL' t) -- ^ DSL declaration
343 | PSyntax FC Syntax -- ^ Syntax definition
344 | PMutual FC [PDecl' t] -- ^ Mutual block
345 | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad.
346 | PProvider SyntaxInfo FC Name t t -- ^ Type provider. The first t is the type, the second is the term
347 deriving Functor
348{-!
349deriving instance Binary PDecl'
350!-}
352-- | One clause of a top-level definition. Term arguments to constructors are:
353--
354-- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause)
355--
356-- 2. The list of patterns
357--
358-- 3. The right-hand side
359--
360-- 4. The where block (PDecl' t)
361data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition.
362 | PWith FC Name t [t] t [PDecl' t]
363 | PClauseR FC [t] t [PDecl' t]
364 | PWithR FC [t] t [PDecl' t]
365 deriving Functor
366{-!
367deriving instance Binary PClause'
368!-}
370-- | Data declaration
371data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype
372 d_tcon :: t, -- ^ Type constructor
373 d_cons :: [(String, Name, t, FC)] -- ^ Constructors
374 }
375 -- ^ Data declaration
376 | PLaterdecl { d_name :: Name, d_tcon :: t }
377 -- ^ "Placeholder" for data whose constructors are defined later
378 deriving Functor
379{-!
380deriving instance Binary PData'
381!-}
383-- Handy to get a free function for applying PTerm -> PTerm functions
384-- across a program, by deriving Functor
386type PDecl = PDecl' PTerm
387type PData = PData' PTerm
388type PClause = PClause' PTerm
390-- get all the names declared in a decl
392declared :: PDecl -> [Name]
393declared (PFix _ _ _) = []
394declared (PTy _ _ _ _ n t) = [n]
395declared (PPostulate _ _ _ _ n t) = [n]
396declared (PClauses _ _ n _) = [] -- not a declaration
397declared (PCAF _ n _) = [n]
398declared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
399 where fstt (_, a, _, _) = a
400declared (PData _ _ _ _ (PLaterdecl n _)) = [n]
401declared (PParams _ _ ds) = concatMap declared ds
402declared (PNamespace _ ds) = concatMap declared ds
403declared (PRecord _ _ _ n _ _ c _) = [n, c]
404declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms
405declared (PInstance _ _ _ _ _ _ _ _) = []
406declared (PDSL n _) = [n]
407declared (PSyntax _ _) = []
408declared (PMutual _ ds) = concatMap declared ds
409declared (PDirective _) = []
411-- get the names declared, not counting nested parameter blocks
412tldeclared :: PDecl -> [Name]
413tldeclared (PFix _ _ _) = []
414tldeclared (PTy _ _ _ _ n t) = [n]
415tldeclared (PPostulate _ _ _ _ n t) = [n]
416tldeclared (PClauses _ _ n _) = [] -- not a declaration
417tldeclared (PRecord _ _ _ n _ _ c _) = [n, c]
418tldeclared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
419 where fstt (_, a, _, _) = a
420tldeclared (PParams _ _ ds) = []
421tldeclared (PMutual _ ds) = concatMap tldeclared ds
422tldeclared (PNamespace _ ds) = concatMap tldeclared ds
425defined :: PDecl -> [Name]
426defined (PFix _ _ _) = []
427defined (PTy _ _ _ _ n t) = []
428defined (PPostulate _ _ _ _ n t) = []
429defined (PClauses _ _ n _) = [n] -- not a declaration
430defined (PCAF _ n _) = [n]
431defined (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts
432 where fstt (_, a, _, _) = a
433defined (PData _ _ _ _ (PLaterdecl n _)) = []
434defined (PParams _ _ ds) = concatMap defined ds
435defined (PNamespace _ ds) = concatMap defined ds
436defined (PRecord _ _ _ n _ _ c _) = [n, c]
437defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms
438defined (PInstance _ _ _ _ _ _ _ _) = []
439defined (PDSL n _) = [n]
440defined (PSyntax _ _) = []
441defined (PMutual _ ds) = concatMap defined ds
442defined (PDirective _) = []
443--defined _ = []
445updateN :: [(Name, Name)] -> Name -> Name
446updateN ns n | Just n' <- lookup n ns = n'
447updateN _ n = n
449updateNs :: [(Name, Name)] -> PTerm -> PTerm
450updateNs [] t = t
451updateNs ns t = mapPT updateRef t
452 where updateRef (PRef fc f) = PRef fc (updateN ns f)
453 updateRef t = t
455-- updateDNs :: [(Name, Name)] -> PDecl -> PDecl
456-- updateDNs [] t = t
457-- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t
458-- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c)
459-- where updateCNs ns (PClause n l ts r ds)
460-- = PClause (updateN ns n) (fmap (updateNs ns) l)
461-- (map (fmap (updateNs ns)) ts)
462-- (fmap (updateNs ns) r)
463-- (map (updateDNs ns) ds)
464-- updateDNs ns c = c
466-- | High level language terms
467data PTerm = PQuote Raw
468 | PRef FC Name
469 | PInferRef FC Name -- ^ A name to be defined later
470 | PPatvar FC Name
471 | PLam Name PTerm PTerm
472 | PPi Plicity Name PTerm PTerm
473 | PLet Name PTerm PTerm PTerm
474 | PTyped PTerm PTerm -- ^ Term with explicit type
475 | PApp FC PTerm [PArg]
476 | PCase FC PTerm [(PTerm, PTerm)]
477 | PTrue FC
478 | PFalse FC
479 | PRefl FC PTerm
480 | PResolveTC FC
481 | PEq FC PTerm PTerm
482 | PRewrite FC PTerm PTerm
483 | PPair FC PTerm PTerm
484 | PDPair FC PTerm PTerm PTerm
485 | PAlternative Bool [PTerm] -- True if only one may work
486 | PHidden PTerm -- ^ Irrelevant or hidden pattern
487 | PType
488 | PConstant Const
489 | Placeholder
490 | PDoBlock [PDo]
491 | PIdiom FC PTerm
492 | PReturn FC
493 | PMetavar Name
494 | PProof [PTactic] -- ^ Proof script
495 | PTactics [PTactic] -- ^ As PProof, but no auto solving
496 | PElabError Err -- ^ Error to report on elaboration
497 | PImpossible -- ^ Special case for declaring when an LHS can't typecheck
498 | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice
499 deriving Eq
500{-!
501deriving instance Binary PTerm
502!-}
504mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm
505mapPT f t = f (mpt t) where
506 mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s)
507 mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s)
508 mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s)
509 mpt (PRewrite fc t s) = PRewrite fc (mapPT f t) (mapPT f s)
510 mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as)
511 mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os)
512 mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r)
513 mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r)
514 mpt (PPair fc l r) = PPair fc (mapPT f l) (mapPT f r)
515 mpt (PDPair fc l t r) = PDPair fc (mapPT f l) (mapPT f t) (mapPT f r)
516 mpt (PAlternative a as) = PAlternative a (map (mapPT f) as)
517 mpt (PHidden t) = PHidden (mapPT f t)
518 mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds)
519 mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts)
520 mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts)
521 mpt x = x
524data PTactic' t = Intro [Name] | Intros | Focus Name
525 | Refine Name [Bool] | Rewrite t
526 | LetTac Name t | LetTacTy Name t t
527 | Exact t | Compute | Trivial
528 | Solve
529 | Attack
530 | ProofState | ProofTerm | Undo
531 | Try (PTactic' t) (PTactic' t)
532 | TSeq (PTactic' t) (PTactic' t)
533 | ReflectTac t -- see Language.Reflection module
534 | GoalType String (PTactic' t)
535 | Qed | Abandon
536 deriving (Show, Eq, Functor)
537{-!
538deriving instance Binary PTactic'
539!-}
541instance Sized a => Sized (PTactic' a) where
542 size (Intro nms) = 1 + size nms
543 size Intros = 1
544 size (Focus nm) = 1 + size nm
545 size (Refine nm bs) = 1 + size nm + length bs
546 size (Rewrite t) = 1 + size t
547 size (LetTac nm t) = 1 + size nm + size t
548 size (Exact t) = 1 + size t
549 size Compute = 1
550 size Trivial = 1
551 size Solve = 1
552 size Attack = 1
553 size ProofState = 1
554 size ProofTerm = 1
555 size Undo = 1
556 size (Try l r) = 1 + size l + size r
557 size (TSeq l r) = 1 + size l + size r
558 size Qed = 1
559 size Abandon = 1
561type PTactic = PTactic' PTerm
563data PDo' t = DoExp FC t
564 | DoBind FC Name t
565 | DoBindP FC t t
566 | DoLet FC Name t t
567 | DoLetP FC t t
568 deriving (Eq, Functor)
569{-!
570deriving instance Binary PDo'
571!-}
573instance Sized a => Sized (PDo' a) where
574 size (DoExp fc t) = 1 + size fc + size t
575 size (DoBind fc nm t) = 1 + size fc + size nm + size t
576 size (DoBindP fc l r) = 1 + size fc + size l + size r
577 size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r
578 size (DoLetP fc l r) = 1 + size fc + size l + size r
580type PDo = PDo' PTerm
582-- The priority gives a hint as to elaboration order. Best to elaborate
583-- things early which will help give a more concrete type to other
584-- variables, e.g. a before (interpTy a).
585-- TODO: priority no longer serves any purpose, drop it!
587data PArg' t = PImp { priority :: Int,
588 lazyarg :: Bool, pname :: Name, getTm :: t,
589 pargdoc :: String }
590 | PExp { priority :: Int,
591 lazyarg :: Bool, getTm :: t,
592 pargdoc :: String }
593 | PConstraint { priority :: Int,
594 lazyarg :: Bool, getTm :: t,
595 pargdoc :: String }
596 | PTacImplicit { priority :: Int,
597 lazyarg :: Bool, pname :: Name,
598 getScript :: t,
599 getTm :: t,
600 pargdoc :: String }
601 deriving (Show, Eq, Functor)
603instance Sized a => Sized (PArg' a) where
604 size (PImp p l nm trm _) = 1 + size nm + size trm
605 size (PExp p l trm _) = 1 + size trm
606 size (PConstraint p l trm _) = 1 + size trm
607 size (PTacImplicit p l nm scr trm _) = 1 + size nm + size scr + size trm
609{-!
610deriving instance Binary PArg'
611!-}
613pimp n t = PImp 0 True n t ""
614pexp t = PExp 0 False t ""
615pconst t = PConstraint 0 False t ""
616ptacimp n s t = PTacImplicit 0 True n s t ""
618type PArg = PArg' PTerm
620-- Type class data
622data ClassInfo = CI { instanceName :: Name,
623 class_methods :: [(Name, (FnOpts, PTerm))],
624 class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl
625 class_params :: [Name],
626 class_instances :: [Name] }
627 deriving Show
628{-!
629deriving instance Binary ClassInfo
630!-}
632data OptInfo = Optimise { collapsible :: Bool,
633 forceable :: [Int], -- argument positions
634 recursive :: [Int] }
635 deriving Show
636{-!
637deriving instance Binary OptInfo
638!-}
641data TypeInfo = TI { con_names :: [Name],
642 codata :: Bool,
643 param_pos :: [Int] }
644 deriving Show
645{-!
646deriving instance Binary TypeInfo
647!-}
649-- Syntactic sugar info
651data DSL' t = DSL { dsl_bind :: t,
652 dsl_return :: t,
653 dsl_apply :: t,
654 dsl_pure :: t,
655 dsl_var :: Maybe t,
656 index_first :: Maybe t,
657 index_next :: Maybe t,
658 dsl_lambda :: Maybe t,
659 dsl_let :: Maybe t
660 }
661 deriving (Show, Functor)
662{-!
663deriving instance Binary DSL'
664!-}
666type DSL = DSL' PTerm
668data SynContext = PatternSyntax | TermSyntax | AnySyntax
669 deriving Show
670{-!
671deriving instance Binary SynContext
672!-}
674data Syntax = Rule [SSymbol] PTerm SynContext
675 deriving Show
676{-!
677deriving instance Binary Syntax
678!-}
680data SSymbol = Keyword Name
681 | Symbol String
682 | Binding Name
683 | Expr Name
684 | SimpleExpr Name
685 deriving Show
686{-!
687deriving instance Binary SSymbol
688!-}
690initDSL = DSL (PRef f (UN ">>="))
691 (PRef f (UN "return"))
692 (PRef f (UN "<$>"))
693 (PRef f (UN "pure"))
694 Nothing
695 Nothing
696 Nothing
697 Nothing
698 Nothing
699 where f = FC "(builtin)" 0
701data SyntaxInfo = Syn { using :: [(Name, PTerm)],
702 syn_params :: [(Name, PTerm)],
703 syn_namespace :: [String],
704 no_imp :: [Name],
705 decoration :: Name -> Name,
706 inPattern :: Bool,
707 implicitAllowed :: Bool,
708 dsl_info :: DSL }
709 deriving Show
710{-!
711deriving instance Binary SyntaxInfo
712!-}
714defaultSyntax = Syn [] [] [] [] id False False initDSL
716expandNS :: SyntaxInfo -> Name -> Name
717expandNS syn n@(NS _ _) = n
718expandNS syn n = case syn_namespace syn of
719 [] -> n
720 xs -> NS n xs
723--- Pretty printing declarations and terms
725instance Show PTerm where
726 show tm = showImp False tm
728instance Pretty PTerm where
729 pretty = prettyImp False
731instance Show PDecl where
732 show d = showDeclImp False d
734instance Show PClause where
735 show c = showCImp True c
737instance Show PData where
738 show d = showDImp False d
740showDeclImp _ (PFix _ f ops) = show f ++ " " ++ showSep ", " ops
741showDeclImp t (PTy _ _ _ _ n ty) = show n ++ " : " ++ showImp t ty
742showDeclImp t (PPostulate _ _ _ _ n ty) = show n ++ " : " ++ showImp t ty
743showDeclImp _ (PClauses _ _ n c) = showSep "\n" (map show c)
744showDeclImp _ (PData _ _ _ _ d) = show d
745showDeclImp _ (PParams f ns ps) = "parameters " ++ show ns ++ "\n" ++
746 showSep "\n" (map show ps)
749showCImp :: Bool -> PClause -> String
750showCImp impl (PClause _ n l ws r w)
751 = showImp impl l ++ showWs ws ++ " = " ++ showImp impl r
752 ++ " where " ++ show w
753 where
754 showWs [] = ""
755 showWs (x : xs) = " | " ++ showImp impl x ++ showWs xs
756showCImp impl (PWith _ n l ws r w)
757 = showImp impl l ++ showWs ws ++ " with " ++ showImp impl r
758 ++ " { " ++ show w ++ " } "
759 where
760 showWs [] = ""
761 showWs (x : xs) = " | " ++ showImp impl x ++ showWs xs
764showDImp :: Bool -> PData -> String
765showDImp impl (PDatadecl n ty cons)
766 = "data " ++ show n ++ " : " ++ showImp impl ty ++ " where\n\t"
767 ++ showSep "\n\t| "
768 (map (\ (_, n, t, _) -> show n ++ " : " ++ showImp impl t) cons)
770getImps :: [PArg] -> [(Name, PTerm)]
771getImps [] = []
772getImps (PImp _ _ n tm _ : xs) = (n, tm) : getImps xs
773getImps (_ : xs) = getImps xs
775getExps :: [PArg] -> [PTerm]
776getExps [] = []
777getExps (PExp _ _ tm _ : xs) = tm : getExps xs
778getExps (_ : xs) = getExps xs
780getConsts :: [PArg] -> [PTerm]
781getConsts [] = []
782getConsts (PConstraint _ _ tm _ : xs) = tm : getConsts xs
783getConsts (_ : xs) = getConsts xs
785getAll :: [PArg] -> [PTerm]
786getAll = map getTm
788prettyImp :: Bool -> PTerm -> Doc
789prettyImp impl = prettySe 10
790 where
791 prettySe p (PQuote r) =
792 if size r > breakingSize then
793 text "![" $$ pretty r <> text "]"
794 else
795 text "![" <> pretty r <> text "]"
796 prettySe p (PPatvar fc n) = pretty n
797 prettySe p (PRef fc n) =
798 if impl then
799 pretty n
800 else
801 prettyBasic n
802 where
803 prettyBasic n@(UN _) = pretty n
804 prettyBasic (MN _ s) = text s
805 prettyBasic (NS n s) = (foldr (<>) empty (intersperse (text ".") (map text $ reverse s))) <> prettyBasic n
806 prettySe p (PLam n ty sc) =
807 bracket p 2 $
808 if size sc > breakingSize then
809 text "λ" <> pretty n <+> text "=>" $+$ pretty sc
810 else
811 text "λ" <> pretty n <+> text "=>" <+> pretty sc
812 prettySe p (PLet n ty v sc) =
813 bracket p 2 $
814 if size sc > breakingSize then
815 text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" $+$
816 nest nestingSize (prettySe 10 sc)
817 else
818 text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" <+>
819 prettySe 10 sc
820 prettySe p (PPi (Exp l s _) n ty sc)
821 | n `elem` allNamesIn sc || impl =
822 let open = if l then text "|" <> lparen else lparen in
823 bracket p 2 $
824 if size sc > breakingSize then
825 open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+>
826 st <+> text "->" $+$ prettySe 10 sc
827 else
828 open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+>
829 st <+> text "->" <+> prettySe 10 sc
830 | otherwise =
831 bracket p 2 $
832 if size sc > breakingSize then
833 prettySe 0 ty <+> st <+> text "->" $+$ prettySe 10 sc
834 else
835 prettySe 0 ty <+> st <+> text "->" <+> prettySe 10 sc
836 where
837 st =
838 case s of
839 Static -> text "[static]"
840 _ -> empty
841 prettySe p (PPi (Imp l s _) n ty sc)
842 | impl =
843 let open = if l then text "|" <> lbrace else lbrace in
844 bracket p 2 $
845 if size sc > breakingSize then
846 open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+>
847 st <+> text "->" <+> prettySe 10 sc
848 else
849 open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+>
850 st <+> text "->" <+> prettySe 10 sc
851 | otherwise = prettySe 10 sc
852 where
853 st =
854 case s of
855 Static -> text $ "[static]"
856 _ -> empty
857 prettySe p (PPi (Constraint _ _ _) n ty sc) =
858 bracket p 2 $
859 if size sc > breakingSize then
860 prettySe 10 ty <+> text "=>" <+> prettySe 10 sc
861 else
862 prettySe 10 ty <+> text "=>" $+$ prettySe 10 sc
863 prettySe p (PPi (TacImp _ _ s _) n ty sc) =
864 bracket p 2 $
865 if size sc > breakingSize then
866 lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <>
867 rbrace <+> text "->" $+$ prettySe 10 sc
868 else
869 lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <>
870 rbrace <+> text "->" <+> prettySe 10 sc
871 prettySe p (PApp _ (PRef _ f) [])
872 | not impl = pretty f
873 prettySe p (PApp _ (PRef _ op@(UN (f:_))) args)
874 | length (getExps args) == 2 && (not impl) && (not $ isAlpha f) =
875 let [l, r] = getExps args in
876 bracket p 1 $
877 if size r > breakingSize then
878 prettySe 1 l <+> pretty op $+$ prettySe 0 r
879 else
880 prettySe 1 l <+> pretty op <+> prettySe 0 r
881 prettySe p (PApp _ f as) =
882 let args = getExps as in
883 bracket p 1 $
884 prettySe 1 f <+>
885 if impl then
886 foldl fS empty as
887 -- foldr (<+>) empty $ map prettyArgS as
888 else
889 foldl fSe empty args
890 -- foldr (<+>) empty $ map prettyArgSe args
891 where
892 fS l r =
893 if size r > breakingSize then
894 l $+$ nest nestingSize (prettyArgS r)
895 else
896 l <+> prettyArgS r
898 fSe l r =
899 if size r > breakingSize then
900 l $+$ nest nestingSize (prettyArgSe r)
901 else
902 l <+> prettyArgSe r
903 prettySe p (PCase _ scr opts) =
904 text "case" <+> prettySe 10 scr <+> text "of" $+$ nest nestingSize prettyBody
905 where
906 prettyBody = foldr ($$) empty $ intersperse (text "|") $ map sc opts
908 sc (l, r) = prettySe 10 l <+> text "=>" <+> prettySe 10 r
909 prettySe p (PHidden tm) = text "." <> prettySe 0 tm
910 prettySe p (PRefl _ _) = text "refl"
911 prettySe p (PResolveTC _) = text "resolvetc"
912 prettySe p (PTrue _) = text "()"
913 prettySe p (PFalse _) = text "_|_"
914 prettySe p (PEq _ l r) =
915 bracket p 2 $
916 if size r > breakingSize then
917 prettySe 10 l <+> text "=" $$ nest nestingSize (prettySe 10 r)
918 else
919 prettySe 10 l <+> text "=" <+> prettySe 10 r
920 prettySe p (PRewrite _ l r) =
921 bracket p 2 $
922 if size r > breakingSize then
923 text "rewrite" <+> prettySe 10 l <+> text "in" $$ nest nestingSize (prettySe 10 r)
924 else
925 text "rewrite" <+> prettySe 10 l <+> text "in" <+> prettySe 10 r
926 prettySe p (PTyped l r) =
927 lparen <> prettySe 10 l <+> colon <+> prettySe 10 r <> rparen
928 prettySe p (PPair _ l r) =
929 if size r > breakingSize then
930 lparen <> prettySe 10 l <> text "," $+$
931 prettySe 10 r <> rparen
932 else
933 lparen <> prettySe 10 l <> text "," <+> prettySe 10 r <> rparen
934 prettySe p (PDPair _ l t r) =
935 if size r > breakingSize then
936 lparen <> prettySe 10 l <+> text "**" $+$
937 prettySe 10 r <> rparen
938 else
939 lparen <> prettySe 10 l <+> text "**" <+> prettySe 10 r <> rparen
940 prettySe p (PAlternative a as) =
941 lparen <> text "|" <> prettyAs <> text "|" <> rparen
942 where
943 prettyAs =
944 foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10) as
945 prettySe p PType = text "Type"
946 prettySe p (PConstant c) = pretty c
947 -- XXX: add pretty for tactics
948 prettySe p (PProof ts) =
949 text "proof" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace
950 prettySe p (PTactics ts) =
951 text "tactics" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace
952 prettySe p (PMetavar n) = text "?" <> pretty n
953 prettySe p (PReturn f) = text "return"
954 prettySe p PImpossible = text "impossible"
955 prettySe p Placeholder = text "_"
956 prettySe p (PDoBlock _) = text "do block pretty not implemented"
957 prettySe p (PElabError s) = pretty s
959 prettySe p _ = text "test"
961 prettyArgS (PImp _ _ n tm _) = prettyArgSi (n, tm)
962 prettyArgS (PExp _ _ tm _) = prettyArgSe tm
963 prettyArgS (PConstraint _ _ tm _) = prettyArgSc tm
964 prettyArgS (PTacImplicit _ _ n _ tm _) = prettyArgSti (n, tm)
966 prettyArgSe arg = prettySe 0 arg
967 prettyArgSi (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 val <> rbrace
968 prettyArgSc val = lbrace <> lbrace <> prettySe 10 val <> rbrace <> rbrace
969 prettyArgSti (n, val) = lbrace <> text "auto" <+> pretty n <+> text "=" <+> prettySe 10 val <> rbrace
971 bracket outer inner doc
972 | inner > outer = lparen <> doc <> rparen
973 | otherwise = doc
975showImp :: Bool -> PTerm -> String
976showImp impl tm = se 10 tm where
977 se p (PQuote r) = "![" ++ show r ++ "]"
978 se p (PPatvar fc n) = show n
979 se p (PInferRef fc n) = "!" ++ show n -- ++ "[" ++ show fc ++ "]"
980 se p (PRef fc n) = if impl then show n -- ++ "[" ++ show fc ++ "]"
981 else showbasic n
982 where showbasic n@(UN _) = show n
983 showbasic (MN _ s) = s
984 showbasic (NS n s) = showSep "." (reverse s) ++ "." ++ showbasic n
985 se p (PLam n ty sc) = bracket p 2 $ "\\ " ++ show n ++
986 (if impl then " : " ++ se 10 ty else "") ++ " => "
987 ++ se 10 sc
988 se p (PLet n ty v sc) = bracket p 2 $ "let " ++ show n ++ " = " ++ se 10 v ++
989 " in " ++ se 10 sc
990 se p (PPi (Exp l s _) n ty sc)
991 | n `elem` allNamesIn sc || impl
992 = bracket p 2 $
993 (if l then "|(" else "(") ++
994 show n ++ " : " ++ se 10 ty ++
995 ") " ++ st ++
996 "-> " ++ se 10 sc
997 | otherwise = bracket p 2 $ se 0 ty ++ " " ++ st ++ "-> " ++ se 10 sc
998 where st = case s of
999 Static -> "[static] "
1000 _ -> ""
1001 se p (PPi (Imp l s _) n ty sc)
1002 | impl = bracket p 2 $ (if l then "|{" else "{") ++
1003 show n ++ " : " ++ se 10 ty ++
1004 "} " ++ st ++ "-> " ++ se 10 sc
1005 | otherwise = se 10 sc
1006 where st = case s of
1007 Static -> "[static] "
1008 _ -> ""
1009 se p (PPi (Constraint _ _ _) n ty sc)
1010 = bracket p 2 $ se 10 ty ++ " => " ++ se 10 sc
1011 se p (PPi (TacImp _ _ s _) n ty sc)
1012 = bracket p 2 $ "{tacimp " ++ show n ++ " : " ++ se 10 ty ++ "} -> " ++ se 10 sc
1013 se p (PApp _ (PRef _ f) [])
1014 | not impl = show f
1015 se p (PApp _ (PRef _ op@(UN (f:_))) args)
1016 | length (getExps args) == 2 && not impl && not (isAlpha f)
1017 = let [l, r] = getExps args in
1018 bracket p 1 $ se 1 l ++ " " ++ show op ++ " " ++ se 0 r
1019 se p (PApp _ f as)
1020 = let args = getExps as in
1021 bracket p 1 $ se 1 f ++ if impl then concatMap sArg as
1022 else concatMap seArg args
1023 se p (PCase _ scr opts) = "case " ++ se 10 scr ++ " of " ++ showSep " | " (map sc opts)
1024 where sc (l, r) = se 10 l ++ " => " ++ se 10 r
1025 se p (PHidden tm) = "." ++ se 0 tm
1026 se p (PRefl _ t)
1027 | not impl = "refl"
1028 | otherwise = "refl {" ++ se 10 t ++ "}"
1029 se p (PResolveTC _) = "resolvetc"
1030 se p (PTrue _) = "()"
1031 se p (PFalse _) = "_|_"
1032 se p (PEq _ l r) = bracket p 2 $ se 10 l ++ " = " ++ se 10 r
1033 se p (PRewrite _ l r) = bracket p 2 $ "rewrite " ++ se 10 l ++ " in " ++ se 10 r
1034 se p (PTyped l r) = "(" ++ se 10 l ++ " : " ++ se 10 r ++ ")"
1035 se p (PPair _ l r) = "(" ++ se 10 l ++ ", " ++ se 10 r ++ ")"
1036 se p (PDPair _ l t r) = "(" ++ se 10 l ++ " ** " ++ se 10 r ++ ")"
1037 se p (PAlternative a as) = "(|" ++ showSep " , " (map (se 10) as) ++ "|)"
1038 se p PType = "Type"
1039 se p (PConstant c) = show c
1040 se p (PProof ts) = "proof { " ++ show ts ++ "}"
1041 se p (PTactics ts) = "tactics { " ++ show ts ++ "}"
1042 se p (PMetavar n) = "?" ++ show n
1043 se p (PReturn f) = "return"
1044 se p PImpossible = "impossible"
1045 se p Placeholder = "_"
1046 se p (PDoBlock _) = "do block show not implemented"
1047 se p (PElabError s) = show s
1048 se p (PCoerced t) = se p t
1049-- se p x = "Not implemented"
1051 sArg (PImp _ _ n tm _) = siArg (n, tm)
1052 sArg (PExp _ _ tm _) = seArg tm
1053 sArg (PConstraint _ _ tm _) = scArg tm
1054 sArg (PTacImplicit _ _ n _ tm _) = stiArg (n, tm)
1056 seArg arg = " " ++ se 0 arg
1057 siArg (n, val) = " {" ++ show n ++ " = " ++ se 10 val ++ "}"
1058 scArg val = " {{" ++ se 10 val ++ "}}"
1059 stiArg (n, val) = " {auto " ++ show n ++ " = " ++ se 10 val ++ "}"
1061 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
1062 | otherwise = str
1065instance Sized PTerm where
1066 size (PQuote rawTerm) = size rawTerm
1067 size (PRef fc name) = size name
1068 size (PLam name ty bdy) = 1 + size ty + size bdy
1069 size (PPi plicity name ty bdy) = 1 + size ty + size bdy
1070 size (PLet name ty def bdy) = 1 + size ty + size def + size bdy
1071 size (PTyped trm ty) = 1 + size trm + size ty
1072 size (PApp fc name args) = 1 + size args
1073 size (PCase fc trm bdy) = 1 + size trm + size bdy
1074 size (PTrue fc) = 1
1075 size (PFalse fc) = 1
1076 size (PRefl fc _) = 1
1077 size (PResolveTC fc) = 1
1078 size (PEq fc left right) = 1 + size left + size right
1079 size (PRewrite fc left right) = 1 + size left + size right
1080 size (PPair fc left right) = 1 + size left + size right
1081 size (PDPair fs left ty right) = 1 + size left + size ty + size right
1082 size (PAlternative a alts) = 1 + size alts
1083 size (PHidden hidden) = size hidden
1084 size PType = 1
1085 size (PConstant const) = 1 + size const
1086 size Placeholder = 1
1087 size (PDoBlock dos) = 1 + size dos
1088 size (PIdiom fc term) = 1 + size term
1089 size (PReturn fc) = 1
1090 size (PMetavar name) = 1
1091 size (PProof tactics) = size tactics
1092 size (PElabError err) = size err
1093 size PImpossible = 1
1095getPArity :: PTerm -> Int
1096getPArity (PPi _ _ _ sc) = 1 + getPArity sc
1097getPArity _ = 0
1099-- Return all names, free or globally bound, in the given term.
1101allNamesIn :: PTerm -> [Name]
1102allNamesIn tm = nub $ ni [] tm
1103 where
1104 ni env (PRef _ n)
1105 | not (n `elem` env) = [n]
1106 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1107 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1108 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1109 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1110 ni env (PHidden tm) = ni env tm
1111 ni env (PEq _ l r) = ni env l ++ ni env r
1112 ni env (PRewrite _ l r) = ni env l ++ ni env r
1113 ni env (PTyped l r) = ni env l ++ ni env r
1114 ni env (PPair _ l r) = ni env l ++ ni env r
1115 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1116 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1117 ni env (PAlternative a ls) = concatMap (ni env) ls
1118 ni env _ = []
1120-- Return names which are free in the given term.
1122namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name]
1123namesIn uvars ist tm = nub $ ni [] tm
1124 where
1125 ni env (PRef _ n)
1126 | not (n `elem` env)
1127 = case lookupTy Nothing n (tt_ctxt ist) of
1128 [] -> [n]
1129 _ -> if n `elem` (map fst uvars) then [n] else []
1130 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1131 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1132 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1133 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1134 ni env (PEq _ l r) = ni env l ++ ni env r
1135 ni env (PRewrite _ l r) = ni env l ++ ni env r
1136 ni env (PTyped l r) = ni env l ++ ni env r
1137 ni env (PPair _ l r) = ni env l ++ ni env r
1138 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1139 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1140 ni env (PAlternative a as) = concatMap (ni env) as
1141 ni env (PHidden tm) = ni env tm
1142 ni env _ = []
1144-- Return which of the given names are used in the given term.
1146usedNamesIn :: [Name] -> IState -> PTerm -> [Name]
1147usedNamesIn vars ist tm = nub $ ni [] tm
1148 where
1149 ni env (PRef _ n)
1150 | n `elem` vars && not (n `elem` env)
1151 = case lookupTy Nothing n (tt_ctxt ist) of
1152 [] -> [n]
1153 _ -> []
1154 ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as)
1155 ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os)
1156 ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc
1157 ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc
1158 ni env (PEq _ l r) = ni env l ++ ni env r
1159 ni env (PRewrite _ l r) = ni env l ++ ni env r
1160 ni env (PTyped l r) = ni env l ++ ni env r
1161 ni env (PPair _ l r) = ni env l ++ ni env r
1162 ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r
1163 ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r
1164 ni env (PAlternative a as) = concatMap (ni env) as
1165 ni env (PHidden tm) = ni env tm
1166 ni env _ = []