@@ -1,1125 +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, Expr)] -> Check [(Ident, (Expr, 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, Expr)] -> UnifyT Type Check ([(Ident, (Expr, 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, (Expr, Maybe (Type, Bool))) -> M.Map (ModuleName, Ident) (Type, NameKind, NameVisibility) -> [(Ident, Type)] -> UnifyT Type Check (Ident, (Expr, 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, Expr) -> (Ident, (Expr, 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) -> Expr -> Expr
252−overTypes f = let (_, f', _) = everywhereOnValues id g id in f'
253− where
254− g :: Expr -> Expr
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 -> Expr -> Check Expr
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 Expr
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 Expr
358− dictionaryValueToValue :: DictionaryValue -> Expr
359− dictionaryValueToValue (LocalDictionaryValue fnName) = Var fnName
360− dictionaryValueToValue (GlobalDictionaryValue fnName) = App (Var fnName) valUndefined
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− valUndefined
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− valUndefined :: Expr
397− valUndefined = Var (Qualified (Just (ModuleName [ProperName C.prim])) (Ident C.undefined))
398−
399−-- |
400−-- Check all values in a list pairwise match a predicate
401−--
402−pairwise :: (a -> a -> Bool) -> [a] -> Bool
403−pairwise _ [] = True
404−pairwise _ [_] = True
405−pairwise p (x : xs) = all (p x) xs && pairwise p xs
406−
407−-- |
408−-- Check that two types unify
409−--
410−unifiesWith :: Environment -> Type -> Type -> Bool
411−unifiesWith _ (TUnknown u1) (TUnknown u2) | u1 == u2 = True
412−unifiesWith _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = True
413−unifiesWith _ (TypeVar v1) (TypeVar v2) | v1 == v2 = True
414−unifiesWith _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = True
415−unifiesWith e (TypeApp h1 t1) (TypeApp h2 t2) = unifiesWith e h1 h2 && unifiesWith e t1 t2
416−unifiesWith e (SaturatedTypeSynonym name args) t2 =
417− case expandTypeSynonym' e name args of
418− Left _ -> False
419− Right t1 -> unifiesWith e t1 t2
420−unifiesWith e t1 t2@(SaturatedTypeSynonym _ _) = unifiesWith e t2 t1
421−unifiesWith _ _ _ = False
422−
423−-- |
424−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
425−-- and return a substitution from type variables to types which makes the type heads unify.
426−--
427−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
428−typeHeadsAreEqual _ _ (Skolem _ s1 _) (Skolem _ s2 _) | s1 == s2 = Just []
429−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
430−typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
431−typeHeadsAreEqual m e (TypeApp h1 t1) (TypeApp h2 t2) = (++) <$> typeHeadsAreEqual m e h1 h2 <*> typeHeadsAreEqual m e t1 t2
432−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
433− Left _ -> Nothing
434− Right t1 -> typeHeadsAreEqual m e t1 t2
435−typeHeadsAreEqual _ _ _ _ = Nothing
436−
437−-- |
438−-- Ensure skolem variables do not escape their scope
439−--
440−skolemEscapeCheck :: Expr -> Check ()
441−skolemEscapeCheck (TypedValue False _ _) = return ()
442−skolemEscapeCheck root@TypedValue{} =
443− -- Every skolem variable is created when a ForAll type is skolemized.
444− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
445− -- field of the ForAll constructor.
446− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
447− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
448− -- an escaped skolem variable.
449− let (_, f, _, _, _) = everythingWithContextOnValues [] [] (++) def go def def def
450− in case f root of
451− [] -> return ()
452− ((binding, val) : _) -> throwError $ mkErrorStack ("Rigid/skolem type variable " ++ maybe "" (("bound by " ++) . prettyPrintValue) binding ++ " has escaped.") (Just (ExprError val))
453− where
454− def s _ = (s, [])
455−
456− go :: [(SkolemScope, Expr)] -> Expr -> ([(SkolemScope, Expr)], [(Maybe Expr, Expr)])
457− go scos val@(TypedValue _ _ (ForAll _ _ (Just sco))) = ((sco, val) : scos, [])
458− go scos val@(TypedValue _ _ ty) = case collectSkolems ty \\ map fst scos of
459− (sco : _) -> (scos, [(findBindingScope sco, val)])
460− _ -> (scos, [])
461− where
462− collectSkolems :: Type -> [SkolemScope]
463− collectSkolems = nub . everythingOnTypes (++) collect
464− where
465− collect (Skolem _ _ scope) = [scope]
466− collect _ = []
467− go scos _ = (scos, [])
468− findBindingScope :: SkolemScope -> Maybe Expr
469− findBindingScope sco =
470− let (_, f, _, _, _) = everythingOnValues mappend (const mempty) go' (const mempty) (const mempty) (const mempty)
471− in getFirst $ f root
472− where
473− go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = First (Just val)
474− go' _ = mempty
475−skolemEscapeCheck val = throwError $ mkErrorStack "Untyped value passed to skolemEscapeCheck" (Just (ExprError val))
476−
477−-- |
478−-- Ensure a row contains no duplicate labels
479−--
480−setify :: Type -> Type
481−setify = rowFromList . first (M.toList . M.fromList) . rowToList
482−
483−-- |
484−-- \"Setify\" all rows occuring inside a value
485−--
486−setifyAll :: Type -> Type
487−setifyAll = everywhereOnTypes setify
488−
489−-- |
490−-- Replace outermost unsolved unification variables with named type variables
491−--
492−varIfUnknown :: Type -> Type
493−varIfUnknown ty =
494− let unks = nub $ unknowns ty
495− toName = (:) 't' . show
496− ty' = everywhereOnTypes typeToVar ty
497− typeToVar :: Type -> Type
498− typeToVar (TUnknown u) = TypeVar (toName u)
499− typeToVar t = t
500− in mkForAll (sort . map toName $ unks) ty'
501−
502−-- |
503−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
504−-- or TypeClassDictionary values.
505−--
506−-- This is necessary during type checking to avoid unifying a polymorphic type with a
507−-- unification variable.
508−--
509−instantiatePolyTypeWithUnknowns :: Expr -> Type -> UnifyT Type Check (Expr, Type)
510−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
511− ty' <- replaceVarWithUnknown ident ty
512− instantiatePolyTypeWithUnknowns val ty'
513−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
514− dicts <- getTypeClassDictionaries
515− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
516− return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
517−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
518−
519−-- |
520−-- Replace a single type variable with a new unification variable
521−--
522−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
523−replaceVarWithUnknown ident ty = do
524− tu <- fresh
525− return $ replaceTypeVars ident tu ty
526−
527−-- |
528−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
529−-- better error messages during unification.
530−--
531−replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
532−replaceAllTypeSynonyms' env d =
533− let
534− syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
535− in
536− saturateAllTypeSynonyms syns d
537−
538−replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
539−replaceAllTypeSynonyms d = do
540− env <- getEnv
541− either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
542−
543−-- |
544−-- \"Desaturate\" @SaturatedTypeSynonym@s
545−--
546−desaturateAllTypeSynonyms :: Type -> Type
547−desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
548− where
549− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
550− replaceSaturatedTypeSynonym t = t
551−
552−-- |
553−-- Replace a type synonym and its arguments with the aliased type
554−--
555−expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
556−expandTypeSynonym' env name args =
557− case M.lookup name (typeSynonyms env) of
558− Just (synArgs, body) -> do
559− let repl = replaceAllTypeVars (zip synArgs args) body
560− replaceAllTypeSynonyms' env repl
561− Nothing -> error "Type synonym was not defined"
562−
563−expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
564−expandTypeSynonym name args = do
565− env <- getEnv
566− either (throwError . strMsg) return $ expandTypeSynonym' env name args
567−
568−expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
569−expandAllTypeSynonyms = everywhereOnTypesTopDownM go
570− where
571− go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
572− go other = return other
573−
574−-- |
575−-- Ensure a set of property names and value does not contain duplicate labels
576−--
577−ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Expr)] -> m ()
578−ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
579−
580−-- |
581−-- Infer a type for a value, rethrowing any error to provide a more useful error message
582−--
583−infer :: Expr -> UnifyT Type Check Expr
584−infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ExprError val)) <>) $ infer' val
585−
586−-- |
587−-- Infer a type for a value
588−--
589−infer' :: Expr -> UnifyT Type Check Expr
590−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
591−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
592−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
593−infer' (ArrayLiteral vals) = do
594− ts <- mapM infer vals
595− els <- fresh
596− forM_ ts $ \(TypedValue _ _ t) -> els =?= t
597− return $ TypedValue True (ArrayLiteral ts) (TypeApp tyArray els)
598−infer' (ObjectLiteral ps) = do
599− ensureNoDuplicateProperties ps
600− ts <- mapM (infer . snd) ps
601− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
602− ty = TypeApp tyObject $ rowFromList (fields, REmpty)
603− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
604−infer' (ObjectUpdate o ps) = do
605− ensureNoDuplicateProperties ps
606− row <- fresh
607− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
608− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
609− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
610− let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
611− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
612− return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
613−infer' (Accessor prop val) = do
614− typed@(TypedValue _ _ objTy) <- infer val
615− propTy <- inferProperty objTy prop
616− case propTy of
617− Nothing -> do
618− field <- fresh
619− rest <- fresh
620− _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
621− return $ TypedValue True (Accessor prop typed) field
622− Just ty -> return $ TypedValue True (Accessor prop typed) ty
623−infer' (Abs (Left arg) ret) = do
624− ty <- fresh
625− Just moduleName <- checkCurrentModule <$> get
626− makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, ty, Defined)] $ do
627− body@(TypedValue _ _ bodyTy) <- infer' ret
628− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
629−infer' (Abs (Right _) _) = error "Binder was not desugared"
630−infer' (App f arg) = do
631− f'@(TypedValue _ _ ft) <- infer f
632− (ret, app) <- checkFunctionApplication f' ft arg Nothing
633− return $ TypedValue True app ret
634−infer' (Var var) = do
635− Just moduleName <- checkCurrentModule <$> get
636− checkVisibility moduleName var
637− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
638− case ty of
639− ConstrainedType constraints ty' -> do
640− dicts <- getTypeClassDictionaries
641− return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
642− _ -> return $ TypedValue True (Var var) ty
643−infer' v@(Constructor c) = do
644− env <- getEnv
645− case M.lookup c (dataConstructors env) of
646− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
647− Just (_, _, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
648− return $ TypedValue True v ty'
649−infer' (Case vals binders) = do
650− ts <- mapM infer vals
651− ret <- fresh
652− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
653− return $ TypedValue True (Case ts binders') ret
654−infer' (IfThenElse cond th el) = do
655− cond' <- check cond tyBoolean
656− v2@(TypedValue _ _ t2) <- infer th
657− v3@(TypedValue _ _ t3) <- infer el
658− t2 =?= t3
659− return $ TypedValue True (IfThenElse cond' v2 v3) t2
660−infer' (Let ds val) = do
661− (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
662− return $ TypedValue True (Let ds' val') valTy
663−infer' (SuperClassDictionary className tys) = do
664− dicts <- getTypeClassDictionaries
665− return $ TypeClassDictionary False (className, tys) dicts
666−infer' (TypedValue checkType val ty) = do
667− Just moduleName <- checkCurrentModule <$> get
668− kind <- liftCheck $ kindOf moduleName ty
669− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
670− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
671− val' <- if checkType then check val ty' else return val
672− return $ TypedValue True val' ty'
673−infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
674−infer' _ = error "Invalid argument to infer"
675−
676−inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Type Check Expr) -> UnifyT Type Check ([Declaration], Expr)
677−inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
678−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing tv@(TypedValue checkType val ty) : rest) ret j = do
679− Just moduleName <- checkCurrentModule <$> get
680− kind <- liftCheck $ kindOf moduleName ty
681− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
682− let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
683− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
684− TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
685− bindNames (M.singleton (moduleName, ident) (ty'', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing (TypedValue checkType val' ty'')]) rest ret j
686−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
687− valTy <- fresh
688− Just moduleName <- checkCurrentModule <$> get
689− let dict = M.singleton (moduleName, ident) (valTy, nameKind, Undefined)
690− TypedValue _ val' valTy' <- bindNames dict $ infer val
691− valTy =?= valTy'
692− bindNames (M.singleton (moduleName, ident) (valTy', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
693−inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
694− Just moduleName <- checkCurrentModule <$> get
695− (es, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
696− ds' <- forM es $ \e -> do
697− (ident, (val', _)) <- typeForBindingGroupElement moduleName e dict untypedDict
698− return $ (ident, LocalVariable, val')
699− makeBindingGroupVisible $ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
700−inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
701− ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
702− return (PositionedDeclaration pos d' : ds', val')
703−inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
704−
705−-- |
706−-- Infer the type of a property inside a record with a given type
707−--
708−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
709−inferProperty (TypeApp obj row) prop | obj == tyObject = do
710− let (props, _) = rowToList row
711− return $ lookup prop props
712−inferProperty (SaturatedTypeSynonym name args) prop = do
713− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
714− inferProperty replaced prop
715−inferProperty (ForAll ident ty _) prop = do
716− replaced <- replaceVarWithUnknown ident ty
717− inferProperty replaced prop
718−inferProperty _ _ = return Nothing
719−
720−-- |
721−-- Infer the types of variables brought into scope by a binder
722−--
723−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
724−inferBinder _ NullBinder = return M.empty
725−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
726−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
727−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
728−inferBinder val (VarBinder name) = return $ M.singleton name val
729−inferBinder val (ConstructorBinder ctor binders) = do
730− env <- getEnv
731− case M.lookup ctor (dataConstructors env) of
732− Just (_, _, ty) -> do
733− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
734− fn' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ fn
735− go binders fn'
736− where
737− go [] ty' = do
738− _ <- subsumes Nothing val ty'
739− return M.empty
740− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
741− M.union <$> inferBinder obj binder <*> go binders' ret
742− go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
743− _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
744−inferBinder val (ObjectBinder props) = do
745− row <- fresh
746− rest <- fresh
747− m1 <- inferRowProperties row rest props
748− val =?= TypeApp tyObject row
749− return m1
750− where
751− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
752− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
753− inferRowProperties nrow row ((name, binder):binders) = do
754− propTy <- fresh
755− m1 <- inferBinder propTy binder
756− m2 <- inferRowProperties nrow (RCons name propTy row) binders
757− return $ m1 `M.union` m2
758−inferBinder val (ArrayBinder binders) = do
759− el <- fresh
760− m1 <- M.unions <$> mapM (inferBinder el) binders
761− val =?= TypeApp tyArray el
762− return m1
763−inferBinder val (ConsBinder headBinder tailBinder) = do
764− el <- fresh
765− m1 <- inferBinder el headBinder
766− m2 <- inferBinder val tailBinder
767− val =?= TypeApp tyArray el
768− return $ m1 `M.union` m2
769−inferBinder val (NamedBinder name binder) = do
770− m <- inferBinder val binder
771− return $ M.insert name val m
772−inferBinder val (PositionedBinder pos binder) =
773− rethrowWithPosition pos $ inferBinder val binder
774−
775−-- |
776−-- Check the types of the return values in a set of binders in a case statement
777−--
778−checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
779−checkBinders _ _ [] = return []
780−checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
781− Just moduleName <- checkCurrentModule <$> get
782− m1 <- M.unions <$> zipWithM inferBinder nvals binders
783− r <- bindLocalVariables moduleName [ (name, ty, Defined) | (name, ty) <- M.toList m1 ] $ do
784− val' <- TypedValue True <$> check val ret <*> pure ret
785− case grd of
786− Nothing -> return $ CaseAlternative binders Nothing val'
787− Just g -> do
788− g' <- check g tyBoolean
789− return $ CaseAlternative binders (Just g') val'
790− rs <- checkBinders nvals ret bs
791− return $ r : rs
792−
793−-- |
794−-- Generate a new skolem constant
795−--
796−newSkolemConstant :: UnifyT Type Check Int
797−newSkolemConstant = fresh'
798−
799−-- |
800−-- Generate a new skolem scope
801−--
802−newSkolemScope :: UnifyT Type Check SkolemScope
803−newSkolemScope = SkolemScope <$> fresh'
804−
805−-- |
806−-- Skolemize a type variable by replacing its instances with fresh skolem constants
807−--
808−skolemize :: String -> Int -> SkolemScope -> Type -> Type
809−skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
810−
811−-- |
812−-- This function has one purpose - to skolemize type variables appearing in a
813−-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
814−-- only example of scoped type variables.
815−--
816−skolemizeTypesInValue :: String -> Int -> SkolemScope -> Expr -> Expr
817−skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
818− where
819− go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
820− go other = other
821−
822−-- |
823−-- Introduce skolem scope at every occurence of a ForAll
824−--
825−introduceSkolemScope :: Type -> UnifyT Type Check Type
826−introduceSkolemScope = everywhereOnTypesM go
827− where
828− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
829− go other = return other
830−
831−-- |
832−-- Check the type of a value, rethrowing errors to provide a better error message
833−--
834−check :: Expr -> Type -> UnifyT Type Check Expr
835−check val ty = rethrow (mkErrorStack errorMessage (Just (ExprError val)) <>) $ check' val ty
836− where
837− errorMessage =
838− "Error checking type of term " ++
839− prettyPrintValue val ++
840− " against type " ++
841− prettyPrintType ty
842−
843−-- |
844−-- Check the type of a value
845−--
846−check' :: Expr -> Type -> UnifyT Type Check Expr
847−check' val (ForAll ident ty _) = do
848− scope <- newSkolemScope
849− sko <- newSkolemConstant
850− let sk = skolemize ident sko scope ty
851− let skVal = skolemizeTypesInValue ident sko scope val
852− val' <- check skVal sk
853− return $ TypedValue True val' (ForAll ident ty (Just scope))
854−check' val t@(ConstrainedType constraints ty) = do
855− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
856− n <- liftCheck freshDictionaryName
857− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
858− val' <- makeBindingGroupVisible $ withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
859− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
860− constraints) $ check val ty
861− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
862−check' val (SaturatedTypeSynonym name args) = do
863− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
864− check val ty
865−check' val u@(TUnknown _) = do
866− val'@(TypedValue _ _ ty) <- infer val
867− -- Don't unify an unknown with an inferred polytype
868− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
869− ty' =?= u
870− return $ TypedValue True val'' ty'
871−check' v@(NumericLiteral _) t | t == tyNumber =
872− return $ TypedValue True v t
873−check' v@(StringLiteral _) t | t == tyString =
874− return $ TypedValue True v t
875−check' v@(BooleanLiteral _) t | t == tyBoolean =
876− return $ TypedValue True v t
877−check' (ArrayLiteral vals) t@(TypeApp a ty) = do
878− a =?= tyArray
879− array <- ArrayLiteral <$> forM vals (`check` ty)
880− return $ TypedValue True array t
881−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
882− Just moduleName <- checkCurrentModule <$> get
883− ret' <- makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, argTy, Defined)] $ check ret retTy
884− return $ TypedValue True (Abs (Left arg) ret') ty
885−check' (Abs (Right _) _) _ = error "Binder was not desugared"
886−check' (App f arg) ret = do
887− f'@(TypedValue _ _ ft) <- infer f
888− (_, app) <- checkFunctionApplication f' ft arg (Just ret)
889− return $ TypedValue True app ret
890−check' v@(Var var) ty = do
891− Just moduleName <- checkCurrentModule <$> get
892− checkVisibility moduleName var
893− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
894− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
895− v' <- subsumes (Just v) repl ty'
896− case v' of
897− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
898− Just v'' -> return $ TypedValue True v'' ty'
899−check' (SuperClassDictionary className tys) _ = do
900− {-
901− -- Here, we replace a placeholder for a superclass dictionary with a regular
902− -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
903− -- correct super instance dictionaries in scope, and these are not available when the type class
904− -- declaration gets desugared.
905− --
906− -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
907− -- to consider superclass instances when searching for this dictionary - doing so might lead
908− -- to traversing a cycle in the instance graph.
909− -}
910− dicts <- getTypeClassDictionaries
911− return $ TypeClassDictionary False (className, tys) dicts
912−check' (TypedValue checkType val ty1) ty2 = do
913− Just moduleName <- checkCurrentModule <$> get
914− kind <- liftCheck $ kindOf moduleName ty1
915− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
916− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
917− ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty2
918− val' <- subsumes (Just val) ty1' ty2'
919− case val' of
920− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
921− Just val'' -> do
922− val''' <- if checkType then check val'' ty2' else return val''
923− return $ TypedValue checkType (TypedValue True val''' ty1') ty2'
924−check' (Case vals binders) ret = do
925− vals' <- mapM infer vals
926− let ts = map (\(TypedValue _ _ t) -> t) vals'
927− binders' <- checkBinders ts ret binders
928− return $ TypedValue True (Case vals' binders') ret
929−check' (IfThenElse cond th el) ty = do
930− cond' <- check cond tyBoolean
931− th' <- check th ty
932− el' <- check el ty
933− return $ TypedValue True (IfThenElse cond' th' el') ty
934−check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
935− ensureNoDuplicateProperties ps
936− ps' <- checkProperties ps row False
937− return $ TypedValue True (ObjectLiteral ps') t
938−check' (TypeClassDictionaryConstructorApp name ps) t = do
939− ps' <- check' ps t
940− return $ TypedValue True (TypeClassDictionaryConstructorApp name ps') t
941−check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
942− ensureNoDuplicateProperties ps
943− us <- zip (map fst ps) <$> replicateM (length ps) fresh
944− let (propsToCheck, rest) = rowToList row
945− propsToRemove = map fst ps
946− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
947− obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
948− ps' <- checkProperties ps row True
949− return $ TypedValue True (ObjectUpdate obj' ps') t
950−check' (Accessor prop val) ty = do
951− rest <- fresh
952− val' <- check val (TypeApp tyObject (RCons prop ty rest))
953− return $ TypedValue True (Accessor prop val') ty
954−check' (Constructor c) ty = do
955− env <- getEnv
956− case M.lookup c (dataConstructors env) of
957− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
958− Just (_, _, ty1) -> do
959− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
960− _ <- subsumes Nothing repl ty
961− return $ TypedValue True (Constructor c) ty
962−check' (Let ds val) ty = do
963− (ds', val') <- inferLetBinding [] ds val (flip check ty)
964− return $ TypedValue True (Let ds' val') ty
965−check' val ty | containsTypeSynonyms ty = do
966− ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
967− check val ty'
968−check' (PositionedValue pos val) ty =
969− rethrowWithPosition pos $ check val ty
970−check' val ty = throwError $ mkErrorStack ("Expr does not have type " ++ prettyPrintType ty) (Just (ExprError val))
971−
972−containsTypeSynonyms :: Type -> Bool
973−containsTypeSynonyms = everythingOnTypes (||) go where
974− go (SaturatedTypeSynonym _ _) = True
975− go _ = False
976−
977−-- |
978−-- Check the type of a collection of named record fields
979−--
980−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
981−--
982−checkProperties :: [(String, Expr)] -> Type -> Bool -> UnifyT Type Check [(String, Expr)]
983−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
984− go [] [] REmpty = return []
985− go [] [] u@(TUnknown _) = do u =?= REmpty
986− return []
987− go [] [] (Skolem _ _ _) | lax = return []
988− go [] ((p, _): _) _ | lax = return []
989− | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ExprError (ObjectLiteral ps)))
990− go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ExprError (ObjectLiteral ps)))
991− go ((p,v):ps') [] u@(TUnknown _) = do
992− v'@(TypedValue _ _ ty) <- infer v
993− rest <- fresh
994− u =?= RCons p ty rest
995− ps'' <- go ps' [] rest
996− return $ (p, v') : ps''
997− go ((p,v):ps') ts r =
998− case lookup p ts of
999− Nothing -> do
1000− v'@(TypedValue _ _ ty) <- infer v
1001− rest <- fresh
1002− r =?= RCons p ty rest
1003− ps'' <- go ps' ts rest
1004− return $ (p, v') : ps''
1005− Just ty -> do
1006− v' <- check v ty
1007− ps'' <- go ps' (delete (p, ty) ts) r
1008− return $ (p, v') : ps''
1009− go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ExprError (ObjectLiteral ps)))
1010−
1011−-- |
1012−-- Check the type of a function application, rethrowing errors to provide a better error message
1013−--
1014−checkFunctionApplication :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
1015−checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ExprError fn)) <>) $ do
1016− subst <- unifyCurrentSubstitution <$> UnifyT get
1017− checkFunctionApplication' fn (subst $? fnTy) arg (($?) subst <$> ret)
1018− where
1019− errorMessage = "Error applying function of type "
1020− ++ prettyPrintType fnTy
1021− ++ " to argument " ++ prettyPrintValue arg
1022−
1023−-- |
1024−-- Check the type of a function application
1025−--
1026−checkFunctionApplication' :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
1027−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
1028− tyFunction' =?= tyFunction
1029− arg' <- check arg argTy
1030− case ret of
1031− Nothing -> return (retTy, App fn arg')
1032− Just ret' -> do
1033− Just app' <- subsumes (Just (App fn arg')) retTy ret'
1034− return (retTy, app')
1035−checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
1036− replaced <- replaceVarWithUnknown ident ty
1037− checkFunctionApplication fn replaced arg ret
1038−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1039− arg' <- do
1040− TypedValue _ arg' t <- infer arg
1041− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
1042− return $ TypedValue True arg'' t'
1043− let ty = (\(TypedValue _ _ t) -> t) arg'
1044− ret' <- maybe fresh return ret
1045− u =?= function ty ret'
1046− return (ret', App fn arg')
1047−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1048− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1049− checkFunctionApplication fn ty arg ret
1050−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1051− dicts <- getTypeClassDictionaries
1052− checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1053−checkFunctionApplication' fn fnTy dict@(TypeClassDictionary _ _ _) _ =
1054− return (fnTy, App fn dict)
1055−checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1056− ++ prettyPrintType fnTy
1057− ++ " to argument " ++ prettyPrintValue arg
1058−
1059−-- |
1060−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1061−--
1062−subsumes :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1063−subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ExprError <$> val) <>) $ subsumes' val ty1 ty2
1064− where
1065− errorMessage = "Error checking that type "
1066− ++ prettyPrintType ty1
1067− ++ " subsumes type "
1068− ++ prettyPrintType ty2
1069−
1070−-- |
1071−-- Check whether one type subsumes another
1072−--
1073−subsumes' :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1074−subsumes' val (ForAll ident ty1 _) ty2 = do
1075− replaced <- replaceVarWithUnknown ident ty1
1076− subsumes val replaced ty2
1077−subsumes' val ty1 (ForAll ident ty2 sco) =
1078− case sco of
1079− Just sco' -> do
1080− sko <- newSkolemConstant
1081− let sk = skolemize ident sko sco' ty2
1082− subsumes val ty1 sk
1083− Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1084−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1085− _ <- subsumes Nothing arg2 arg1
1086− _ <- subsumes Nothing ret1 ret2
1087− return val
1088−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1089− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1090− subsumes val ty1 ty2
1091−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1092− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1093− subsumes val ty1 ty2
1094−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1095− dicts <- getTypeClassDictionaries
1096− subsumes' (Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)) ty1 ty2
1097−subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1098− let
1099− (ts1, r1') = rowToList r1
1100− (ts2, r2') = rowToList r2
1101− ts1' = sortBy (comparing fst) ts1
1102− ts2' = sortBy (comparing fst) ts2
1103− go ts1' ts2' r1' r2'
1104− return val
1105− where
1106− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1107− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1108− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1109− | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1110− go ts1 ts2 r1' r2'
1111− | p1 < p2 = do rest <- fresh
1112− r2' =?= RCons p1 ty1 rest
1113− go ts1 ((p2, ty2) : ts2) r1' rest
1114− | otherwise = do rest <- fresh
1115− r1' =?= RCons p2 ty2 rest
1116− go ((p1, ty1) : ts1) ts2 rest r2'
1117−subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1118−subsumes' val ty1 ty2 = do
1119− ty1 =?= ty2
1120− return val
1121−
1122−
1123−
1124−
1125−