on bc3e807 help sign in
833 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: Type : Type1, Type1 : Type2, ...
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 = TTypeInTType
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. Type:Type)
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
262 | W8 Word8 | W16 Word16
263 | W8Type | W16Type
265 | PtrType | VoidType | Forgot
266 deriving (Eq, Ord)
267{-!
268deriving instance Binary Const
269!-}
271instance Sized Const where
272 size _ = 1
274instance Pretty Const where
275 pretty (I i) = text . show $ i
276 pretty (BI i) = text . show $ i
277 pretty (Fl f) = text . show $ f
278 pretty (Ch c) = text . show $ c
279 pretty (Str s) = text s
280 pretty IType = text "Int"
281 pretty BIType = text "BigInt"
282 pretty FlType = text "Float"
283 pretty ChType = text "Char"
284 pretty StrType = text "String"
285 pretty PtrType = text "Ptr"
286 pretty VoidType = text "Void"
287 pretty Forgot = text "Forgot"
288 pretty W8Type = text "Word8"
289 pretty W16Type = text "Word16"
291data Raw = Var Name
292 | RBind Name (Binder Raw) Raw
293 | RApp Raw Raw
294 | RType
295 | RForce Raw
296 | RConstant Const
297 deriving (Show, Eq)
299instance Sized Raw where
300 size (Var name) = 1
301 size (RBind name bind right) = 1 + size bind + size right
302 size (RApp left right) = 1 + size left + size right
303 size RType = 1
304 size (RForce raw) = 1 + size raw
305 size (RConstant const) = size const
307instance Pretty Raw where
308 pretty = text . show
310{-!
311deriving instance Binary Raw
312!-}
314data Binder b = Lam { binderTy :: b }
315 | Pi { binderTy :: b }
316 | Let { binderTy :: b,
317 binderVal :: b }
318 | NLet { binderTy :: b,
319 binderVal :: b }
320 | Hole { binderTy :: b}
321 | GHole { binderTy :: b}
322 | Guess { binderTy :: b,
323 binderVal :: b }
324 | PVar { binderTy :: b }
325 | PVTy { binderTy :: b }
326 deriving (Show, Eq, Ord, Functor)
327{-!
328deriving instance Binary Binder
329!-}
331instance Sized a => Sized (Binder a) where
332 size (Lam ty) = 1 + size ty
333 size (Pi ty) = 1 + size ty
334 size (Let ty val) = 1 + size ty + size val
335 size (NLet ty val) = 1 + size ty + size val
336 size (Hole ty) = 1 + size ty
337 size (GHole ty) = 1 + size ty
338 size (Guess ty val) = 1 + size ty + size val
339 size (PVar ty) = 1 + size ty
340 size (PVTy ty) = 1 + size ty
342fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
343fmapMB f (Let t v) = liftM2 Let (f t) (f v)
344fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
345fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
346fmapMB f (Lam t) = liftM Lam (f t)
347fmapMB f (Pi t) = liftM Pi (f t)
348fmapMB f (Hole t) = liftM Hole (f t)
349fmapMB f (GHole t) = liftM GHole (f t)
350fmapMB f (PVar t) = liftM PVar (f t)
351fmapMB f (PVTy t) = liftM PVTy (f t)
353raw_apply :: Raw -> [Raw] -> Raw
354raw_apply f [] = f
355raw_apply f (a : as) = raw_apply (RApp f a) as
357raw_unapply :: Raw -> (Raw, [Raw])
358raw_unapply t = ua [] t where
359 ua args (RApp f a) = ua (a:args) f
360 ua args t = (t, args)
362data RawFun = RawFun { rtype :: Raw,
363 rval :: Raw
364 }
365 deriving Show
367data RawDatatype = RDatatype Name Raw [(Name, Raw)]
368 deriving Show
370data RDef = RFunction RawFun
371 | RConst Raw
372 | RData RawDatatype
373 deriving Show
375type RProgram = [(Name, RDef)]
377-- WELL TYPED TERMS ---------------------------------------------------------
379data UExp = UVar Int -- universe variable
380 | UVal Int -- explicit universe level
381 deriving (Eq, Ord)
383instance Sized UExp where
384 size _ = 1
386-- We assume that universe levels have been checked, so anything external
387-- can just have the same universe variable and we won't get any new
388-- cycles.
390instance Binary UExp where
391 put x = return ()
392 get = return (UVar (-1))
394instance Show UExp where
395 show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
396 | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
397 show (UVal x) = show x
398-- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")"
400data UConstraint = ULT UExp UExp
401 | ULE UExp UExp
402 deriving Eq
404instance Show UConstraint where
405 show (ULT x y) = show x ++ " < " ++ show y
406 show (ULE x y) = show x ++ " <= " ++ show y
408type UCs = (Int, [UConstraint])
410data NameType = Bound | Ref | DCon Int Int | TCon Int Int
411 deriving (Show, Ord)
412{-!
413deriving instance Binary NameType
414!-}
416instance Sized NameType where
417 size _ = 1
419instance Pretty NameType where
420 pretty = text . show
422instance Eq NameType where
423 Bound == Bound = True
424 Ref == Ref = True
425 DCon _ a == DCon _ b = (a == b) -- ignore tag
426 TCon _ a == TCon _ b = (a == b) -- ignore tag
427 _ == _ = False
429data TT n = P NameType n (TT n) -- embed type
430 | V Int
431 | Bind n (Binder (TT n)) (TT n)
432 | App (TT n) (TT n) -- function, function type, arg
433 | Constant Const
434 | Proj (TT n) Int -- argument projection; runtime only
435 | Erased
436 | Impossible -- special case for totality checking
437 | TType UExp
438 deriving (Ord, Functor)
439{-!
440deriving instance Binary TT
441!-}
443class TermSize a where
444 termsize :: Name -> a -> Int
446instance TermSize a => TermSize [a] where
447 termsize n [] = 0
448 termsize n (x : xs) = termsize n x + termsize n xs
450instance TermSize (TT Name) where
451 termsize n (P _ x _)
452 | x == n = 1000000 -- recursive => really big
453 | otherwise = 1
454 termsize n (V _) = 1
455 termsize n (Bind n' (Let t v) sc)
456 = let rn = if n == n' then MN 0 "noname" else n in
457 termsize rn v + termsize rn sc
458 termsize n (App f a) = termsize n f + termsize n a
459 termsize n _ = 1
461instance Sized a => Sized (TT a) where
462 size (P name n trm) = 1 + size name + size n + size trm
463 size (V v) = 1
464 size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy
465 size (App l r) = 1 + size l + size r
466 size (Constant c) = size c
467 size Erased = 1
468 size (TType u) = 1 + size u
470instance Pretty a => Pretty (TT a) where
471 pretty _ = text "test"
473type EnvTT n = [(n, Binder (TT n))]
475data Datatype n = Data { d_typename :: n,
476 d_typetag :: Int,
477 d_type :: (TT n),
478 d_cons :: [(n, TT n)] }
479 deriving (Show, Functor, Eq)
481instance Eq n => Eq (TT n) where
482 (==) (P xt x _) (P yt y _) = xt == yt && x == y
483 (==) (V x) (V y) = x == y
484 (==) (Bind _ xb xs) (Bind _ yb ys) = xb == yb && xs == ys
485 (==) (App fx ax) (App fy ay) = fx == fy && ax == ay
486 (==) (TType _) (TType _) = True -- deal with constraints later
487 (==) (Constant x) (Constant y) = x == y
488 (==) (Proj x i) (Proj y j) = x == y && i == j
489 (==) Erased _ = True
490 (==) _ Erased = True
491 (==) _ _ = False
493-- A few handy operations on well typed terms:
495isInjective :: TT n -> Bool
496isInjective (P (DCon _ _) _ _) = True
497isInjective (P (TCon _ _) _ _) = True
498isInjective (Constant _) = True
499isInjective (TType x) = True
500isInjective (Bind _ (Pi _) sc) = True
501isInjective (App f a) = isInjective f
502isInjective _ = False
504-- Count the number of instances of a de Bruijn index in a term
505vinstances :: Int -> TT n -> Int
506vinstances i (V x) | i == x = 1
507vinstances i (App f a) = vinstances i f + vinstances i a
508vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc
509 where instancesB (Let t v) = vinstances i v
510 instancesB _ = 0
511vinstances i t = 0
513instantiate :: TT n -> TT n -> TT n
514instantiate e = subst 0 where
515 subst i (V x) | i == x = e
516 subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
517 subst i (App f a) = App (subst i f) (subst i a)
518 subst i (Proj x idx) = Proj (subst i x) idx
519 subst i t = t
521pToV :: Eq n => n -> TT n -> TT n
522pToV n = pToV' n 0
523pToV' n i (P _ x _) | n == x = V i
524pToV' n i (Bind x b sc)
525-- We can assume the inner scope has been pToVed already, so continue to
526-- resolve names from the *outer* scope which may happen to have the same id.
527-- | n == x = Bind x (fmap (pToV' n i) b) sc
528 | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
529pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
530pToV' n i (Proj t idx) = Proj (pToV' n i t) idx
531pToV' n i t = t
533-- Convert several names. First in the list comes out as V 0
534pToVs :: Eq n => [n] -> TT n -> TT n
535pToVs ns tm = pToVs' ns tm 0 where
536 pToVs' [] tm i = tm
537 pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
539vToP :: TT n -> TT n
540vToP = vToP' [] where
541 vToP' env (V i) = let (n, b) = (env !! i) in
542 P Bound n (binderTy b)
543 vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
544 Bind n b' (vToP' ((n, b'):env) sc)
545 vToP' env (App f a) = App (vToP' env f) (vToP' env a)
546 vToP' env t = t
548finalise :: Eq n => TT n -> TT n
549finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
550finalise (App f a) = App (finalise f) (finalise a)
551finalise t = t
553subst :: Eq n => n -> TT n -> TT n -> TT n
554subst n v tm = instantiate v (pToV n tm)
556substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
557substNames [] t = t
558substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
560-- Returns true if V 0 and bound name n do not occur in the term
562noOccurrence :: Eq n => n -> TT n -> Bool
563noOccurrence n t = no' 0 t
564 where
565 no' i (V x) = not (i == x)
566 no' i (P Bound x _) = not (n == x)
567 no' i (Bind n b sc) = noB' i b && no' (i+1) sc
568 where noB' i (Let t v) = no' i t && no' i v
569 noB' i (Guess t v) = no' i t && no' i v
570 noB' i b = no' i (binderTy b)
571 no' i (App f a) = no' i f && no' i a
572 no' i (Proj x _) = no' i x
573 no' i _ = True
575-- Returns all names used free in the term
577freeNames :: Eq n => TT n -> [n]
578freeNames (P _ n _) = [n]
579freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n])
580 ++ freeNames t
581freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
582freeNames (App f a) = nub $ freeNames f ++ freeNames a
583freeNames (Proj x i) = nub $ freeNames x
584freeNames _ = []
586-- Return the arity of a (normalised) type
588arity :: TT n -> Int
589arity (Bind n (Pi t) sc) = 1 + arity sc
590arity _ = 0
592-- deconstruct an application; returns the function and a list of arguments
594unApply :: TT n -> (TT n, [TT n])
595unApply t = ua [] t where
596 ua args (App f a) = ua (a:args) f
597 ua args t = (t, args)
599mkApp :: TT n -> [TT n] -> TT n
600mkApp f [] = f
601mkApp f (a:as) = mkApp (App f a) as
603forget :: TT Name -> Raw
604forget tm = fe [] tm
605 where
606 fe env (P _ n _) = Var n
607 fe env (V i) = Var (env !! i)
608 fe env (Bind n b sc) = RBind n (fmap (fe env) b)
609 (fe (n:env) sc)
610 fe env (App f a) = RApp (fe env f) (fe env a)
611 fe env (Constant c)
612 = RConstant c
613 fe env (TType i) = RType
614 fe env Erased = RConstant Forgot
616bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
617bindAll [] t =t
618bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
620bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
621bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
623getArgTys :: TT n -> [(n, TT n)]
624getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
625getArgTys _ = []
627getRetTy :: TT n -> TT n
628getRetTy (Bind n (PVar _) sc) = getRetTy sc
629getRetTy (Bind n (PVTy _) sc) = getRetTy sc
630getRetTy (Bind n (Pi _) sc) = getRetTy sc
631getRetTy sc = sc
633uniqueName :: Name -> [Name] -> Name
634uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
635 | otherwise = n
637uniqueBinders :: [Name] -> TT Name -> TT Name
638uniqueBinders ns (Bind n b sc)
639 = let n' = uniqueName n ns in
640 Bind n' (fmap (uniqueBinders (n':ns)) b) (uniqueBinders ns sc)
641uniqueBinders ns (App f a) = App (uniqueBinders ns f) (uniqueBinders ns a)
642uniqueBinders ns t = t
645nextName (NS x s) = NS (nextName x) s
646nextName (MN i n) = MN (i+1) n
647nextName (UN x) = let (num', nm') = span isDigit (reverse x)
648 nm = reverse nm'
649 num = readN (reverse num') in
650 UN (nm ++ show (num+1))
651 where
652 readN "" = 0
653 readN x = read x
655type Term = TT Name
656type Type = Term
658type Env = EnvTT Name
660-- an environment with de Bruijn indices 'normalised' so that they all refer to
661-- this environment
663newtype WkEnvTT n = Wk (EnvTT n)
664type WkEnv = WkEnvTT Name
666instance (Eq n, Show n) => Show (TT n) where
667 show t = showEnv [] t
669instance Show Const where
670 show (I i) = show i
671 show (BI i) = show i ++ "L"
672 show (Fl f) = show f
673 show (Ch c) = show c
674 show (Str s) = show s
675 show (W8 x) = show x
676 show (W16 x) = show x
677 show IType = "Int"
678 show BIType = "Integer"
679 show FlType = "Float"
680 show ChType = "Char"
681 show StrType = "String"
682 show PtrType = "Ptr"
683 show W8Type = "Word8"
684 show W16Type = "Word16"
685 show VoidType = "Void"
687showEnv env t = showEnv' env t False
688showEnvDbg env t = showEnv' env t True
690prettyEnv env t = prettyEnv' env t False
691 where
692 prettyEnv' env t dbg = prettySe 10 env t dbg
694 bracket outer inner p
695 | inner > outer = lparen <> p <> rparen
696 | otherwise = p
698 prettySe p env (P nt n t) debug =
699 pretty n <+>
700 if debug then
701 lbrack <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbrack
702 else
703 empty
704 prettySe p env (V i) debug
705 | i < length env =
706 if debug then
707 text . show . fst $ env!!i
708 else
709 lbrack <+> text (show i) <+> rbrack
710 | otherwise = text "unbound" <+> text (show i) <+> text "!"
711 prettySe p env (Bind n b@(Pi t) sc) debug
712 | noOccurrence n sc && not debug =
713 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
714 prettySe p env (Bind n b sc) debug =
715 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
716 prettySe p env (App f a) debug =
717 bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug
718 prettySe p env (Proj x i) debug =
719 prettySe 1 env x debug <+> text ("!" ++ show i)
720 prettySe p env (Constant c) debug = pretty c
721 prettySe p env Erased debug = text "[_]"
722 prettySe p env (TType i) debug = text "Type" <+> (text . show $ i)
724 prettySb env n (Lam t) = prettyB env "λ" "=>" n t
725 prettySb env n (Hole t) = prettyB env "?defer" "." n t
726 prettySb env n (Pi t) = prettyB env "(" ") ->" n t
727 prettySb env n (PVar t) = prettyB env "pat" "." n t
728 prettySb env n (PVTy t) = prettyB env "pty" "." n t
729 prettySb env n (Let t v) = prettyBv env "let" "in" n t v
730 prettySb env n (Guess t v) = prettyBv env "??" "in" n t v
732 prettyB env op sc n t debug =
733 text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc
735 prettyBv env op sc n t v debug =
736 text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+>
737 prettySe 10 env v debug <> text sc
740showEnv' env t dbg = se 10 env t where
741 se p env (P nt n t) = show n
742 ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
743 se p env (V i) | i < length env = (show $ fst $ env!!i) ++
744 if dbg then "{" ++ show i ++ "}" else ""
745 | otherwise = "!!V " ++ show i ++ "!!"
746 se p env (Bind n b@(Pi t) sc)
747 | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
748 se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
749 se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
750 se p env (Proj x i) = se 1 env x ++ "!" ++ show i
751 se p env (Constant c) = show c
752 se p env Erased = "[__]"
753 se p env Impossible = "[impossible]"
754 se p env (TType i) = "Type " ++ show i
756 sb env n (Lam t) = showb env "\\ " " => " n t
757 sb env n (Hole t) = showb env "? " ". " n t
758 sb env n (GHole t) = showb env "?defer " ". " n t
759 sb env n (Pi t) = showb env "(" ") -> " n t
760 sb env n (PVar t) = showb env "pat " ". " n t
761 sb env n (PVTy t) = showb env "pty " ". " n t
762 sb env n (Let t v) = showbv env "let " " in " n t v
763 sb env n (Guess t v) = showbv env "?? " " in " n t v
765 showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
766 showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
767 se 10 env v ++ sc
769 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
770 | otherwise = str
772-- Check whether a term has any holes in it - impure if so
774pureTerm :: TT n -> Bool
775pureTerm (App f a) = pureTerm f && pureTerm a
776pureTerm (Bind n b sc) = pureBinder b && pureTerm sc where
777 pureBinder (Hole _) = False
778 pureBinder (Guess _ _) = False
779 pureBinder (Let t v) = pureTerm t && pureTerm v
780 pureBinder t = pureTerm (binderTy t)
781pureTerm _ = True
783-- weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings)
785weakenTm :: Int -> TT n -> TT n
786weakenTm i t = wk i 0 t
787 where wk i min (V x) | x >= min = V (i + x)
788 wk i m (App f a) = App (wk i m f) (wk i m a)
789 wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
790 wk i m t = t
791 wkb i m t = fmap (wk i m) t
793-- weaken an environment so that all the de Bruijn indices are correct according
794-- to the latest bound variable
796weakenEnv :: EnvTT n -> EnvTT n
797weakenEnv env = wk (length env - 1) env
798 where wk i [] = []
799 wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
800 weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
801 weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
802 weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
804weakenTmEnv :: Int -> EnvTT n -> EnvTT n
805weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
807orderPats :: Term -> Term
808orderPats tm = op [] tm
809 where
810 op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc
811 op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc
812 op ps sc = bindAll (map (\ (n, t) -> (n, t)) (sortP ps)) sc
814 sortP ps = pick [] (reverse ps)
816 namesIn (P _ n _) = [n]
817 namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
818 where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
819 nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
820 nb t = namesIn (binderTy t)
821 namesIn (App f a) = nub (namesIn f ++ namesIn a)
822 namesIn _ = []
824 pick acc [] = reverse acc
825 pick acc ((n, t) : ps) = pick (insert n t acc) ps
827 insert n t [] = [(n, t)]
828 insert n t ((n',t') : ps)
829 | n `elem` (namesIn (binderTy t') ++
830 concatMap namesIn (map (binderTy . snd) ps))
831 = (n', t') : insert n t ps
832 | otherwise = (n,t):(n',t'):ps