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