@@ -0,0 +1,925 @@
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 FlexibleContexts #-}
18+{-# LANGUAGE MultiParamTypeClasses #-}
20+module Language.PureScript.TypeChecker.Types (
25+ The following functions represent the corresponding type checking judgements:
28+ Synthesize a type for a value
31+ Check a value has a given type
34+ Check an object with a given type contains specified properties
36+ checkFunctionApplication
37+ Check a function of a given type returns a value of another type when applied to its arguments
40+ Check a type subsumes another type
44+import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
45+import qualified Data.Data as D
47+ (everythingWithContext, mkM, everywhereM, everything, mkT,
48+ something, everywhere, mkQ)
49+import Data.Generics.Extras
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
59+import Language.PureScript.Prim
61+import Control.Monad.State
62+import Control.Monad.Error
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 Data.Ord (comparing)
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) $
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) =
111+ guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (c1 == c2)
112+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
115+ unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
116+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
117+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
118+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
119+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
120+ unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
123+-- Unify two rows, updating the current substitution
125+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
126+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
129+unifyRows :: Type -> Type -> UnifyT Type Check ()
132+ (s1, r1') = rowToList r1
133+ (s2, r2') = rowToList r2
134+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
135+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
136+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
138+ forM_ int (uncurry (=?=))
139+ unifyRows' sd1 r1' sd2 r2'
141+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
142+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
143+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
144+ unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
146+ forM_ row $ \(_, t) -> occursCheck un t
148+ u =?= RCons name ty u'
149+ unifyRows' row r others u'
150+ unifyRows' [] REmpty [] REmpty = return ()
151+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
152+ unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
153+ unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")."
156+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
157+-- type class dictionaries and type annotations.
159+typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
160+typesOf mainModuleName moduleName vals = do
161+ tys <- fmap tidyUp . liftUnify $ do
163+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
164+ es = map isTyped vals
165+ -- Filter the typed and untyped declarations
166+ typed = filter (isJust . snd . snd) es
167+ untyped = filter (isNothing . snd . snd) es
168+ -- Make a map of names to typed declarations
169+ typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
170+ -- Create fresh unification variables for the types of untyped declarations
171+ untypedNames <- replicateM (length untyped) fresh
173+ -- Make a map of names to the unification variables of untyped declarations
174+ untypedDict = zip (map fst untyped) untypedNames
175+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
176+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
177+ forM es $ \e@(_, (val, _)) -> do
178+ -- If the declaration is a function, it has access to other values in the binding group.
179+ -- If not, the generated code might fail at runtime since those values might be undefined.
180+ let dict' = if isFunction val then dict else M.empty
181+ triple@(_, (val', ty)) <- case e of
182+ -- Typed declarations
183+ (ident, (val', Just (ty, checkType))) -> do
185+ kind <- liftCheck $ kindOf moduleName ty
186+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
187+ -- Check the type with the new names in scope
188+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
189+ val'' <- bindNames dict' $ if checkType
190+ then TypedValue True <$> check val' ty' <*> pure ty'
191+ else return (TypedValue False val' ty')
192+ return (ident, (val'', ty'))
193+ -- Untyped declarations
194+ (ident, (val', Nothing)) -> do
195+ -- Infer the type with the new names in scope
196+ TypedValue _ val'' ty <- bindNames dict' $ infer val'
197+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
198+ return (ident, (TypedValue True val'' ty, ty))
199+ -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
200+ when (Just moduleName == mainModuleName && fst e == Ident "main") $ do
201+ [eff, a] <- replicateM 2 fresh
202+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
203+ -- Make sure unification variables do not escape
206+ forM tys $ \(ident, (val, ty)) -> do
207+ -- Replace type class dictionary placeholders with actual dictionaries
208+ val' <- replaceTypeClassDictionaries moduleName val
209+ -- Check skolem variables did not escape their scope
210+ skolemEscapeCheck val'
211+ -- Remove type synonyms placeholders, remove duplicate row fields, and replace
212+ -- top-level unification variables with named type variables.
213+ let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
214+ ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
215+ return (ident, (val'', ty'))
217+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
218+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
221+-- Check if a value introduces a function
223+isFunction :: Value -> Bool
224+isFunction (Abs _ _) = True
225+isFunction (TypedValue _ val _) = isFunction val
229+-- Check if a value contains a type annotation
231+isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
232+isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
233+isTyped (name, value) = (name, (value, Nothing))
236+-- Map a function over type annotations appearing inside a value
238+overTypes :: (Type -> Type) -> Value -> Value
239+overTypes f = everywhere (mkT f)
242+-- Replace type class dictionary placeholders with inferred type class dictionaries
244+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
245+replaceTypeClassDictionaries mn = everywhereM' (mkM go)
247+ go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
248+ go other = return other
251+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
252+-- return a type class dictionary reference.
254+entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Check Value
255+entails moduleName context goal@(className, tys) = do
258+ [] -> throwError $ "No " ++ show className ++ " instance found for " ++ intercalate ", " (map prettyPrintType tys)
259+ (dict : _) -> return dict
261+ go env (className', tys') =
262+ [ mkDictionary (canonicalizeDictionary tcd) args
264+ -- Choose type class dictionaries in scope in the current module
266+ -- Make sure the type class name matches the one we are trying to satisfy
267+ , className' == tcdClassName tcd
268+ -- Make sure the type unifies with the type in the type instance definition
269+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
270+ -- Solve any necessary subgoals
271+ , args <- solveSubgoals env subst (tcdDependencies tcd) ]
272+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
273+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
274+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
275+ solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [Value]]
276+ solveSubgoals _ _ Nothing = return Nothing
277+ solveSubgoals env subst (Just subgoals) = do
278+ dict <- mapM (go env . second (map (replaceAllTypeVars subst))) subgoals
280+ -- Make a dictionary from subgoal dictionaries by applying the correct function
281+ mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
282+ mkDictionary fnName Nothing = Var fnName
283+ mkDictionary fnName (Just []) = App (Var fnName) (ObjectLiteral [])
284+ mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
285+ -- Filter out type dictionaries which are in scope in the current module
286+ filterModule :: TypeClassDictionaryInScope -> Bool
287+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
288+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
289+ filterModule _ = False
290+ canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
291+ canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
292+ canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
293+ -- Ensure that a substitution is valid
294+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
295+ verifySubstitution subst = do
296+ let grps = groupBy ((==) `on` fst) subst
297+ guard (all ((==) 1 . length . nubBy ((==) `on` snd)) grps)
298+ return $ map head grps
301+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
302+-- and return a substitution from type variables to types which makes the type heads unify.
304+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
305+typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
306+typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
307+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
308+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
309+typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
310+typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
311+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
313+ Right t1 -> typeHeadsAreEqual m e t1 t2
314+typeHeadsAreEqual _ _ _ _ = Nothing
317+-- Ensure unsolved unification variables do not escape
319+escapeCheck :: Value -> Type -> UnifyT Type Check ()
320+escapeCheck value ty = do
321+ subst <- unifyCurrentSubstitution <$> UnifyT get
322+ let visibleUnknowns = nub $ unknowns $ subst $? ty
323+ let allUnknowns = findAllTypes value
324+ forM_ allUnknowns $ \t -> do
325+ let unsolvedUnknowns = nub . unknowns $ subst $? t
326+ guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
329+-- Find all type annotations occuring inside a value
331+findAllTypes :: Value -> [Type]
332+findAllTypes = everything (++) (mkQ [] go)
334+ go (TypedValue _ _ ty) = [ty]
338+-- Ensure skolem variables do not escape their scope
340+skolemEscapeCheck :: Value -> Check ()
341+skolemEscapeCheck (TypedValue False _ _) = return ()
342+skolemEscapeCheck root@TypedValue{} =
343+ -- Every skolem variable is created when a ForAll type is skolemized.
344+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
345+ -- field of the ForAll constructor.
346+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
347+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
348+ -- an escaped skolem variable.
349+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
351+ ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
353+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
354+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
355+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
356+ (sco : _) -> ([(findBindingScope sco, val)], scos)
359+ collectSkolems :: Type -> [SkolemScope]
360+ collectSkolems = nub . everything (++) (mkQ [] collect)
362+ collect (Skolem _ scope) = [scope]
364+ go _ scos = ([], scos)
365+ findBindingScope :: SkolemScope -> Maybe Value
366+ findBindingScope sco = something (mkQ Nothing go') root
368+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
370+skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
373+-- Ensure a row contains no duplicate labels
375+setify :: Type -> Type
376+setify = rowFromList . first (M.toList . M.fromList) . rowToList
379+-- \"Setify\" all rows occuring inside a value
381+setifyAll :: (D.Data d) => d -> d
382+setifyAll = everywhere (mkT setify)
385+-- Replace outermost unsolved unification variables with named type variables
387+varIfUnknown :: Type -> Type
389+ let unks = nub $ unknowns ty
390+ toName = (:) 't' . show
391+ ty' = everywhere (mkT typeToVar) ty
392+ typeToVar :: Type -> Type
393+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
395+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
398+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
399+-- or TypeClassDictionary values.
401+-- This is necessary during type checking to avoid unifying a polymorphic type with a
402+-- unification variable.
404+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
405+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
406+ ty' <- replaceVarWithUnknown ident ty
407+ instantiatePolyTypeWithUnknowns val ty'
408+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
409+ dicts <- getTypeClassDictionaries
410+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
411+ return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
412+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
415+-- Replace a single type variable with a new unification variable
417+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
418+replaceVarWithUnknown ident ty = do
420+ return $ replaceTypeVars ident tu ty
423+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
424+-- better error messages during unification.
426+replaceAllTypeSynonyms' :: (D.Data d) => Environment -> d -> Either String d
427+replaceAllTypeSynonyms' env d =
429+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
431+ saturateAllTypeSynonyms syns d
433+replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
434+replaceAllTypeSynonyms d = do
436+ either throwError return $ replaceAllTypeSynonyms' env d
439+-- \"Desaturate\" @SaturatedTypeSynonym@s
441+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
442+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
444+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
445+ replaceSaturatedTypeSynonym t = t
448+-- Replace a type synonym and its arguments with the aliased type
450+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
451+expandTypeSynonym' env name args =
452+ case M.lookup name (typeSynonyms env) of
453+ Just (synArgs, body) -> do
454+ let repl = replaceAllTypeVars (zip synArgs args) body
455+ replaceAllTypeSynonyms' env repl
456+ Nothing -> error "Type synonym was not defined"
458+expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
459+expandTypeSynonym name args = do
461+ either throwError return $ expandTypeSynonym' env name args
464+-- Ensure a set of property names and value does not contain duplicate labels
466+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
467+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
470+-- Infer a type for a value, rethrowing any error to provide a more useful error message
472+infer :: Value -> UnifyT Type Check Value
473+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
476+-- Infer a type for a value
478+infer' :: Value -> UnifyT Type Check Value
479+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
480+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
481+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
482+infer' (ArrayLiteral vals) = do
483+ ts <- mapM infer vals
485+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
486+ return $ TypedValue True (ArrayLiteral ts) els
487+infer' (ObjectLiteral ps) = do
488+ ensureNoDuplicateProperties ps
489+ ts <- mapM (infer . snd) ps
490+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
491+ ty = Object $ rowFromList (fields, REmpty)
492+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
493+infer' (ObjectUpdate o ps) = do
494+ ensureNoDuplicateProperties ps
496+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
497+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
498+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
499+ let oldTy = Object $ rowFromList (oldTys, row)
500+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
501+ return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
502+infer' (Accessor prop val) = do
503+ typed@(TypedValue _ _ objTy) <- infer val
504+ propTy <- inferProperty objTy prop
509+ _ <- subsumes Nothing objTy (Object (RCons prop field rest))
510+ return $ TypedValue True (Accessor prop typed) field
511+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
512+infer' (Abs (Left arg) ret) = do
514+ Just moduleName <- checkCurrentModule <$> get
515+ bindLocalVariables moduleName [(arg, ty)] $ do
516+ body@(TypedValue _ _ bodyTy) <- infer' ret
517+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
518+infer' (Abs (Right _) _) = error "Binder was not desugared"
519+infer' (App f arg) = do
520+ f'@(TypedValue _ _ ft) <- infer f
521+ (ret, app) <- checkFunctionApplication f' ft arg
522+ return $ TypedValue True app ret
523+infer' (Var var) = do
524+ Just moduleName <- checkCurrentModule <$> get
525+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
527+ ConstrainedType constraints ty' -> do
528+ dicts <- getTypeClassDictionaries
529+ return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) constraints)) ty'
530+ _ -> return $ TypedValue True (Var var) ty
531+infer' v@(Constructor c) = do
533+ case M.lookup c (dataConstructors env) of
534+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
535+ Just ty -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
536+ return $ TypedValue True v ty'
537+infer' (Case vals binders) = do
538+ ts <- mapM infer vals
540+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
541+ return $ TypedValue True (Case ts binders') ret
542+infer' (IfThenElse cond th el) = do
543+ cond' <- check cond tyBoolean
544+ v2@(TypedValue _ _ t2) <- infer th
545+ v3@(TypedValue _ _ t3) <- infer el
547+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
548+infer' (TypedValue checkType val ty) = do
549+ Just moduleName <- checkCurrentModule <$> get
550+ kind <- liftCheck $ kindOf moduleName ty
551+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
552+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
553+ val' <- if checkType then check val ty' else return val
554+ return $ TypedValue True val' ty'
555+infer' _ = error "Invalid argument to infer"
558+-- Infer the type of a property inside a record with a given type
560+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
561+inferProperty (Object row) prop = do
562+ let (props, _) = rowToList row
563+ return $ lookup prop props
564+inferProperty (SaturatedTypeSynonym name args) prop = do
565+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
566+ inferProperty replaced prop
567+inferProperty (ForAll ident ty _) prop = do
568+ replaced <- replaceVarWithUnknown ident ty
569+ inferProperty replaced prop
570+inferProperty _ _ = return Nothing
573+-- Infer the types of variables brought into scope by a binder
575+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
576+inferBinder _ NullBinder = return M.empty
577+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
578+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
579+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
580+inferBinder val (VarBinder name) = return $ M.singleton name val
581+inferBinder val (ConstructorBinder ctor binders) = do
583+ case M.lookup ctor (dataConstructors env) of
585+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contains constraints") ty
589+ _ <- subsumes Nothing val ty'
591+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
592+ M.union <$> inferBinder obj binder <*> go binders' ret
593+ go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
594+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
595+inferBinder val (ObjectBinder props) = do
598+ m1 <- inferRowProperties row rest props
602+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
603+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
604+ inferRowProperties nrow row ((name, binder):binders) = do
606+ m1 <- inferBinder propTy binder
607+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
608+ return $ m1 `M.union` m2
609+inferBinder val (ArrayBinder binders) = do
611+ m1 <- M.unions <$> mapM (inferBinder el) binders
612+ val =?= TypeApp tyArray el
614+inferBinder val (ConsBinder headBinder tailBinder) = do
616+ m1 <- inferBinder el headBinder
617+ m2 <- inferBinder val tailBinder
618+ val =?= TypeApp tyArray el
619+ return $ m1 `M.union` m2
620+inferBinder val (NamedBinder name binder) = do
621+ m <- inferBinder val binder
622+ return $ M.insert name val m
625+-- Check the types of the return values in a set of binders in a case statement
627+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
628+checkBinders _ _ [] = return []
629+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
630+ Just moduleName <- checkCurrentModule <$> get
631+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
632+ r <- bindLocalVariables moduleName (M.toList m1) $ do
633+ val' <- TypedValue True <$> check val ret <*> pure ret
635+ Nothing -> return $ CaseAlternative binders Nothing val'
637+ g' <- check g tyBoolean
638+ return $ CaseAlternative binders (Just g') val'
639+ rs <- checkBinders nvals ret bs
643+-- Generate a new skolem constant
645+newSkolemConstant :: UnifyT Type Check Int
646+newSkolemConstant = runUnknown <$> fresh'
649+-- Generate a new skolem scope
651+newSkolemScope :: UnifyT Type Check SkolemScope
652+newSkolemScope = SkolemScope . runUnknown <$> fresh'
655+-- Skolemize a type variable by replacing its instances with fresh skolem constants
657+skolemize :: String -> Int -> SkolemScope -> Type -> Type
658+skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
661+-- Introduce skolem scope at every occurence of a ForAll
663+introduceSkolemScope :: Type -> UnifyT Type Check Type
664+introduceSkolemScope = everywhereM (mkM go)
666+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
667+ go other = return other
670+-- Check the type of a value, rethrowing errors to provide a better error message
672+check :: Value -> Type -> UnifyT Type Check Value
673+check val ty = rethrow errorMessage $ check' val ty
676+ "Error checking type of term " ++
677+ prettyPrintValue val ++
679+ prettyPrintType ty ++
684+-- Check the type of a value
686+check' :: Value -> Type -> UnifyT Type Check Value
687+check' val (ForAll ident ty _) = do
688+ scope <- newSkolemScope
689+ sko <- newSkolemConstant
690+ let sk = skolemize ident sko scope ty
691+ val' <- check val sk
692+ return $ TypedValue True val' (ForAll ident ty (Just scope))
693+check' val t@(ConstrainedType constraints ty) = do
694+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
695+ n <- liftCheck freshDictionaryName
696+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
697+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
698+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
699+ constraints) $ check val ty
700+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
701+check' val (SaturatedTypeSynonym name args) = do
702+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
703+ val' <- check val ty
704+ return $ TypedValue True val' ty
705+check' val u@(TUnknown _) = do
706+ val'@(TypedValue _ _ ty) <- infer val
707+ -- Don't unify an unknown with an inferred polytype
708+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
710+ return $ TypedValue True val'' ty'
711+check' v@(NumericLiteral _) t | t == tyNumber =
712+ return $ TypedValue True v t
713+check' v@(StringLiteral _) t | t == tyString =
714+ return $ TypedValue True v t
715+check' v@(BooleanLiteral _) t | t == tyBoolean =
716+ return $ TypedValue True v t
717+check' (ArrayLiteral vals) t@(TypeApp a ty) | a == tyArray = do
718+ array <- ArrayLiteral <$> forM vals (`check` ty)
719+ return $ TypedValue True array t
720+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
721+ Just moduleName <- checkCurrentModule <$> get
722+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
723+ return $ TypedValue True (Abs (Left arg) ret') ty
724+check' (Abs (Right _) _) _ = error "Binder was not desugared"
725+check' (App f arg) ret = do
726+ f'@(TypedValue _ _ ft) <- infer f
727+ (ret', app) <- checkFunctionApplication f' ft arg
728+ _ <- subsumes Nothing ret' ret
729+ return $ TypedValue True app ret
730+check' v@(Var var) ty = do
731+ Just moduleName <- checkCurrentModule <$> get
732+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
733+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
734+ v' <- subsumes (Just v) repl ty'
736+ Nothing -> throwError "Unable to check type subsumption"
737+ Just v'' -> return $ TypedValue True v'' ty'
738+check' (TypedValue checkType val ty1) ty2 = do
739+ Just moduleName <- checkCurrentModule <$> get
740+ kind <- liftCheck $ kindOf moduleName ty1
741+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
742+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
743+ val' <- subsumes (Just val) ty1' ty2
745+ Nothing -> throwError "Unable to check type subsumption"
747+ val''' <- if checkType then check val'' ty1 else return val''
748+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
749+check' (Case vals binders) ret = do
750+ vals' <- mapM infer vals
751+ let ts = map (\(TypedValue _ _ t) -> t) vals'
752+ binders' <- checkBinders ts ret binders
753+ return $ TypedValue True (Case vals' binders') ret
754+check' (IfThenElse cond th el) ty = do
755+ cond' <- check cond tyBoolean
758+ return $ TypedValue True (IfThenElse cond' th' el') ty
759+check' (ObjectLiteral ps) t@(Object row) = do
760+ ensureNoDuplicateProperties ps
761+ ps' <- checkProperties ps row False
762+ return $ TypedValue True (ObjectLiteral ps') t
763+check' (ObjectUpdate obj ps) t@(Object row) = do
764+ ensureNoDuplicateProperties ps
765+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
766+ let (propsToCheck, rest) = rowToList row
767+ propsToRemove = map fst ps
768+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
769+ obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
770+ ps' <- checkProperties ps row True
771+ return $ TypedValue True (ObjectUpdate obj' ps') t
772+check' (Accessor prop val) ty = do
774+ val' <- check val (Object (RCons prop ty rest))
775+ return $ TypedValue True (Accessor prop val') ty
776+check' (Constructor c) ty = do
778+ case M.lookup c (dataConstructors env) of
779+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
781+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
782+ _ <- subsumes Nothing repl ty
783+ return $ TypedValue True (Constructor c) ty
784+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
787+-- Check the type of a collection of named record fields
789+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
791+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
792+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
793+ go [] [] REmpty = return []
794+ go [] [] u@(TUnknown _) = do u =?= REmpty
796+ go [] [] (Skolem _ _) | lax = return []
797+ go [] ((p, _): _) _ | lax = return []
798+ | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
799+ go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
800+ go ((p,v):ps') [] u@(TUnknown _) = do
801+ v'@(TypedValue _ _ ty) <- infer v
803+ u =?= RCons p ty rest
804+ ps'' <- go ps' [] rest
805+ return $ (p, v') : ps''
806+ go ((p,v):ps') ts r =
809+ v'@(TypedValue _ _ ty) <- infer v
811+ r =?= RCons p ty rest
812+ ps'' <- go ps' ts rest
813+ return $ (p, v') : ps''
816+ ps'' <- go ps' (delete (p, ty) ts) r
817+ return $ (p, v') : ps''
818+ go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
821+-- Check the type of a function application, rethrowing errors to provide a better error message
823+checkFunctionApplication :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
824+checkFunctionApplication fn fnTy arg = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg
826+ errorMessage msg = "Error applying function of type "
827+ ++ prettyPrintType fnTy
828+ ++ " to argument " ++ prettyPrintValue arg
832+-- Check the type of a function application
834+checkFunctionApplication' :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
835+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg = do
836+ tyFunction' =?= tyFunction
837+ arg' <- check arg argTy
838+ return (retTy, App fn arg')
839+checkFunctionApplication' fn (ForAll ident ty _) arg = do
840+ replaced <- replaceVarWithUnknown ident ty
841+ checkFunctionApplication fn replaced arg
842+checkFunctionApplication' fn u@(TUnknown _) arg = do
844+ TypedValue _ arg' t <- infer arg
845+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
846+ return $ TypedValue True arg'' t'
847+ let ty = (\(TypedValue _ _ t) -> t) arg'
849+ u =?= function ty ret
850+ return (ret, App fn arg')
851+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg = do
852+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
853+ checkFunctionApplication fn ty arg
854+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg = do
855+ dicts <- getTypeClassDictionaries
856+ checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg
857+checkFunctionApplication' _ fnTy arg = throwError $ "Cannot apply a function of type "
858+ ++ prettyPrintType fnTy
859+ ++ " to argument " ++ prettyPrintValue arg
862+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
864+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
865+subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
867+ errorMessage msg = "Error checking that type "
868+ ++ prettyPrintType ty1
869+ ++ " subsumes type "
870+ ++ prettyPrintType ty2
874+-- Check whether one type subsumes another
876+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
877+subsumes' val (ForAll ident ty1 _) ty2 = do
878+ replaced <- replaceVarWithUnknown ident ty1
879+ subsumes val replaced ty2
880+subsumes' val ty1 (ForAll ident ty2 sco) =
883+ sko <- newSkolemConstant
884+ let sk = skolemize ident sko sco' ty2
886+ Nothing -> throwError "Skolem variable scope is unspecified"
887+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
888+ _ <- subsumes Nothing arg2 arg1
889+ _ <- subsumes Nothing ret1 ret2
891+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
892+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
893+ subsumes val ty1 ty2
894+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
895+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
896+ subsumes val ty1 ty2
897+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
898+ dicts <- getTypeClassDictionaries
899+ _ <- subsumes' Nothing ty1 ty2
900+ return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
901+subsumes' val (Object r1) (Object r2) = do
903+ (ts1, r1') = rowToList r1
904+ (ts2, r2') = rowToList r2
905+ ts1' = sortBy (comparing fst) ts1
906+ ts2' = sortBy (comparing fst) ts2
907+ go ts1' ts2' r1' r2'
910+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
911+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
912+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
913+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
915+ | p1 < p2 = do rest <- fresh
916+ r2' =?= RCons p1 ty1 rest
917+ go ts1 ((p2, ty2) : ts2) r1' rest
918+ | otherwise = do rest <- fresh
919+ r1' =?= RCons p2 ty2 rest
920+ go ((p1, ty1) : ts1) ts2 rest r2'
921+subsumes' val ty1 ty2@(Object _) = subsumes val ty2 ty1
922+subsumes' val ty1 ty2 = do