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