@@ -1,953 +0,0 @@
1−-----------------------------------------------------------------------------
3−-- Module : Language.PureScript.TypeChecker.Types
4−-- Copyright : (c) Phil Freeman 2013
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
12−-- This module implements the type checker
14−-----------------------------------------------------------------------------
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE DeriveDataTypeable #-}
18−{-# LANGUAGE FlexibleContexts #-}
19−{-# LANGUAGE MultiParamTypeClasses #-}
21−module Language.PureScript.TypeChecker.Types (
26− The following functions represent the corresponding type checking judgements:
29− Synthesize a type for a value
32− Check a value has a given type
35− Check an object with a given type contains specified properties
37− checkFunctionApplication
38− Check a function of a given type returns a value of another type when applied to its arguments
41− Check a type subsumes another type
45−import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46−import qualified Data.Data as D
48− (everythingWithContext, mkM, everywhereM, everything, mkT,
49− something, everywhere, mkQ)
51−import Language.PureScript.Values
52−import Language.PureScript.Types
53−import Language.PureScript.Kinds
54−import Language.PureScript.Names
55−import Language.PureScript.TypeChecker.Monad
56−import Language.PureScript.TypeChecker.Kinds
57−import Language.PureScript.TypeChecker.Synonyms
58−import Language.PureScript.Pretty
60−import Control.Monad.State
61−import Control.Monad.Error
62−import Control.Monad.Reader
63−import Control.Monad.Unify
65−import Control.Applicative
66−import Control.Arrow (Arrow(..))
68−import qualified Data.Map as M
69−import Data.Function (on)
70−import Debug.Trace (trace)
72−instance Partial Type where
74− isUnknown (TUnknown u) = Just u
75− isUnknown _ = Nothing
77−instance Unifiable Check Type where
81−-- Unify two types, updating the current substitution
83−unifyTypes :: Type -> Type -> UnifyT Type Check ()
84−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
87− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
88− unifyTypes' (TUnknown u) t = u =:= t
89− unifyTypes' t (TUnknown u) = u =:= t
90− unifyTypes' (SaturatedTypeSynonym name args) ty = do
91− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
93− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
94− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
96− (Just sc1', Just sc2') -> do
97− sko <- newSkolemConstant
98− let sk1 = skolemize ident1 sko sc1' ty1
99− let sk2 = skolemize ident2 sko sc2' ty2
100− sk1 `unifyTypes` sk2
101− _ -> throwError (prettyPrintType ty1)
102− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
103− sko <- newSkolemConstant
104− let sk = skolemize ident sko sc ty1
106− unifyTypes' (ForAll _ _ _) _ = throwError "Skolem variable scope is unspecified"
107− unifyTypes' ty f@(ForAll _ _ _) = f `unifyTypes` ty
108− unifyTypes' (Object row1) (Object row2) = row1 =?= row2
109− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
110− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
112− Just moduleName <- checkCurrentModule <$> get
113− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
114− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
117− unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
118− unifyTypes' r1@(RCons _ _ _) r2 = unifyRows r1 r2
119− unifyTypes' r1 r2@(RCons _ _ _) = unifyRows r1 r2
120− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
121− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
122− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
125−-- Unify two rows, updating the current substitution
127−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
128−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
131−unifyRows :: Type -> Type -> UnifyT Type Check ()
134− (s1, r1') = rowToList r1
135− (s2, r2') = rowToList r2
136− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
137− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
138− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
140− forM_ int (uncurry (=?=))
141− unifyRows' sd1 r1' sd2 r2'
143− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
144− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
145− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
146− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
148− forM_ row $ \(_, t) -> occursCheck un t
150− u =?= RCons name ty u'
151− unifyRows' row r others u'
152− unifyRows' [] REmpty [] REmpty = return ()
153− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
154− unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
155− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
158−-- Ensure type constructors are equal after canonicalization
160−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
161−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
164−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
165−-- type class dictionaries and type annotations.
167−typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
168−typesOf moduleName vals = do
169− tys <- fmap tidyUp . liftUnify $ do
170− let es = map isTyped vals
171− typed = filter (isJust . snd . snd) es
172− untyped = filter (isNothing . snd . snd) es
173− typedDict = map (\(ident, (_, Just ty)) -> (ident, ty)) typed
174− untypedNames <- replicateM (length untyped) fresh
175− let untypedDict = zip (map fst untyped) untypedNames
176− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ (map (id *** fst) typedDict) ++ untypedDict)
178− triple@(_, (val, ty)) <- case e of
179− (ident, (val, Just (ty, checkType))) -> do
180− kind <- liftCheck $ kindOf moduleName ty
181− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
182− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
183− val' <- bindNames dict $ if checkType
184− then TypedValue True <$> check val ty' <*> pure ty'
185− else return (TypedValue False val ty')
186− return (ident, (val', ty'))
187− (ident, (val, Nothing)) -> do
188− TypedValue _ val' ty <- bindNames dict $ infer val
189− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
190− return (ident, (TypedValue True val' ty, ty))
191− when (moduleName == ModuleName (ProperName "Main") && fst e == Ident "main") $ do
192− [eff, a] <- replicateM 2 fresh
193− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName (ProperName "Eff"))) (ProperName "Eff"))) eff) a
196− forM tys $ \(ident, (val, ty)) -> do
197− val' <- replaceTypeClassDictionaries moduleName val
198− rethrow (("Error in " ++ show ident ++ ": \n") ++) $ skolemEscapeCheck val'
199− return $ (ident, (overTypes (desaturateAllTypeSynonyms . setifyAll) $ val'
200− , varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty))
202− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
205−-- Check if a value contains a type annotation
207−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
208−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
209−isTyped (name, value) = (name, (value, Nothing))
212−-- Map a function over type annotations appearing inside a value
214−overTypes :: (Type -> Type) -> Value -> Value
215−overTypes f = everywhere (mkT f)
218−-- Replace type class dictionary placeholders with inferred type class dictionaries
220−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
221−replaceTypeClassDictionaries mn = everywhereM (mkM go)
223− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
224− go other = return other
227−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
228−-- return a type class dictionary reference.
230−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
231−entails moduleName context goal@(className, ty) = do
234− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
235− (dict : _) -> return dict
237− go env (className', ty') =
238− [ mkDictionary (canonicalizeDictionary tcd) args
241− , typeConstructorsAreEqual env moduleName className' (tcdClassName tcd)
242− , subst <- maybeToList $ typeHeadsAreEqual moduleName env ty' (tcdInstanceType tcd)
243− , args <- solveSubgoals env subst (tcdDependencies tcd) ]
244− solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, Type)] -> [Maybe [Value]]
245− solveSubgoals _ _ Nothing = return Nothing
246− solveSubgoals env subst (Just subgoals) = do
247− dict <- mapM (go env) (replaceAllTypeVars subst subgoals)
249− mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
250− mkDictionary fnName Nothing = Var fnName
251− mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
252− filterModule :: TypeClassDictionaryInScope -> Bool
253− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
254− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
255− filterModule _ = False
256− canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
257− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
258− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
261−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
262−-- and return a substitution from type variables to types which makes the type heads unify.
264−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
265−typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
266−typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
267−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
268−typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | typeConstructorsAreEqual e m c1 c2 = Just []
269−typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
270−typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
271−typeHeadsAreEqual _ _ _ _ = Nothing
274−-- Ensure unsolved unification variables do not escape
276−escapeCheck :: Value -> Type -> UnifyT Type Check ()
277−escapeCheck value ty = do
278− subst <- unifyCurrentSubstitution <$> UnifyT get
279− let visibleUnknowns = nub $ unknowns $ subst $? ty
280− let allUnknowns = findAllTypes value
281− forM_ allUnknowns $ \t -> do
282− let unsolvedUnknowns = nub . unknowns $ subst $? t
283− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
286−-- Find all type annotations occuring inside a value
288−findAllTypes :: Value -> [Type]
289−findAllTypes = everything (++) (mkQ [] go)
291− go (TypedValue _ _ ty) = [ty]
295−-- Ensure skolem variables do not escape their scope
297−skolemEscapeCheck :: Value -> Check ()
298−skolemEscapeCheck (TypedValue False _ _) = return ()
299−skolemEscapeCheck root@(TypedValue _ _ _) =
300− case everythingWithContext [] (++) (mkQ ((,) []) go) root of
302− ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
304− go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
305− go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
306− go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
307− (sco : _) -> ([(findBindingScope sco, val)], scos)
310− collectSkolems :: Type -> [SkolemScope]
311− collectSkolems = nub . everything (++) (mkQ [] collect)
313− collect (Skolem _ scope) = [scope]
315− go _ scos = ([], scos)
316− findBindingScope :: SkolemScope -> Maybe Value
317− findBindingScope sco = something (mkQ Nothing go) root
319− go val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
321−skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
324−-- Ensure a row contains no duplicate labels
326−setify :: Type -> Type
327−setify = rowFromList . first (M.toList . M.fromList) . rowToList
330−-- \"Setify\" all rows occuring inside a value
332−setifyAll :: (D.Data d) => d -> d
333−setifyAll = everywhere (mkT setify)
336−-- Replace outermost unsolved unification variables with named type variables
338−varIfUnknown :: Type -> Type
340− let unks = nub $ unknowns ty
341− toName = (:) 't' . show
342− ty' = everywhere (mkT typeToVar) $ ty
343− typeToVar :: Type -> Type
344− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
346− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
349−-- Replace named type variables with types
351−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
352−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
355−-- Replace named type variables with new unification variables
357−instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
358−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
359− ty' <- replaceVarWithUnknown ident ty
360− instantiatePolyTypeWithUnknowns val ty'
361−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
363− Just moduleName <- checkCurrentModule <$> get
364− dicts <- getTypeClassDictionaries
365− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
366− return (foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints)), ty')
367−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
370−-- Replace a single type variable with a new unification variable
372−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
373−replaceVarWithUnknown ident ty = do
375− return $ replaceTypeVars ident tu $ ty
378−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
379−-- better error messages during unification.
381−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
382−replaceAllTypeSynonyms d = do
384− Just moduleName <- checkCurrentModule <$> get
385− let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
386− either throwError return $ saturateAllTypeSynonyms env moduleName syns d
389−-- \"Desaturate\" @SaturatedTypeSynonym@s
391−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
392−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
394− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
395− replaceSaturatedTypeSynonym t = t
398−-- Replace a type synonym and its arguments with the aliased type
400−expandTypeSynonym :: Qualified ProperName -> [Type] -> UnifyT Type Check Type
401−expandTypeSynonym name args = do
403− Just moduleName <- checkCurrentModule <$> get
404− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
405− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
406− Nothing -> error "Type synonym was not defined"
409−-- Ensure a set of property names and value does not contain duplicate labels
411−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
412−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
415−-- Infer a type for a value, rethrowing any error to provide a more useful error message
417−infer :: Value -> UnifyT Type Check Value
418−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
421−-- Infer a type for a value
423−infer' :: Value -> UnifyT Type Check Value
424−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
425−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
426−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
427−infer' (ArrayLiteral vals) = do
428− ts <- mapM infer vals
430− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
431− return $ TypedValue True (ArrayLiteral ts) els
432−infer' (ObjectLiteral ps) = do
433− ensureNoDuplicateProperties ps
434− ts <- mapM (infer . snd) ps
435− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
436− ty = Object $ rowFromList (fields, REmpty)
437− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
438−infer' (ObjectUpdate o ps) = do
439− ensureNoDuplicateProperties ps
441− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
442− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
443− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
444− let oldTy = Object $ rowFromList (oldTys, row)
445− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
446− return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
447−infer' (Accessor prop val) = do
448− typed@(TypedValue _ _ objTy) <- infer val
449− propTy <- inferProperty objTy prop
454− _ <- subsumes Nothing objTy (Object (RCons prop field rest))
455− return $ TypedValue True (Accessor prop typed) field
456− Just ty -> return $ TypedValue True (Accessor prop typed) ty
457−infer' (Abs arg ret) = do
459− Just moduleName <- checkCurrentModule <$> get
460− bindLocalVariables moduleName [(arg, ty)] $ do
461− body@(TypedValue _ _ bodyTy) <- infer' ret
462− return $ TypedValue True (Abs arg body) $ function ty bodyTy
463−infer' (App f arg) = do
464− f'@(TypedValue _ _ ft) <- infer f
465− (ret, app) <- checkFunctionApplication f' ft arg
466− return $ TypedValue True app ret
467−infer' (Var var) = do
468− Just moduleName <- checkCurrentModule <$> get
469− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
471− ConstrainedType constraints ty' -> do
473− dicts <- getTypeClassDictionaries
474− return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) ty'
475− _ -> return $ TypedValue True (Var var) ty
476−infer' (Block ss) = do
478− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
479− guardWith "Block is missing a return statement" allCodePathsReturn
480− return $ TypedValue True (Block ss') ret
481−infer' v@(Constructor c) = do
483− Just moduleName <- checkCurrentModule <$> get
484− case M.lookup (qualify moduleName c) (dataConstructors env) of
485− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
486− Just (ty, _) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
487− return $ TypedValue True v ty'
488−infer' (Case vals binders) = do
489− ts <- mapM infer vals
491− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
492− return $ TypedValue True (Case ts binders') ret
493−infer' (IfThenElse cond th el) = do
494− cond' <- check cond tyBoolean
495− v2@(TypedValue _ _ t2) <- infer th
496− v3@(TypedValue _ _ t3) <- infer el
498− return $ TypedValue True (IfThenElse cond' v2 v3) t2
499−infer' (TypedValue checkType val ty) = do
500− Just moduleName <- checkCurrentModule <$> get
501− kind <- liftCheck $ kindOf moduleName ty
502− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
503− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
504− val' <- if checkType then check val ty' else return val
505− return $ TypedValue True val' ty'
506−infer' _ = error "Invalid argument to infer"
509−-- Infer the type of a property inside a record with a given type
511−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
512−inferProperty (Object row) prop = do
513− let (props, _) = rowToList row
514− return $ lookup prop props
515−inferProperty (SaturatedTypeSynonym name args) prop = do
516− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
517− inferProperty replaced prop
518−inferProperty (ForAll ident ty _) prop = do
519− replaced <- replaceVarWithUnknown ident ty
520− inferProperty replaced prop
521−inferProperty _ _ = return Nothing
524−-- Infer the types of variables brought into scope by a binder
526−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
527−inferBinder _ NullBinder = return M.empty
528−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
529−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
530−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
531−inferBinder val (VarBinder name) = return $ M.singleton name val
532−inferBinder val (NullaryBinder ctor) = do
534− Just moduleName <- checkCurrentModule <$> get
535− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
537− _ <- subsumes Nothing ty val
539− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
540−inferBinder val (UnaryBinder ctor binder) = do
542− Just moduleName <- checkCurrentModule <$> get
543− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
545− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contains constraints") ty
547− TypeApp (TypeApp t obj) ret | t == tyFunction -> do
548− _ <- subsumes Nothing val ret
549− inferBinder obj binder
550− _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
551− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
552−inferBinder val (ObjectBinder props) = do
555− m1 <- inferRowProperties row rest props
559− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
560− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
561− inferRowProperties nrow row ((name, binder):binders) = do
563− m1 <- inferBinder propTy binder
564− m2 <- inferRowProperties nrow (RCons name propTy row) binders
565− return $ m1 `M.union` m2
566−inferBinder val (ArrayBinder binders) = do
568− m1 <- M.unions <$> mapM (inferBinder el) binders
569− val =?= TypeApp tyArray el
571−inferBinder val (ConsBinder headBinder tailBinder) = do
573− m1 <- inferBinder el headBinder
574− m2 <- inferBinder val tailBinder
575− val =?= TypeApp tyArray el
576− return $ m1 `M.union` m2
577−inferBinder val (NamedBinder name binder) = do
578− m <- inferBinder val binder
579− return $ M.insert name val m
582−-- Check the types of the return values in a set of binders in a case statement
584−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Type Check [([Binder], Maybe Guard, Value)]
585−checkBinders _ _ [] = return []
586−checkBinders nvals ret ((binders, grd, val):bs) = do
587− Just moduleName <- checkCurrentModule <$> get
588− m1 <- M.unions <$> zipWithM inferBinder nvals binders
589− r <- bindLocalVariables moduleName (M.toList m1) $ do
590− val' <- TypedValue True <$> check val ret <*> pure ret
592− Nothing -> return (binders, Nothing, val')
594− g' <- check g tyBoolean
595− return (binders, Just g', val')
596− rs <- checkBinders nvals ret bs
600−-- Check that a local variable name is not already used
602−assignVariable :: Ident -> UnifyT Type Check ()
603−assignVariable name = do
604− env <- checkEnv <$> get
605− Just moduleName <- checkCurrentModule <$> get
606− case M.lookup (moduleName, name) (names env) of
607− Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
611−-- Check the type of the return values of a statement, returning whether or not the statement returns on
614−checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Type Check (Bool, M.Map Ident Type, Statement)
615−checkStatement mass _ (VariableIntroduction name val) = do
617− val'@(TypedValue _ _ t) <- infer val
618− return (False, M.insert name t mass, VariableIntroduction name val')
619−checkStatement mass _ (Assignment ident val) = do
620− val'@(TypedValue _ _ t) <- infer val
621− case M.lookup ident mass of
622− Nothing -> throwError $ "No local variable with name " ++ show ident
623− Just ty -> do t =?= ty
624− return (False, mass, Assignment ident val')
625−checkStatement mass ret (While val inner) = do
626− val' <- check val tyBoolean
627− (allCodePathsReturn, _, inner') <- checkBlock mass ret inner
628− return (allCodePathsReturn, mass, While val' inner')
629−checkStatement mass ret (If ifst) = do
630− (allCodePathsReturn, ifst') <- checkIfStatement mass ret ifst
631− return (allCodePathsReturn, mass, If ifst')
632−checkStatement mass ret (For ident start end inner) = do
633− Just moduleName <- checkCurrentModule <$> get
634− assignVariable ident
635− start' <- check start tyNumber
636− end' <- check end tyNumber
637− (allCodePathsReturn, _, inner') <- bindLocalVariables moduleName [(ident, tyNumber)] $ checkBlock mass ret inner
638− return (allCodePathsReturn, mass, For ident start' end' inner')
639−checkStatement mass ret (Return val) = do
640− val' <- check val ret
641− return (True, mass, Return (TypedValue True val' ret))
644−-- Check the type of an if-then-else statement
646−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> UnifyT Type Check (Bool, IfStatement)
647−checkIfStatement mass ret (IfStatement val thens Nothing) = do
648− val' <- check val tyBoolean
649− (_, _, thens') <- checkBlock mass ret thens
650− return (False, IfStatement val' thens' Nothing)
651−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
652− val' <- check val tyBoolean
653− (allCodePathsReturn1, _, thens') <- checkBlock mass ret thens
654− (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
655− return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
658−-- Check the type of an else statement
660−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> UnifyT Type Check (Bool, ElseStatement)
661−checkElseStatement mass ret (Else elses) = do
662− (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
663− return (allCodePathsReturn, Else elses')
664−checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
667−-- Check the type of the return value of a block of statements
669−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> UnifyT Type Check (Bool, M.Map Ident Type, [Statement])
670−checkBlock mass _ [] = return (False, mass, [])
671−checkBlock mass ret (s:ss) = do
672− Just moduleName <- checkCurrentModule <$> get
673− (b1, mass1, s') <- checkStatement mass ret s
674− bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
675− (True, []) -> return (True, mass1, [s'])
676− (True, _) -> throwError "Unreachable code"
678− (b, m, ss'') <- checkBlock mass1 ret ss'
679− return (b, m, s':ss'')
682−-- Generate a new skolem constant
684−newSkolemConstant :: UnifyT Type Check Int
685−newSkolemConstant = runUnknown <$> fresh'
688−-- Generate a new skolem scope
690−newSkolemScope :: UnifyT Type Check SkolemScope
691−newSkolemScope = SkolemScope . runUnknown <$> fresh'
694−-- Skolemize a type variable by replacing its instances with fresh skolem constants
696−skolemize :: (D.Data d) => String -> Int -> SkolemScope -> d -> d
697−skolemize ident sko scope d = replaceTypeVars ident (Skolem sko scope) d
700−-- Introduce skolem scope at every occurence of a ForAll
702−introduceSkolemScope :: Type -> UnifyT Type Check Type
703−introduceSkolemScope = everywhereM (mkM go)
705− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
706− go other = return other
709−-- Check the type of a value, rethrowing errors to provide a better error message
711−check :: Value -> Type -> UnifyT Type Check Value
712−check val ty = rethrow errorMessage $ check' val ty
715− "Error checking type of term " ++
716− prettyPrintValue val ++
718− prettyPrintType ty ++
723−-- Check the type of a value
725−check' :: Value -> Type -> UnifyT Type Check Value
726−check' val t@(ForAll ident ty _) = do
727− scope <- newSkolemScope
728− sko <- newSkolemConstant
729− let sk = skolemize ident sko scope ty
730− val' <- check val sk
731− return $ TypedValue True val' (ForAll ident ty (Just scope))
732−check' val t@(ConstrainedType constraints ty) = do
734− Just moduleName <- checkCurrentModule <$> get
735− dictNames <- flip mapM constraints $ \(Qualified _ (ProperName className), _) -> do
736− n <- liftCheck freshDictionaryName
737− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
738− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
739− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
740− (qualifyAllUnqualifiedNames moduleName env constraints)) $
742− return $ TypedValue True (foldr Abs val' dictNames) t
743−check' val t@(SaturatedTypeSynonym name args) = do
744− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
745− val' <- check val ty
746− return $ TypedValue True val' ty
747−check' val u@(TUnknown _) = do
748− val'@(TypedValue _ _ ty) <- infer val
749− -- Don't unify an unknown with an inferred polytype
750− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
752− return $ TypedValue True val'' ty'
753−check' v@(NumericLiteral _) t | t == tyNumber =
754− return $ TypedValue True v t
755−check' v@(StringLiteral _) t | t == tyString =
756− return $ TypedValue True v t
757−check' v@(BooleanLiteral _) t | t == tyBoolean =
758− return $ TypedValue True v t
759−check' (ArrayLiteral vals) t@(TypeApp a ty) | a == tyArray = do
760− arr <- ArrayLiteral <$> forM vals (\val -> check val ty)
761− return $ TypedValue True arr t
762−check' (Abs arg ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
763− Just moduleName <- checkCurrentModule <$> get
764− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
765− return $ TypedValue True (Abs arg ret') ty
766−check' (App f arg) ret = do
767− f'@(TypedValue _ _ ft) <- infer f
768− (ret', app) <- checkFunctionApplication f' ft arg
769− subsumes Nothing ret' ret
770− return $ TypedValue True app ret
771−check' v@(Var var) ty = do
772− Just moduleName <- checkCurrentModule <$> get
773− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
774− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
775− v' <- subsumes (Just v) repl ty'
777− Nothing -> throwError "Unable to check type subsumption"
778− Just v'' -> return $ TypedValue True v'' ty'
779−check' (TypedValue checkType val ty1) ty2 = do
780− Just moduleName <- checkCurrentModule <$> get
781− kind <- liftCheck $ kindOf moduleName ty1
782− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
783− val' <- subsumes (Just val) ty1 ty2
785− Nothing -> throwError "Unable to check type subsumption"
787− val''' <- if checkType then check val'' ty1 else return val''
788− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
789−check' (Case vals binders) ret = do
790− vals' <- mapM infer vals
791− let ts = map (\(TypedValue _ _ t) -> t) vals'
792− binders' <- checkBinders ts ret binders
793− return $ TypedValue True (Case vals' binders') ret
794−check' (IfThenElse cond th el) ty = do
795− cond' <- check cond tyBoolean
798− return $ TypedValue True (IfThenElse cond' th' el') ty
799−check' (ObjectLiteral ps) t@(Object row) = do
800− ensureNoDuplicateProperties ps
801− ps' <- checkProperties ps row False
802− return $ TypedValue True (ObjectLiteral ps') t
803−check' (ObjectUpdate obj ps) t@(Object row) = do
804− ensureNoDuplicateProperties ps
805− us <- zip (map fst ps) <$> replicateM (length ps) fresh
806− let (propsToCheck, rest) = rowToList row
807− propsToRemove = map fst ps
808− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
809− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
810− ps' <- checkProperties ps row True
811− return $ TypedValue True (ObjectUpdate obj' ps') t
812−check' (Accessor prop val) ty = do
814− val' <- check val (Object (RCons prop ty rest))
815− return $ TypedValue True (Accessor prop val') ty
816−check' (Block ss) ret = do
817− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
818− guardWith "Block is missing a return statement" allCodePathsReturn
819− return $ TypedValue True (Block ss') ret
820−check' (Constructor c) ty = do
822− Just moduleName <- checkCurrentModule <$> get
823− case M.lookup (qualify moduleName c) (dataConstructors env) of
824− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
826− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
827− _ <- subsumes Nothing repl ty
828− return $ TypedValue True (Constructor c) ty
829−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
832−-- Check the type of a collection of named record fields
834−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
836−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
837−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
838− go [] [] REmpty = return []
839− go [] [] u@(TUnknown _) = do u =?= REmpty
841− go [] [] (Skolem _ _) | lax = return []
842− go [] ((p, _): _) _ | lax = return []
843− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
844− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
845− go ((p,v):ps') [] u@(TUnknown _) = do
846− v'@(TypedValue _ _ ty) <- infer v
848− u =?= RCons p ty rest
849− ps'' <- go ps' [] rest
850− return $ (p, v') : ps''
851− go ((p,v):ps') ts r =
854− v'@(TypedValue _ _ ty) <- infer v
856− r =?= RCons p ty rest
857− ps'' <- go ps' ts rest
858− return $ (p, v') : ps''
861− ps'' <- go ps' (delete (p, ty) ts) r
862− return $ (p, v') : ps''
863− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
866−-- Check the type of a function application, rethrowing errors to provide a better error message
868−checkFunctionApplication :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
869−checkFunctionApplication fn fnTy arg = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg
871− errorMessage msg = "Error applying function of type "
872− ++ prettyPrintType fnTy
873− ++ " to argument " ++ prettyPrintValue arg
877−-- Check the type of a function application
879−checkFunctionApplication' :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
880−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg = do
881− tyFunction' =?= tyFunction
882− arg' <- check arg argTy
883− return (retTy, App fn arg')
884−checkFunctionApplication' fn (ForAll ident ty _) arg = do
885− replaced <- replaceVarWithUnknown ident ty
886− checkFunctionApplication fn replaced arg
887−checkFunctionApplication' fn u@(TUnknown _) arg = do
889− TypedValue _ v t <- infer arg
890− (v', t') <- instantiatePolyTypeWithUnknowns arg t
891− return $ TypedValue True v' t'
892− let ty = (\(TypedValue _ _ t) -> t) arg'
894− u =?= function ty ret
895− return (ret, App fn arg')
896−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg = do
897− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
898− checkFunctionApplication fn ty arg
899−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg = do
901− dicts <- getTypeClassDictionaries
902− Just moduleName <- checkCurrentModule <$> get
903− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy arg
904−checkFunctionApplication' _ fnTy arg = throwError $ "Cannot apply a function of type "
905− ++ prettyPrintType fnTy
906− ++ " to argument " ++ prettyPrintValue arg
909−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
911−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
912−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
914− errorMessage msg = "Error checking that type "
915− ++ prettyPrintType ty1
916− ++ " subsumes type "
917− ++ prettyPrintType ty2
921−-- Check whether one type subsumes another
923−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
924−subsumes' val (ForAll ident ty1 _) ty2 = do
925− replaced <- replaceVarWithUnknown ident ty1
926− subsumes val replaced ty2
927−subsumes' val ty1 (ForAll ident ty2 sco) =
930− sko <- newSkolemConstant
931− let sk = skolemize ident sko sco' ty2
933− Nothing -> throwError "Skolem variable scope is unspecified"
934−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
935− subsumes Nothing arg2 arg1
936− subsumes Nothing ret1 ret2
938−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
939− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
940− subsumes val ty1 ty2
941−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
942− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
943− subsumes val ty1 ty2
944−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
946− dicts <- getTypeClassDictionaries
947− Just moduleName <- checkCurrentModule <$> get
948− _ <- subsumes' Nothing ty1 ty2
949− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
950−subsumes' val ty1 ty2 = do