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