@@ -1,1230 +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, remove duplicate row fields, and replace
196− -- top-level unification variables with named type variables.
197− let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
198− ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ 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 _ _ ty) = checkDups ty >> return e
531− go other = return other
532−
533− checkDups :: Type -> Check ()
534− checkDups (TypeApp t1 t2) = checkDups t1 >> checkDups t2
535− checkDups (SaturatedTypeSynonym _ ts) = mapM_ checkDups ts
536− checkDups (ForAll _ t _) = checkDups t
537− checkDups (ConstrainedType args t) = do
538− mapM_ (checkDups) $ concatMap snd args
539− checkDups t
540− checkDups r@(RCons _ _ _) =
541− let (ls, _) = rowToList r in
542− case firstDup . sort . map fst $ ls of
543− Just l -> throwError . strMsg $ "Duplicate label " ++ show l ++ " in row"
544− Nothing -> return ()
545− checkDups _ = return ()
546−
547− firstDup :: (Eq a) => [a] -> Maybe a
548− firstDup (x : xs@(x' : _))
549− | x == x' = Just x
550− | otherwise = firstDup xs
551− firstDup _ = Nothing
552−
553−-- |
554−-- Ensure a row contains no duplicate labels
555−--
556−setify :: Type -> Type
557−setify = rowFromList . first (M.toList . M.fromList) . rowToList
558−
559−-- |
560−-- \"Setify\" all rows occuring inside a value
561−--
562−setifyAll :: Type -> Type
563−setifyAll = everywhereOnTypes setify
564−
565−-- |
566−-- Replace outermost unsolved unification variables with named type variables
567−--
568−varIfUnknown :: Type -> Type
569−varIfUnknown ty =
570− let unks = nub $ unknowns ty
571− toName = (:) 't' . show
572− ty' = everywhereOnTypes typeToVar ty
573− typeToVar :: Type -> Type
574− typeToVar (TUnknown u) = TypeVar (toName u)
575− typeToVar t = t
576− in mkForAll (sort . map toName $ unks) ty'
577−
578−-- |
579−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
580−-- or TypeClassDictionary values.
581−--
582−-- This is necessary during type checking to avoid unifying a polymorphic type with a
583−-- unification variable.
584−--
585−instantiatePolyTypeWithUnknowns :: Expr -> Type -> UnifyT Type Check (Expr, Type)
586−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
587− ty' <- replaceVarWithUnknown ident ty
588− instantiatePolyTypeWithUnknowns val ty'
589−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
590− dicts <- getTypeClassDictionaries
591− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
592− return (foldl App val (map (flip (TypeClassDictionary True) dicts) constraints), ty')
593−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
594−
595−-- |
596−-- Replace a single type variable with a new unification variable
597−--
598−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
599−replaceVarWithUnknown ident ty = do
600− tu <- fresh
601− return $ replaceTypeVars ident tu ty
602−
603−-- |
604−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
605−-- better error messages during unification.
606−--
607−replaceAllTypeSynonyms' :: Environment -> Type -> Either String Type
608−replaceAllTypeSynonyms' env d =
609− let
610− syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
611− in
612− saturateAllTypeSynonyms syns d
613−
614−replaceAllTypeSynonyms :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
615−replaceAllTypeSynonyms d = do
616− env <- getEnv
617− either (throwError . strMsg) return $ replaceAllTypeSynonyms' env d
618−
619−-- |
620−-- \"Desaturate\" @SaturatedTypeSynonym@s
621−--
622−desaturateAllTypeSynonyms :: Type -> Type
623−desaturateAllTypeSynonyms = everywhereOnTypes replaceSaturatedTypeSynonym
624− where
625− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
626− replaceSaturatedTypeSynonym t = t
627−
628−-- |
629−-- Replace a type synonym and its arguments with the aliased type
630−--
631−expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
632−expandTypeSynonym' env name args =
633− case M.lookup name (typeSynonyms env) of
634− Just (synArgs, body) -> do
635− let repl = replaceAllTypeVars (zip (map fst synArgs) args) body
636− replaceAllTypeSynonyms' env repl
637− Nothing -> error "Type synonym was not defined"
638−
639−expandTypeSynonym :: (Error e, Functor m, Monad m, MonadState CheckState m, MonadError e m) => Qualified ProperName -> [Type] -> m Type
640−expandTypeSynonym name args = do
641− env <- getEnv
642− either (throwError . strMsg) return $ expandTypeSynonym' env name args
643−
644−expandAllTypeSynonyms :: (Error e, Functor m, Applicative m, Monad m, MonadState CheckState m, MonadError e m) => Type -> m Type
645−expandAllTypeSynonyms = everywhereOnTypesTopDownM go
646− where
647− go (SaturatedTypeSynonym name args) = expandTypeSynonym name args
648− go other = return other
649−
650−-- |
651−-- Ensure a set of property names and value does not contain duplicate labels
652−--
653−ensureNoDuplicateProperties :: (Error e, MonadError e m) => [(String, Expr)] -> m ()
654−ensureNoDuplicateProperties ps = guardWith (strMsg "Duplicate property names") $ length (nub . map fst $ ps) == length ps
655−
656−-- |
657−-- Infer a type for a value, rethrowing any error to provide a more useful error message
658−--
659−infer :: Expr -> UnifyT Type Check Expr
660−infer val = rethrow (mkErrorStack "Error inferring type of value" (Just (ExprError val)) <>) $ infer' val
661−
662−-- |
663−-- Infer a type for a value
664−--
665−infer' :: Expr -> UnifyT Type Check Expr
666−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
667−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
668−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
669−infer' (ArrayLiteral vals) = do
670− ts <- mapM infer vals
671− els <- fresh
672− forM_ ts $ \(TypedValue _ _ t) -> els =?= t
673− return $ TypedValue True (ArrayLiteral ts) (TypeApp tyArray els)
674−infer' (ObjectLiteral ps) = do
675− ensureNoDuplicateProperties ps
676− ts <- mapM (infer . snd) ps
677− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
678− ty = TypeApp tyObject $ rowFromList (fields, REmpty)
679− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
680−infer' (ObjectUpdate o ps) = do
681− ensureNoDuplicateProperties ps
682− row <- fresh
683− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
684− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
685− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
686− let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
687− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
688− return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
689−infer' (Accessor prop val) = do
690− typed@(TypedValue _ _ objTy) <- infer val
691− propTy <- inferProperty objTy prop
692− case propTy of
693− Nothing -> do
694− field <- fresh
695− rest <- fresh
696− _ <- subsumes Nothing objTy (TypeApp tyObject (RCons prop field rest))
697− return $ TypedValue True (Accessor prop typed) field
698− Just ty -> return $ TypedValue True (Accessor prop typed) ty
699−infer' (Abs (Left arg) ret) = do
700− ty <- fresh
701− Just moduleName <- checkCurrentModule <$> get
702− makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, ty, Defined)] $ do
703− body@(TypedValue _ _ bodyTy) <- infer' ret
704− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
705−infer' (Abs (Right _) _) = error "Binder was not desugared"
706−infer' (App f arg) = do
707− f'@(TypedValue _ _ ft) <- infer f
708− (ret, app) <- checkFunctionApplication f' ft arg Nothing
709− return $ TypedValue True app ret
710−infer' (Var var) = do
711− Just moduleName <- checkCurrentModule <$> get
712− checkVisibility moduleName var
713− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
714− case ty of
715− ConstrainedType constraints ty' -> do
716− dicts <- getTypeClassDictionaries
717− return $ TypedValue True (foldl App (Var var) (map (flip (TypeClassDictionary True) dicts) constraints)) ty'
718− _ -> return $ TypedValue True (Var var) ty
719−infer' v@(Constructor c) = do
720− env <- getEnv
721− case M.lookup c (dataConstructors env) of
722− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
723− Just (_, _, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
724− return $ TypedValue True v ty'
725−infer' (Case vals binders) = do
726− ts <- mapM infer vals
727− ret <- fresh
728− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
729− return $ TypedValue True (Case ts binders') ret
730−infer' (IfThenElse cond th el) = do
731− cond' <- check cond tyBoolean
732− v2@(TypedValue _ _ t2) <- infer th
733− v3@(TypedValue _ _ t3) <- infer el
734− (v2', v3', t) <- meet v2 v3 t2 t3
735− return $ TypedValue True (IfThenElse cond' v2' v3') t
736−infer' (Let ds val) = do
737− (ds', val'@(TypedValue _ _ valTy)) <- inferLetBinding [] ds val infer
738− return $ TypedValue True (Let ds' val') valTy
739−infer' (SuperClassDictionary className tys) = do
740− dicts <- getTypeClassDictionaries
741− return $ TypeClassDictionary False (className, tys) dicts
742−infer' (TypedValue checkType val ty) = do
743− Just moduleName <- checkCurrentModule <$> get
744− kind <- liftCheck $ kindOf moduleName ty
745− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
746− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
747− val' <- if checkType then check val ty' else return val
748− return $ TypedValue True val' ty'
749−infer' (PositionedValue pos val) = rethrowWithPosition pos $ infer' val
750−infer' _ = error "Invalid argument to infer"
751−
752−inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Type Check Expr) -> UnifyT Type Check ([Declaration], Expr)
753−inferLetBinding seen [] ret j = (,) seen <$> makeBindingGroupVisible (j ret)
754−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing tv@(TypedValue checkType val ty) : rest) ret j = do
755− Just moduleName <- checkCurrentModule <$> get
756− kind <- liftCheck $ kindOf moduleName ty
757− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
758− let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
759− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
760− TypedValue _ val' ty'' <- if checkType then bindNames dict (check val ty') else return tv
761− bindNames (M.singleton (moduleName, ident) (ty'', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing (TypedValue checkType val' ty'')]) rest ret j
762−inferLetBinding seen (ValueDeclaration ident nameKind [] Nothing val : rest) ret j = do
763− valTy <- fresh
764− Just moduleName <- checkCurrentModule <$> get
765− let dict = M.singleton (moduleName, ident) (valTy, nameKind, Undefined)
766− TypedValue _ val' valTy' <- bindNames dict $ infer val
767− valTy =?= valTy'
768− bindNames (M.singleton (moduleName, ident) (valTy', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] Nothing val']) rest ret j
769−inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
770− Just moduleName <- checkCurrentModule <$> get
771− (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName (map (\(i, _, v) -> (i, v)) ds)
772− ds1' <- parU typed $ \e -> checkTypedBindingGroupElement moduleName e dict
773− ds2' <- forM untyped $ \e -> typeForBindingGroupElement e dict untypedDict
774− let ds' = [(ident, LocalVariable, val') | (ident, (val', _)) <- ds1' ++ ds2']
775− makeBindingGroupVisible $ bindNames dict $ inferLetBinding (seen ++ [BindingGroupDeclaration ds']) rest ret j
776−inferLetBinding seen (PositionedDeclaration pos d : ds) ret j = rethrowWithPosition pos $ do
777− ((d' : ds'), val') <- inferLetBinding seen (d : ds) ret j
778− return (PositionedDeclaration pos d' : ds', val')
779−inferLetBinding _ _ _ _ = error "Invalid argument to inferLetBinding"
780−
781−-- |
782−-- Infer the type of a property inside a record with a given type
783−--
784−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
785−inferProperty (TypeApp obj row) prop | obj == tyObject = do
786− let (props, _) = rowToList row
787− return $ lookup prop props
788−inferProperty (SaturatedTypeSynonym name args) prop = do
789− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
790− inferProperty replaced prop
791−inferProperty (ForAll ident ty _) prop = do
792− replaced <- replaceVarWithUnknown ident ty
793− inferProperty replaced prop
794−inferProperty _ _ = return Nothing
795−
796−-- |
797−-- Infer the types of variables brought into scope by a binder
798−--
799−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
800−inferBinder _ NullBinder = return M.empty
801−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
802−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
803−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
804−inferBinder val (VarBinder name) = return $ M.singleton name val
805−inferBinder val (ConstructorBinder ctor binders) = do
806− env <- getEnv
807− case M.lookup ctor (dataConstructors env) of
808− Just (_, _, ty) -> do
809− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
810− fn' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ fn
811− go binders fn'
812− where
813− go [] ty' = do
814− _ <- subsumes Nothing val ty'
815− return M.empty
816− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
817− M.union <$> inferBinder obj binder <*> go binders' ret
818− go _ _ = throwError . strMsg $ "Wrong number of arguments to constructor " ++ show ctor
819− _ -> throwError . strMsg $ "Constructor " ++ show ctor ++ " is not defined"
820−inferBinder val (ObjectBinder props) = do
821− row <- fresh
822− rest <- fresh
823− m1 <- inferRowProperties row rest props
824− val =?= TypeApp tyObject row
825− return m1
826− where
827− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
828− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
829− inferRowProperties nrow row ((name, binder):binders) = do
830− propTy <- fresh
831− m1 <- inferBinder propTy binder
832− m2 <- inferRowProperties nrow (RCons name propTy row) binders
833− return $ m1 `M.union` m2
834−inferBinder val (ArrayBinder binders) = do
835− el <- fresh
836− m1 <- M.unions <$> mapM (inferBinder el) binders
837− val =?= TypeApp tyArray el
838− return m1
839−inferBinder val (ConsBinder headBinder tailBinder) = do
840− el <- fresh
841− m1 <- inferBinder el headBinder
842− m2 <- inferBinder val tailBinder
843− val =?= TypeApp tyArray el
844− return $ m1 `M.union` m2
845−inferBinder val (NamedBinder name binder) = do
846− m <- inferBinder val binder
847− return $ M.insert name val m
848−inferBinder val (PositionedBinder pos binder) =
849− rethrowWithPosition pos $ inferBinder val binder
850−
851−-- |
852−-- Check the types of the return values in a set of binders in a case statement
853−--
854−checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
855−checkBinders _ _ [] = return []
856−checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
857− guardWith (strMsg "Overlapping binders in case statement") $
858− let ns = concatMap binderNames binders in length (nub ns) == length ns
859− Just moduleName <- checkCurrentModule <$> get
860− m1 <- M.unions <$> zipWithM inferBinder nvals binders
861− r <- bindLocalVariables moduleName [ (name, ty, Defined) | (name, ty) <- M.toList m1 ] $ do
862− val' <- TypedValue True <$> check val ret <*> pure ret
863− case grd of
864− Nothing -> return $ CaseAlternative binders Nothing val'
865− Just g -> do
866− g' <- check g tyBoolean
867− return $ CaseAlternative binders (Just g') val'
868− rs <- checkBinders nvals ret bs
869− return $ r : rs
870−
871−-- |
872−-- Generate a new skolem constant
873−--
874−newSkolemConstant :: UnifyT Type Check Int
875−newSkolemConstant = fresh'
876−
877−-- |
878−-- Generate a new skolem scope
879−--
880−newSkolemScope :: UnifyT Type Check SkolemScope
881−newSkolemScope = SkolemScope <$> fresh'
882−
883−-- |
884−-- Skolemize a type variable by replacing its instances with fresh skolem constants
885−--
886−skolemize :: String -> Int -> SkolemScope -> Type -> Type
887−skolemize ident sko scope = replaceTypeVars ident (Skolem ident sko scope)
888−
889−-- |
890−-- This function has one purpose - to skolemize type variables appearing in a
891−-- SuperClassDictionary placeholder. These type variables are somewhat unique since they are the
892−-- only example of scoped type variables.
893−--
894−skolemizeTypesInValue :: String -> Int -> SkolemScope -> Expr -> Expr
895−skolemizeTypesInValue ident sko scope = let (_, f, _) = everywhereOnValues id go id in f
896− where
897− go (SuperClassDictionary c ts) = SuperClassDictionary c (map (skolemize ident sko scope) ts)
898− go other = other
899−
900−-- |
901−-- Introduce skolem scope at every occurence of a ForAll
902−--
903−introduceSkolemScope :: Type -> UnifyT Type Check Type
904−introduceSkolemScope = everywhereOnTypesM go
905− where
906− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
907− go other = return other
908−
909−-- |
910−-- Check the type of a value, rethrowing errors to provide a better error message
911−--
912−check :: Expr -> Type -> UnifyT Type Check Expr
913−check val ty = rethrow (mkErrorStack errorMessage (Just (ExprError val)) <>) $ check' val ty
914− where
915− errorMessage =
916− "Error checking type of term " ++
917− prettyPrintValue val ++
918− " against type " ++
919− prettyPrintType ty
920−
921−-- |
922−-- Check the type of a value
923−--
924−check' :: Expr -> Type -> UnifyT Type Check Expr
925−check' val (ForAll ident ty _) = do
926− scope <- newSkolemScope
927− sko <- newSkolemConstant
928− let sk = skolemize ident sko scope ty
929− let skVal = skolemizeTypesInValue ident sko scope val
930− val' <- check skVal sk
931− return $ TypedValue True val' (ForAll ident ty (Just scope))
932−check' val t@(ConstrainedType constraints ty) = do
933− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
934− n <- liftCheck freshDictionaryName
935− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
936− val' <- makeBindingGroupVisible $ withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
937− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular False) (map (Qualified Nothing) dictNames)
938− constraints) $ check val ty
939− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
940−check' val (SaturatedTypeSynonym name args) = do
941− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
942− check val ty
943−check' val u@(TUnknown _) = do
944− val'@(TypedValue _ _ ty) <- infer val
945− -- Don't unify an unknown with an inferred polytype
946− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
947− ty' =?= u
948− return $ TypedValue True val'' ty'
949−check' v@(NumericLiteral _) t | t == tyNumber =
950− return $ TypedValue True v t
951−check' v@(StringLiteral _) t | t == tyString =
952− return $ TypedValue True v t
953−check' v@(BooleanLiteral _) t | t == tyBoolean =
954− return $ TypedValue True v t
955−check' (ArrayLiteral vals) t@(TypeApp a ty) = do
956− a =?= tyArray
957− array <- ArrayLiteral <$> forM vals (`check` ty)
958− return $ TypedValue True array t
959−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
960− Just moduleName <- checkCurrentModule <$> get
961− ret' <- makeBindingGroupVisible $ bindLocalVariables moduleName [(arg, argTy, Defined)] $ check ret retTy
962− return $ TypedValue True (Abs (Left arg) ret') ty
963−check' (Abs (Right _) _) _ = error "Binder was not desugared"
964−check' (App f arg) ret = do
965− f'@(TypedValue _ _ ft) <- infer f
966− (_, app) <- checkFunctionApplication f' ft arg (Just ret)
967− return $ TypedValue True app ret
968−check' v@(Var var) ty = do
969− Just moduleName <- checkCurrentModule <$> get
970− checkVisibility moduleName var
971− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
972− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
973− v' <- subsumes (Just v) repl ty'
974− case v' of
975− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
976− Just v'' -> return $ TypedValue True v'' ty'
977−check' (SuperClassDictionary className tys) _ = do
978− {-
979− -- Here, we replace a placeholder for a superclass dictionary with a regular
980− -- TypeClassDictionary placeholder. The reason we do this is that it is necessary to have the
981− -- correct super instance dictionaries in scope, and these are not available when the type class
982− -- declaration gets desugared.
983− --
984− -- Note also that the first argument to TypeClassDictionary is False, meaning we _do not_ want
985− -- to consider superclass instances when searching for this dictionary - doing so might lead
986− -- to traversing a cycle in the instance graph.
987− -}
988− dicts <- getTypeClassDictionaries
989− return $ TypeClassDictionary False (className, tys) dicts
990−check' (TypedValue checkType val ty1) ty2 = do
991− Just moduleName <- checkCurrentModule <$> get
992− kind <- liftCheck $ kindOf moduleName ty1
993− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
994− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
995− ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty2
996− val' <- subsumes (Just val) ty1' ty2'
997− case val' of
998− Nothing -> throwError . strMsg $ "Unable to check type subsumption"
999− Just val'' -> do
1000− val''' <- if checkType then check val'' ty2' else return val''
1001− return $ TypedValue checkType (TypedValue True val''' ty1') ty2'
1002−check' (Case vals binders) ret = do
1003− vals' <- mapM infer vals
1004− let ts = map (\(TypedValue _ _ t) -> t) vals'
1005− binders' <- checkBinders ts ret binders
1006− return $ TypedValue True (Case vals' binders') ret
1007−check' (IfThenElse cond th el) ty = do
1008− cond' <- check cond tyBoolean
1009− th' <- check th ty
1010− el' <- check el ty
1011− return $ TypedValue True (IfThenElse cond' th' el') ty
1012−check' (ObjectLiteral ps) t@(TypeApp obj row) | obj == tyObject = do
1013− ensureNoDuplicateProperties ps
1014− ps' <- checkProperties ps row False
1015− return $ TypedValue True (ObjectLiteral ps') t
1016−check' (TypeClassDictionaryConstructorApp name ps) t = do
1017− ps' <- check' ps t
1018− return $ TypedValue True (TypeClassDictionaryConstructorApp name ps') t
1019−check' (ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
1020− ensureNoDuplicateProperties ps
1021− us <- zip (map fst ps) <$> replicateM (length ps) fresh
1022− let (propsToCheck, rest) = rowToList row
1023− propsToRemove = map fst ps
1024− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
1025− obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
1026− ps' <- checkProperties ps row True
1027− return $ TypedValue True (ObjectUpdate obj' ps') t
1028−check' (Accessor prop val) ty = do
1029− rest <- fresh
1030− val' <- check val (TypeApp tyObject (RCons prop ty rest))
1031− return $ TypedValue True (Accessor prop val') ty
1032−check' (Constructor c) ty = do
1033− env <- getEnv
1034− case M.lookup c (dataConstructors env) of
1035− Nothing -> throwError . strMsg $ "Constructor " ++ show c ++ " is undefined"
1036− Just (_, _, ty1) -> do
1037− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
1038− _ <- subsumes Nothing repl ty
1039− return $ TypedValue True (Constructor c) ty
1040−check' (Let ds val) ty = do
1041− (ds', val') <- inferLetBinding [] ds val (flip check ty)
1042− return $ TypedValue True (Let ds' val') ty
1043−check' val ty | containsTypeSynonyms ty = do
1044− ty' <- introduceSkolemScope <=< expandAllTypeSynonyms $ ty
1045− check val ty'
1046−check' val kt@(KindedType ty kind) = do
1047− guardWith (strMsg $ "Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
1048− val' <- check' val ty
1049− return $ TypedValue True val' kt
1050−check' (PositionedValue pos val) ty =
1051− rethrowWithPosition pos $ check val ty
1052−check' val ty = throwError $ mkErrorStack ("Expr does not have type " ++ prettyPrintType ty) (Just (ExprError val))
1053−
1054−containsTypeSynonyms :: Type -> Bool
1055−containsTypeSynonyms = everythingOnTypes (||) go where
1056− go (SaturatedTypeSynonym _ _) = True
1057− go _ = False
1058−
1059−-- |
1060−-- Check the type of a collection of named record fields
1061−--
1062−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
1063−--
1064−checkProperties :: [(String, Expr)] -> Type -> Bool -> UnifyT Type Check [(String, Expr)]
1065−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
1066− go [] [] REmpty = return []
1067− go [] [] u@(TUnknown _) = do u =?= REmpty
1068− return []
1069− go [] [] (Skolem _ _ _) | lax = return []
1070− go [] ((p, _): _) _ | lax = return []
1071− | otherwise = throwError $ mkErrorStack ("Object does not have property " ++ p) (Just (ExprError (ObjectLiteral ps)))
1072− go ((p,_):_) [] REmpty = throwError $ mkErrorStack ("Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row) (Just (ExprError (ObjectLiteral ps)))
1073− go ((p,v):ps') [] u@(TUnknown _) = do
1074− v'@(TypedValue _ _ ty) <- infer v
1075− rest <- fresh
1076− u =?= RCons p ty rest
1077− ps'' <- go ps' [] rest
1078− return $ (p, v') : ps''
1079− go ((p,v):ps') ts r =
1080− case lookup p ts of
1081− Nothing -> do
1082− v'@(TypedValue _ _ ty) <- infer v
1083− rest <- fresh
1084− r =?= RCons p ty rest
1085− ps'' <- go ps' ts rest
1086− return $ (p, v') : ps''
1087− Just ty -> do
1088− v' <- check v ty
1089− ps'' <- go ps' (delete (p, ty) ts) r
1090− return $ (p, v') : ps''
1091− go _ _ _ = throwError $ mkErrorStack ("Object does not have type " ++ prettyPrintType (TypeApp tyObject row)) (Just (ExprError (ObjectLiteral ps)))
1092−
1093−-- |
1094−-- Check the type of a function application, rethrowing errors to provide a better error message
1095−--
1096−checkFunctionApplication :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
1097−checkFunctionApplication fn fnTy arg ret = rethrow (mkErrorStack errorMessage (Just (ExprError fn)) <>) $ do
1098− subst <- unifyCurrentSubstitution <$> UnifyT get
1099− checkFunctionApplication' fn (subst $? fnTy) arg (($?) subst <$> ret)
1100− where
1101− errorMessage = "Error applying function of type "
1102− ++ prettyPrintType fnTy
1103− ++ " to argument " ++ prettyPrintValue arg
1104−
1105−-- |
1106−-- Check the type of a function application
1107−--
1108−checkFunctionApplication' :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
1109−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
1110− tyFunction' =?= tyFunction
1111− arg' <- check arg argTy
1112− case ret of
1113− Nothing -> return (retTy, App fn arg')
1114− Just ret' -> do
1115− Just app' <- subsumes (Just (App fn arg')) retTy ret'
1116− return (retTy, app')
1117−checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
1118− replaced <- replaceVarWithUnknown ident ty
1119− checkFunctionApplication fn replaced arg ret
1120−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
1121− arg' <- do
1122− TypedValue _ arg' t <- infer arg
1123− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
1124− return $ TypedValue True arg'' t'
1125− let ty = (\(TypedValue _ _ t) -> t) arg'
1126− ret' <- maybe fresh return ret
1127− u =?= function ty ret'
1128− return (ret', App fn arg')
1129−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
1130− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1131− checkFunctionApplication fn ty arg ret
1132−checkFunctionApplication' fn (KindedType ty _) arg ret = do
1133− checkFunctionApplication fn ty arg ret
1134−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
1135− dicts <- getTypeClassDictionaries
1136− checkFunctionApplication' (foldl App fn (map (flip (TypeClassDictionary True) dicts) constraints)) fnTy arg ret
1137−checkFunctionApplication' fn fnTy dict@(TypeClassDictionary _ _ _) _ =
1138− return (fnTy, App fn dict)
1139−checkFunctionApplication' _ fnTy arg _ = throwError . strMsg $ "Cannot apply a function of type "
1140− ++ prettyPrintType fnTy
1141− ++ " to argument " ++ prettyPrintValue arg
1142−
1143−-- |
1144−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
1145−--
1146−subsumes :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1147−subsumes val ty1 ty2 = rethrow (mkErrorStack errorMessage (ExprError <$> val) <>) $ subsumes' val ty1 ty2
1148− where
1149− errorMessage = "Error checking that type "
1150− ++ prettyPrintType ty1
1151− ++ " subsumes type "
1152− ++ prettyPrintType ty2
1153−
1154−-- |
1155−-- Check whether one type subsumes another
1156−--
1157−subsumes' :: Maybe Expr -> Type -> Type -> UnifyT Type Check (Maybe Expr)
1158−subsumes' val (ForAll ident ty1 _) ty2 = do
1159− replaced <- replaceVarWithUnknown ident ty1
1160− subsumes val replaced ty2
1161−subsumes' val ty1 (ForAll ident ty2 sco) =
1162− case sco of
1163− Just sco' -> do
1164− sko <- newSkolemConstant
1165− let sk = skolemize ident sko sco' ty2
1166− subsumes val ty1 sk
1167− Nothing -> throwError . strMsg $ "Skolem variable scope is unspecified"
1168−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1169− _ <- subsumes Nothing arg2 arg1
1170− _ <- subsumes Nothing ret1 ret2
1171− return val
1172−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1173− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1174− subsumes val ty1 ty2
1175−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1176− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1177− subsumes val ty1 ty2
1178−subsumes' val (KindedType ty1 _) ty2 = do
1179− subsumes val ty1 ty2
1180−subsumes' val ty1 (KindedType ty2 _) = do
1181− subsumes val ty1 ty2
1182−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1183− dicts <- getTypeClassDictionaries
1184− subsumes' (Just $ foldl App val (map (flip (TypeClassDictionary True) dicts) constraints)) ty1 ty2
1185−subsumes' val (TypeApp f1 r1) (TypeApp f2 r2) | f1 == tyObject && f2 == tyObject = do
1186− let
1187− (ts1, r1') = rowToList r1
1188− (ts2, r2') = rowToList r2
1189− ts1' = sortBy (comparing fst) ts1
1190− ts2' = sortBy (comparing fst) ts2
1191− go ts1' ts2' r1' r2'
1192− return val
1193− where
1194− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
1195− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
1196− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
1197− | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
1198− go ts1 ts2 r1' r2'
1199− | p1 < p2 = do rest <- fresh
1200− r2' =?= RCons p1 ty1 rest
1201− go ts1 ((p2, ty2) : ts2) r1' rest
1202− | otherwise = do rest <- fresh
1203− r1' =?= RCons p2 ty2 rest
1204− go ((p1, ty1) : ts1) ts2 rest r2'
1205−subsumes' val ty1 ty2@(TypeApp obj _) | obj == tyObject = subsumes val ty2 ty1
1206−subsumes' val ty1 ty2 = do
1207− ty1 =?= ty2
1208− return val
1209−
1210−-- |
1211−-- Compute the meet of two types, i.e. the most general type which both types subsume.
1212−-- TODO: handle constrained types
1213−--
1214−meet :: Expr -> Expr -> Type -> Type -> UnifyT Type Check (Expr, Expr, Type)
1215−meet e1 e2 (ForAll ident t1 _) t2 = do
1216− t1' <- replaceVarWithUnknown ident t1
1217− meet e1 e2 t1' t2
1218−meet e1 e2 t1 (ForAll ident t2 _) = do
1219− t2' <- replaceVarWithUnknown ident t2
1220− meet e1 e2 t1 t2'
1221−meet e1 e2 t1 t2 = do
1222− t1 =?= t2
1223− return (e1, e2, t1)
1224−
1225−
1226−
1227−
1228−
1229−
1230−