@@ -1,1119 +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.Function (on)
47−import Data.Ord (comparing)
48−import Data.Monoid
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 qualified Data.HashMap.Strict as H
72−
73−instance Partial Type where
74− unknown = TUnknown
75− isUnknown (TUnknown u) = Just u
76− isUnknown _ = Nothing
77− unknowns = everythingOnTypes (++) go
78− where
79− go (TUnknown u) = [u]
80− go _ = []
81− ($?) sub = everywhereOnTypes go
82− where
83− go t@(TUnknown u) = case H.lookup u (runSubstitution sub) of
84− Nothing -> t
85− Just t' -> t'
86− go other = other
87−
88−instance Unifiable Check Type where
89− (=?=) = unifyTypes
90−
91−-- |
92−-- Unify two types, updating the current substitution
93−--
94−unifyTypes :: Type -> Type -> UnifyT Type Check ()
95−unifyTypes t1 t2 = rethrow (mkErrorStack ("Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2) Nothing <>) $
96− unifyTypes' t1 t2
97− where
98− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
99− unifyTypes' (TUnknown u) t = u =:= t
100− unifyTypes' t (TUnknown u) = u =:= t
101− unifyTypes' (SaturatedTypeSynonym name args) ty = do
102− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
103− ty1 `unifyTypes` ty
104− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
105− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
106− case (sc1, sc2) of
107− (Just sc1', Just sc2') -> do
108− sko <- newSkolemConstant
109− let sk1 = skolemize ident1 sko sc1' ty1
110− let sk2 = skolemize ident2 sko sc2' ty2
111− sk1 `unifyTypes` sk2
112− _ -> error "Skolemized type variable was not given a scope"
113− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
114− sko <- newSkolemConstant
115− let sk = skolemize ident sko sc ty1
116− sk `unifyTypes` ty2
117− unifyTypes' ForAll{} _ = throwError . strMsg $ "Skolem variable scope is unspecified"
118− unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
119− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
120− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
121− guardWith (strMsg ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".")) (c1 == c2)
122− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
123− t3 `unifyTypes` t5
124− t4 `unifyTypes` t6
125− unifyTypes' (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = return ()
126− unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
127− unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
128− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
129− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
130− unifyTypes' t@(ConstrainedType _ _) _ = throwError . strMsg $ "Attempted to unify a constrained type " ++ prettyPrintType t ++ " with another type."
131− unifyTypes' t3 t4@(ConstrainedType _ _) = unifyTypes' t4 t3
132− unifyTypes' t3 t4 = throwError . strMsg $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
133−
134−-- |
135−-- Unify two rows, updating the current substitution
136−--
137−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
138−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
139−-- error.
140−--
141−unifyRows :: Type -> Type -> UnifyT Type Check ()
142−unifyRows r1 r2 =
143− let
144− (s1, r1') = rowToList r1
145− (s2, r2') = rowToList r2
146− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
147− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
148− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
149− in do
150− forM_ int (uncurry (=?=))
151− unifyRows' sd1 r1' sd2 r2'
152− where
153− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
154− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
155− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
156− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
157− occursCheck un ty
158− forM_ row $ \(_, t) -> occursCheck un t
159− u' <- fresh
160− u =?= RCons name ty u'
161− unifyRows' row r others u'
162− unifyRows' [] REmpty [] REmpty = return ()
163− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
164− unifyRows' [] (Skolem _ s1 _) [] (Skolem _ s2 _) | s1 == s2 = return ()
165− unifyRows' sd3 r3 sd4 r4 = throwError . strMsg $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")"
166−
167−-- |
168−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
169−-- type class dictionaries and type annotations.
170−--
171−typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
172−typesOf mainModuleName moduleName vals = do
173− tys <- fmap tidyUp . liftUnify $ do
174− (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
175− forM es $ \e -> do
176− triple@(_, (_, ty)) <- typeForBindingGroupElement moduleName e dict untypedDict
177− -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
178− when (Just moduleName == mainModuleName && fst e == Ident C.main) $ do
179− [eff, a] <- replicateM 2 fresh
180− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
181− return triple
182−
183− forM tys $ \(ident, (val, ty)) -> do
184− -- Replace type class dictionary placeholders with actual dictionaries
185− val' <- replaceTypeClassDictionaries moduleName val
186− -- Check skolem variables did not escape their scope
187− skolemEscapeCheck val'
188− -- Remove type synonyms placeholders, remove duplicate row fields, and replace
189− -- top-level unification variables with named type variables.
190− let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
191− ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
192− return (ident, (val'', ty'))
193− where
194− -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
195− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
196−
197−typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Value)] -> UnifyT Type Check ([(Ident, (Value, Maybe (Type, Bool)))], M.Map (ModuleName, Ident) (Type, NameKind, NameVisibility), [(Ident, Type)])
198−typeDictionaryForBindingGroup moduleName vals = do
199− let
200− -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
201− es = map isTyped vals
202− -- Filter the typed and untyped declarations
203− typed = filter (isJust . snd . snd) es
204− untyped = filter (isNothing . snd . snd) es
205− -- Make a map of names to typed declarations
206− typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
207−
208− -- Create fresh unification variables for the types of untyped declarations
209− untypedNames <- replicateM (length untyped) fresh
210−
211− let
212− -- Make a map of names to the unification variables of untyped declarations
213− untypedDict = zip (map fst untyped) untypedNames
214− -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
215− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable, Undefined))) $ typedDict ++ untypedDict)
216− return (es, dict, untypedDict)
217−
218−typeForBindingGroupElement :: ModuleName -> (Ident, (Value, Maybe (Type, Bool))) -> M.Map (ModuleName, Ident) (Type, NameKind, NameVisibility) -> [(Ident, Type)] -> UnifyT Type Check (Ident, (Value, Type))
219−typeForBindingGroupElement moduleName el dict untypedDict =
220− -- If the declaration is a function, it has access to other values in the binding group.
221− -- If not, the generated code might fail at runtime since those values might be undefined.
222− case el of
223− -- Typed declarations
224− (ident, (val', Just (ty, checkType))) -> do
225− -- Kind check
226− kind <- liftCheck $ kindOf moduleName ty
227− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
228− -- Check the type with the new names in scope
229− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
230− val'' <- if checkType
231− then bindNames dict $ TypedValue True <$> check val' ty' <*> pure ty'
232− else return (TypedValue False val' ty')
233− return (ident, (val'', ty'))
234− -- Untyped declarations
235− (ident, (val', Nothing)) -> do
236− -- Infer the type with the new names in scope
237− TypedValue _ val'' ty <- bindNames dict $ infer val'
238− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
239− return (ident, (TypedValue True val'' ty, ty))
240−
241−-- |
242−-- Check if a value contains a type annotation
243−--
244−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
245−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
246−isTyped (name, value) = (name, (value, Nothing))
247−
248−-- |
249−-- Map a function over type annotations appearing inside a value
250−--
251−overTypes :: (Type -> Type) -> Value -> Value
252−overTypes f = let (_, f', _) = everywhereOnValues id g id in f'
253− where
254− g :: Value -> Value
255− g (TypedValue checkTy val t) = TypedValue checkTy val (f t)
256− g (TypeClassDictionary b (nm, tys) sco) = TypeClassDictionary b (nm, map f tys) sco
257− g other = other
258−
259−-- |
260−-- Replace type class dictionary placeholders with inferred type class dictionaries
261−--
262−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
263−replaceTypeClassDictionaries mn =
264− let (_, f, _) = everywhereOnValuesTopDownM return go return
265− in f
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 (flip lookup subst) 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 (C.__superclass_ ++ show superclassName ++ "_" ++ show index)
364− (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− -- Choose the simplest DictionaryValues from a list of candidates
373− -- The reason for this function is as follows:
374− -- When considering overlapping instances, we don't want to consider the same dictionary
375− -- to be an overlap of itself when obtained as a superclass of another class.
376− -- Observing that we probably don't want to select a superclass instance when an instance
377− -- is available directly, and that there is no way for a superclass instance to actually
378− -- introduce an overlap that wouldn't have been there already, we simply remove dictionaries
379− -- obtained as superclass instances if there are simpler instances available.
380− chooseSimplestDictionaries :: [DictionaryValue] -> [DictionaryValue]
381− chooseSimplestDictionaries ds = case filter isSimpleDictionaryValue ds of
382− [] -> ds
383− simple -> simple
384− isSimpleDictionaryValue SubclassDictionaryValue{} = False
385− isSimpleDictionaryValue (DependentDictionaryValue _ ds) = all isSimpleDictionaryValue ds
386− isSimpleDictionaryValue _ = True
387− -- |
388− -- Get the "trace" of a DictionaryValue - that is, remove all SubclassDictionaryValue
389− -- data constructors
390− --
391− dictTrace :: DictionaryValue -> DictionaryValue
392− dictTrace (DependentDictionaryValue fnName dicts) = DependentDictionaryValue fnName $ map dictTrace dicts
393− dictTrace (SubclassDictionaryValue dict _ _) = dictTrace dict
394− dictTrace other = other
395−
396−-- |
397−-- Check all values in a list pairwise match a predicate
398−--
399−pairwise :: (a -> a -> Bool) -> [a] -> Bool
400−pairwise _ [] = True
401−pairwise _ [_] = True
402−pairwise p (x : xs) = all (p x) xs && pairwise p xs
403−
404−-- |
405−-- Check that two types unify
406−--
407−unifiesWith :: Environment -> Type -> Type -> Bool
408−unifiesWith _ (TUnknown u1) (TUnknown u2) | u1 == u2 = True
409−unifiesWith _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = True
410−unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
411−unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
412−unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
413−unifiesWith e (SaturatedTypeSynonym name args) t2 =
414− case expandTypeSynonym' e name args of
415− Left _ -> False
416− Right t1 -> unifiesWith e t1 t2
417−unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
418−unifiesWith _ _ _ = False
419−
420−-- |
421−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
422−-- and return a substitution from type variables to types which makes the type heads unify.
423−--
424−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
425−typeHeadsAreEqual _ _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = Just []
426−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
427−typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
428−typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
429−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
430− Left _ -> Nothing
431− Right t1 -> typeHeadsAreEqual m e t1 t2
432−typeHeadsAreEqual _ _ _ _ = Nothing
433−
434−-- |
435−-- Ensure skolem variables do not escape their scope
436−--
437−skolemEscapeCheck :: Value -> Check ()
438−skolemEscapeCheck (TypedValue False _ _) = return ()
439−skolemEscapeCheck root@TypedValue{} =
440− -- Every skolem variable is created when a ForAll type is skolemized.
441− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
442− -- field of the ForAll constructor.
443− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
444− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
445− -- an escaped skolem variable.
446− let (_, f, _, _, _) = everythingWithContextOnValues [] [] (++) def go def def def
447− in case f root of
448− [] -> return ()
449− ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ValueError val))
450− where
451− def s _ = (s, [])
452−
453− go :: [(SkolemScope, Value)] -> Value -> ([(SkolemScope, Value)], [(Maybe Value, Value)])
454− go scos val@(TypedValue _ _ (ForAll _ _ (Just sco))) = ((sco, val) : scos, [])
455− go scos val@(TypedValue _ _ ty) = case collectSkolems ty \\ map fst scos of
456− (sco : _) -> (scos, [(findBindingScope sco, val)])
457− _ -> (scos, [])
458− where
459− collectSkolems :: Type -> [SkolemScope]
460− collectSkolems = nub . everythingOnTypes (++) collect
461− where
462− collect (Skolem _ _ scope) = [scope]
463− collect _ = []
464− go scos _ = (scos, [])
465− findBindingScope :: SkolemScope -> Maybe Value
466− findBindingScope sco =
467− let (_, f, _, _, _) = everythingOnValues mappend (const mempty) go' (const mempty) (const mempty) (const mempty)
468− in getFirst $ f root
469− where
470− go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
471− go' _ = mempty
472−skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ValueError val))
473−
474−-- |
475−-- Ensure a row contains no duplicate labels
476−--
477−setify :: Type -> Type
478−setify = rowFromList . first (M.toList . M.fromList) . rowToList
479−
480−-- |
481−-- \"Setify\" all rows occuring inside a value
482−--
483−setifyAll :: Type -> Type
484−setifyAll = everywhereOnTypes setify
485−
486−-- |
487−-- Replace outermost unsolved unification variables with named type variables
488−--
489−varIfUnknown :: Type -> Type
490−varIfUnknown ty =
491− let unks = nub $ unknowns ty
492− toName = (:) 't' . show
493− ty' = everywhereOnTypes typeToVar ty
494− typeToVar :: Type -> Type
495− typeToVar (TUnknown u) = TypeVar (toName u)
496− typeToVar t = t
497− in mkForAll (sort . map toName $ unks) ty'
498−
499−-- |
500−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
501−-- or TypeClassDictionary values.
502−--
503−-- This is necessary during type checking to avoid unifying a polymorphic type with a
504−-- unification variable.
505−--
506−instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
507−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
508− ty' <- replaceVarWithUnknown ident ty
509− instantiatePolyTypeWithUnknowns val ty'
510−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
511− dicts <- getTypeClassDictionaries
512− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
513− return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
514−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
515−
516−-- |
517−-- Replace a single type variable with a new unification variable
518−--
519−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
520−replaceVarWithUnknown ident ty = do
521− tu <- fresh
522− return $ replaceTypeVars ident tu ty
523−
524−-- |
525−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
526−-- better error messages during unification.
527−--
528−replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
529−replaceAllTypeSynonyms' env d =
530− let
531− syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
532− in
533− saturateAllTypeSynonyms syns d
534−
535−replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
536−replaceAllTypeSynonyms d = do
537− env <- getEnv
538− either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
539−
540−-- |
541−-- \"Desaturate\" @SaturatedTypeSynonym@s
542−--
543−desaturateAllTypeSynonyms :: Type -> Type
544−desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
545− where
546− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
547− replaceSaturatedTypeSynonym t = t
548−
549−-- |
550−-- Replace a type synonym and its arguments with the aliased type
551−--
552−expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
553−expandTypeSynonym' env name args =
554− case M.lookup name (typeSynonyms env) of
555− Just (synArgs, body) -> do
556− let repl = replaceAllTypeVars (zip synArgs args) body
557− replaceAllTypeSynonyms' env repl
558− Nothing -> error "Type synonym was not defined"
559−
560−expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
561−expandTypeSynonym name args = do
562− env <- getEnv
563− either (throwError . strMsg) return $ expandTypeSynonym' env name args
564−
565−expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
566−expandAllTypeSynonyms = everywhereOnTypesTopDownM go
567− where
568− go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
569− go other = return other
570−
571−-- |
572−-- Ensure a set of property names and value does not contain duplicate labels
573−--
574−ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Value)] -> m ()
575−ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
576−
577−-- |
578−-- Infer a type for a value, rethrowing any error to provide a more useful error message
579−--
580−infer :: Value -> UnifyT Type Check Value
581−infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ValueError val)) <>) $ infer' val
582−
583−-- |
584−-- Infer a type for a value
585−--
586−infer' :: Value -> UnifyT Type Check Value
587−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
588−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
589−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
590−infer' (ArrayLiteral vals) = do
591− ts <- mapM infer vals
592− els <- fresh
593− forM_ ts $ \(TypedValue _ _ t) -> els =?= t
594− return $ TypedValue True (ArrayLiteral ts) (TypeApp tyArray els)
595−infer' (ObjectLiteral ps) = do
596− ensureNoDuplicateProperties ps
597− ts <- mapM (infer . snd) ps
598− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
599− ty = TypeApp tyObject $ rowFromList (fields, REmpty)
600− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
601−infer' (ObjectUpdate o ps) = do
602− ensureNoDuplicateProperties ps
603− row <- fresh
604− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
605− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
606− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
607− let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
608− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
609− return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
610−infer' (Accessor prop val) = do
611− typed@(TypedValue _ _ objTy) <- infer val
612− propTy <- inferProperty objTy prop
613− case propTy of
614− Nothing -> do
615− field <- fresh
616− rest <- fresh
617− _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
618− return $ TypedValue True (Accessor prop typed) field
619− Just ty -> return $ TypedValue True (Accessor prop typed) ty
620−infer' (Abs (Left arg) ret) = do
621− ty <- fresh
622− Just moduleName <- checkCurrentModule <$> get
623− makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, ty, Defined)] $ do
624− body@(TypedValue _ _ bodyTy) <- infer' ret
625− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
626−infer' (Abs (Right _) _) = error "Binder was not desugared"
627−infer' (App f arg) = do
628− f'@(TypedValue _ _ ft) <- infer f
629− (ret, app) <- checkFunctionApplication f' ft arg Nothing
630− return $ TypedValue True app ret
631−infer' (Var var) = do
632− Just moduleName <- checkCurrentModule <$> get
633− checkVisibility moduleName var
634− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
635− case ty of
636− ConstrainedType constraints ty' -> do
637− dicts <- getTypeClassDictionaries
638− return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
639− _ -> return $ TypedValue True (Var var) ty
640−infer' v@(Constructor c) = do
641− env <- getEnv
642− case M.lookup c (dataConstructors env) of
643− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
644− Just (_, _, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
645− return $ TypedValue True v ty'
646−infer' (Case vals binders) = do
647− ts <- mapM infer vals
648− ret <- fresh
649− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
650− return $ TypedValue True (Case ts binders') ret
651−infer' (IfThenElse cond th el) = do
652− cond' <- check cond tyBoolean
653− v2@(TypedValue _ _ t2) <- infer th
654− v3@(TypedValue _ _ t3) <- infer el
655− t2 =?= t3
656− return $ TypedValue True (IfThenElse cond' v2 v3) t2
657−infer' (Let ds val) = do
658− (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
659− return $ TypedValue True (Let ds' val') valTy
660−infer' (SuperClassDictionary className tys) = do
661− dicts <- getTypeClassDictionaries
662− return $ TypeClassDictionary False (className, tys) dicts
663−infer' (TypedValue checkType val ty) = do
664− Just moduleName <- checkCurrentModule <$> get
665− kind <- liftCheck $ kindOf moduleName ty
666− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
667− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
668− val' <- if checkType then check val ty' else return val
669− return $ TypedValue True val' ty'
670−infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
671−infer' _ = error "Invalid argument to infer"
672−
673−inferLetBinding :: [Declaration] -> [Declaration] -> Value -> (Value -> UnifyT Type Check Value) -> UnifyT Type Check ([Declaration], Value)
674−inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
675−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing tv@(TypedValue checkType val ty) : rest) ret j = do
676− Just moduleName <- checkCurrentModule <$> get
677− kind <- liftCheck $ kindOf moduleName ty
678− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
679− let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
680− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
681− TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
682− bindNames (M.singleton (moduleName, ident) (ty'', nameKind, Defined)) $ 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 = M.singleton (moduleName, ident) (valTy, nameKind, Undefined)
687− TypedValue _ val' valTy' <- bindNames dict $ infer val
688− valTy =?= valTy'
689− bindNames (M.singleton (moduleName, ident) (valTy', nameKind, Defined)) $ 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− makeBindingGroupVisible $ 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' <- introduceSkolemScope <=< 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 [ (name, ty, Defined) | (name, ty) <- 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 = fresh'
795−
796−-- |
797−-- Generate a new skolem scope
798−--
799−newSkolemScope :: UnifyT Type Check SkolemScope
800−newSkolemScope = SkolemScope <$> 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 = let (_, f, _) = everywhereOnValues id go id in f
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' <- makeBindingGroupVisible $ 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' <- makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, argTy, Defined)] $ 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− checkVisibility moduleName var
890− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
891− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
892− v' <- subsumes (Just v) repl ty'
893− case v' of
894− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
895− Just v'' -> return $ TypedValue True v'' ty'
896−check' (SuperClassDictionary className tys) _ = do
897− {-
898− -- Here, we replace a placeholder for a superclass dictionary with a regular
899− -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
900− -- correct super instance dictionaries in scope, and these are not available when the type class
901− -- declaration gets desugared.
902− --
903− -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
904− -- to consider superclass instances when searching for this dictionary - doing so might lead
905− -- to traversing a cycle in the instance graph.
906− -}
907− dicts <- getTypeClassDictionaries
908− return $ TypeClassDictionary False (className, tys) dicts
909−check' (TypedValue checkType val ty1) ty2 = do
910− Just moduleName <- checkCurrentModule <$> get
911− kind <- liftCheck $ kindOf moduleName ty1
912− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
913− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
914− val' <- subsumes (Just val) ty1' ty2
915− case val' of
916− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
917− Just val'' -> do
918− val''' <- if checkType then check val'' ty1' else return val''
919− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
920−check' (Case vals binders) ret = do
921− vals' <- mapM infer vals
922− let ts = map (\(TypedValue _ _ t) -> t) vals'
923− binders' <- checkBinders ts ret binders
924− return $ TypedValue True (Case vals' binders') ret
925−check' (IfThenElse cond th el) ty = do
926− cond' <- check cond tyBoolean
927− th' <- check th ty
928− el' <- check el ty
929− return $ TypedValue True (IfThenElse cond' th' el') ty
930−check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
931− ensureNoDuplicateProperties ps
932− ps' <- checkProperties ps row False
933− return $ TypedValue True (ObjectLiteral ps') t
934−check' (TypeClassDictionaryConstructorApp name ps) t = do
935− ps' <- check' ps t
936− return $ TypedValue True (TypeClassDictionaryConstructorApp name ps') t
937−check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
938− ensureNoDuplicateProperties ps
939− us <- zip (map fst ps) <$> replicateM (length ps) fresh
940− let (propsToCheck, rest) = rowToList row
941− propsToRemove = map fst ps
942− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
943− obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
944− ps' <- checkProperties ps row True
945− return $ TypedValue True (ObjectUpdate obj' ps') t
946−check' (Accessor prop val) ty = do
947− rest <- fresh
948− val' <- check val (TypeApp tyObject (RCons prop ty rest))
949− return $ TypedValue True (Accessor prop val') ty
950−check' (Constructor c) ty = do
951− env <- getEnv
952− case M.lookup c (dataConstructors env) of
953− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
954− Just (_, _, ty1) -> do
955− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
956− _ <- subsumes Nothing repl ty
957− return $ TypedValue True (Constructor c) ty
958−check' (Let ds val) ty = do
959− (ds', val') <- inferLetBinding [] ds val (flip check ty)
960− return $ TypedValue True (Let ds' val') ty
961−check' val ty | containsTypeSynonyms ty = do
962− ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
963− check val ty'
964−check' (PositionedValue pos val) ty =
965− rethrowWithPosition pos $ check val ty
966−check' val ty = throwError $ mkErrorStack ("Value does not have type " ++ prettyPrintType ty) (Just (ValueError val))
967−
968−containsTypeSynonyms :: Type -> Bool
969−containsTypeSynonyms = everythingOnTypes (||) go where
970− go (SaturatedTypeSynonym _ _) = True
971− go _ = False
972−
973−-- |
974−-- Check the type of a collection of named record fields
975−--
976−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
977−--
978−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
979−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
980− go [] [] REmpty = return []
981− go [] [] u@(TUnknown _) = do u =?= REmpty
982− return []
983− go [] [] (Skolem _ _ _) | lax = return []
984− go [] ((p, _): _) _ | lax = return []
985− | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ValueError (ObjectLiteral ps)))
986− go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ValueError (ObjectLiteral ps)))
987− go ((p,v):ps') [] u@(TUnknown _) = do
988− v'@(TypedValue _ _ ty) <- infer v
989− rest <- fresh
990− u =?= RCons p ty rest
991− ps'' <- go ps' [] rest
992− return $ (p, v') : ps''
993− go ((p,v):ps') ts r =
994− case lookup p ts of
995− Nothing -> do
996− v'@(TypedValue _ _ ty) <- infer v
997− rest <- fresh
998− r =?= RCons p ty rest
999− ps'' <- go ps' ts rest
1000− return $ (p, v') : ps''
1001− Just ty -> do
1002− v' <- check v ty
1003− ps'' <- go ps' (delete (p, ty) ts) r
1004− return $ (p, v') : ps''
1005− go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ValueError (ObjectLiteral ps)))
1006−
1007−-- |
1008−-- Check the type of a function application, rethrowing errors to provide a better error message
1009−--
1010−checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
1011−checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ValueError fn)) <>) $ do
1012− subst <- unifyCurrentSubstitution <$> UnifyT get
1013− checkFunctionApplication' fn (subst $? fnTy) arg (($?) subst <$> ret)
1014− where
1015− errorMessage = "Error applying function of type "
1016− ++ prettyPrintType fnTy
1017− ++ " to argument " ++ prettyPrintValue arg
1018−
1019−-- |
1020−-- Check the type of a function application
1021−--
1022−checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
1023−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
1024− tyFunction' =?= tyFunction
1025− arg' <- check arg argTy
1026− case ret of
1027− Nothing -> return (retTy, App fn arg')
1028− Just ret' -> do
1029− Just app' <- subsumes (Just (App fn arg')) retTy ret'
1030− return (retTy, app')
1031−checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
1032− replaced <- replaceVarWithUnknown ident ty
1033− checkFunctionApplication fn replaced arg ret
1034−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1035− arg' <- do
1036− TypedValue _ arg' t <- infer arg
1037− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
1038− return $ TypedValue True arg'' t'
1039− let ty = (\(TypedValue _ _ t) -> t) arg'
1040− ret' <- maybe fresh return ret
1041− u =?= function ty ret'
1042− return (ret', App fn arg')
1043−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1044− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1045− checkFunctionApplication fn ty arg ret
1046−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1047− dicts <- getTypeClassDictionaries
1048− checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1049−checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1050− ++ prettyPrintType fnTy
1051− ++ " to argument " ++ prettyPrintValue arg
1052−
1053−-- |
1054−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1055−--
1056−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1057−subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ValueError <$> val) <>) $ subsumes' val ty1 ty2
1058− where
1059− errorMessage = "Error checking that type "
1060− ++ prettyPrintType ty1
1061− ++ " subsumes type "
1062− ++ prettyPrintType ty2
1063−
1064−-- |
1065−-- Check whether one type subsumes another
1066−--
1067−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
1068−subsumes' val (ForAll ident ty1 _) ty2 = do
1069− replaced <- replaceVarWithUnknown ident ty1
1070− subsumes val replaced ty2
1071−subsumes' val ty1 (ForAll ident ty2 sco) =
1072− case sco of
1073− Just sco' -> do
1074− sko <- newSkolemConstant
1075− let sk = skolemize ident sko sco' ty2
1076− subsumes val ty1 sk
1077− Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1078−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1079− _ <- subsumes Nothing arg2 arg1
1080− _ <- subsumes Nothing ret1 ret2
1081− return val
1082−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1083− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1084− subsumes val ty1 ty2
1085−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1086− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1087− subsumes val ty1 ty2
1088−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1089− dicts <- getTypeClassDictionaries
1090− subsumes' (Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)) ty1 ty2
1091−subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1092− let
1093− (ts1, r1') = rowToList r1
1094− (ts2, r2') = rowToList r2
1095− ts1' = sortBy (comparing fst) ts1
1096− ts2' = sortBy (comparing fst) ts2
1097− go ts1' ts2' r1' r2'
1098− return val
1099− where
1100− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1101− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1102− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1103− | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1104− go ts1 ts2 r1' r2'
1105− | p1 < p2 = do rest <- fresh
1106− r2' =?= RCons p1 ty1 rest
1107− go ts1 ((p2, ty2) : ts2) r1' rest
1108− | otherwise = do rest <- fresh
1109− r1' =?= RCons p2 ty2 rest
1110− go ((p1, ty1) : ts1) ts2 rest r2'
1111−subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1112−subsumes' val ty1 ty2 = do
1113− ty1 =?= ty2
1114− return val
1115−
1116−
1117−
1118−
1119−