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