1{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveFunctor #-}
5import Control.Monad.State
7import qualified Data.Map as Map
10import qualified Data.Binary as B
11import Data.Binary hiding (get, put)
14 * Full dependent types
15 * A hierarchy of universes, with cumulativity: Set : Set1, Set1 : Set2, ...
16 * Pattern matching letrec binding
17 * (primitive types defined externally)
20 * Typechecker is kept as simple as possible
21 - no unification, just a checker for incomplete terms.
22 * We have a simple collection of tactics which we use to elaborate source
23 programs with implicit syntax into fully explicit terms.
30data FC = FC { fc_fname :: String,
34deriving instance Binary FC
38 show (FC f l) = f ++ ":" ++ show l
41 | CantUnify Term Term Err Int -- Int is 'score' - how much we did unify
42 | NotInjective Term Term Term
51score (CantUnify _ _ m s) = s + score m
52score (CantResolve _) = 20
55instance Show Err where
57 show (CantUnify l r e i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
58 ++ show e ++ " " ++ show i
63 deriving (Eq, Functor)
65instance Show a => Show (TC a) where
67 show (Error str) = "Error: " ++ show str
69-- at some point, this instance should also carry type checking options
72instance Monad TC where
77 fail e = Error (Msg e)
82trun :: FC -> TC a -> TC a
84trun fc (Error e) = Error (At fc e)
86instance MonadPlus TC where
87 mzero = fail "Unknown error"
88 (OK x) `mplus` _ = OK x
89 _ `mplus` (OK y) = OK y
92discard :: Monad m => m a -> m ()
93discard f = f >> return ()
95showSep :: String -> [String] -> String
98showSep sep (x:xs) = x ++ sep ++ showSep sep xs
100pmap f (x, y) = (f x, f y)
102traceWhen True msg a = trace msg a
103traceWhen False _ a = a
105-- RAW TERMS ----------------------------------------------------------------
107-- Names are hierarchies of strings, describing scope (so no danger of
108-- duplicate names, but need to be careful on lookup).
109-- Also MN for machine chosen names
112 | NS Name [String] -- root, namespaces
116deriving instance Binary Name
119instance Show Name where
121 show (NS n s) = showSep "." (reverse s) ++ "." ++ show n
122 show (MN i s) = "{" ++ s ++ show i ++ "}"
125-- Contexts allow us to map names to things. A root name maps to a collection
126-- of things in different namespaces with that name.
128type Ctxt a = Map.Map Name (Map.Map Name a)
129emptyContext = Map.empty
134addDef :: Name -> a -> Ctxt a -> Ctxt a
135addDef n v ctxt = case Map.lookup (nsroot n) ctxt of
136 Nothing -> Map.insert (nsroot n)
137 (Map.insert n v Map.empty) ctxt
138 Just xs -> Map.insert (nsroot n)
139 (Map.insert n v xs) ctxt
141{- lookup a name in the context, given an optional namespace.
142 The name (n) may itself have a (partial) namespace given.
144 Rules for resolution:
145 - if an explicit namespace is given, return the names which match it. If none
146 match, return all names.
147 - if the name has has explicit namespace given, return the names which match it
148 and ignore the given namespace.
149 - otherwise, return all names.
153lookupCtxtName :: Maybe [String] -> Name -> Ctxt a -> [(Name, a)]
154lookupCtxtName nspace n ctxt = case Map.lookup (nsroot n) ctxt of
155 Just xs -> filterNS (Map.toList xs)
159 filterNS ((found, v) : xs)
160 | nsmatch n found = (found, v) : filterNS xs
161 | otherwise = filterNS xs
163 nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps
164 nsmatch (NS _ _) _ = False
165 nsmatch looking found = True
167lookupCtxt :: Maybe [String] -> Name -> Ctxt a -> [a]
168lookupCtxt ns n ctxt = map snd (lookupCtxtName ns n ctxt)
170updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a
172 = let ds = lookupCtxtName Nothing n ctxt in
173 foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds
175toAlist :: Ctxt a -> [(Name, a)]
176toAlist ctxt = let allns = map snd (Map.toList ctxt) in
177 concat (map (Map.toList) allns)
179addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
180addAlist [] ctxt = ctxt
181addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
183data Const = I Int | BI Integer | Fl Double | Ch Char | Str String
184 | IType | BIType | FlType | ChType | StrType
188deriving instance Binary Const
192 | RBind Name (Binder Raw) Raw
199deriving instance Binary Raw
202data Binder b = Lam { binderTy :: b }
203 | Pi { binderTy :: b }
204 | Let { binderTy :: b,
206 | NLet { binderTy :: b,
208 | Hole { binderTy :: b}
209 | GHole { binderTy :: b}
210 | Guess { binderTy :: b,
212 | PVar { binderTy :: b }
213 | PVTy { binderTy :: b }
214 deriving (Show, Eq, Functor)
216deriving instance Binary Binder
219fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
220fmapMB f (Let t v) = liftM2 Let (f t) (f v)
221fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
222fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
223fmapMB f (Lam t) = liftM Lam (f t)
224fmapMB f (Pi t) = liftM Pi (f t)
225fmapMB f (Hole t) = liftM Hole (f t)
226fmapMB f (GHole t) = liftM GHole (f t)
227fmapMB f (PVar t) = liftM PVar (f t)
228fmapMB f (PVTy t) = liftM PVTy (f t)
230raw_apply :: Raw -> [Raw] -> Raw
232raw_apply f (a : as) = raw_apply (RApp f a) as
234raw_unapply :: Raw -> (Raw, [Raw])
235raw_unapply t = ua [] t where
236 ua args (RApp f a) = ua (a:args) f
237 ua args t = (t, args)
239data RawFun = RawFun { rtype :: Raw,
244data RawDatatype = RDatatype Name Raw [(Name, Raw)]
247data RDef = RFunction RawFun
252type RProgram = [(Name, RDef)]
254-- WELL TYPED TERMS ---------------------------------------------------------
256data UExp = UVar Int -- universe variable
257 | UVal Int -- explicit universe level
260-- We assume that universe levels have been checked, so anything external
261-- can just have the same universe variable and we won't get any new
264instance Binary UExp where
266 get = return (UVar (-1))
268instance Show UExp where
269 show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
270 | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
271 show (UVal x) = show x
272-- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")"
274data UConstraint = ULT UExp UExp
278instance Show UConstraint where
279 show (ULT x y) = show x ++ " < " ++ show y
280 show (ULE x y) = show x ++ " <= " ++ show y
282type UCs = (Int, [UConstraint])
284data NameType = Bound | Ref | DCon Int Int | TCon Int Int
287deriving instance Binary NameType
290instance Eq NameType where
291 Bound == Bound = True
293 DCon _ a == DCon _ b = (a == b) -- ignore tag
294 TCon _ a == TCon _ b = (a == b) -- ignore tag
297data TT n = P NameType n (TT n) -- embed type
299 | Bind n (Binder (TT n)) (TT n)
300 | App (TT n) (TT n) -- function, function type, arg
306deriving instance Binary TT
309type EnvTT n = [(n, Binder (TT n))]
311data Datatype n = Data { d_typename :: n,
314 d_cons :: [(n, TT n)] }
315 deriving (Show, Functor, Eq)
317instance Eq n => Eq (TT n) where
318 (==) (P xt x _) (P yt y _) = xt == yt && x == y
319 (==) (V x) (V y) = x == y
320 (==) (Bind _ xb xs) (Bind _ yb ys) = xb == yb && xs == ys
321 (==) (App fx ax) (App fy ay) = fx == fy && ax == ay
322 (==) (Set _) (Set _) = True -- deal with constraints later
323 (==) (Constant x) (Constant y) = x == y
328convEq :: Eq n => TT n -> TT n -> StateT UCs TC Bool
329convEq (P xt x _) (P yt y _) = return (xt == yt && x == y)
330convEq (V x) (V y) = return (x == y)
331convEq (Bind _ xb xs) (Bind _ yb ys)
332 = liftM2 (&&) (convEqB xb yb) (convEq xs ys)
333 where convEqB (Let v t) (Let v' t') = liftM2 (&&) (convEq v v') (convEq t t')
334 convEqB (Guess v t) (Guess v' t') = liftM2 (&&) (convEq v v') (convEq t t')
335 convEqB b b' = convEq (binderTy b) (binderTy b')
336convEq (App fx ax) (App fy ay) = liftM2 (&&) (convEq fx fy) (convEq ax ay)
337convEq (Constant x) (Constant y) = return (x == y)
338convEq (Set x) (Set y) = do (v, cs) <- get
339 put (v, ULE x y : cs)
341convEq Erased _ = return True
342convEq _ Erased = return True
343convEq _ _ = return False
345-- A few handy operations on well typed terms:
347isInjective :: TT n -> Bool
348isInjective (P (DCon _ _) _ _) = True
349isInjective (P (TCon _ _) _ _) = True
350isInjective (Constant _) = True
351isInjective (Set x) = True
352isInjective (Bind _ (Pi _) sc) = True
353isInjective (App f a) = isInjective f
356instantiate :: TT n -> TT n -> TT n
357instantiate e = subst 0 where
358 subst i (V x) | i == x = e
359 subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
360 subst i (App f a) = App (subst i f) (subst i a)
363pToV :: Eq n => n -> TT n -> TT n
365pToV' n i (P _ x _) | n == x = V i
366pToV' n i (Bind x b sc)
367 | n == x = Bind x (fmap (pToV' n i) b) sc
368 | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
369pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
372-- Convert several names. First in the list comes out as V 0
373pToVs :: Eq n => [n] -> TT n -> TT n
374pToVs ns tm = pToVs' ns tm 0 where
376 pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
380 vToP' env (V i) = let (n, b) = (env !! i) in
381 P Bound n (binderTy b)
382 vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
383 Bind n b' (vToP' ((n, b'):env) sc)
384 vToP' env (App f a) = App (vToP' env f) (vToP' env a)
387finalise :: Eq n => TT n -> TT n
388finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
389finalise (App f a) = App (finalise f) (finalise a)
392subst :: Eq n => n -> TT n -> TT n -> TT n
393subst n v tm = instantiate v (pToV n tm)
395substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
397substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
399-- Returns true if V 0 and bound name n do not occur in the term
401noOccurrence :: Eq n => n -> TT n -> Bool
402noOccurrence n t = no' 0 t
404 no' i (V x) = not (i == x)
405 no' i (P Bound x _) = not (n == x)
406 no' i (Bind n b sc) = noB' i b && no' (i+1) sc
407 where noB' i (Let t v) = no' i t && no' i v
408 noB' i (Guess t v) = no' i t && no' i v
409 noB' i b = no' i (binderTy b)
410 no' i (App f a) = no' i f && no' i a
413-- Return the arity of a (normalised) type
416arity (Bind n (Pi t) sc) = 1 + arity sc
419-- deconstruct an application; returns the function and a list of arguments
421unApply :: TT n -> (TT n, [TT n])
422unApply t = ua [] t where
423 ua args (App f a) = ua (a:args) f
424 ua args t = (t, args)
426mkApp :: TT n -> [TT n] -> TT n
428mkApp f (a:as) = mkApp (App f a) as
430forget :: TT Name -> Raw
433 fe env (P _ n _) = Var n
434 fe env (V i) = Var (env !! i)
435 fe env (Bind n b sc) = RBind n (fmap (fe env) b)
437 fe env (App f a) = RApp (fe env f) (fe env a)
440 fe env (Set i) = RSet
441 fe env Erased = RConstant Forgot
443bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
445bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
447bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
448bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
450getArgTys :: TT n -> [(n, TT n)]
451getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
454getRetTy :: TT n -> TT n
455getRetTy (Bind n (PVar _) sc) = getRetTy sc
456getRetTy (Bind n (PVTy _) sc) = getRetTy sc
457getRetTy (Bind n (Pi _) sc) = getRetTy sc
460uniqueName :: Name -> [Name] -> Name
461uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
464nextName (NS x s) = NS (nextName x) s
465nextName (MN i n) = MN (i+1) n
466nextName (UN x) = let (num', nm') = span isDigit (reverse x)
468 num = readN (reverse num') in
469 UN (nm ++ show (num+1))
479-- an environment with de Bruijn indices 'normalised' so that they all refer to
482newtype WkEnvTT n = Wk (EnvTT n)
483type WkEnv = WkEnvTT Name
485instance (Eq n, Show n) => Show (TT n) where
486 show t = showEnv [] t
488instance Show Const where
490 show (BI i) = show i ++ "L"
493 show (Str s) = show s
495 show BIType = "Integer"
496 show FlType = "Float"
498 show StrType = "String"
501showEnv env t = showEnv' env t False
502showEnvDbg env t = showEnv' env t True
504showEnv' env t dbg = se 10 env t where
505 se p env (P nt n t) = show n
506 ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
507 se p env (V i) | i < length env = (show $ fst $ env!!i) ++
508 if dbg then "{" ++ show i ++ "}" else ""
509 | otherwise = "!!V " ++ show i ++ "!!"
510 se p env (Bind n b@(Pi t) sc)
511 | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
512 se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
513 se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
514 se p env (Constant c) = show c
515 se p env Erased = "[__]"
516 se p env (Set i) = "Set " ++ show i
518 sb env n (Lam t) = showb env "\\ " " => " n t
519 sb env n (Hole t) = showb env "? " ". " n t
520 sb env n (GHole t) = showb env "?defer " ". " n t
521 sb env n (Pi t) = showb env "(" ") -> " n t
522 sb env n (PVar t) = showb env "pat " ". " n t
523 sb env n (PVTy t) = showb env "pty " ". " n t
524 sb env n (Let t v) = showbv env "let " " in " n t v
525 sb env n (Guess t v) = showbv env "?? " " in " n t v
527 showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
528 showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
531 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
534-- Check whether a term has any holes in it - impure if so
536pureTerm :: TT n -> Bool
537pureTerm (App f a) = pureTerm f && pureTerm a
538pureTerm (Bind n b sc) = pureBinder b && pureTerm sc where
539 pureBinder (Hole _) = False
540 pureBinder (Guess _ _) = False
541 pureBinder (Let t v) = pureTerm t && pureTerm v
542 pureBinder t = pureTerm (binderTy t)
545-- weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings)
547weakenTm :: Int -> TT n -> TT n
548weakenTm i t = wk i 0 t
549 where wk i min (V x) | x >= min = V (i + x)
550 wk i m (App f a) = App (wk i m f) (wk i m a)
551 wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
553 wkb i m t = fmap (wk i m) t
555-- weaken an environment so that all the de Bruijn indices are correct according
556-- to the latest bound variable
558weakenEnv :: EnvTT n -> EnvTT n
559weakenEnv env = wk (length env - 1) env
561 wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
562 weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
563 weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
564 weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
566weakenTmEnv :: Int -> EnvTT n -> EnvTT n
567weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
569orderPats :: Term -> Term
570orderPats tm = op [] tm
572 op ps (Bind n (PVar t) sc) = op ((n, t) : ps) sc
573 op ps sc = bindAll (map (\ (n, t) -> (n, PVar t)) (sortP ps)) sc
575 sortP ps = pick [] (reverse ps)
577 namesIn (P _ n _) = [n]
578 namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
579 where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
580 nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
581 nb t = namesIn (binderTy t)
582 namesIn (App f a) = nub (namesIn f ++ namesIn a)
585 pick acc [] = reverse acc
586 pick acc ((n, t) : ps) = pick (insert n t acc) ps
588 insert n t [] = [(n, t)]
589 insert n t ((n',t') : ps)
590 | n `elem` (namesIn t' ++ concatMap namesIn (map snd ps))
591 = (n', t') : insert n t ps
592 | otherwise = (n,t):(n',t'):ps
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list