@@ -1,676 +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−{-# LANGUAGE FlexibleContexts, MultiParamTypeClasses #-}
18−module Language.PureScript.TypeChecker.Types (
23− The following functions represent the corresponding type checking judgements:
26− Synthesize a type for a value
29− Check a value has a given type
32− Check an object with a given type contains specified properties
34− checkFunctionApplication
35− Check a function of a given type returns a value of another type when applied to its arguments
38−import Data.Either (lefts, rights)
40−import Data.Maybe (fromMaybe)
42−import qualified Data.Map as M
44−import Control.Applicative
45−import Control.Monad.Error
46−import Control.Monad.State
47−import Control.Monad.Unify
49−import Language.PureScript.AST
50−import Language.PureScript.Environment
51−import Language.PureScript.Errors
52−import Language.PureScript.Kinds
53−import Language.PureScript.Names
54−import Language.PureScript.Pretty
55−import Language.PureScript.TypeChecker.Entailment
56−import Language.PureScript.TypeChecker.Kinds
57−import Language.PureScript.TypeChecker.Monad
58−import Language.PureScript.TypeChecker.Rows
59−import Language.PureScript.TypeChecker.Skolems
60−import Language.PureScript.TypeChecker.Subsumption
61−import Language.PureScript.TypeChecker.Synonyms
62−import Language.PureScript.TypeChecker.Unify
63−import Language.PureScript.TypeClassDictionaries
64−import Language.PureScript.Types
65−import qualified Language.PureScript.Constants as C
68−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
69−-- type class dictionaries and type annotations.
71−typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Expr)] -> Check [(Ident, (Expr, Type))]
72−typesOf mainModuleName moduleName vals = do
73− tys <- fmap tidyUp . liftUnify $ do
74− (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
75− ds1 <- parU typed $ \e -> do
76− triple@(_, (_, ty)) <- checkTypedBindingGroupElement moduleName e dict
79− ds2 <- forM untyped $ \e -> do
80− triple@(_, (_, ty)) <- typeForBindingGroupElement e dict untypedDict
85− forM tys $ \(ident, (val, ty)) -> do
86− -- Replace type class dictionary placeholders with actual dictionaries
87− val' <- replaceTypeClassDictionaries moduleName val
88− -- Check skolem variables did not escape their scope
89− skolemEscapeCheck val'
90− -- Check rows do not contain duplicate labels
91− checkDuplicateLabels val'
92− -- Remove type synonyms placeholders, and replace
93− -- top-level unification variables with named type variables.
94− let val'' = overTypes desaturateAllTypeSynonyms val'
95− ty' = varIfUnknown . desaturateAllTypeSynonyms $ ty
96− return (ident, (val'', ty'))
98− -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
99− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
100− -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
101− checkMain nm ty = when (Just moduleName == mainModuleName && nm == Ident C.main) $ do
102− [eff, a] <- replicateM 2 fresh
103− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
105−type TypeData = M.Map (ModuleName, Ident) (Type, NameKind, NameVisibility)
107−type UntypedData = [(Ident, Type)]
109−typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Expr)] -> UnifyT Type Check ([(Ident, Expr)], [(Ident, (Expr, Type, Bool))], TypeData, UntypedData)
110−typeDictionaryForBindingGroup moduleName vals = do
112− -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
113− es = map isTyped vals
114− -- Filter the typed and untyped declarations
117− -- Make a map of names to typed declarations
118− typedDict = map (\(ident, (_, ty, _)) -> (ident, ty)) typed
120− -- Create fresh unification variables for the types of untyped declarations
121− untypedNames <- replicateM (length untyped) fresh
124− -- Make a map of names to the unification variables of untyped declarations
125− untypedDict = zip (map fst untyped) untypedNames
126− -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
127− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable, Undefined))) $ typedDict ++ untypedDict)
128− return (untyped, typed, dict, untypedDict)
130−checkTypedBindingGroupElement :: ModuleName -> (Ident, (Expr, Type, Bool)) -> TypeData -> UnifyT Type Check (Ident, (Expr, Type))
131−checkTypedBindingGroupElement moduleName (ident, (val', ty, checkType)) dict = do
133− kind <- liftCheck $ kindOf moduleName ty
134− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
135− -- Check the type with the new names in scope
136− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
137− val'' <- if checkType
138− then bindNames dict $ TypedValue True <$> check val' ty' <*> pure ty'
139− else return (TypedValue False val' ty')
140− return (ident, (val'', ty'))
142−typeForBindingGroupElement :: (Ident, Expr) -> TypeData -> UntypedData -> UnifyT Type Check (Ident, (Expr, Type))
143−typeForBindingGroupElement (ident, val) dict untypedDict = do
144− -- Infer the type with the new names in scope
145− TypedValue _ val' ty <- bindNames dict $ infer val
146− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
147− return (ident, (TypedValue True val' ty, ty))
150−-- Check if a value contains a type annotation
152−isTyped :: (Ident, Expr) -> Either (Ident, Expr) (Ident, (Expr, Type, Bool))
153−isTyped (name, TypedValue checkType value ty) = Right (name, (value, ty, checkType))
154−isTyped (name, value) = Left (name, value)
157−-- Map a function over type annotations appearing inside a value
159−overTypes :: (Type -> Type) -> Expr -> Expr
160−overTypes f = let (_, f', _) = everywhereOnValues id g id in f'
163− g (TypedValue checkTy val t) = TypedValue checkTy val (f t)
164− g (TypeClassDictionary b (nm, tys) sco) = TypeClassDictionary b (nm, map f tys) sco
168−-- Replace type class dictionary placeholders with inferred type class dictionaries
170−replaceTypeClassDictionaries :: ModuleName -> Expr -> Check Expr
171−replaceTypeClassDictionaries mn =
172− let (_, f, _) = everywhereOnValuesTopDownM return go return
175− go (TypeClassDictionary trySuperclasses constraint dicts) = do
177− entails env mn dicts constraint trySuperclasses
178− go other = return other
181−-- Check the kind of a type, failing if it is not of kind *.
183−checkTypeKind :: ModuleName -> Type -> UnifyT t Check ()
184−checkTypeKind moduleName ty = do
185− kind <- liftCheck $ kindOf moduleName ty
186− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
189−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
190−-- or TypeClassDictionary values.
192−-- This is necessary during type checking to avoid unifying a polymorphic type with a
193−-- unification variable.
195−instantiatePolyTypeWithUnknowns :: Expr -> Type -> UnifyT Type Check (Expr, Type)
196−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
197− ty' <- replaceVarWithUnknown ident ty
198− instantiatePolyTypeWithUnknowns val ty'
199−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
200− dicts <- getTypeClassDictionaries
201− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
202− return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
203−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
206−-- Infer a type for a value, rethrowing any error to provide a more useful error message
208−infer :: Expr -> UnifyT Type Check Expr
209−infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ExprError val)) <>) $ infer' val
212−-- Infer a type for a value
214−infer' :: Expr -> UnifyT Type Check Expr
215−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
216−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
217−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
218−infer' (ArrayLiteral vals) = do
219− ts <- mapM infer vals
221− forM_ ts $ \(TypedValue _ _ t) -> els =?= t
222− return $ TypedValue True (ArrayLiteral ts) (TypeApp tyArray els)
223−infer' (ObjectLiteral ps) = do
224− ensureNoDuplicateProperties ps
225− ts <- mapM (infer . snd) ps
226− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
227− ty = TypeApp tyObject $ rowFromList (fields, REmpty)
228− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
229−infer' (ObjectUpdate o ps) = do
230− ensureNoDuplicateProperties ps
232− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
233− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
234− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
235− let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
236− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
237− return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
238−infer' (Accessor prop val) = do
239− typed@(TypedValue _ _ objTy) <- infer val
240− propTy <- inferProperty objTy prop
245− _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
246− return $ TypedValue True (Accessor prop typed) field
247− Just ty -> return $ TypedValue True (Accessor prop typed) ty
248−infer' (Abs (Left arg) ret) = do
250− Just moduleName <- checkCurrentModule <$> get
251− makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, ty, Defined)] $ do
252− body@(TypedValue _ _ bodyTy) <- infer' ret
253− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
254−infer' (Abs (Right _) _) = error "Binder was not desugared"
255−infer' (App f arg) = do
256− f'@(TypedValue _ _ ft) <- infer f
257− (ret, app) <- checkFunctionApplication f' ft arg Nothing
258− return $ TypedValue True app ret
259−infer' (Var var) = do
260− Just moduleName <- checkCurrentModule <$> get
261− checkVisibility moduleName var
262− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
264− ConstrainedType constraints ty' -> do
265− dicts <- getTypeClassDictionaries
266− return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
267− _ -> return $ TypedValue True (Var var) ty
268−infer' v@(Constructor c) = do
270− case M.lookup c (dataConstructors env) of
271− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
272− Just (_, _, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
273− return $ TypedValue True v ty'
274−infer' (Case vals binders) = do
275− ts <- mapM infer vals
277− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
278− return $ TypedValue True (Case ts binders') ret
279−infer' (IfThenElse cond th el) = do
280− cond' <- check cond tyBoolean
281− v2@(TypedValue _ _ t2) <- infer th
282− v3@(TypedValue _ _ t3) <- infer el
283− (v2', v3', t) <- meet v2 v3 t2 t3
284− return $ TypedValue True (IfThenElse cond' v2' v3') t
285−infer' (Let ds val) = do
286− (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
287− return $ TypedValue True (Let ds' val') valTy
288−infer' (SuperClassDictionary className tys) = do
289− dicts <- getTypeClassDictionaries
290− return $ TypeClassDictionary False (className, tys) dicts
291−infer' (TypedValue checkType val ty) = do
292− Just moduleName <- checkCurrentModule <$> get
293− checkTypeKind moduleName ty
294− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
295− val' <- if checkType then check val ty' else return val
296− return $ TypedValue True val' ty'
297−infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
298−infer' _ = error "Invalid argument to infer"
300−inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Type Check Expr) -> UnifyT Type Check ([Declaration], Expr)
301−inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
302−inferLetBinding seen (ValueDeclaration ident nameKind [] (Right (tv@(TypedValue checkType val ty))) : rest) ret j = do
303− Just moduleName <- checkCurrentModule <$> get
304− checkTypeKind moduleName ty
305− let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
306− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
307− TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
308− bindNames (M.singleton (moduleName, ident) (ty'', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] (Right (TypedValue checkType val' ty''))]) rest ret j
309−inferLetBinding seen (ValueDeclaration ident nameKind [] (Right val) : rest) ret j = do
311− Just moduleName <- checkCurrentModule <$> get
312− let dict = M.singleton (moduleName, ident) (valTy, nameKind, Undefined)
313− TypedValue _ val' valTy' <- bindNames dict $ infer val
315− bindNames (M.singleton (moduleName, ident) (valTy', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] (Right val')]) rest ret j
316−inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
317− Just moduleName <- checkCurrentModule <$> get
318− (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
319− ds1' <- parU typed $ \e -> checkTypedBindingGroupElement moduleName e dict
320− ds2' <- forM untyped $ \e -> typeForBindingGroupElement e dict untypedDict
321− let ds' = [(ident, LocalVariable, val') | (ident, (val', _)) <- ds1' ++ ds2']
322− makeBindingGroupVisible $ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
323−inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
324− (d' : ds', val') <- inferLetBinding seen (d : ds) ret j
325− return (PositionedDeclaration pos d' : ds', val')
326−inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
329−-- Infer the type of a property inside a record with a given type
331−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
332−inferProperty (TypeApp obj row) prop | obj == tyObject = do
333− let (props, _) = rowToList row
334− return $ lookup prop props
335−inferProperty (SaturatedTypeSynonym name args) prop = do
336− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
337− inferProperty replaced prop
338−inferProperty (ForAll ident ty _) prop = do
339− replaced <- replaceVarWithUnknown ident ty
340− inferProperty replaced prop
341−inferProperty _ _ = return Nothing
344−-- Infer the types of variables brought into scope by a binder
346−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
347−inferBinder _ NullBinder = return M.empty
348−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
349−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
350−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
351−inferBinder val (VarBinder name) = return $ M.singleton name val
352−inferBinder val (ConstructorBinder ctor binders) = do
354− case M.lookup ctor (dataConstructors env) of
355− Just (_, _, ty) -> do
356− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
357− fn' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ fn
361− _ <- subsumes Nothing val ty'
363− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
364− M.union <$> inferBinder obj binder <*> go binders' ret
365− go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
366− _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
367−inferBinder val (ObjectBinder props) = do
370− m1 <- inferRowProperties row rest props
371− val =?= TypeApp tyObject row
374− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
375− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
376− inferRowProperties nrow row ((name, binder):binders) = do
378− m1 <- inferBinder propTy binder
379− m2 <- inferRowProperties nrow (RCons name propTy row) binders
380− return $ m1 `M.union` m2
381−inferBinder val (ArrayBinder binders) = do
383− m1 <- M.unions <$> mapM (inferBinder el) binders
384− val =?= TypeApp tyArray el
386−inferBinder val (ConsBinder headBinder tailBinder) = do
388− m1 <- inferBinder el headBinder
389− m2 <- inferBinder val tailBinder
390− val =?= TypeApp tyArray el
391− return $ m1 `M.union` m2
392−inferBinder val (NamedBinder name binder) = do
393− m <- inferBinder val binder
394− return $ M.insert name val m
395−inferBinder val (PositionedBinder pos binder) =
396− rethrowWithPosition pos $ inferBinder val binder
399−-- Check the types of the return values in a set of binders in a case statement
401−checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
402−checkBinders _ _ [] = return []
403−checkBinders nvals ret (CaseAlternative binders result : bs) = do
404− guardWith (strMsg "Overlapping binders in case statement") $
405− let ns = concatMap binderNames binders in length (nub ns) == length ns
406− Just moduleName <- checkCurrentModule <$> get
407− m1 <- M.unions <$> zipWithM inferBinder nvals binders
408− r <- bindLocalVariables moduleName [ (name, ty, Defined) | (name, ty) <- M.toList m1 ] $
409− CaseAlternative binders <$>
412− gs' <- forM gs $ \(grd, val) -> do
413− grd' <- check grd tyBoolean
414− val' <- TypedValue True <$> check val ret <*> pure ret
418− val' <- TypedValue True <$> check val ret <*> pure ret
420− rs <- checkBinders nvals ret bs
424−-- Check the type of a value, rethrowing errors to provide a better error message
426−check :: Expr -> Type -> UnifyT Type Check Expr
427−check val ty = rethrow (mkErrorStack errorMessage (Just (ExprError val)) <>) $ check' val ty
430− "Error checking type of term " ++
431− prettyPrintValue val ++
436−-- Check the type of a value
438−check' :: Expr -> Type -> UnifyT Type Check Expr
439−check' val (ForAll ident ty _) = do
440− scope <- newSkolemScope
441− sko <- newSkolemConstant
442− let sk = skolemize ident sko scope ty
443− let skVal = skolemizeTypesInValue ident sko scope val
444− val' <- check skVal sk
445− return $ TypedValue True val' (ForAll ident ty (Just scope))
446−check' val t@(ConstrainedType constraints ty) = do
447− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
448− n <- liftCheck freshDictionaryName
449− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
450− val' <- makeBindingGroupVisible $ withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
451− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular False) (map (Qualified Nothing) dictNames)
452− constraints) $ check val ty
453− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
454−check' val (SaturatedTypeSynonym name args) = do
455− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
457−check' val u@(TUnknown _) = do
458− val'@(TypedValue _ _ ty) <- infer val
459− -- Don't unify an unknown with an inferred polytype
460− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
462− return $ TypedValue True val'' ty'
463−check' v@(NumericLiteral _) t | t == tyNumber =
464− return $ TypedValue True v t
465−check' v@(StringLiteral _) t | t == tyString =
466− return $ TypedValue True v t
467−check' v@(BooleanLiteral _) t | t == tyBoolean =
468− return $ TypedValue True v t
469−check' (ArrayLiteral vals) t@(TypeApp a ty) = do
471− array <- ArrayLiteral <$> forM vals (`check` ty)
472− return $ TypedValue True array t
473−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
474− Just moduleName <- checkCurrentModule <$> get
475− ret' <- makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, argTy, Defined)] $ check ret retTy
476− return $ TypedValue True (Abs (Left arg) ret') ty
477−check' (Abs (Right _) _) _ = error "Binder was not desugared"
478−check' (App f arg) ret = do
479− f'@(TypedValue _ _ ft) <- infer f
480− (_, app) <- checkFunctionApplication f' ft arg (Just ret)
481− return $ TypedValue True app ret
482−check' v@(Var var) ty = do
483− Just moduleName <- checkCurrentModule <$> get
484− checkVisibility moduleName var
485− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
486− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
487− v' <- subsumes (Just v) repl ty'
489− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
490− Just v'' -> return $ TypedValue True v'' ty'
491−check' (SuperClassDictionary className tys) _ = do
493− -- Here, we replace a placeholder for a superclass dictionary with a regular
494− -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
495− -- correct super instance dictionaries in scope, and these are not available when the type class
496− -- declaration gets desugared.
498− -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
499− -- to consider superclass instances when searching for this dictionary - doing so might lead
500− -- to traversing a cycle in the instance graph.
502− dicts <- getTypeClassDictionaries
503− return $ TypeClassDictionary False (className, tys) dicts
504−check' (TypedValue checkType val ty1) ty2 = do
505− Just moduleName <- checkCurrentModule <$> get
506− checkTypeKind moduleName ty1
507− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
508− ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty2
509− val' <- subsumes (Just val) ty1' ty2'
511− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
513− val''' <- if checkType then check val'' ty2' else return val''
514− return $ TypedValue checkType (TypedValue True val''' ty1') ty2'
515−check' (Case vals binders) ret = do
516− vals' <- mapM infer vals
517− let ts = map (\(TypedValue _ _ t) -> t) vals'
518− binders' <- checkBinders ts ret binders
519− return $ TypedValue True (Case vals' binders') ret
520−check' (IfThenElse cond th el) ty = do
521− cond' <- check cond tyBoolean
524− return $ TypedValue True (IfThenElse cond' th' el') ty
525−check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
526− ensureNoDuplicateProperties ps
527− ps' <- checkProperties ps row False
528− return $ TypedValue True (ObjectLiteral ps') t
529−check' (TypeClassDictionaryConstructorApp name ps) t = do
531− return $ TypedValue True (TypeClassDictionaryConstructorApp name ps') t
532−check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
533− ensureNoDuplicateProperties ps
534− -- We need to be careful to avoid duplicate labels here.
535− -- We check _obj_ agaist the type _t_ with the types in _ps_ replaced with unknowns.
536− let (propsToCheck, rest) = rowToList row
537− (removedProps, remainingProps) = partition (\(p, _) -> p `elem` map fst ps) propsToCheck
538− us <- zip (map fst removedProps) <$> replicateM (length ps) fresh
539− obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
540− ps' <- checkProperties ps row True
541− return $ TypedValue True (ObjectUpdate obj' ps') t
542−check' (Accessor prop val) ty = do
544− val' <- check val (TypeApp tyObject (RCons prop ty rest))
545− return $ TypedValue True (Accessor prop val') ty
546−check' (Constructor c) ty = do
548− case M.lookup c (dataConstructors env) of
549− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
550− Just (_, _, ty1) -> do
551− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
552− _ <- subsumes Nothing repl ty
553− return $ TypedValue True (Constructor c) ty
554−check' (Let ds val) ty = do
555− (ds', val') <- inferLetBinding [] ds val (`check` ty)
556− return $ TypedValue True (Let ds' val') ty
557−check' val ty | containsTypeSynonyms ty = do
558− ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
560−check' val kt@(KindedType ty kind) = do
561− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
562− val' <- check' val ty
563− return $ TypedValue True val' kt
564−check' (PositionedValue pos val) ty =
565− rethrowWithPosition pos $ check val ty
566−check' val ty = throwError $ mkErrorStack ("Expr does not have type " ++ prettyPrintType ty) (Just (ExprError val))
568−containsTypeSynonyms :: Type -> Bool
569−containsTypeSynonyms = everythingOnTypes (||) go where
570− go (SaturatedTypeSynonym _ _) = True
574−-- Check the type of a collection of named record fields
576−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
578−checkProperties :: [(String, Expr)] -> Type -> Bool -> UnifyT Type Check [(String, Expr)]
579−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
580− go [] [] REmpty = return []
581− go [] [] u@(TUnknown _) = do u =?= REmpty
583− go [] [] Skolem{} | lax = return []
584− go [] ((p, _): _) _ | lax = return []
585− | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ExprError (ObjectLiteral ps)))
586− go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ExprError (ObjectLiteral ps)))
587− go ((p,v):ps') [] u@(TUnknown _) = do
588− v'@(TypedValue _ _ ty) <- infer v
590− u =?= RCons p ty rest
591− ps'' <- go ps' [] rest
592− return $ (p, v') : ps''
593− go ((p,v):ps') ts r =
596− v'@(TypedValue _ _ ty) <- infer v
598− r =?= RCons p ty rest
599− ps'' <- go ps' ts rest
600− return $ (p, v') : ps''
603− ps'' <- go ps' (delete (p, ty) ts) r
604− return $ (p, v') : ps''
605− go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ExprError (ObjectLiteral ps)))
608−-- Check the type of a function application, rethrowing errors to provide a better error message
610−checkFunctionApplication :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
611−checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ExprError fn)) <>) $ do
612− subst <- unifyCurrentSubstitution <$> UnifyT get
613− checkFunctionApplication' fn (subst $? fnTy) arg (($?) subst <$> ret)
615− errorMessage = "Error applying function of type "
616− ++ prettyPrintType fnTy
617− ++ " to argument " ++ prettyPrintValue arg
620−-- Check the type of a function application
622−checkFunctionApplication' :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
623−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
624− tyFunction' =?= tyFunction
625− arg' <- check arg argTy
627− Nothing -> return (retTy, App fn arg')
629− Just app' <- subsumes (Just (App fn arg')) retTy ret'
630− return (retTy, app')
631−checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
632− replaced <- replaceVarWithUnknown ident ty
633− checkFunctionApplication fn replaced arg ret
634−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
636− TypedValue _ arg' t <- infer arg
637− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
638− return $ TypedValue True arg'' t'
639− let ty = (\(TypedValue _ _ t) -> t) arg'
640− ret' <- maybe fresh return ret
641− u =?= function ty ret'
642− return (ret', App fn arg')
643−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
644− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
645− checkFunctionApplication fn ty arg ret
646−checkFunctionApplication' fn (KindedType ty _) arg ret =
647− checkFunctionApplication fn ty arg ret
648−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
649− dicts <- getTypeClassDictionaries
650− checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
651−checkFunctionApplication' fn fnTy dict@TypeClassDictionary{} _ =
652− return (fnTy, App fn dict)
653−checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
654− ++ prettyPrintType fnTy
655− ++ " to argument " ++ prettyPrintValue arg
658−-- Compute the meet of two types, i.e. the most general type which both types subsume.
659−-- TODO: handle constrained types
661−meet :: Expr -> Expr -> Type -> Type -> UnifyT Type Check (Expr, Expr, Type)
662−meet e1 e2 (ForAll ident t1 _) t2 = do
663− t1' <- replaceVarWithUnknown ident t1
665−meet e1 e2 t1 (ForAll ident t2 _) = do
666− t2' <- replaceVarWithUnknown ident t2
668−meet e1 e2 t1 t2 = do
673−-- Ensure a set of property names and value does not contain duplicate labels
675−ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Expr)] -> m ()
676−ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps