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