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)
13import Util.Pretty hiding (Str)
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)
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.
32data FC = FC { fc_fname :: String,
36deriving instance Binary FC
40 show (FC f l) = f ++ ":" ++ show l
43 | CantUnify Term Term Err Int -- Int is 'score' - how much we did unify
45 | NotInjective Term Term Term
54score (CantUnify _ _ m s) = s + score m
55score (CantResolve _) = 20
56score (NoSuchVariable _) = 1000
59instance Show Err where
61 show (CantUnify l r e i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
62 ++ show e ++ " " ++ show i
67 deriving (Eq, Functor)
69instance Show a => Show (TC a) where
71 show (Error str) = "Error: " ++ show str
73-- at some point, this instance should also carry type checking options
76instance Monad TC where
81 fail e = Error (Msg e)
86trun :: FC -> TC a -> TC 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
96discard :: Monad m => m a -> m ()
97discard f = f >> return ()
99showSep :: String -> [String] -> String
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
116 | NS Name [String] -- root, namespaces
120deriving instance Binary Name
123instance Show Name where
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
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.
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)
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
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
192deriving instance Binary Const
196 | RBind Name (Binder Raw) Raw
203instance Sized Raw where
205 size (RBind name bind right) = 1 + size bind + size right
206 size (RApp left right) = 1 + size left + size right
208 size (RForce raw) = 1 + size raw
209 size (RConstant const) = size const
212deriving instance Binary Raw
215data Binder b = Lam { binderTy :: b }
216 | Pi { binderTy :: b }
217 | Let { binderTy :: b,
219 | NLet { binderTy :: b,
221 | Hole { binderTy :: b}
222 | GHole { binderTy :: b}
223 | Guess { binderTy :: b,
225 | PVar { binderTy :: b }
226 | PVTy { binderTy :: b }
227 deriving (Show, Eq, Functor)
229deriving instance Binary Binder
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
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,
257data RawDatatype = RDatatype Name Raw [(Name, Raw)]
260data RDef = RFunction RawFun
265type RProgram = [(Name, RDef)]
267-- WELL TYPED TERMS ---------------------------------------------------------
269data UExp = UVar Int -- universe variable
270 | UVal Int -- explicit universe level
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
277instance Binary UExp where
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
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
300deriving instance Binary NameType
303instance Eq NameType where
304 Bound == Bound = True
306 DCon _ a == DCon _ b = (a == b) -- ignore tag
307 TCon _ a == TCon _ b = (a == b) -- ignore tag
310data TT n = P NameType n (TT n) -- embed type
312 | Bind n (Binder (TT n)) (TT n)
313 | App (TT n) (TT n) -- function, function type, arg
319deriving instance Binary TT
322type EnvTT n = [(n, Binder (TT n))]
324data Datatype n = Data { d_typename :: 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
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
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)
359pToV :: Eq n => n -> TT n -> TT n
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)
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
372 pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
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)
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)
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
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
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
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])
415freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
416freeNames (App f a) = nub $ freeNames f ++ freeNames a
419-- Return the arity of a (normalised) type
422arity (Bind n (Pi t) sc) = 1 + arity sc
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
434mkApp f (a:as) = mkApp (App f a) as
436forget :: TT Name -> Raw
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)
443 fe env (App f a) = RApp (fe env f) (fe env a)
446 fe env (Set i) = RSet
447 fe env Erased = RConstant Forgot
449bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
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
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
466uniqueName :: Name -> [Name] -> Name
467uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
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)
474 num = readN (reverse num') in
475 UN (nm ++ show (num+1))
485-- an environment with de Bruijn indices 'normalised' so that they all refer to
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
496 show (BI i) = show i ++ "L"
499 show (Str s) = show s
501 show BIType = "Integer"
502 show FlType = "Float"
504 show StrType = "String"
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 ++ " = " ++
537 bracket outer inner str | inner > outer = "(" ++ 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)
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)
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
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
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)
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
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