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