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