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
39instance Sized FC where
40 size (FC f l) = 1 + length f
43 show (FC f l) = f ++ ":" ++ show l
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
52 | NotInjective Term Term Term
54 | CantResolveAlts [String]
62instance Sized Err where
63 size (Msg msg) = length msg
64 size (InternalMsg msg) = length msg
65 size (CantUnify _ left right err _ score) = size left + size right + size err
66 size (NoSuchVariable name) = size name
67 size (NotInjective l c r) = size l + size c + size r
68 size (CantResolve trm) = size trm
69 size (CantResolveAlts _) = 1
70 size (IncompleteTerm trm) = size trm
71 size UniverseError = 1
72 size ProgramLineComment = 1
73 size (At fc err) = size fc + size err
74 size (Inaccessible _) = 1
77score (CantUnify _ _ _ m _ s) = s + score m
78score (CantResolve _) = 20
79score (NoSuchVariable _) = 1000
82instance Show Err where
84 show (InternalMsg s) = "Internal error: " ++ show s
85 show (CantUnify _ l r e sc i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
86 ++ show e ++ " in " ++ show sc ++ " " ++ show i
87 show (Inaccessible n) = show n ++ " is not an accessible pattern variable"
90instance Pretty Err where
91 pretty (Msg m) = text m
92 pretty (CantUnify _ l r e _ i) =
93 if size l + size r > breakingSize then
94 text "Cannot unify" <+> colon $$
95 nest nestingSize (pretty l <+> text "and" <+> pretty r) $$
96 nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
98 text "Cannot unify" <+> colon <+> pretty l <+> text "and" <+> pretty r $$
99 nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
100 pretty _ = text "Error"
104 deriving (Eq, Functor)
106instance Pretty a => Pretty (TC a) where
107 pretty (OK ok) = pretty ok
109 if size err > breakingSize then
110 text "Error" <+> colon $$ (nest nestingSize $ pretty err)
112 text "Error" <+> colon <+> pretty err
114instance Show a => Show (TC a) where
116 show (Error str) = "Error: " ++ show str
118-- at some point, this instance should also carry type checking options
121instance Monad TC where
126 fail e = Error (InternalMsg e)
131trun :: FC -> TC a -> TC a
133trun fc (Error e) = Error (At fc e)
135instance MonadPlus TC where
136 mzero = fail "Unknown error"
137 (OK x) `mplus` _ = OK x
138 _ `mplus` (OK y) = OK y
141discard :: Monad m => m a -> m ()
142discard f = f >> return ()
144showSep :: String -> [String] -> String
147showSep sep (x:xs) = x ++ sep ++ showSep sep xs
149pmap f (x, y) = (f x, f y)
151traceWhen True msg a = trace msg a
152traceWhen False _ a = a
154-- RAW TERMS ----------------------------------------------------------------
156-- Names are hierarchies of strings, describing scope (so no danger of
157-- duplicate names, but need to be careful on lookup).
158-- Also MN for machine chosen names
161 | NS Name [String] -- root, namespaces
165deriving instance Binary Name
168instance Sized Name where
170 size (NS n els) = 1 + length els
173instance Pretty Name where
174 pretty (UN n) = text n
175 pretty (NS n s) = pretty n
176 pretty (MN i s) = lbrace <+> text s <+> (text . show $ i) <+> rbrace
178instance Show Name where
180 show (NS n s) = showSep "." (reverse s) ++ "." ++ show n
181 show (MN i s) = "{" ++ s ++ show i ++ "}"
184-- Contexts allow us to map names to things. A root name maps to a collection
185-- of things in different namespaces with that name.
187type Ctxt a = Map.Map Name (Map.Map Name a)
188emptyContext = Map.empty
193addDef :: Name -> a -> Ctxt a -> Ctxt a
194addDef n v ctxt = case Map.lookup (nsroot n) ctxt of
195 Nothing -> Map.insert (nsroot n)
196 (Map.insert n v Map.empty) ctxt
197 Just xs -> Map.insert (nsroot n)
198 (Map.insert n v xs) ctxt
200{- lookup a name in the context, given an optional namespace.
201 The name (n) may itself have a (partial) namespace given.
203 Rules for resolution:
204 - if an explicit namespace is given, return the names which match it. If none
205 match, return all names.
206 - if the name has has explicit namespace given, return the names which match it
207 and ignore the given namespace.
208 - otherwise, return all names.
212lookupCtxtName :: Maybe [String] -> Name -> Ctxt a -> [(Name, a)]
213lookupCtxtName nspace n ctxt = case Map.lookup (nsroot n) ctxt of
214 Just xs -> filterNS (Map.toList xs)
218 filterNS ((found, v) : xs)
219 | nsmatch n found = (found, v) : filterNS xs
220 | otherwise = filterNS xs
222 nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps
223 nsmatch (NS _ _) _ = False
224 nsmatch looking found = True
226lookupCtxt :: Maybe [String] -> Name -> Ctxt a -> [a]
227lookupCtxt ns n ctxt = map snd (lookupCtxtName ns n ctxt)
229updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a
231 = let ds = lookupCtxtName Nothing n ctxt in
232 foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds
234toAlist :: Ctxt a -> [(Name, a)]
235toAlist ctxt = let allns = map snd (Map.toList ctxt) in
236 concat (map (Map.toList) allns)
238addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
239addAlist [] ctxt = ctxt
240addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
242data Const = I Int | BI Integer | Fl Double | Ch Char | Str String
243 | IType | BIType | FlType | ChType | StrType
244 | PtrType | VoidType | Forgot
247deriving instance Binary Const
250instance Sized Const where
253instance Pretty Const where
254 pretty (I i) = text . show $ i
255 pretty (BI i) = text . show $ i
256 pretty (Fl f) = text . show $ f
257 pretty (Ch c) = text . show $ c
258 pretty (Str s) = text s
259 pretty IType = text "Int"
260 pretty BIType = text "BigInt"
261 pretty FlType = text "Float"
262 pretty ChType = text "Char"
263 pretty StrType = text "String"
264 pretty PtrType = text "Ptr"
265 pretty VoidType = text "Void"
266 pretty Forgot = text "Forgot"
269 | RBind Name (Binder Raw) Raw
276instance Sized Raw where
278 size (RBind name bind right) = 1 + size bind + size right
279 size (RApp left right) = 1 + size left + size right
281 size (RForce raw) = 1 + size raw
282 size (RConstant const) = size const
284instance Pretty Raw where
288deriving instance Binary Raw
291data Binder b = Lam { binderTy :: b }
292 | Pi { binderTy :: b }
293 | Let { binderTy :: b,
295 | NLet { binderTy :: b,
297 | Hole { binderTy :: b}
298 | GHole { binderTy :: b}
299 | Guess { binderTy :: b,
301 | PVar { binderTy :: b }
302 | PVTy { binderTy :: b }
303 deriving (Show, Eq, Ord, Functor)
305deriving instance Binary Binder
308instance Sized a => Sized (Binder a) where
309 size (Lam ty) = 1 + size ty
310 size (Pi ty) = 1 + size ty
311 size (Let ty val) = 1 + size ty + size val
312 size (NLet ty val) = 1 + size ty + size val
313 size (Hole ty) = 1 + size ty
314 size (GHole ty) = 1 + size ty
315 size (Guess ty val) = 1 + size ty + size val
316 size (PVar ty) = 1 + size ty
317 size (PVTy ty) = 1 + size ty
319fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
320fmapMB f (Let t v) = liftM2 Let (f t) (f v)
321fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
322fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
323fmapMB f (Lam t) = liftM Lam (f t)
324fmapMB f (Pi t) = liftM Pi (f t)
325fmapMB f (Hole t) = liftM Hole (f t)
326fmapMB f (GHole t) = liftM GHole (f t)
327fmapMB f (PVar t) = liftM PVar (f t)
328fmapMB f (PVTy t) = liftM PVTy (f t)
330raw_apply :: Raw -> [Raw] -> Raw
332raw_apply f (a : as) = raw_apply (RApp f a) as
334raw_unapply :: Raw -> (Raw, [Raw])
335raw_unapply t = ua [] t where
336 ua args (RApp f a) = ua (a:args) f
337 ua args t = (t, args)
339data RawFun = RawFun { rtype :: Raw,
344data RawDatatype = RDatatype Name Raw [(Name, Raw)]
347data RDef = RFunction RawFun
352type RProgram = [(Name, RDef)]
354-- WELL TYPED TERMS ---------------------------------------------------------
356data UExp = UVar Int -- universe variable
357 | UVal Int -- explicit universe level
360instance Sized UExp where
363-- We assume that universe levels have been checked, so anything external
364-- can just have the same universe variable and we won't get any new
367instance Binary UExp where
369 get = return (UVar (-1))
371instance Show UExp where
372 show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
373 | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
374 show (UVal x) = show x
375-- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")"
377data UConstraint = ULT UExp UExp
381instance Show UConstraint where
382 show (ULT x y) = show x ++ " < " ++ show y
383 show (ULE x y) = show x ++ " <= " ++ show y
385type UCs = (Int, [UConstraint])
387data NameType = Bound | Ref | DCon Int Int | TCon Int Int
390deriving instance Binary NameType
393instance Sized NameType where
396instance Pretty NameType where
399instance Eq NameType where
400 Bound == Bound = True
402 DCon _ a == DCon _ b = (a == b) -- ignore tag
403 TCon _ a == TCon _ b = (a == b) -- ignore tag
406data TT n = P NameType n (TT n) -- embed type
408 | Bind n (Binder (TT n)) (TT n)
409 | App (TT n) (TT n) -- function, function type, arg
413 deriving (Ord, Functor)
415deriving instance Binary TT
418instance Sized a => Sized (TT a) where
419 size (P name n trm) = 1 + size name + size n + size trm
421 size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy
422 size (App l r) = 1 + size l + size r
423 size (Constant c) = size c
425 size (Set u) = 1 + size u
427instance Pretty a => Pretty (TT a) where
428 pretty _ = text "test"
430type EnvTT n = [(n, Binder (TT n))]
432data Datatype n = Data { d_typename :: n,
435 d_cons :: [(n, TT n)] }
436 deriving (Show, Functor, Eq)
438instance Eq n => Eq (TT n) where
439 (==) (P xt x _) (P yt y _) = xt == yt && x == y
440 (==) (V x) (V y) = x == y
441 (==) (Bind _ xb xs) (Bind _ yb ys) = xb == yb && xs == ys
442 (==) (App fx ax) (App fy ay) = fx == fy && ax == ay
443 (==) (Set _) (Set _) = True -- deal with constraints later
444 (==) (Constant x) (Constant y) = x == y
449-- A few handy operations on well typed terms:
451isInjective :: TT n -> Bool
452isInjective (P (DCon _ _) _ _) = True
453isInjective (P (TCon _ _) _ _) = True
454isInjective (Constant _) = True
455isInjective (Set x) = True
456isInjective (Bind _ (Pi _) sc) = True
457isInjective (App f a) = isInjective f
460instantiate :: TT n -> TT n -> TT n
461instantiate e = subst 0 where
462 subst i (V x) | i == x = e
463 subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
464 subst i (App f a) = App (subst i f) (subst i a)
467pToV :: Eq n => n -> TT n -> TT n
469pToV' n i (P _ x _) | n == x = V i
470pToV' n i (Bind x b sc)
471 | n == x = Bind x (fmap (pToV' n i) b) sc
472 | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
473pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
476-- Convert several names. First in the list comes out as V 0
477pToVs :: Eq n => [n] -> TT n -> TT n
478pToVs ns tm = pToVs' ns tm 0 where
480 pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
484 vToP' env (V i) = let (n, b) = (env !! i) in
485 P Bound n (binderTy b)
486 vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
487 Bind n b' (vToP' ((n, b'):env) sc)
488 vToP' env (App f a) = App (vToP' env f) (vToP' env a)
491finalise :: Eq n => TT n -> TT n
492finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
493finalise (App f a) = App (finalise f) (finalise a)
496subst :: Eq n => n -> TT n -> TT n -> TT n
497subst n v tm = instantiate v (pToV n tm)
499substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
501substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
503-- Returns true if V 0 and bound name n do not occur in the term
505noOccurrence :: Eq n => n -> TT n -> Bool
506noOccurrence n t = no' 0 t
508 no' i (V x) = not (i == x)
509 no' i (P Bound x _) = not (n == x)
510 no' i (Bind n b sc) = noB' i b && no' (i+1) sc
511 where noB' i (Let t v) = no' i t && no' i v
512 noB' i (Guess t v) = no' i t && no' i v
513 noB' i b = no' i (binderTy b)
514 no' i (App f a) = no' i f && no' i a
517-- Returns all names used free in the term
519freeNames :: Eq n => TT n -> [n]
520freeNames (P _ n _) = [n]
521freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n])
523freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
524freeNames (App f a) = nub $ freeNames f ++ freeNames a
527-- Return the arity of a (normalised) type
530arity (Bind n (Pi t) sc) = 1 + arity sc
533-- deconstruct an application; returns the function and a list of arguments
535unApply :: TT n -> (TT n, [TT n])
536unApply t = ua [] t where
537 ua args (App f a) = ua (a:args) f
538 ua args t = (t, args)
540mkApp :: TT n -> [TT n] -> TT n
542mkApp f (a:as) = mkApp (App f a) as
544forget :: TT Name -> Raw
547 fe env (P _ n _) = Var n
548 fe env (V i) = Var (env !! i)
549 fe env (Bind n b sc) = RBind n (fmap (fe env) b)
551 fe env (App f a) = RApp (fe env f) (fe env a)
554 fe env (Set i) = RSet
555 fe env Erased = RConstant Forgot
557bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
559bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
561bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
562bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
564getArgTys :: TT n -> [(n, TT n)]
565getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
568getRetTy :: TT n -> TT n
569getRetTy (Bind n (PVar _) sc) = getRetTy sc
570getRetTy (Bind n (PVTy _) sc) = getRetTy sc
571getRetTy (Bind n (Pi _) sc) = getRetTy sc
574uniqueName :: Name -> [Name] -> Name
575uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
578nextName (NS x s) = NS (nextName x) s
579nextName (MN i n) = MN (i+1) n
580nextName (UN x) = let (num', nm') = span isDigit (reverse x)
582 num = readN (reverse num') in
583 UN (nm ++ show (num+1))
593-- an environment with de Bruijn indices 'normalised' so that they all refer to
596newtype WkEnvTT n = Wk (EnvTT n)
597type WkEnv = WkEnvTT Name
599instance (Eq n, Show n) => Show (TT n) where
600 show t = showEnv [] t
602instance Show Const where
604 show (BI i) = show i ++ "L"
607 show (Str s) = show s
609 show BIType = "Integer"
610 show FlType = "Float"
612 show StrType = "String"
614 show VoidType = "Void"
616showEnv env t = showEnv' env t False
617showEnvDbg env t = showEnv' env t True
619prettyEnv env t = prettyEnv' env t False
621 prettyEnv' env t dbg = prettySe 10 env t dbg
623 bracket outer inner p
624 | inner > outer = lparen <> p <> rparen
627 prettySe p env (P nt n t) debug =
630 lbrack <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbrack
633 prettySe p env (V i) debug
636 text . show . fst $ env!!i
638 lbrack <+> text (show i) <+> rbrack
639 | otherwise = text "unbound" <+> text (show i) <+> text "!"
640 prettySe p env (Bind n b@(Pi t) sc) debug
641 | noOccurrence n sc && not debug =
642 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
643 prettySe p env (Bind n b sc) debug =
644 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
645 prettySe p env (App f a) debug =
646 bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug
647 prettySe p env (Constant c) debug = pretty c
648 prettySe p env Erased debug = text "[_]"
649 prettySe p env (Set i) debug = text "Set" <+> (text . show $ i)
651 prettySb env n (Lam t) = prettyB env "λ" "=>" n t
652 prettySb env n (Hole t) = prettyB env "?defer" "." n t
653 prettySb env n (Pi t) = prettyB env "(" ") ->" n t
654 prettySb env n (PVar t) = prettyB env "pat" "." n t
655 prettySb env n (PVTy t) = prettyB env "pty" "." n t
656 prettySb env n (Let t v) = prettyBv env "let" "in" n t v
657 prettySb env n (Guess t v) = prettyBv env "??" "in" n t v
659 prettyB env op sc n t debug =
660 text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc
662 prettyBv env op sc n t v debug =
663 text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+>
664 prettySe 10 env v debug <> text sc
667showEnv' env t dbg = se 10 env t where
668 se p env (P nt n t) = show n
669 ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
670 se p env (V i) | i < length env = (show $ fst $ env!!i) ++
671 if dbg then "{" ++ show i ++ "}" else ""
672 | otherwise = "!!V " ++ show i ++ "!!"
673 se p env (Bind n b@(Pi t) sc)
674 | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
675 se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
676 se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
677 se p env (Constant c) = show c
678 se p env Erased = "[__]"
679 se p env (Set i) = "Set " ++ show i
681 sb env n (Lam t) = showb env "\\ " " => " n t
682 sb env n (Hole t) = showb env "? " ". " n t
683 sb env n (GHole t) = showb env "?defer " ". " n t
684 sb env n (Pi t) = showb env "(" ") -> " n t
685 sb env n (PVar t) = showb env "pat " ". " n t
686 sb env n (PVTy t) = showb env "pty " ". " n t
687 sb env n (Let t v) = showbv env "let " " in " n t v
688 sb env n (Guess t v) = showbv env "?? " " in " n t v
690 showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
691 showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
694 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
697-- Check whether a term has any holes in it - impure if so
699pureTerm :: TT n -> Bool
700pureTerm (App f a) = pureTerm f && pureTerm a
701pureTerm (Bind n b sc) = pureBinder b && pureTerm sc where
702 pureBinder (Hole _) = False
703 pureBinder (Guess _ _) = False
704 pureBinder (Let t v) = pureTerm t && pureTerm v
705 pureBinder t = pureTerm (binderTy t)
708-- weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings)
710weakenTm :: Int -> TT n -> TT n
711weakenTm i t = wk i 0 t
712 where wk i min (V x) | x >= min = V (i + x)
713 wk i m (App f a) = App (wk i m f) (wk i m a)
714 wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
716 wkb i m t = fmap (wk i m) t
718-- weaken an environment so that all the de Bruijn indices are correct according
719-- to the latest bound variable
721weakenEnv :: EnvTT n -> EnvTT n
722weakenEnv env = wk (length env - 1) env
724 wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
725 weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
726 weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
727 weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
729weakenTmEnv :: Int -> EnvTT n -> EnvTT n
730weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
732orderPats :: Term -> Term
733orderPats tm = op [] tm
735 op ps (Bind n (PVar t) sc) = op ((n, t) : ps) sc
736 op ps sc = bindAll (map (\ (n, t) -> (n, PVar t)) (sortP ps)) sc
738 sortP ps = pick [] (reverse ps)
740 namesIn (P _ n _) = [n]
741 namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
742 where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
743 nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
744 nb t = namesIn (binderTy t)
745 namesIn (App f a) = nub (namesIn f ++ namesIn a)
748 pick acc [] = reverse acc
749 pick acc ((n, t) : ps) = pick (insert n t acc) ps
751 insert n t [] = [(n, t)]
752 insert n t ((n',t') : ps)
753 | n `elem` (namesIn t' ++ concatMap namesIn (map snd ps))
754 = (n', t') : insert n t ps
755 | 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