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