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