on aa7262e help sign in
823 lines 27 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveFunctor #-}
3module Core.TT where
5import Control.Monad.State
6import Debug.Trace
7import qualified Data.Map as Map
8import Data.Char
9import Data.List
10import qualified Data.Binary as B
11import Data.Binary hiding (get, put)
13import Util.Pretty hiding (Str)
15{- The language has:
16 * Full dependent types
17 * A hierarchy of universes, with cumulativity: Set : Set1, Set1 : Set2, ...
18 * Pattern matching letrec binding
19 * (primitive types defined externally)
21 Some technical stuff:
22 * Typechecker is kept as simple as possible
23 - no unification, just a checker for incomplete terms.
24 * We have a simple collection of tactics which we use to elaborate source
25 programs with implicit syntax into fully explicit terms.
26-}
28data Option = SetInSet
29 | CheckConv
30 deriving Eq
32data FC = FC { fc_fname :: String,
33 fc_line :: Int }
34 deriving Eq
35{-!
36deriving instance Binary FC
37!-}
39instance Sized FC where
40 size (FC f l) = 1 + length f
42instance Show FC where
43 show (FC f l) = f ++ ":" ++ show l
45data Err = Msg String
46 | InternalMsg String
47 | CantUnify Bool Term Term Err [(Name, Type)] Int
48 -- Int is 'score' - how much we did unify
49 -- Bool indicates recoverability, True indicates more info may make
50 -- unification succeed
51 | InfiniteUnify Name Term [(Name, Type)]
52 | CantConvert Term Term [(Name, Type)]
53 | NoSuchVariable Name
54 | NoTypeDecl Name
55 | NotInjective Term Term Term
56 | CantResolve Term
57 | CantResolveAlts [String]
58 | IncompleteTerm Term
59 | UniverseError
60 | ProgramLineComment
61 | Inaccessible Name
62 | NonCollapsiblePostulate Name
63 | At FC Err
64 deriving Eq
66instance Sized Err where
67 size (Msg msg) = length msg
68 size (InternalMsg msg) = length msg
69 size (CantUnify _ left right err _ score) = size left + size right + size err
70 size (InfiniteUnify _ right _) = size right
71 size (CantConvert left right _) = size left + size right
72 size (NoSuchVariable name) = size name
73 size (NoTypeDecl name) = size name
74 size (NotInjective l c r) = size l + size c + size r
75 size (CantResolve trm) = size trm
76 size (CantResolveAlts _) = 1
77 size (IncompleteTerm trm) = size trm
78 size UniverseError = 1
79 size ProgramLineComment = 1
80 size (At fc err) = size fc + size err
81 size (Inaccessible _) = 1
83score :: Err -> Int
84score (CantUnify _ _ _ m _ s) = s + score m
85score (CantResolve _) = 20
86score (NoSuchVariable _) = 1000
87score _ = 0
89instance Show Err where
90 show (Msg s) = s
91 show (InternalMsg s) = "Internal error: " ++ show s
92 show (CantUnify _ l r e sc i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
93 ++ show e ++ " in " ++ show sc ++ " " ++ show i
94 show (Inaccessible n) = show n ++ " is not an accessible pattern variable"
95 show _ = "Error"
97instance Pretty Err where
98 pretty (Msg m) = text m
99 pretty (CantUnify _ l r e _ i) =
100 if size l + size r > breakingSize then
101 text "Cannot unify" <+> colon $$
102 nest nestingSize (pretty l <+> text "and" <+> pretty r) $$
103 nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
104 else
105 text "Cannot unify" <+> colon <+> pretty l <+> text "and" <+> pretty r $$
106 nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
107 pretty _ = text "Error"
109data TC a = OK a
110 | Error Err
111 deriving (Eq, Functor)
113instance Pretty a => Pretty (TC a) where
114 pretty (OK ok) = pretty ok
115 pretty (Error err) =
116 if size err > breakingSize then
117 text "Error" <+> colon $$ (nest nestingSize $ pretty err)
118 else
119 text "Error" <+> colon <+> pretty err
121instance Show a => Show (TC a) where
122 show (OK x) = show x
123 show (Error str) = "Error: " ++ show str
125-- at some point, this instance should also carry type checking options
126-- (e.g. Set:Set)
128instance Monad TC where
129 return = OK
130 x >>= k = case x of
131 OK v -> k v
132 Error e -> Error e
133 fail e = Error (InternalMsg e)
135tfail :: Err -> TC a
136tfail e = Error e
138trun :: FC -> TC a -> TC a
139trun fc (OK a) = OK a
140trun fc (Error e) = Error (At fc e)
142instance MonadPlus TC where
143 mzero = fail "Unknown error"
144 (OK x) `mplus` _ = OK x
145 _ `mplus` (OK y) = OK y
146 err `mplus` _ = err
148discard :: Monad m => m a -> m ()
149discard f = f >> return ()
151showSep :: String -> [String] -> String
152showSep sep [] = ""
153showSep sep [x] = x
154showSep sep (x:xs) = x ++ sep ++ showSep sep xs
156pmap f (x, y) = (f x, f y)
158traceWhen True msg a = trace msg a
159traceWhen False _ a = a
161-- RAW TERMS ----------------------------------------------------------------
163-- Names are hierarchies of strings, describing scope (so no danger of
164-- duplicate names, but need to be careful on lookup).
165-- Also MN for machine chosen names
167data Name = UN String
168 | NS Name [String] -- root, namespaces
169 | MN Int String
170 | NErased -- name of somethng which is never used in scope
171 deriving (Eq, Ord)
172{-!
173deriving instance Binary Name
174!-}
176instance Sized Name where
177 size (UN n) = 1
178 size (NS n els) = 1 + length els
179 size (MN i n) = 1
180 size NErased = 1
182instance Pretty Name where
183 pretty (UN n) = text n
184 pretty (NS n s) = pretty n
185 pretty (MN i s) = lbrace <+> text s <+> (text . show $ i) <+> rbrace
187instance Show Name where
188 show (UN n) = n
189 show (NS n s) = showSep "." (reverse s) ++ "." ++ show n
190 show (MN i s) = "{" ++ s ++ show i ++ "}"
191 show NErased = "_"
193-- Contexts allow us to map names to things. A root name maps to a collection
194-- of things in different namespaces with that name.
196type Ctxt a = Map.Map Name (Map.Map Name a)
197emptyContext = Map.empty
199tcname (UN ('@':_)) = True
200tcname (NS n _) = tcname n
201tcname _ = False
203implicitable (NS n _) = implicitable n
204implicitable (UN (x:xs)) = isLower x
205implicitable _ = False
207nsroot (NS n _) = n
208nsroot n = n
210addDef :: Name -> a -> Ctxt a -> Ctxt a
211addDef n v ctxt = case Map.lookup (nsroot n) ctxt of
212 Nothing -> Map.insert (nsroot n)
213 (Map.insert n v Map.empty) ctxt
214 Just xs -> Map.insert (nsroot n)
215 (Map.insert n v xs) ctxt
217{- lookup a name in the context, given an optional namespace.
218 The name (n) may itself have a (partial) namespace given.
220 Rules for resolution:
221 - if an explicit namespace is given, return the names which match it. If none
222 match, return all names.
223 - if the name has has explicit namespace given, return the names which match it
224 and ignore the given namespace.
225 - otherwise, return all names.
227-}
229lookupCtxtName :: Maybe [String] -> Name -> Ctxt a -> [(Name, a)]
230lookupCtxtName nspace n ctxt = case Map.lookup (nsroot n) ctxt of
231 Just xs -> filterNS (Map.toList xs)
232 Nothing -> []
233 where
234 filterNS [] = []
235 filterNS ((found, v) : xs)
236 | nsmatch n found = (found, v) : filterNS xs
237 | otherwise = filterNS xs
239 nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps
240 nsmatch (NS _ _) _ = False
241 nsmatch looking found = True
243lookupCtxt :: Maybe [String] -> Name -> Ctxt a -> [a]
244lookupCtxt ns n ctxt = map snd (lookupCtxtName ns n ctxt)
246updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a
247updateDef n f ctxt
248 = let ds = lookupCtxtName Nothing n ctxt in
249 foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds
251toAlist :: Ctxt a -> [(Name, a)]
252toAlist ctxt = let allns = map snd (Map.toList ctxt) in
253 concat (map (Map.toList) allns)
255addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
256addAlist [] ctxt = ctxt
257addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
259data Const = I Int | BI Integer | Fl Double | Ch Char | Str String
260 | IType | BIType | FlType | ChType | StrType
261 | PtrType | VoidType | Forgot
262 deriving (Eq, Ord)
263{-!
264deriving instance Binary Const
265!-}
267instance Sized Const where
268 size _ = 1
270instance Pretty Const where
271 pretty (I i) = text . show $ i
272 pretty (BI i) = text . show $ i
273 pretty (Fl f) = text . show $ f
274 pretty (Ch c) = text . show $ c
275 pretty (Str s) = text s
276 pretty IType = text "Int"
277 pretty BIType = text "BigInt"
278 pretty FlType = text "Float"
279 pretty ChType = text "Char"
280 pretty StrType = text "String"
281 pretty PtrType = text "Ptr"
282 pretty VoidType = text "Void"
283 pretty Forgot = text "Forgot"
285data Raw = Var Name
286 | RBind Name (Binder Raw) Raw
287 | RApp Raw Raw
288 | RSet
289 | RForce Raw
290 | RConstant Const
291 deriving (Show, Eq)
293instance Sized Raw where
294 size (Var name) = 1
295 size (RBind name bind right) = 1 + size bind + size right
296 size (RApp left right) = 1 + size left + size right
297 size RSet = 1
298 size (RForce raw) = 1 + size raw
299 size (RConstant const) = size const
301instance Pretty Raw where
302 pretty = text . show
304{-!
305deriving instance Binary Raw
306!-}
308data Binder b = Lam { binderTy :: b }
309 | Pi { binderTy :: b }
310 | Let { binderTy :: b,
311 binderVal :: b }
312 | NLet { binderTy :: b,
313 binderVal :: b }
314 | Hole { binderTy :: b}
315 | GHole { binderTy :: b}
316 | Guess { binderTy :: b,
317 binderVal :: b }
318 | PVar { binderTy :: b }
319 | PVTy { binderTy :: b }
320 deriving (Show, Eq, Ord, Functor)
321{-!
322deriving instance Binary Binder
323!-}
325instance Sized a => Sized (Binder a) where
326 size (Lam ty) = 1 + size ty
327 size (Pi ty) = 1 + size ty
328 size (Let ty val) = 1 + size ty + size val
329 size (NLet ty val) = 1 + size ty + size val
330 size (Hole ty) = 1 + size ty
331 size (GHole ty) = 1 + size ty
332 size (Guess ty val) = 1 + size ty + size val
333 size (PVar ty) = 1 + size ty
334 size (PVTy ty) = 1 + size ty
336fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
337fmapMB f (Let t v) = liftM2 Let (f t) (f v)
338fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
339fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
340fmapMB f (Lam t) = liftM Lam (f t)
341fmapMB f (Pi t) = liftM Pi (f t)
342fmapMB f (Hole t) = liftM Hole (f t)
343fmapMB f (GHole t) = liftM GHole (f t)
344fmapMB f (PVar t) = liftM PVar (f t)
345fmapMB f (PVTy t) = liftM PVTy (f t)
347raw_apply :: Raw -> [Raw] -> Raw
348raw_apply f [] = f
349raw_apply f (a : as) = raw_apply (RApp f a) as
351raw_unapply :: Raw -> (Raw, [Raw])
352raw_unapply t = ua [] t where
353 ua args (RApp f a) = ua (a:args) f
354 ua args t = (t, args)
356data RawFun = RawFun { rtype :: Raw,
357 rval :: Raw
358 }
359 deriving Show
361data RawDatatype = RDatatype Name Raw [(Name, Raw)]
362 deriving Show
364data RDef = RFunction RawFun
365 | RConst Raw
366 | RData RawDatatype
367 deriving Show
369type RProgram = [(Name, RDef)]
371-- WELL TYPED TERMS ---------------------------------------------------------
373data UExp = UVar Int -- universe variable
374 | UVal Int -- explicit universe level
375 deriving (Eq, Ord)
377instance Sized UExp where
378 size _ = 1
380-- We assume that universe levels have been checked, so anything external
381-- can just have the same universe variable and we won't get any new
382-- cycles.
384instance Binary UExp where
385 put x = return ()
386 get = return (UVar (-1))
388instance Show UExp where
389 show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
390 | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
391 show (UVal x) = show x
392-- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")"
394data UConstraint = ULT UExp UExp
395 | ULE UExp UExp
396 deriving Eq
398instance Show UConstraint where
399 show (ULT x y) = show x ++ " < " ++ show y
400 show (ULE x y) = show x ++ " <= " ++ show y
402type UCs = (Int, [UConstraint])
404data NameType = Bound | Ref | DCon Int Int | TCon Int Int
405 deriving (Show, Ord)
406{-!
407deriving instance Binary NameType
408!-}
410instance Sized NameType where
411 size _ = 1
413instance Pretty NameType where
414 pretty = text . show
416instance Eq NameType where
417 Bound == Bound = True
418 Ref == Ref = True
419 DCon _ a == DCon _ b = (a == b) -- ignore tag
420 TCon _ a == TCon _ b = (a == b) -- ignore tag
421 _ == _ = False
423data TT n = P NameType n (TT n) -- embed type
424 | V Int
425 | Bind n (Binder (TT n)) (TT n)
426 | App (TT n) (TT n) -- function, function type, arg
427 | Constant Const
428 | Proj (TT n) Int -- argument projection; runtime only
429 | Erased
430 | Impossible -- special case for totality checking
431 | Set UExp
432 deriving (Ord, Functor)
433{-!
434deriving instance Binary TT
435!-}
437class TermSize a where
438 termsize :: Name -> a -> Int
440instance TermSize a => TermSize [a] where
441 termsize n [] = 0
442 termsize n (x : xs) = termsize n x + termsize n xs
444instance TermSize (TT Name) where
445 termsize n (P _ x _)
446 | x == n = 1000000 -- recursive => really big
447 | otherwise = 1
448 termsize n (V _) = 1
449 termsize n (Bind n' (Let t v) sc)
450 = let rn = if n == n' then MN 0 "noname" else n in
451 termsize rn v + termsize rn sc
452 termsize n (App f a) = termsize n f + termsize n a
453 termsize n _ = 1
455instance Sized a => Sized (TT a) where
456 size (P name n trm) = 1 + size name + size n + size trm
457 size (V v) = 1
458 size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy
459 size (App l r) = 1 + size l + size r
460 size (Constant c) = size c
461 size Erased = 1
462 size (Set u) = 1 + size u
464instance Pretty a => Pretty (TT a) where
465 pretty _ = text "test"
467type EnvTT n = [(n, Binder (TT n))]
469data Datatype n = Data { d_typename :: n,
470 d_typetag :: Int,
471 d_type :: (TT n),
472 d_cons :: [(n, TT n)] }
473 deriving (Show, Functor, Eq)
475instance Eq n => Eq (TT n) where
476 (==) (P xt x _) (P yt y _) = xt == yt && x == y
477 (==) (V x) (V y) = x == y
478 (==) (Bind _ xb xs) (Bind _ yb ys) = xb == yb && xs == ys
479 (==) (App fx ax) (App fy ay) = fx == fy && ax == ay
480 (==) (Set _) (Set _) = True -- deal with constraints later
481 (==) (Constant x) (Constant y) = x == y
482 (==) (Proj x i) (Proj y j) = x == y && i == j
483 (==) Erased _ = True
484 (==) _ Erased = True
485 (==) _ _ = False
487-- A few handy operations on well typed terms:
489isInjective :: TT n -> Bool
490isInjective (P (DCon _ _) _ _) = True
491isInjective (P (TCon _ _) _ _) = True
492isInjective (Constant _) = True
493isInjective (Set x) = True
494isInjective (Bind _ (Pi _) sc) = True
495isInjective (App f a) = isInjective f
496isInjective _ = False
498-- Count the number of instances of a de Bruijn index in a term
499vinstances :: Int -> TT n -> Int
500vinstances i (V x) | i == x = 1
501vinstances i (App f a) = vinstances i f + vinstances i a
502vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc
503 where instancesB (Let t v) = vinstances i v
504 instancesB _ = 0
505vinstances i t = 0
507instantiate :: TT n -> TT n -> TT n
508instantiate e = subst 0 where
509 subst i (V x) | i == x = e
510 subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
511 subst i (App f a) = App (subst i f) (subst i a)
512 subst i (Proj x idx) = Proj (subst i x) idx
513 subst i t = t
515pToV :: Eq n => n -> TT n -> TT n
516pToV n = pToV' n 0
517pToV' n i (P _ x _) | n == x = V i
518pToV' n i (Bind x b sc)
519-- We can assume the inner scope has been pToVed already, so continue to
520-- resolve names from the *outer* scope which may happen to have the same id.
521-- | n == x = Bind x (fmap (pToV' n i) b) sc
522 | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
523pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
524pToV' n i (Proj t idx) = Proj (pToV' n i t) idx
525pToV' n i t = t
527-- Convert several names. First in the list comes out as V 0
528pToVs :: Eq n => [n] -> TT n -> TT n
529pToVs ns tm = pToVs' ns tm 0 where
530 pToVs' [] tm i = tm
531 pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
533vToP :: TT n -> TT n
534vToP = vToP' [] where
535 vToP' env (V i) = let (n, b) = (env !! i) in
536 P Bound n (binderTy b)
537 vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
538 Bind n b' (vToP' ((n, b'):env) sc)
539 vToP' env (App f a) = App (vToP' env f) (vToP' env a)
540 vToP' env t = t
542finalise :: Eq n => TT n -> TT n
543finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
544finalise (App f a) = App (finalise f) (finalise a)
545finalise t = t
547subst :: Eq n => n -> TT n -> TT n -> TT n
548subst n v tm = instantiate v (pToV n tm)
550substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
551substNames [] t = t
552substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
554-- Returns true if V 0 and bound name n do not occur in the term
556noOccurrence :: Eq n => n -> TT n -> Bool
557noOccurrence n t = no' 0 t
558 where
559 no' i (V x) = not (i == x)
560 no' i (P Bound x _) = not (n == x)
561 no' i (Bind n b sc) = noB' i b && no' (i+1) sc
562 where noB' i (Let t v) = no' i t && no' i v
563 noB' i (Guess t v) = no' i t && no' i v
564 noB' i b = no' i (binderTy b)
565 no' i (App f a) = no' i f && no' i a
566 no' i (Proj x _) = no' i x
567 no' i _ = True
569-- Returns all names used free in the term
571freeNames :: Eq n => TT n -> [n]
572freeNames (P _ n _) = [n]
573freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n])
574 ++ freeNames t
575freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
576freeNames (App f a) = nub $ freeNames f ++ freeNames a
577freeNames (Proj x i) = nub $ freeNames x
578freeNames _ = []
580-- Return the arity of a (normalised) type
582arity :: TT n -> Int
583arity (Bind n (Pi t) sc) = 1 + arity sc
584arity _ = 0
586-- deconstruct an application; returns the function and a list of arguments
588unApply :: TT n -> (TT n, [TT n])
589unApply t = ua [] t where
590 ua args (App f a) = ua (a:args) f
591 ua args t = (t, args)
593mkApp :: TT n -> [TT n] -> TT n
594mkApp f [] = f
595mkApp f (a:as) = mkApp (App f a) as
597forget :: TT Name -> Raw
598forget tm = fe [] tm
599 where
600 fe env (P _ n _) = Var n
601 fe env (V i) = Var (env !! i)
602 fe env (Bind n b sc) = RBind n (fmap (fe env) b)
603 (fe (n:env) sc)
604 fe env (App f a) = RApp (fe env f) (fe env a)
605 fe env (Constant c)
606 = RConstant c
607 fe env (Set i) = RSet
608 fe env Erased = RConstant Forgot
610bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
611bindAll [] t =t
612bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
614bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
615bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
617getArgTys :: TT n -> [(n, TT n)]
618getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
619getArgTys _ = []
621getRetTy :: TT n -> TT n
622getRetTy (Bind n (PVar _) sc) = getRetTy sc
623getRetTy (Bind n (PVTy _) sc) = getRetTy sc
624getRetTy (Bind n (Pi _) sc) = getRetTy sc
625getRetTy sc = sc
627uniqueName :: Name -> [Name] -> Name
628uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
629 | otherwise = n
631uniqueBinders :: [Name] -> TT Name -> TT Name
632uniqueBinders ns (Bind n b sc)
633 = let n' = uniqueName n ns in
634 Bind n' (fmap (uniqueBinders (n':ns)) b) (uniqueBinders ns sc)
635uniqueBinders ns (App f a) = App (uniqueBinders ns f) (uniqueBinders ns a)
636uniqueBinders ns t = t
639nextName (NS x s) = NS (nextName x) s
640nextName (MN i n) = MN (i+1) n
641nextName (UN x) = let (num', nm') = span isDigit (reverse x)
642 nm = reverse nm'
643 num = readN (reverse num') in
644 UN (nm ++ show (num+1))
645 where
646 readN "" = 0
647 readN x = read x
649type Term = TT Name
650type Type = Term
652type Env = EnvTT Name
654-- an environment with de Bruijn indices 'normalised' so that they all refer to
655-- this environment
657newtype WkEnvTT n = Wk (EnvTT n)
658type WkEnv = WkEnvTT Name
660instance (Eq n, Show n) => Show (TT n) where
661 show t = showEnv [] t
663instance Show Const where
664 show (I i) = show i
665 show (BI i) = show i ++ "L"
666 show (Fl f) = show f
667 show (Ch c) = show c
668 show (Str s) = show s
669 show IType = "Int"
670 show BIType = "Integer"
671 show FlType = "Float"
672 show ChType = "Char"
673 show StrType = "String"
674 show PtrType = "Ptr"
675 show VoidType = "Void"
677showEnv env t = showEnv' env t False
678showEnvDbg env t = showEnv' env t True
680prettyEnv env t = prettyEnv' env t False
681 where
682 prettyEnv' env t dbg = prettySe 10 env t dbg
684 bracket outer inner p
685 | inner > outer = lparen <> p <> rparen
686 | otherwise = p
688 prettySe p env (P nt n t) debug =
689 pretty n <+>
690 if debug then
691 lbrack <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbrack
692 else
693 empty
694 prettySe p env (V i) debug
695 | i < length env =
696 if debug then
697 text . show . fst $ env!!i
698 else
699 lbrack <+> text (show i) <+> rbrack
700 | otherwise = text "unbound" <+> text (show i) <+> text "!"
701 prettySe p env (Bind n b@(Pi t) sc) debug
702 | noOccurrence n sc && not debug =
703 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
704 prettySe p env (Bind n b sc) debug =
705 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
706 prettySe p env (App f a) debug =
707 bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug
708 prettySe p env (Proj x i) debug =
709 prettySe 1 env x debug <+> text ("!" ++ show i)
710 prettySe p env (Constant c) debug = pretty c
711 prettySe p env Erased debug = text "[_]"
712 prettySe p env (Set i) debug = text "Set" <+> (text . show $ i)
714 prettySb env n (Lam t) = prettyB env "λ" "=>" n t
715 prettySb env n (Hole t) = prettyB env "?defer" "." n t
716 prettySb env n (Pi t) = prettyB env "(" ") ->" n t
717 prettySb env n (PVar t) = prettyB env "pat" "." n t
718 prettySb env n (PVTy t) = prettyB env "pty" "." n t
719 prettySb env n (Let t v) = prettyBv env "let" "in" n t v
720 prettySb env n (Guess t v) = prettyBv env "??" "in" n t v
722 prettyB env op sc n t debug =
723 text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc
725 prettyBv env op sc n t v debug =
726 text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+>
727 prettySe 10 env v debug <> text sc
730showEnv' env t dbg = se 10 env t where
731 se p env (P nt n t) = show n
732 ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
733 se p env (V i) | i < length env = (show $ fst $ env!!i) ++
734 if dbg then "{" ++ show i ++ "}" else ""
735 | otherwise = "!!V " ++ show i ++ "!!"
736 se p env (Bind n b@(Pi t) sc)
737 | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
738 se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
739 se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
740 se p env (Proj x i) = se 1 env x ++ "!" ++ show i
741 se p env (Constant c) = show c
742 se p env Erased = "[__]"
743 se p env Impossible = "[impossible]"
744 se p env (Set i) = "Set " ++ show i
746 sb env n (Lam t) = showb env "\\ " " => " n t
747 sb env n (Hole t) = showb env "? " ". " n t
748 sb env n (GHole t) = showb env "?defer " ". " n t
749 sb env n (Pi t) = showb env "(" ") -> " n t
750 sb env n (PVar t) = showb env "pat " ". " n t
751 sb env n (PVTy t) = showb env "pty " ". " n t
752 sb env n (Let t v) = showbv env "let " " in " n t v
753 sb env n (Guess t v) = showbv env "?? " " in " n t v
755 showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
756 showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
757 se 10 env v ++ sc
759 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
760 | otherwise = str
762-- Check whether a term has any holes in it - impure if so
764pureTerm :: TT n -> Bool
765pureTerm (App f a) = pureTerm f && pureTerm a
766pureTerm (Bind n b sc) = pureBinder b && pureTerm sc where
767 pureBinder (Hole _) = False
768 pureBinder (Guess _ _) = False
769 pureBinder (Let t v) = pureTerm t && pureTerm v
770 pureBinder t = pureTerm (binderTy t)
771pureTerm _ = True
773-- weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings)
775weakenTm :: Int -> TT n -> TT n
776weakenTm i t = wk i 0 t
777 where wk i min (V x) | x >= min = V (i + x)
778 wk i m (App f a) = App (wk i m f) (wk i m a)
779 wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
780 wk i m t = t
781 wkb i m t = fmap (wk i m) t
783-- weaken an environment so that all the de Bruijn indices are correct according
784-- to the latest bound variable
786weakenEnv :: EnvTT n -> EnvTT n
787weakenEnv env = wk (length env - 1) env
788 where wk i [] = []
789 wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
790 weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
791 weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
792 weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
794weakenTmEnv :: Int -> EnvTT n -> EnvTT n
795weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
797orderPats :: Term -> Term
798orderPats tm = op [] tm
799 where
800 op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc
801 op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc
802 op ps sc = bindAll (map (\ (n, t) -> (n, t)) (sortP ps)) sc
804 sortP ps = pick [] (reverse ps)
806 namesIn (P _ n _) = [n]
807 namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
808 where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
809 nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
810 nb t = namesIn (binderTy t)
811 namesIn (App f a) = nub (namesIn f ++ namesIn a)
812 namesIn _ = []
814 pick acc [] = reverse acc
815 pick acc ((n, t) : ps) = pick (insert n t acc) ps
817 insert n t [] = [(n, t)]
818 insert n t ((n',t') : ps)
819 | n `elem` (namesIn (binderTy t') ++
820 concatMap namesIn (map (binderTy . snd) ps))
821 = (n', t') : insert n t ps
822 | otherwise = (n,t):(n',t'):ps