on df5bf81 help sign in
871 lines 29 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveFunctor #-}
3{-| TT is the core language of Idris. The language has:
5 * Full dependent types
7 * A hierarchy of universes, with cumulativity: Type : Type1, Type1 : Type2, ...
9 * Pattern matching letrec binding
11 * (primitive types defined externally)
13 Some technical stuff:
15 * Typechecker is kept as simple as possible - no unification, just a checker for incomplete terms.
17 * We have a simple collection of tactics which we use to elaborate source
18 programs with implicit syntax into fully explicit terms.
19-}
21module Core.TT where
23import Control.Monad.State
24import Debug.Trace
25import qualified Data.Map as Map
26import Data.Char
27import Data.List
28import qualified Data.Binary as B
29import Data.Binary hiding (get, put)
31import Util.Pretty hiding (Str)
33data Option = TTypeInTType
34 | CheckConv
35 deriving Eq
37-- | Source location. These are typically produced by the parser 'Idris.Parser.pfc'
38data FC = FC { fc_fname :: String, -- ^ Filename
39 fc_line :: Int -- ^ Line number
40 }
41 deriving Eq
42{-!
43deriving instance Binary FC
44!-}
46instance Sized FC where
47 size (FC f l) = 1 + length f
49instance Show FC where
50 show (FC f l) = f ++ ":" ++ show l
52data Err = Msg String
53 | InternalMsg String
54 | CantUnify Bool Term Term Err [(Name, Type)] Int
55 -- Int is 'score' - how much we did unify
56 -- Bool indicates recoverability, True indicates more info may make
57 -- unification succeed
58 | InfiniteUnify Name Term [(Name, Type)]
59 | CantConvert Term Term [(Name, Type)]
60 | NoSuchVariable Name
61 | NoTypeDecl Name
62 | NotInjective Term Term Term
63 | CantResolve Term
64 | CantResolveAlts [String]
65 | IncompleteTerm Term
66 | UniverseError
67 | ProgramLineComment
68 | Inaccessible Name
69 | NonCollapsiblePostulate Name
70 | AlreadyDefined Name
71 | ProofSearchFail Err
72 | At FC Err
73 deriving Eq
75instance Sized Err where
76 size (Msg msg) = length msg
77 size (InternalMsg msg) = length msg
78 size (CantUnify _ left right err _ score) = size left + size right + size err
79 size (InfiniteUnify _ right _) = size right
80 size (CantConvert left right _) = size left + size right
81 size (NoSuchVariable name) = size name
82 size (NoTypeDecl name) = size name
83 size (NotInjective l c r) = size l + size c + size r
84 size (CantResolve trm) = size trm
85 size (CantResolveAlts _) = 1
86 size (IncompleteTerm trm) = size trm
87 size UniverseError = 1
88 size ProgramLineComment = 1
89 size (At fc err) = size fc + size err
90 size _ = 1
92score :: Err -> Int
93score (CantUnify _ _ _ m _ s) = s + score m
94score (CantResolve _) = 20
95score (NoSuchVariable _) = 1000
96score (ProofSearchFail _) = 10000
97score _ = 0
99instance Show Err where
100 show (Msg s) = s
101 show (InternalMsg s) = "Internal error: " ++ show s
102 show (CantUnify _ l r e sc i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
103 ++ show e ++ " in " ++ show sc ++ " " ++ show i
104 show (Inaccessible n) = show n ++ " is not an accessible pattern variable"
105 show _ = "Error"
107instance Pretty Err where
108 pretty (Msg m) = text m
109 pretty (CantUnify _ l r e _ i) =
110 if size l + size r > breakingSize then
111 text "Cannot unify" <+> colon $$
112 nest nestingSize (pretty l <+> text "and" <+> pretty r) $$
113 nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
114 else
115 text "Cannot unify" <+> colon <+> pretty l <+> text "and" <+> pretty r $$
116 nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
117 pretty _ = text "Error"
119data TC a = OK a
120 | Error Err
121 deriving (Eq, Functor)
123instance Pretty a => Pretty (TC a) where
124 pretty (OK ok) = pretty ok
125 pretty (Error err) =
126 if size err > breakingSize then
127 text "Error" <+> colon $$ (nest nestingSize $ pretty err)
128 else
129 text "Error" <+> colon <+> pretty err
131instance Show a => Show (TC a) where
132 show (OK x) = show x
133 show (Error str) = "Error: " ++ show str
135-- at some point, this instance should also carry type checking options
136-- (e.g. Type:Type)
138instance Monad TC where
139 return = OK
140 x >>= k = case x of
141 OK v -> k v
142 Error e -> Error e
143 fail e = Error (InternalMsg e)
145tfail :: Err -> TC a
146tfail e = Error e
148trun :: FC -> TC a -> TC a
149trun fc (OK a) = OK a
150trun fc (Error e) = Error (At fc e)
152instance MonadPlus TC where
153 mzero = fail "Unknown error"
154 (OK x) `mplus` _ = OK x
155 _ `mplus` (OK y) = OK y
156 err `mplus` _ = err
158discard :: Monad m => m a -> m ()
159discard f = f >> return ()
161showSep :: String -> [String] -> String
162showSep sep [] = ""
163showSep sep [x] = x
164showSep sep (x:xs) = x ++ sep ++ showSep sep xs
166pmap f (x, y) = (f x, f y)
168traceWhen True msg a = trace msg a
169traceWhen False _ a = a
171-- RAW TERMS ----------------------------------------------------------------
173-- | Names are hierarchies of strings, describing scope (so no danger of
174-- duplicate names, but need to be careful on lookup).
175data Name = UN String -- ^ User-provided name
176 | NS Name [String] -- ^ Root, namespaces
177 | MN Int String -- ^ Machine chosen names
178 | NErased -- ^ Name of somethng which is never used in scope
179 deriving (Eq, Ord)
180{-!
181deriving instance Binary Name
182!-}
184instance Sized Name where
185 size (UN n) = 1
186 size (NS n els) = 1 + length els
187 size (MN i n) = 1
188 size NErased = 1
190instance Pretty Name where
191 pretty (UN n) = text n
192 pretty (NS n s) = pretty n
193 pretty (MN i s) = lbrace <+> text s <+> (text . show $ i) <+> rbrace
195instance Show Name where
196 show (UN n) = n
197 show (NS n s) = showSep "." (reverse s) ++ "." ++ show n
198 show (MN i s) = "{" ++ s ++ show i ++ "}"
199 show NErased = "_"
201-- |Contexts allow us to map names to things. A root name maps to a collection
202-- of things in different namespaces with that name.
203type Ctxt a = Map.Map Name (Map.Map Name a)
204emptyContext = Map.empty
206tcname (UN ('@':_)) = True
207tcname (NS n _) = tcname n
208tcname _ = False
210implicitable (NS n _) = implicitable n
211implicitable (UN (x:xs)) = isLower x
212implicitable _ = False
214nsroot (NS n _) = n
215nsroot n = n
217addDef :: Name -> a -> Ctxt a -> Ctxt a
218addDef n v ctxt = case Map.lookup (nsroot n) ctxt of
219 Nothing -> Map.insert (nsroot n)
220 (Map.insert n v Map.empty) ctxt
221 Just xs -> Map.insert (nsroot n)
222 (Map.insert n v xs) ctxt
224{-| Look up a name in the context, given an optional namespace.
225 The name (n) may itself have a (partial) namespace given.
227 Rules for resolution:
229 - if an explicit namespace is given, return the names which match it. If none
230 match, return all names.
232 - if the name has has explicit namespace given, return the names which match it
233 and ignore the given namespace.
235 - otherwise, return all names.
237-}
239lookupCtxtName :: Maybe [String] -> Name -> Ctxt a -> [(Name, a)]
240lookupCtxtName nspace n ctxt = case Map.lookup (nsroot n) ctxt of
241 Just xs -> filterNS (Map.toList xs)
242 Nothing -> []
243 where
244 filterNS [] = []
245 filterNS ((found, v) : xs)
246 | nsmatch n found = (found, v) : filterNS xs
247 | otherwise = filterNS xs
249 nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps
250 nsmatch (NS _ _) _ = False
251 nsmatch looking found = True
253lookupCtxt :: Maybe [String] -> Name -> Ctxt a -> [a]
254lookupCtxt ns n ctxt = map snd (lookupCtxtName ns n ctxt)
256updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a
257updateDef n f ctxt
258 = let ds = lookupCtxtName Nothing n ctxt in
259 foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds
261toAlist :: Ctxt a -> [(Name, a)]
262toAlist ctxt = let allns = map snd (Map.toList ctxt) in
263 concat (map (Map.toList) allns)
265addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
266addAlist [] ctxt = ctxt
267addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
269data Const = I Int | BI Integer | Fl Double | Ch Char | Str String
270 | IType | BIType | FlType | ChType | StrType
272 | B8 Word8 | B16 Word16 | B32 Word32 | B64 Word64
273 | B8Type | B16Type | B32Type | B64Type
275 | PtrType | VoidType | Forgot
276 deriving (Eq, Ord)
277{-!
278deriving instance Binary Const
279!-}
281instance Sized Const where
282 size _ = 1
284instance Pretty Const where
285 pretty (I i) = text . show $ i
286 pretty (BI i) = text . show $ i
287 pretty (Fl f) = text . show $ f
288 pretty (Ch c) = text . show $ c
289 pretty (Str s) = text s
290 pretty IType = text "Int"
291 pretty BIType = text "BigInt"
292 pretty FlType = text "Float"
293 pretty ChType = text "Char"
294 pretty StrType = text "String"
295 pretty PtrType = text "Ptr"
296 pretty VoidType = text "Void"
297 pretty Forgot = text "Forgot"
298 pretty B8Type = text "Bits8"
299 pretty B16Type = text "Bits16"
300 pretty B32Type = text "Bits32"
301 pretty B64Type = text "Bits64"
303data Raw = Var Name
304 | RBind Name (Binder Raw) Raw
305 | RApp Raw Raw
306 | RType
307 | RForce Raw
308 | RConstant Const
309 deriving (Show, Eq)
311instance Sized Raw where
312 size (Var name) = 1
313 size (RBind name bind right) = 1 + size bind + size right
314 size (RApp left right) = 1 + size left + size right
315 size RType = 1
316 size (RForce raw) = 1 + size raw
317 size (RConstant const) = size const
319instance Pretty Raw where
320 pretty = text . show
322{-!
323deriving instance Binary Raw
324!-}
326-- | All binding forms are represented in a unform fashion.
327data Binder b = Lam { binderTy :: b {-^ type annotation for bound variable-}}
328 | Pi { binderTy :: b }
329 | Let { binderTy :: b,
330 binderVal :: b {-^ value for bound variable-}}
331 | NLet { binderTy :: b,
332 binderVal :: b }
333 | Hole { binderTy :: b}
334 | GHole { binderTy :: b}
335 | Guess { binderTy :: b,
336 binderVal :: b }
337 | PVar { binderTy :: b }
338 | PVTy { binderTy :: b }
339 deriving (Show, Eq, Ord, Functor)
340{-!
341deriving instance Binary Binder
342!-}
344instance Sized a => Sized (Binder a) where
345 size (Lam ty) = 1 + size ty
346 size (Pi ty) = 1 + size ty
347 size (Let ty val) = 1 + size ty + size val
348 size (NLet ty val) = 1 + size ty + size val
349 size (Hole ty) = 1 + size ty
350 size (GHole ty) = 1 + size ty
351 size (Guess ty val) = 1 + size ty + size val
352 size (PVar ty) = 1 + size ty
353 size (PVTy ty) = 1 + size ty
355fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
356fmapMB f (Let t v) = liftM2 Let (f t) (f v)
357fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
358fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
359fmapMB f (Lam t) = liftM Lam (f t)
360fmapMB f (Pi t) = liftM Pi (f t)
361fmapMB f (Hole t) = liftM Hole (f t)
362fmapMB f (GHole t) = liftM GHole (f t)
363fmapMB f (PVar t) = liftM PVar (f t)
364fmapMB f (PVTy t) = liftM PVTy (f t)
366raw_apply :: Raw -> [Raw] -> Raw
367raw_apply f [] = f
368raw_apply f (a : as) = raw_apply (RApp f a) as
370raw_unapply :: Raw -> (Raw, [Raw])
371raw_unapply t = ua [] t where
372 ua args (RApp f a) = ua (a:args) f
373 ua args t = (t, args)
375data RawFun = RawFun { rtype :: Raw,
376 rval :: Raw
377 }
378 deriving Show
380data RawDatatype = RDatatype Name Raw [(Name, Raw)]
381 deriving Show
383data RDef = RFunction RawFun
384 | RConst Raw
385 | RData RawDatatype
386 deriving Show
388type RProgram = [(Name, RDef)]
390-- WELL TYPED TERMS ---------------------------------------------------------
392-- | Universe expressions for universe checking
393data UExp = UVar Int -- ^ universe variable
394 | UVal Int -- ^ explicit universe level
395 deriving (Eq, Ord)
397instance Sized UExp where
398 size _ = 1
400-- We assume that universe levels have been checked, so anything external
401-- can just have the same universe variable and we won't get any new
402-- cycles.
404instance Binary UExp where
405 put x = return ()
406 get = return (UVar (-1))
408instance Show UExp where
409 show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
410 | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
411 show (UVal x) = show x
412-- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")"
414-- | Universe constraints
415data UConstraint = ULT UExp UExp -- ^ Strictly less than
416 | ULE UExp UExp -- ^ Less than or equal to
417 deriving Eq
419instance Show UConstraint where
420 show (ULT x y) = show x ++ " < " ++ show y
421 show (ULE x y) = show x ++ " <= " ++ show y
423type UCs = (Int, [UConstraint])
425data NameType = Bound | Ref | DCon Int Int | TCon Int Int
426 deriving (Show, Ord)
427{-!
428deriving instance Binary NameType
429!-}
431instance Sized NameType where
432 size _ = 1
434instance Pretty NameType where
435 pretty = text . show
437instance Eq NameType where
438 Bound == Bound = True
439 Ref == Ref = True
440 DCon _ a == DCon _ b = (a == b) -- ignore tag
441 TCon _ a == TCon _ b = (a == b) -- ignore tag
442 _ == _ = False
444-- | Terms in the core language
445data TT n = P NameType n (TT n) -- ^ named references
446 | V Int -- ^ a resolved de Bruijn-indexed variable
447 | Bind n (Binder (TT n)) (TT n) -- ^ a binding
448 | App (TT n) (TT n) -- ^ function, function type, arg
449 | Constant Const -- ^ constant
450 | Proj (TT n) Int -- ^ argument projection; runtime only
451 | Erased -- ^ an erased term
452 | Impossible -- ^ special case for totality checking
453 | TType UExp -- ^ the type of types at some level
454 deriving (Ord, Functor)
455{-!
456deriving instance Binary TT
457!-}
459class TermSize a where
460 termsize :: Name -> a -> Int
462instance TermSize a => TermSize [a] where
463 termsize n [] = 0
464 termsize n (x : xs) = termsize n x + termsize n xs
466instance TermSize (TT Name) where
467 termsize n (P _ x _)
468 | x == n = 1000000 -- recursive => really big
469 | otherwise = 1
470 termsize n (V _) = 1
471 termsize n (Bind n' (Let t v) sc)
472 = let rn = if n == n' then MN 0 "noname" else n in
473 termsize rn v + termsize rn sc
474 termsize n (App f a) = termsize n f + termsize n a
475 termsize n _ = 1
477instance Sized a => Sized (TT a) where
478 size (P name n trm) = 1 + size name + size n + size trm
479 size (V v) = 1
480 size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy
481 size (App l r) = 1 + size l + size r
482 size (Constant c) = size c
483 size Erased = 1
484 size (TType u) = 1 + size u
486instance Pretty a => Pretty (TT a) where
487 pretty _ = text "test"
489type EnvTT n = [(n, Binder (TT n))]
491data Datatype n = Data { d_typename :: n,
492 d_typetag :: Int,
493 d_type :: (TT n),
494 d_cons :: [(n, TT n)] }
495 deriving (Show, Functor, Eq)
497instance Eq n => Eq (TT n) where
498 (==) (P xt x _) (P yt y _) = x == y
499 (==) (V x) (V y) = x == y
500 (==) (Bind _ xb xs) (Bind _ yb ys) = xb == yb && xs == ys
501 (==) (App fx ax) (App fy ay) = fx == fy && ax == ay
502 (==) (TType _) (TType _) = True -- deal with constraints later
503 (==) (Constant x) (Constant y) = x == y
504 (==) (Proj x i) (Proj y j) = x == y && i == j
505 (==) Erased _ = True
506 (==) _ Erased = True
507 (==) _ _ = False
509-- * A few handy operations on well typed terms:
511-- | A term is injective iff it is a data constructor, type constructor,
512-- constant, the type Type, pi-binding, or an application of an injective
513-- term.
514isInjective :: TT n -> Bool
515isInjective (P (DCon _ _) _ _) = True
516isInjective (P (TCon _ _) _ _) = True
517isInjective (Constant _) = True
518isInjective (TType x) = True
519isInjective (Bind _ (Pi _) sc) = True
520isInjective (App f a) = isInjective f
521isInjective _ = False
523-- | Count the number of instances of a de Bruijn index in a term
524vinstances :: Int -> TT n -> Int
525vinstances i (V x) | i == x = 1
526vinstances i (App f a) = vinstances i f + vinstances i a
527vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc
528 where instancesB (Let t v) = vinstances i v
529 instancesB _ = 0
530vinstances i t = 0
532instantiate :: TT n -> TT n -> TT n
533instantiate e = subst 0 where
534 subst i (V x) | i == x = e
535 subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
536 subst i (App f a) = App (subst i f) (subst i a)
537 subst i (Proj x idx) = Proj (subst i x) idx
538 subst i t = t
540explicitNames :: TT n -> TT n
541explicitNames (Bind x b sc) = let b' = fmap explicitNames b in
542 Bind x b'
543 (explicitNames (instantiate
544 (P Bound x (binderTy b')) sc))
545explicitNames (App f a) = App (explicitNames f) (explicitNames a)
546explicitNames (Proj x idx) = Proj (explicitNames x) idx
547explicitNames t = t
549pToV :: Eq n => n -> TT n -> TT n
550pToV n = pToV' n 0
551pToV' n i (P _ x _) | n == x = V i
552pToV' n i (Bind x b sc)
553-- We can assume the inner scope has been pToVed already, so continue to
554-- resolve names from the *outer* scope which may happen to have the same id.
555-- | n == x = Bind x (fmap (pToV' n i) b) sc
556 | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
557pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
558pToV' n i (Proj t idx) = Proj (pToV' n i t) idx
559pToV' n i t = t
561-- | Convert several names. First in the list comes out as V 0
562pToVs :: Eq n => [n] -> TT n -> TT n
563pToVs ns tm = pToVs' ns tm 0 where
564 pToVs' [] tm i = tm
565 pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
567vToP :: TT n -> TT n
568vToP = vToP' [] where
569 vToP' env (V i) = let (n, b) = (env !! i) in
570 P Bound n (binderTy b)
571 vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
572 Bind n b' (vToP' ((n, b'):env) sc)
573 vToP' env (App f a) = App (vToP' env f) (vToP' env a)
574 vToP' env t = t
576finalise :: Eq n => TT n -> TT n
577finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
578finalise (App f a) = App (finalise f) (finalise a)
579finalise t = t
581subst :: Eq n => n -> TT n -> TT n -> TT n
582subst n v tm = instantiate v (pToV n tm)
584substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
585substNames [] t = t
586substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
588substTerm :: Eq n => TT n -> TT n -> TT n -> TT n
589substTerm old new = st where
590 st t | t == old = new
591 st (App f a) = App (st f) (st a)
592 st (Bind x b sc) = Bind x (fmap st b) (st sc)
593 st t = t
595-- Returns true if V 0 and bound name n do not occur in the term
597noOccurrence :: Eq n => n -> TT n -> Bool
598noOccurrence n t = no' 0 t
599 where
600 no' i (V x) = not (i == x)
601 no' i (P Bound x _) = not (n == x)
602 no' i (Bind n b sc) = noB' i b && no' (i+1) sc
603 where noB' i (Let t v) = no' i t && no' i v
604 noB' i (Guess t v) = no' i t && no' i v
605 noB' i b = no' i (binderTy b)
606 no' i (App f a) = no' i f && no' i a
607 no' i (Proj x _) = no' i x
608 no' i _ = True
610-- | Returns all names used free in the term
611freeNames :: Eq n => TT n -> [n]
612freeNames (P _ n _) = [n]
613freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n])
614 ++ freeNames t
615freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
616freeNames (App f a) = nub $ freeNames f ++ freeNames a
617freeNames (Proj x i) = nub $ freeNames x
618freeNames _ = []
620-- | Return the arity of a (normalised) type
621arity :: TT n -> Int
622arity (Bind n (Pi t) sc) = 1 + arity sc
623arity _ = 0
625-- | Deconstruct an application; returns the function and a list of arguments
626unApply :: TT n -> (TT n, [TT n])
627unApply t = ua [] t where
628 ua args (App f a) = ua (a:args) f
629 ua args t = (t, args)
631mkApp :: TT n -> [TT n] -> TT n
632mkApp f [] = f
633mkApp f (a:as) = mkApp (App f a) as
635forget :: TT Name -> Raw
636forget tm = fe [] tm
637 where
638 fe env (P _ n _) = Var n
639 fe env (V i) = Var (env !! i)
640 fe env (Bind n b sc) = RBind n (fmap (fe env) b)
641 (fe (n:env) sc)
642 fe env (App f a) = RApp (fe env f) (fe env a)
643 fe env (Constant c)
644 = RConstant c
645 fe env (TType i) = RType
646 fe env Erased = RConstant Forgot
648bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
649bindAll [] t =t
650bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
652bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
653bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
655getArgTys :: TT n -> [(n, TT n)]
656getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
657getArgTys _ = []
659getRetTy :: TT n -> TT n
660getRetTy (Bind n (PVar _) sc) = getRetTy sc
661getRetTy (Bind n (PVTy _) sc) = getRetTy sc
662getRetTy (Bind n (Pi _) sc) = getRetTy sc
663getRetTy sc = sc
665uniqueName :: Name -> [Name] -> Name
666uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
667 | otherwise = n
669uniqueBinders :: [Name] -> TT Name -> TT Name
670uniqueBinders ns (Bind n b sc)
671 = let n' = uniqueName n ns in
672 Bind n' (fmap (uniqueBinders (n':ns)) b) (uniqueBinders ns sc)
673uniqueBinders ns (App f a) = App (uniqueBinders ns f) (uniqueBinders ns a)
674uniqueBinders ns t = t
677nextName (NS x s) = NS (nextName x) s
678nextName (MN i n) = MN (i+1) n
679nextName (UN x) = let (num', nm') = span isDigit (reverse x)
680 nm = reverse nm'
681 num = readN (reverse num') in
682 UN (nm ++ show (num+1))
683 where
684 readN "" = 0
685 readN x = read x
687type Term = TT Name
688type Type = Term
690type Env = EnvTT Name
692-- an environment with de Bruijn indices 'normalised' so that they all refer to
693-- this environment
695newtype WkEnvTT n = Wk (EnvTT n)
696type WkEnv = WkEnvTT Name
698instance (Eq n, Show n) => Show (TT n) where
699 show t = showEnv [] t
701instance Show Const where
702 show (I i) = show i
703 show (BI i) = show i ++ "L"
704 show (Fl f) = show f
705 show (Ch c) = show c
706 show (Str s) = show s
707 show (B8 x) = show x
708 show (B16 x) = show x
709 show (B32 x) = show x
710 show (B64 x) = show x
711 show IType = "Int"
712 show BIType = "Integer"
713 show FlType = "Float"
714 show ChType = "Char"
715 show StrType = "String"
716 show PtrType = "Ptr"
717 show B8Type = "Bits8"
718 show B16Type = "Bits16"
719 show B32Type = "Bits32"
720 show B64Type = "Bits64"
721 show VoidType = "Void"
723showEnv env t = showEnv' env t False
724showEnvDbg env t = showEnv' env t True
726prettyEnv env t = prettyEnv' env t False
727 where
728 prettyEnv' env t dbg = prettySe 10 env t dbg
730 bracket outer inner p
731 | inner > outer = lparen <> p <> rparen
732 | otherwise = p
734 prettySe p env (P nt n t) debug =
735 pretty n <+>
736 if debug then
737 lbrack <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbrack
738 else
739 empty
740 prettySe p env (V i) debug
741 | i < length env =
742 if debug then
743 text . show . fst $ env!!i
744 else
745 lbrack <+> text (show i) <+> rbrack
746 | otherwise = text "unbound" <+> text (show i) <+> text "!"
747 prettySe p env (Bind n b@(Pi t) sc) debug
748 | noOccurrence n sc && not debug =
749 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
750 prettySe p env (Bind n b sc) debug =
751 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
752 prettySe p env (App f a) debug =
753 bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug
754 prettySe p env (Proj x i) debug =
755 prettySe 1 env x debug <+> text ("!" ++ show i)
756 prettySe p env (Constant c) debug = pretty c
757 prettySe p env Erased debug = text "[_]"
758 prettySe p env (TType i) debug = text "Type" <+> (text . show $ i)
760 prettySb env n (Lam t) = prettyB env "λ" "=>" n t
761 prettySb env n (Hole t) = prettyB env "?defer" "." n t
762 prettySb env n (Pi t) = prettyB env "(" ") ->" n t
763 prettySb env n (PVar t) = prettyB env "pat" "." n t
764 prettySb env n (PVTy t) = prettyB env "pty" "." n t
765 prettySb env n (Let t v) = prettyBv env "let" "in" n t v
766 prettySb env n (Guess t v) = prettyBv env "??" "in" n t v
768 prettyB env op sc n t debug =
769 text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc
771 prettyBv env op sc n t v debug =
772 text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+>
773 prettySe 10 env v debug <> text sc
776showEnv' env t dbg = se 10 env t where
777 se p env (P nt n t) = show n
778 ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
779 se p env (V i) | i < length env = (show $ fst $ env!!i) ++
780 if dbg then "{" ++ show i ++ "}" else ""
781 | otherwise = "!!V " ++ show i ++ "!!"
782 se p env (Bind n b@(Pi t) sc)
783 | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
784 se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
785 se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
786 se p env (Proj x i) = se 1 env x ++ "!" ++ show i
787 se p env (Constant c) = show c
788 se p env Erased = "[__]"
789 se p env Impossible = "[impossible]"
790 se p env (TType i) = "Type " ++ show i
792 sb env n (Lam t) = showb env "\\ " " => " n t
793 sb env n (Hole t) = showb env "? " ". " n t
794 sb env n (GHole t) = showb env "?defer " ". " n t
795 sb env n (Pi t) = showb env "(" ") -> " n t
796 sb env n (PVar t) = showb env "pat " ". " n t
797 sb env n (PVTy t) = showb env "pty " ". " n t
798 sb env n (Let t v) = showbv env "let " " in " n t v
799 sb env n (Guess t v) = showbv env "?? " " in " n t v
801 showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
802 showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
803 se 10 env v ++ sc
805 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
806 | otherwise = str
808-- | Check whether a term has any holes in it - impure if so
809pureTerm :: TT Name -> Bool
810pureTerm (App f a) = pureTerm f && pureTerm a
811pureTerm (Bind n b sc) = notClassName n && pureBinder b && pureTerm sc where
812 pureBinder (Hole _) = False
813 pureBinder (Guess _ _) = False
814 pureBinder (Let t v) = pureTerm t && pureTerm v
815 pureBinder t = pureTerm (binderTy t)
817 notClassName (MN _ "class") = False
818 notClassName _ = True
820pureTerm _ = True
822-- | Weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings)
823weakenTm :: Int -> TT n -> TT n
824weakenTm i t = wk i 0 t
825 where wk i min (V x) | x >= min = V (i + x)
826 wk i m (App f a) = App (wk i m f) (wk i m a)
827 wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
828 wk i m t = t
829 wkb i m t = fmap (wk i m) t
831-- | Weaken an environment so that all the de Bruijn indices are correct according
832-- to the latest bound variable
834weakenEnv :: EnvTT n -> EnvTT n
835weakenEnv env = wk (length env - 1) env
836 where wk i [] = []
837 wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
838 weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
839 weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
840 weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
842weakenTmEnv :: Int -> EnvTT n -> EnvTT n
843weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
845orderPats :: Term -> Term
846orderPats tm = op [] tm
847 where
848 op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc
849 op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc
850 op ps sc = bindAll (map (\ (n, t) -> (n, t)) (sortP ps)) sc
852 sortP ps = pick [] (reverse ps)
854 namesIn (P _ n _) = [n]
855 namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
856 where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
857 nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
858 nb t = namesIn (binderTy t)
859 namesIn (App f a) = nub (namesIn f ++ namesIn a)
860 namesIn _ = []
862 pick acc [] = reverse acc
863 pick acc ((n, t) : ps) = pick (insert n t acc) ps
865 insert n t [] = [(n, t)]
866 insert n t ((n',t') : ps)
867 | n `elem` (namesIn (binderTy t') ++
868 concatMap namesIn (map (binderTy . snd) ps))
869 = (n', t') : insert n t ps
870 | otherwise = (n,t):(n',t'):ps