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