on d254ce1 help sign in
599 lines 19 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 Show FC where
40 show (FC f l) = f ++ ":" ++ show l
42data Err = Msg String
43 | CantUnify Term Term Err Int -- Int is 'score' - how much we did unify
44 | NoSuchVariable Name
45 | NotInjective Term Term Term
46 | CantResolve Term
47 | IncompleteTerm Term
48 | UniverseError
49 | ProgramLineComment
50 | At FC Err
51 deriving Eq
53score :: Err -> Int
54score (CantUnify _ _ m s) = s + score m
55score (CantResolve _) = 20
56score (NoSuchVariable _) = 1000
57score _ = 0
59instance Show Err where
60 show (Msg s) = s
61 show (CantUnify l r e i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
62 ++ show e ++ " " ++ show i
63 show _ = "Error"
65data TC a = OK a
66 | Error Err
67 deriving (Eq, Functor)
69instance Show a => Show (TC a) where
70 show (OK x) = show x
71 show (Error str) = "Error: " ++ show str
73-- at some point, this instance should also carry type checking options
74-- (e.g. Set:Set)
76instance Monad TC where
77 return = OK
78 x >>= k = case x of
79 OK v -> k v
80 Error e -> Error e
81 fail e = Error (Msg e)
83tfail :: Err -> TC a
84tfail e = Error e
86trun :: FC -> TC a -> TC a
87trun fc (OK a) = OK a
88trun fc (Error e) = Error (At fc e)
90instance MonadPlus TC where
91 mzero = fail "Unknown error"
92 (OK x) `mplus` _ = OK x
93 _ `mplus` (OK y) = OK y
94 err `mplus` _ = err
96discard :: Monad m => m a -> m ()
97discard f = f >> return ()
99showSep :: String -> [String] -> String
100showSep sep [] = ""
101showSep sep [x] = x
102showSep sep (x:xs) = x ++ sep ++ showSep sep xs
104pmap f (x, y) = (f x, f y)
106traceWhen True msg a = trace msg a
107traceWhen False _ a = a
109-- RAW TERMS ----------------------------------------------------------------
111-- Names are hierarchies of strings, describing scope (so no danger of
112-- duplicate names, but need to be careful on lookup).
113-- Also MN for machine chosen names
115data Name = UN String
116 | NS Name [String] -- root, namespaces
117 | MN Int String
118 deriving (Eq, Ord)
119{-!
120deriving instance Binary Name
121!-}
123instance Show Name where
124 show (UN n) = n
125 show (NS n s) = showSep "." (reverse s) ++ "." ++ show n
126 show (MN i s) = "{" ++ s ++ show i ++ "}"
129-- Contexts allow us to map names to things. A root name maps to a collection
130-- of things in different namespaces with that name.
132type Ctxt a = Map.Map Name (Map.Map Name a)
133emptyContext = Map.empty
135nsroot (NS n _) = n
136nsroot n = n
138addDef :: Name -> a -> Ctxt a -> Ctxt a
139addDef n v ctxt = case Map.lookup (nsroot n) ctxt of
140 Nothing -> Map.insert (nsroot n)
141 (Map.insert n v Map.empty) ctxt
142 Just xs -> Map.insert (nsroot n)
143 (Map.insert n v xs) ctxt
145{- lookup a name in the context, given an optional namespace.
146 The name (n) may itself have a (partial) namespace given.
148 Rules for resolution:
149 - if an explicit namespace is given, return the names which match it. If none
150 match, return all names.
151 - if the name has has explicit namespace given, return the names which match it
152 and ignore the given namespace.
153 - otherwise, return all names.
155-}
157lookupCtxtName :: Maybe [String] -> Name -> Ctxt a -> [(Name, a)]
158lookupCtxtName nspace n ctxt = case Map.lookup (nsroot n) ctxt of
159 Just xs -> filterNS (Map.toList xs)
160 Nothing -> []
161 where
162 filterNS [] = []
163 filterNS ((found, v) : xs)
164 | nsmatch n found = (found, v) : filterNS xs
165 | otherwise = filterNS xs
167 nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps
168 nsmatch (NS _ _) _ = False
169 nsmatch looking found = True
171lookupCtxt :: Maybe [String] -> Name -> Ctxt a -> [a]
172lookupCtxt ns n ctxt = map snd (lookupCtxtName ns n ctxt)
174updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a
175updateDef n f ctxt
176 = let ds = lookupCtxtName Nothing n ctxt in
177 foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds
179toAlist :: Ctxt a -> [(Name, a)]
180toAlist ctxt = let allns = map snd (Map.toList ctxt) in
181 concat (map (Map.toList) allns)
183addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
184addAlist [] ctxt = ctxt
185addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
187data Const = I Int | BI Integer | Fl Double | Ch Char | Str String
188 | IType | BIType | FlType | ChType | StrType
189 | PtrType | Forgot
190 deriving Eq
191{-!
192deriving instance Binary Const
193!-}
195data Raw = Var Name
196 | RBind Name (Binder Raw) Raw
197 | RApp Raw Raw
198 | RSet
199 | RForce Raw
200 | RConstant Const
201 deriving (Show, Eq)
203instance Sized Raw where
204 size (Var name) = 1
205 size (RBind name bind right) = 1 + size bind + size right
206 size (RApp left right) = 1 + size left + size right
207 size RSet = 1
208 size (RForce raw) = 1 + size raw
209 size (RConstant const) = size const
211{-!
212deriving instance Binary Raw
213!-}
215data Binder b = Lam { binderTy :: b }
216 | Pi { binderTy :: b }
217 | Let { binderTy :: b,
218 binderVal :: b }
219 | NLet { binderTy :: b,
220 binderVal :: b }
221 | Hole { binderTy :: b}
222 | GHole { binderTy :: b}
223 | Guess { binderTy :: b,
224 binderVal :: b }
225 | PVar { binderTy :: b }
226 | PVTy { binderTy :: b }
227 deriving (Show, Eq, Functor)
228{-!
229deriving instance Binary Binder
230!-}
232fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
233fmapMB f (Let t v) = liftM2 Let (f t) (f v)
234fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
235fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
236fmapMB f (Lam t) = liftM Lam (f t)
237fmapMB f (Pi t) = liftM Pi (f t)
238fmapMB f (Hole t) = liftM Hole (f t)
239fmapMB f (GHole t) = liftM GHole (f t)
240fmapMB f (PVar t) = liftM PVar (f t)
241fmapMB f (PVTy t) = liftM PVTy (f t)
243raw_apply :: Raw -> [Raw] -> Raw
244raw_apply f [] = f
245raw_apply f (a : as) = raw_apply (RApp f a) as
247raw_unapply :: Raw -> (Raw, [Raw])
248raw_unapply t = ua [] t where
249 ua args (RApp f a) = ua (a:args) f
250 ua args t = (t, args)
252data RawFun = RawFun { rtype :: Raw,
253 rval :: Raw
254 }
255 deriving Show
257data RawDatatype = RDatatype Name Raw [(Name, Raw)]
258 deriving Show
260data RDef = RFunction RawFun
261 | RConst Raw
262 | RData RawDatatype
263 deriving Show
265type RProgram = [(Name, RDef)]
267-- WELL TYPED TERMS ---------------------------------------------------------
269data UExp = UVar Int -- universe variable
270 | UVal Int -- explicit universe level
271 deriving (Eq, Ord)
273-- We assume that universe levels have been checked, so anything external
274-- can just have the same universe variable and we won't get any new
275-- cycles.
277instance Binary UExp where
278 put x = return ()
279 get = return (UVar (-1))
281instance Show UExp where
282 show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
283 | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
284 show (UVal x) = show x
285-- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")"
287data UConstraint = ULT UExp UExp
288 | ULE UExp UExp
289 deriving Eq
291instance Show UConstraint where
292 show (ULT x y) = show x ++ " < " ++ show y
293 show (ULE x y) = show x ++ " <= " ++ show y
295type UCs = (Int, [UConstraint])
297data NameType = Bound | Ref | DCon Int Int | TCon Int Int
298 deriving (Show)
299{-!
300deriving instance Binary NameType
301!-}
303instance Eq NameType where
304 Bound == Bound = True
305 Ref == Ref = True
306 DCon _ a == DCon _ b = (a == b) -- ignore tag
307 TCon _ a == TCon _ b = (a == b) -- ignore tag
308 _ == _ = False
310data TT n = P NameType n (TT n) -- embed type
311 | V Int
312 | Bind n (Binder (TT n)) (TT n)
313 | App (TT n) (TT n) -- function, function type, arg
314 | Constant Const
315 | Erased
316 | Set UExp
317 deriving Functor
318{-!
319deriving instance Binary TT
320!-}
322type EnvTT n = [(n, Binder (TT n))]
324data Datatype n = Data { d_typename :: n,
325 d_typetag :: Int,
326 d_type :: (TT n),
327 d_cons :: [(n, TT n)] }
328 deriving (Show, Functor, Eq)
330instance Eq n => Eq (TT n) where
331 (==) (P xt x _) (P yt y _) = xt == yt && x == y
332 (==) (V x) (V y) = x == y
333 (==) (Bind _ xb xs) (Bind _ yb ys) = xb == yb && xs == ys
334 (==) (App fx ax) (App fy ay) = fx == fy && ax == ay
335 (==) (Set _) (Set _) = True -- deal with constraints later
336 (==) (Constant x) (Constant y) = x == y
337 (==) Erased _ = True
338 (==) _ Erased = True
339 (==) _ _ = False
341-- A few handy operations on well typed terms:
343isInjective :: TT n -> Bool
344isInjective (P (DCon _ _) _ _) = True
345isInjective (P (TCon _ _) _ _) = True
346isInjective (Constant _) = True
347isInjective (Set x) = True
348isInjective (Bind _ (Pi _) sc) = True
349isInjective (App f a) = isInjective f
350isInjective _ = False
352instantiate :: TT n -> TT n -> TT n
353instantiate e = subst 0 where
354 subst i (V x) | i == x = e
355 subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
356 subst i (App f a) = App (subst i f) (subst i a)
357 subst i t = t
359pToV :: Eq n => n -> TT n -> TT n
360pToV n = pToV' n 0
361pToV' n i (P _ x _) | n == x = V i
362pToV' n i (Bind x b sc)
363 | n == x = Bind x (fmap (pToV' n i) b) sc
364 | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
365pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
366pToV' n i t = t
368-- Convert several names. First in the list comes out as V 0
369pToVs :: Eq n => [n] -> TT n -> TT n
370pToVs ns tm = pToVs' ns tm 0 where
371 pToVs' [] tm i = tm
372 pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
374vToP :: TT n -> TT n
375vToP = vToP' [] where
376 vToP' env (V i) = let (n, b) = (env !! i) in
377 P Bound n (binderTy b)
378 vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
379 Bind n b' (vToP' ((n, b'):env) sc)
380 vToP' env (App f a) = App (vToP' env f) (vToP' env a)
381 vToP' env t = t
383finalise :: Eq n => TT n -> TT n
384finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
385finalise (App f a) = App (finalise f) (finalise a)
386finalise t = t
388subst :: Eq n => n -> TT n -> TT n -> TT n
389subst n v tm = instantiate v (pToV n tm)
391substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
392substNames [] t = t
393substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
395-- Returns true if V 0 and bound name n do not occur in the term
397noOccurrence :: Eq n => n -> TT n -> Bool
398noOccurrence n t = no' 0 t
399 where
400 no' i (V x) = not (i == x)
401 no' i (P Bound x _) = not (n == x)
402 no' i (Bind n b sc) = noB' i b && no' (i+1) sc
403 where noB' i (Let t v) = no' i t && no' i v
404 noB' i (Guess t v) = no' i t && no' i v
405 noB' i b = no' i (binderTy b)
406 no' i (App f a) = no' i f && no' i a
407 no' i _ = True
409-- Returns all names used free in the term
411freeNames :: Eq n => TT n -> [n]
412freeNames (P _ n _) = [n]
413freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n])
414 ++ freeNames t
415freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
416freeNames (App f a) = nub $ freeNames f ++ freeNames a
417freeNames _ = []
419-- Return the arity of a (normalised) type
421arity :: TT n -> Int
422arity (Bind n (Pi t) sc) = 1 + arity sc
423arity _ = 0
425-- deconstruct an application; returns the function and a list of arguments
427unApply :: TT n -> (TT n, [TT n])
428unApply t = ua [] t where
429 ua args (App f a) = ua (a:args) f
430 ua args t = (t, args)
432mkApp :: TT n -> [TT n] -> TT n
433mkApp f [] = f
434mkApp f (a:as) = mkApp (App f a) as
436forget :: TT Name -> Raw
437forget tm = fe [] tm
438 where
439 fe env (P _ n _) = Var n
440 fe env (V i) = Var (env !! i)
441 fe env (Bind n b sc) = RBind n (fmap (fe env) b)
442 (fe (n:env) sc)
443 fe env (App f a) = RApp (fe env f) (fe env a)
444 fe env (Constant c)
445 = RConstant c
446 fe env (Set i) = RSet
447 fe env Erased = RConstant Forgot
449bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
450bindAll [] t =t
451bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
453bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
454bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
456getArgTys :: TT n -> [(n, TT n)]
457getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
458getArgTys _ = []
460getRetTy :: TT n -> TT n
461getRetTy (Bind n (PVar _) sc) = getRetTy sc
462getRetTy (Bind n (PVTy _) sc) = getRetTy sc
463getRetTy (Bind n (Pi _) sc) = getRetTy sc
464getRetTy sc = sc
466uniqueName :: Name -> [Name] -> Name
467uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
468 | otherwise = n
470nextName (NS x s) = NS (nextName x) s
471nextName (MN i n) = MN (i+1) n
472nextName (UN x) = let (num', nm') = span isDigit (reverse x)
473 nm = reverse nm'
474 num = readN (reverse num') in
475 UN (nm ++ show (num+1))
476 where
477 readN "" = 0
478 readN x = read x
480type Term = TT Name
481type Type = Term
483type Env = EnvTT Name
485-- an environment with de Bruijn indices 'normalised' so that they all refer to
486-- this environment
488newtype WkEnvTT n = Wk (EnvTT n)
489type WkEnv = WkEnvTT Name
491instance (Eq n, Show n) => Show (TT n) where
492 show t = showEnv [] t
494instance Show Const where
495 show (I i) = show i
496 show (BI i) = show i ++ "L"
497 show (Fl f) = show f
498 show (Ch c) = show c
499 show (Str s) = show s
500 show IType = "Int"
501 show BIType = "Integer"
502 show FlType = "Float"
503 show ChType = "Char"
504 show StrType = "String"
505 show PtrType = "Ptr"
507showEnv env t = showEnv' env t False
508showEnvDbg env t = showEnv' env t True
510showEnv' env t dbg = se 10 env t where
511 se p env (P nt n t) = show n
512 ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
513 se p env (V i) | i < length env = (show $ fst $ env!!i) ++
514 if dbg then "{" ++ show i ++ "}" else ""
515 | otherwise = "!!V " ++ show i ++ "!!"
516 se p env (Bind n b@(Pi t) sc)
517 | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
518 se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
519 se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
520 se p env (Constant c) = show c
521 se p env Erased = "[__]"
522 se p env (Set i) = "Set " ++ show i
524 sb env n (Lam t) = showb env "\\ " " => " n t
525 sb env n (Hole t) = showb env "? " ". " n t
526 sb env n (GHole t) = showb env "?defer " ". " n t
527 sb env n (Pi t) = showb env "(" ") -> " n t
528 sb env n (PVar t) = showb env "pat " ". " n t
529 sb env n (PVTy t) = showb env "pty " ". " n t
530 sb env n (Let t v) = showbv env "let " " in " n t v
531 sb env n (Guess t v) = showbv env "?? " " in " n t v
533 showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
534 showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
535 se 10 env v ++ sc
537 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
538 | otherwise = str
540-- Check whether a term has any holes in it - impure if so
542pureTerm :: TT n -> Bool
543pureTerm (App f a) = pureTerm f && pureTerm a
544pureTerm (Bind n b sc) = pureBinder b && pureTerm sc where
545 pureBinder (Hole _) = False
546 pureBinder (Guess _ _) = False
547 pureBinder (Let t v) = pureTerm t && pureTerm v
548 pureBinder t = pureTerm (binderTy t)
549pureTerm _ = True
551-- weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings)
553weakenTm :: Int -> TT n -> TT n
554weakenTm i t = wk i 0 t
555 where wk i min (V x) | x >= min = V (i + x)
556 wk i m (App f a) = App (wk i m f) (wk i m a)
557 wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
558 wk i m t = t
559 wkb i m t = fmap (wk i m) t
561-- weaken an environment so that all the de Bruijn indices are correct according
562-- to the latest bound variable
564weakenEnv :: EnvTT n -> EnvTT n
565weakenEnv env = wk (length env - 1) env
566 where wk i [] = []
567 wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
568 weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
569 weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
570 weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
572weakenTmEnv :: Int -> EnvTT n -> EnvTT n
573weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
575orderPats :: Term -> Term
576orderPats tm = op [] tm
577 where
578 op ps (Bind n (PVar t) sc) = op ((n, t) : ps) sc
579 op ps sc = bindAll (map (\ (n, t) -> (n, PVar t)) (sortP ps)) sc
581 sortP ps = pick [] (reverse ps)
583 namesIn (P _ n _) = [n]
584 namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
585 where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
586 nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
587 nb t = namesIn (binderTy t)
588 namesIn (App f a) = nub (namesIn f ++ namesIn a)
589 namesIn _ = []
591 pick acc [] = reverse acc
592 pick acc ((n, t) : ps) = pick (insert n t acc) ps
594 insert n t [] = [(n, t)]
595 insert n t ((n',t') : ps)
596 | n `elem` (namesIn t' ++ concatMap namesIn (map snd ps))
597 = (n', t') : insert n t ps
598 | otherwise = (n,t):(n',t'):ps