@@ -0,0 +1,906 @@
1+-----------------------------------------------------------------------------
2+--
3+-- Module : Language.PureScript.TypeChecker.Types
4+-- Copyright : (c) Phil Freeman 2013
5+-- License : MIT
6+--
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
9+-- Portability :
10+--
11+-- |
12+-- This module implements the type checker
13+--
14+-----------------------------------------------------------------------------
15+
16+{-# OPTIONS_GHC -fno-warn-orphans #-}
17+{-# LANGUAGE FlexibleContexts #-}
18+{-# LANGUAGE MultiParamTypeClasses #-}
19+
20+module Language.PureScript.TypeChecker.Types (
21+ typesOf
22+) where
23+
24+{-
25+ The following functions represent the corresponding type checking judgements:
26+
27+ infer
28+ Synthesize a type for a value
29+
30+ check
31+ Check a value has a given type
32+
33+ checkProperties
34+ Check an object with a given type contains specified properties
35+
36+ checkFunctionApplication
37+ Check a function of a given type returns a value of another type when applied to its arguments
38+
39+ subsumes
40+ Check a type subsumes another type
41+-}
42+
43+import Data.List
44+import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
45+import qualified Data.Data as D
46+import Data.Generics
47+ (everythingWithContext, mkM, everywhereM, everything, mkT,
48+ something, everywhere, mkQ)
49+import Data.Generics.Extras
50+
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.Environment
60+import qualified Language.PureScript.Constants as C
61+
62+import Control.Monad.State
63+import Control.Monad.Error
64+import Control.Monad.Unify
65+
66+import Control.Applicative
67+import Control.Arrow (Arrow(..))
68+
69+import qualified Data.Map as M
70+import Data.Function (on)
71+import Data.Ord (comparing)
72+
73+instance Partial Type where
74+ unknown = TUnknown
75+ isUnknown (TUnknown u) = Just u
76+ isUnknown _ = Nothing
77+
78+instance Unifiable Check Type where
79+ (=?=) = unifyTypes
80+
81+-- |
82+-- Unify two types, updating the current substitution
83+--
84+unifyTypes :: Type -> Type -> UnifyT Type Check ()
85+unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $
86+ unifyTypes' t1 t2
87+ where
88+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
89+ unifyTypes' (TUnknown u) t = u =:= t
90+ unifyTypes' t (TUnknown u) = u =:= t
91+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
92+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
93+ ty1 `unifyTypes` ty
94+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
95+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
96+ case (sc1, sc2) of
97+ (Just sc1', Just sc2') -> do
98+ sko <- newSkolemConstant
99+ let sk1 = skolemize ident1 sko sc1' ty1
100+ let sk2 = skolemize ident2 sko sc2' ty2
101+ sk1 `unifyTypes` sk2
102+ _ -> throwError (prettyPrintType ty1)
103+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
104+ sko <- newSkolemConstant
105+ let sk = skolemize ident sko sc ty1
106+ sk `unifyTypes` ty2
107+ unifyTypes' ForAll{} _ = throwError "Skolem variable scope is unspecified"
108+ unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
109+ unifyTypes' (Object row1) (Object row2) = row1 =?= row2
110+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
111+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
112+ guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (c1 == c2)
113+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
114+ t3 `unifyTypes` t5
115+ t4 `unifyTypes` t6
116+ unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
117+ unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
118+ unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
119+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
120+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
121+ unifyTypes' t@(ConstrainedType _ _) _ = throwError $ "Attempted to unify a constrained type " ++ prettyPrintType t ++
122+ " with another type."
123+ unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
124+ unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
125+
126+-- |
127+-- Unify two rows, updating the current substitution
128+--
129+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
130+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
131+-- error.
132+--
133+unifyRows :: Type -> Type -> UnifyT Type Check ()
134+unifyRows r1 r2 =
135+ let
136+ (s1, r1') = rowToList r1
137+ (s2, r2') = rowToList r2
138+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
139+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
140+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
141+ in do
142+ forM_ int (uncurry (=?=))
143+ unifyRows' sd1 r1' sd2 r2'
144+ where
145+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
146+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
147+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
148+ unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
149+ occursCheck un ty
150+ forM_ row $ \(_, t) -> occursCheck un t
151+ u' <- fresh
152+ u =?= RCons name ty u'
153+ unifyRows' row r others u'
154+ unifyRows' [] REmpty [] REmpty = return ()
155+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
156+ unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
157+ unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")."
158+
159+-- |
160+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
161+-- type class dictionaries and type annotations.
162+--
163+typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
164+typesOf mainModuleName moduleName vals = do
165+ tys <- fmap tidyUp . liftUnify $ do
166+ let
167+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
168+ es = map isTyped vals
169+ -- Filter the typed and untyped declarations
170+ typed = filter (isJust . snd . snd) es
171+ untyped = filter (isNothing . snd . snd) es
172+ -- Make a map of names to typed declarations
173+ typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
174+ -- Create fresh unification variables for the types of untyped declarations
175+ untypedNames <- replicateM (length untyped) fresh
176+ let
177+ -- Make a map of names to the unification variables of untyped declarations
178+ untypedDict = zip (map fst untyped) untypedNames
179+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
180+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
181+ forM es $ \e@(_, (val, _)) -> do
182+ -- If the declaration is a function, it has access to other values in the binding group.
183+ -- If not, the generated code might fail at runtime since those values might be undefined.
184+ let dict' = if isFunction val then dict else M.empty
185+ triple@(_, (_, ty)) <- case e of
186+ -- Typed declarations
187+ (ident, (val', Just (ty, checkType))) -> do
188+ -- Kind check
189+ kind <- liftCheck $ kindOf moduleName ty
190+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
191+ -- Check the type with the new names in scope
192+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
193+ val'' <- bindNames dict' $ if checkType
194+ then TypedValue True <$> check val' ty' <*> pure ty'
195+ else return (TypedValue False val' ty')
196+ return (ident, (val'', ty'))
197+ -- Untyped declarations
198+ (ident, (val', Nothing)) -> do
199+ -- Infer the type with the new names in scope
200+ TypedValue _ val'' ty <- bindNames dict' $ infer val'
201+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
202+ return (ident, (TypedValue True val'' ty, ty))
203+ -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
204+ when (Just moduleName == mainModuleName && fst e == Ident C.main) $ do
205+ [eff, a] <- replicateM 2 fresh
206+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
207+ return triple
208+ forM tys $ \(ident, (val, ty)) -> do
209+ -- Replace type class dictionary placeholders with actual dictionaries
210+ val' <- replaceTypeClassDictionaries moduleName val
211+ -- Check skolem variables did not escape their scope
212+ skolemEscapeCheck val'
213+ -- Remove type synonyms placeholders, remove duplicate row fields, and replace
214+ -- top-level unification variables with named type variables.
215+ let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
216+ ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
217+ return (ident, (val'', ty'))
218+ where
219+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
220+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
221+
222+-- |
223+-- Check if a value introduces a function
224+--
225+isFunction :: Value -> Bool
226+isFunction (Abs _ _) = True
227+isFunction (TypedValue _ val _) = isFunction val
228+isFunction _ = False
229+
230+-- |
231+-- Check if a value contains a type annotation
232+--
233+isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
234+isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
235+isTyped (name, value) = (name, (value, Nothing))
236+
237+-- |
238+-- Map a function over type annotations appearing inside a value
239+--
240+overTypes :: (Type -> Type) -> Value -> Value
241+overTypes f = everywhere (mkT f)
242+
243+-- |
244+-- Replace type class dictionary placeholders with inferred type class dictionaries
245+--
246+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
247+replaceTypeClassDictionaries mn = everywhereM' (mkM go)
248+ where
249+ go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
250+ go other = return other
251+
252+-- |
253+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
254+-- return a type class dictionary reference.
255+--
256+entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Check Value
257+entails moduleName context goal@(className, tys) = do
258+ env <- getEnv
259+ case go env goal of
260+ [] -> throwError $ "No " ++ show className ++ " instance found for " ++ intercalate ", " (map prettyPrintType tys)
261+ (dict : _) -> return dict
262+ where
263+ go env (className', tys') =
264+ [ mkDictionary (canonicalizeDictionary tcd) args
265+ | tcd <- context
266+ -- Choose type class dictionaries in scope in the current module
267+ , filterModule tcd
268+ -- Make sure the type class name matches the one we are trying to satisfy
269+ , className' == tcdClassName tcd
270+ -- Make sure the type unifies with the type in the type instance definition
271+ , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
272+ -- Solve any necessary subgoals
273+ , args <- solveSubgoals env subst (tcdDependencies tcd) ]
274+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
275+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
276+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
277+ solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [Value]]
278+ solveSubgoals _ _ Nothing = return Nothing
279+ solveSubgoals env subst (Just subgoals) = do
280+ dict <- mapM (go env . second (map (replaceAllTypeVars subst))) subgoals
281+ return $ Just dict
282+ -- Make a dictionary from subgoal dictionaries by applying the correct function
283+ mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
284+ mkDictionary fnName Nothing = Var fnName
285+ mkDictionary fnName (Just []) = App (Var fnName) (ObjectLiteral [])
286+ mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
287+ -- Filter out type dictionaries which are in scope in the current module
288+ filterModule :: TypeClassDictionaryInScope -> Bool
289+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
290+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
291+ filterModule _ = False
292+ -- Ensure that a substitution is valid
293+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
294+ verifySubstitution subst = do
295+ let grps = groupBy ((==) `on` fst) subst
296+ guard (all ((==) 1 . length . nubBy ((==) `on` snd)) grps)
297+ return $ map head grps
298+
299+-- |
300+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
301+-- and return a substitution from type variables to types which makes the type heads unify.
302+--
303+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
304+typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
305+typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
306+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
307+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
308+typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
309+typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
310+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
311+ Left _ -> Nothing
312+ Right t1 -> typeHeadsAreEqual m e t1 t2
313+typeHeadsAreEqual _ _ _ _ = Nothing
314+
315+-- |
316+-- Ensure skolem variables do not escape their scope
317+--
318+skolemEscapeCheck :: Value -> Check ()
319+skolemEscapeCheck (TypedValue False _ _) = return ()
320+skolemEscapeCheck root@TypedValue{} =
321+ -- Every skolem variable is created when a ForAll type is skolemized.
322+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
323+ -- field of the ForAll constructor.
324+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
325+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
326+ -- an escaped skolem variable.
327+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
328+ [] -> return ()
329+ ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
330+ where
331+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
332+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
333+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
334+ (sco : _) -> ([(findBindingScope sco, val)], scos)
335+ _ -> ([], scos)
336+ where
337+ collectSkolems :: Type -> [SkolemScope]
338+ collectSkolems = nub . everything (++) (mkQ [] collect)
339+ where
340+ collect (Skolem _ scope) = [scope]
341+ collect _ = []
342+ go _ scos = ([], scos)
343+ findBindingScope :: SkolemScope -> Maybe Value
344+ findBindingScope sco = something (mkQ Nothing go') root
345+ where
346+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
347+ go' _ = Nothing
348+skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
349+
350+-- |
351+-- Ensure a row contains no duplicate labels
352+--
353+setify :: Type -> Type
354+setify = rowFromList . first (M.toList . M.fromList) . rowToList
355+
356+-- |
357+-- \"Setify\" all rows occuring inside a value
358+--
359+setifyAll :: (D.Data d) => d -> d
360+setifyAll = everywhere (mkT setify)
361+
362+-- |
363+-- Replace outermost unsolved unification variables with named type variables
364+--
365+varIfUnknown :: Type -> Type
366+varIfUnknown ty =
367+ let unks = nub $ unknowns ty
368+ toName = (:) 't' . show
369+ ty' = everywhere (mkT typeToVar) ty
370+ typeToVar :: Type -> Type
371+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
372+ typeToVar t = t
373+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
374+
375+-- |
376+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
377+-- or TypeClassDictionary values.
378+--
379+-- This is necessary during type checking to avoid unifying a polymorphic type with a
380+-- unification variable.
381+--
382+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
383+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
384+ ty' <- replaceVarWithUnknown ident ty
385+ instantiatePolyTypeWithUnknowns val ty'
386+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
387+ dicts <- getTypeClassDictionaries
388+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
389+ return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
390+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
391+
392+-- |
393+-- Replace a single type variable with a new unification variable
394+--
395+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
396+replaceVarWithUnknown ident ty = do
397+ tu <- fresh
398+ return $ replaceTypeVars ident tu ty
399+
400+-- |
401+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
402+-- better error messages during unification.
403+--
404+replaceAllTypeSynonyms' :: (D.Data d) => Environment -> d -> Either String d
405+replaceAllTypeSynonyms' env d =
406+ let
407+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
408+ in
409+ saturateAllTypeSynonyms syns d
410+
411+replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
412+replaceAllTypeSynonyms d = do
413+ env <- getEnv
414+ either throwError return $ replaceAllTypeSynonyms' env d
415+
416+-- |
417+-- \"Desaturate\" @SaturatedTypeSynonym@s
418+--
419+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
420+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
421+ where
422+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
423+ replaceSaturatedTypeSynonym t = t
424+
425+-- |
426+-- Replace a type synonym and its arguments with the aliased type
427+--
428+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
429+expandTypeSynonym' env name args =
430+ case M.lookup name (typeSynonyms env) of
431+ Just (synArgs, body) -> do
432+ let repl = replaceAllTypeVars (zip synArgs args) body
433+ replaceAllTypeSynonyms' env repl
434+ Nothing -> error "Type synonym was not defined"
435+
436+expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
437+expandTypeSynonym name args = do
438+ env <- getEnv
439+ either throwError return $ expandTypeSynonym' env name args
440+
441+-- |
442+-- Ensure a set of property names and value does not contain duplicate labels
443+--
444+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
445+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
446+
447+-- |
448+-- Infer a type for a value, rethrowing any error to provide a more useful error message
449+--
450+infer :: Value -> UnifyT Type Check Value
451+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
452+
453+-- |
454+-- Infer a type for a value
455+--
456+infer' :: Value -> UnifyT Type Check Value
457+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
458+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
459+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
460+infer' (ArrayLiteral vals) = do
461+ ts <- mapM infer vals
462+ els <- fresh
463+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
464+ return $ TypedValue True (ArrayLiteral ts) els
465+infer' (ObjectLiteral ps) = do
466+ ensureNoDuplicateProperties ps
467+ ts <- mapM (infer . snd) ps
468+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
469+ ty = Object $ rowFromList (fields, REmpty)
470+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
471+infer' (ObjectUpdate o ps) = do
472+ ensureNoDuplicateProperties ps
473+ row <- fresh
474+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
475+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
476+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
477+ let oldTy = Object $ rowFromList (oldTys, row)
478+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
479+ return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
480+infer' (Accessor prop val) = do
481+ typed@(TypedValue _ _ objTy) <- infer val
482+ propTy <- inferProperty objTy prop
483+ case propTy of
484+ Nothing -> do
485+ field <- fresh
486+ rest <- fresh
487+ _ <- subsumes Nothing objTy (Object (RCons prop field rest))
488+ return $ TypedValue True (Accessor prop typed) field
489+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
490+infer' (Abs (Left arg) ret) = do
491+ ty <- fresh
492+ Just moduleName <- checkCurrentModule <$> get
493+ bindLocalVariables moduleName [(arg, ty)] $ do
494+ body@(TypedValue _ _ bodyTy) <- infer' ret
495+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
496+infer' (Abs (Right _) _) = error "Binder was not desugared"
497+infer' (App f arg) = do
498+ f'@(TypedValue _ _ ft) <- infer f
499+ (ret, app) <- checkFunctionApplication f' ft arg Nothing
500+ return $ TypedValue True app ret
501+infer' (Var var) = do
502+ Just moduleName <- checkCurrentModule <$> get
503+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
504+ case ty of
505+ ConstrainedType constraints ty' -> do
506+ dicts <- getTypeClassDictionaries
507+ return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) constraints)) ty'
508+ _ -> return $ TypedValue True (Var var) ty
509+infer' v@(Constructor c) = do
510+ env <- getEnv
511+ case M.lookup c (dataConstructors env) of
512+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
513+ Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
514+ return $ TypedValue True v ty'
515+infer' (Case vals binders) = do
516+ ts <- mapM infer vals
517+ ret <- fresh
518+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
519+ return $ TypedValue True (Case ts binders') ret
520+infer' (IfThenElse cond th el) = do
521+ cond' <- check cond tyBoolean
522+ v2@(TypedValue _ _ t2) <- infer th
523+ v3@(TypedValue _ _ t3) <- infer el
524+ t2 =?= t3
525+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
526+infer' (TypedValue checkType val ty) = do
527+ Just moduleName <- checkCurrentModule <$> get
528+ kind <- liftCheck $ kindOf moduleName ty
529+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
530+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
531+ val' <- if checkType then check val ty' else return val
532+ return $ TypedValue True val' ty'
533+infer' _ = error "Invalid argument to infer"
534+
535+-- |
536+-- Infer the type of a property inside a record with a given type
537+--
538+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
539+inferProperty (Object row) prop = do
540+ let (props, _) = rowToList row
541+ return $ lookup prop props
542+inferProperty (SaturatedTypeSynonym name args) prop = do
543+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
544+ inferProperty replaced prop
545+inferProperty (ForAll ident ty _) prop = do
546+ replaced <- replaceVarWithUnknown ident ty
547+ inferProperty replaced prop
548+inferProperty _ _ = return Nothing
549+
550+-- |
551+-- Infer the types of variables brought into scope by a binder
552+--
553+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
554+inferBinder _ NullBinder = return M.empty
555+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
556+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
557+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
558+inferBinder val (VarBinder name) = return $ M.singleton name val
559+inferBinder val (ConstructorBinder ctor binders) = do
560+ env <- getEnv
561+ case M.lookup ctor (dataConstructors env) of
562+ Just (_, ty) -> do
563+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
564+ fn' <- replaceAllTypeSynonyms fn
565+ go binders fn'
566+ where
567+ go [] ty' = do
568+ _ <- subsumes Nothing val ty'
569+ return M.empty
570+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
571+ M.union <$> inferBinder obj binder <*> go binders' ret
572+ go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
573+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
574+inferBinder val (ObjectBinder props) = do
575+ row <- fresh
576+ rest <- fresh
577+ m1 <- inferRowProperties row rest props
578+ val =?= Object row
579+ return m1
580+ where
581+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
582+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
583+ inferRowProperties nrow row ((name, binder):binders) = do
584+ propTy <- fresh
585+ m1 <- inferBinder propTy binder
586+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
587+ return $ m1 `M.union` m2
588+inferBinder val (ArrayBinder binders) = do
589+ el <- fresh
590+ m1 <- M.unions <$> mapM (inferBinder el) binders
591+ val =?= TypeApp tyArray el
592+ return m1
593+inferBinder val (ConsBinder headBinder tailBinder) = do
594+ el <- fresh
595+ m1 <- inferBinder el headBinder
596+ m2 <- inferBinder val tailBinder
597+ val =?= TypeApp tyArray el
598+ return $ m1 `M.union` m2
599+inferBinder val (NamedBinder name binder) = do
600+ m <- inferBinder val binder
601+ return $ M.insert name val m
602+
603+-- |
604+-- Check the types of the return values in a set of binders in a case statement
605+--
606+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
607+checkBinders _ _ [] = return []
608+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
609+ Just moduleName <- checkCurrentModule <$> get
610+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
611+ r <- bindLocalVariables moduleName (M.toList m1) $ do
612+ val' <- TypedValue True <$> check val ret <*> pure ret
613+ case grd of
614+ Nothing -> return $ CaseAlternative binders Nothing val'
615+ Just g -> do
616+ g' <- check g tyBoolean
617+ return $ CaseAlternative binders (Just g') val'
618+ rs <- checkBinders nvals ret bs
619+ return $ r : rs
620+
621+-- |
622+-- Generate a new skolem constant
623+--
624+newSkolemConstant :: UnifyT Type Check Int
625+newSkolemConstant = runUnknown <$> fresh'
626+
627+-- |
628+-- Generate a new skolem scope
629+--
630+newSkolemScope :: UnifyT Type Check SkolemScope
631+newSkolemScope = SkolemScope . runUnknown <$> fresh'
632+
633+-- |
634+-- Skolemize a type variable by replacing its instances with fresh skolem constants
635+--
636+skolemize :: String -> Int -> SkolemScope -> Type -> Type
637+skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
638+
639+-- |
640+-- Introduce skolem scope at every occurence of a ForAll
641+--
642+introduceSkolemScope :: Type -> UnifyT Type Check Type
643+introduceSkolemScope = everywhereM (mkM go)
644+ where
645+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
646+ go other = return other
647+
648+-- |
649+-- Check the type of a value, rethrowing errors to provide a better error message
650+--
651+check :: Value -> Type -> UnifyT Type Check Value
652+check val ty = rethrow errorMessage $ check' val ty
653+ where
654+ errorMessage msg =
655+ "Error checking type of term " ++
656+ prettyPrintValue val ++
657+ " against type " ++
658+ prettyPrintType ty ++
659+ ":\n" ++
660+ msg
661+
662+-- |
663+-- Check the type of a value
664+--
665+check' :: Value -> Type -> UnifyT Type Check Value
666+check' val (ForAll ident ty _) = do
667+ scope <- newSkolemScope
668+ sko <- newSkolemConstant
669+ let sk = skolemize ident sko scope ty
670+ val' <- check val sk
671+ return $ TypedValue True val' (ForAll ident ty (Just scope))
672+check' val t@(ConstrainedType constraints ty) = do
673+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
674+ n <- liftCheck freshDictionaryName
675+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
676+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
677+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
678+ constraints) $ check val ty
679+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
680+check' val (SaturatedTypeSynonym name args) = do
681+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
682+ val' <- check val ty
683+ return $ TypedValue True val' ty
684+check' val u@(TUnknown _) = do
685+ val'@(TypedValue _ _ ty) <- infer val
686+ -- Don't unify an unknown with an inferred polytype
687+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
688+ ty' =?= u
689+ return $ TypedValue True val'' ty'
690+check' v@(NumericLiteral _) t | t == tyNumber =
691+ return $ TypedValue True v t
692+check' v@(StringLiteral _) t | t == tyString =
693+ return $ TypedValue True v t
694+check' v@(BooleanLiteral _) t | t == tyBoolean =
695+ return $ TypedValue True v t
696+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
697+ a =?= tyArray
698+ array <- ArrayLiteral <$> forM vals (`check` ty)
699+ return $ TypedValue True array t
700+check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
701+ Just moduleName <- checkCurrentModule <$> get
702+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
703+ return $ TypedValue True (Abs (Left arg) ret') ty
704+check' (Abs (Right _) _) _ = error "Binder was not desugared"
705+check' (App f arg) ret = do
706+ f'@(TypedValue _ _ ft) <- infer f
707+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
708+ return $ TypedValue True app ret
709+check' v@(Var var) ty = do
710+ Just moduleName <- checkCurrentModule <$> get
711+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
712+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
713+ v' <- subsumes (Just v) repl ty'
714+ case v' of
715+ Nothing -> throwError "Unable to check type subsumption"
716+ Just v'' -> return $ TypedValue True v'' ty'
717+check' (TypedValue checkType val ty1) ty2 = do
718+ Just moduleName <- checkCurrentModule <$> get
719+ kind <- liftCheck $ kindOf moduleName ty1
720+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
721+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
722+ val' <- subsumes (Just val) ty1' ty2
723+ case val' of
724+ Nothing -> throwError "Unable to check type subsumption"
725+ Just val'' -> do
726+ val''' <- if checkType then check val'' ty1' else return val''
727+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
728+check' (Case vals binders) ret = do
729+ vals' <- mapM infer vals
730+ let ts = map (\(TypedValue _ _ t) -> t) vals'
731+ binders' <- checkBinders ts ret binders
732+ return $ TypedValue True (Case vals' binders') ret
733+check' (IfThenElse cond th el) ty = do
734+ cond' <- check cond tyBoolean
735+ th' <- check th ty
736+ el' <- check el ty
737+ return $ TypedValue True (IfThenElse cond' th' el') ty
738+check' (ObjectLiteral ps) t@(Object row) = do
739+ ensureNoDuplicateProperties ps
740+ ps' <- checkProperties ps row False
741+ return $ TypedValue True (ObjectLiteral ps') t
742+check' (ObjectUpdate obj ps) t@(Object row) = do
743+ ensureNoDuplicateProperties ps
744+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
745+ let (propsToCheck, rest) = rowToList row
746+ propsToRemove = map fst ps
747+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
748+ obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
749+ ps' <- checkProperties ps row True
750+ return $ TypedValue True (ObjectUpdate obj' ps') t
751+check' (Accessor prop val) ty = do
752+ rest <- fresh
753+ val' <- check val (Object (RCons prop ty rest))
754+ return $ TypedValue True (Accessor prop val') ty
755+check' (Constructor c) ty = do
756+ env <- getEnv
757+ case M.lookup c (dataConstructors env) of
758+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
759+ Just (_, ty1) -> do
760+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
761+ _ <- subsumes Nothing repl ty
762+ return $ TypedValue True (Constructor c) ty
763+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
764+
765+-- |
766+-- Check the type of a collection of named record fields
767+--
768+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
769+--
770+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
771+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
772+ go [] [] REmpty = return []
773+ go [] [] u@(TUnknown _) = do u =?= REmpty
774+ return []
775+ go [] [] (Skolem _ _) | lax = return []
776+ go [] ((p, _): _) _ | lax = return []
777+ | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
778+ go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
779+ go ((p,v):ps') [] u@(TUnknown _) = do
780+ v'@(TypedValue _ _ ty) <- infer v
781+ rest <- fresh
782+ u =?= RCons p ty rest
783+ ps'' <- go ps' [] rest
784+ return $ (p, v') : ps''
785+ go ((p,v):ps') ts r =
786+ case lookup p ts of
787+ Nothing -> do
788+ v'@(TypedValue _ _ ty) <- infer v
789+ rest <- fresh
790+ r =?= RCons p ty rest
791+ ps'' <- go ps' ts rest
792+ return $ (p, v') : ps''
793+ Just ty -> do
794+ v' <- check v ty
795+ ps'' <- go ps' (delete (p, ty) ts) r
796+ return $ (p, v') : ps''
797+ go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
798+
799+-- |
800+-- Check the type of a function application, rethrowing errors to provide a better error message
801+--
802+checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
803+checkFunctionApplication fn fnTy arg ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg ret
804+ where
805+ errorMessage msg = "Error applying function of type "
806+ ++ prettyPrintType fnTy
807+ ++ " to argument " ++ prettyPrintValue arg
808+ ++ ":\n" ++ msg
809+
810+-- |
811+-- Check the type of a function application
812+--
813+checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
814+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
815+ tyFunction' =?= tyFunction
816+ _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
817+ subst <- unifyCurrentSubstitution <$> UnifyT get
818+ arg' <- check arg (subst $? argTy)
819+ return (retTy, App fn arg')
820+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
821+ replaced <- replaceVarWithUnknown ident ty
822+ checkFunctionApplication fn replaced arg ret
823+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
824+ arg' <- do
825+ TypedValue _ arg' t <- infer arg
826+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
827+ return $ TypedValue True arg'' t'
828+ let ty = (\(TypedValue _ _ t) -> t) arg'
829+ ret' <- maybe fresh return ret
830+ u =?= function ty ret'
831+ return (ret', App fn arg')
832+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
833+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
834+ checkFunctionApplication fn ty arg ret
835+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
836+ dicts <- getTypeClassDictionaries
837+ checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg ret
838+checkFunctionApplication' _ fnTy arg _ = throwError $ "Cannot apply a function of type "
839+ ++ prettyPrintType fnTy
840+ ++ " to argument " ++ prettyPrintValue arg
841+
842+-- |
843+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
844+--
845+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
846+subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
847+ where
848+ errorMessage msg = "Error checking that type "
849+ ++ prettyPrintType ty1
850+ ++ " subsumes type "
851+ ++ prettyPrintType ty2
852+ ++ ":\n" ++ msg
853+
854+-- |
855+-- Check whether one type subsumes another
856+--
857+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
858+subsumes' val (ForAll ident ty1 _) ty2 = do
859+ replaced <- replaceVarWithUnknown ident ty1
860+ subsumes val replaced ty2
861+subsumes' val ty1 (ForAll ident ty2 sco) =
862+ case sco of
863+ Just sco' -> do
864+ sko <- newSkolemConstant
865+ let sk = skolemize ident sko sco' ty2
866+ subsumes val ty1 sk
867+ Nothing -> throwError "Skolem variable scope is unspecified"
868+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
869+ _ <- subsumes Nothing arg2 arg1
870+ _ <- subsumes Nothing ret1 ret2
871+ return val
872+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
873+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
874+ subsumes val ty1 ty2
875+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
876+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
877+ subsumes val ty1 ty2
878+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
879+ dicts <- getTypeClassDictionaries
880+ _ <- subsumes' Nothing ty1 ty2
881+ return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
882+subsumes' val (Object r1) (Object r2) = do
883+ let
884+ (ts1, r1') = rowToList r1
885+ (ts2, r2') = rowToList r2
886+ ts1' = sortBy (comparing fst) ts1
887+ ts2' = sortBy (comparing fst) ts2
888+ go ts1' ts2' r1' r2'
889+ return val
890+ where
891+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
892+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
893+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
894+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
895+ go ts1 ts2 r1' r2'
896+ | p1 < p2 = do rest <- fresh
897+ r2' =?= RCons p1 ty1 rest
898+ go ts1 ((p2, ty2) : ts2) r1' rest
899+ | otherwise = do rest <- fresh
900+ r1' =?= RCons p2 ty2 rest
901+ go ((p1, ty1) : ts1) ts2 rest r2'
902+subsumes' val ty1 ty2@(Object _) = subsumes val ty2 ty1
903+subsumes' val ty1 ty2 = do
904+ ty1 =?= ty2
905+ return val
906+