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