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