@@ -1,925 +0,0 @@
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 FlexibleContexts #-}
18−{-# LANGUAGE MultiParamTypeClasses #-}
19−
20−module Language.PureScript.TypeChecker.Types (
21− typesOf
22−) where
23−
24−{-
25− The following functions represent the corresponding type checking judgements:
26−
27− infer
28− Synthesize a type for a value
29−
30− check
31− Check a value has a given type
32−
33− checkProperties
34− Check an object with a given type contains specified properties
35−
36− checkFunctionApplication
37− Check a function of a given type returns a value of another type when applied to its arguments
38−
39− subsumes
40− Check a type subsumes another type
41−-}
42−
43−import Data.List
44−import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
45−import qualified Data.Data as D
46−import Data.Generics
47− (everythingWithContext, mkM, everywhereM, everything, mkT,
48− something, everywhere, mkQ)
49−import Data.Generics.Extras
50−
51−import Language.PureScript.Values
52−import Language.PureScript.Types
53−import Language.PureScript.Kinds
54−import Language.PureScript.Names
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.Prim
60−
61−import Control.Monad.State
62−import Control.Monad.Error
63−import Control.Monad.Unify
64−
65−import Control.Applicative
66−import Control.Arrow (Arrow(..))
67−
68−import qualified Data.Map as M
69−import Data.Function (on)
70−import Data.Ord (comparing)
71−
72−instance Partial Type where
73− unknown = TUnknown
74− isUnknown (TUnknown u) = Just u
75− isUnknown _ = Nothing
76−
77−instance Unifiable Check Type where
78− (=?=) = unifyTypes
79−
80−-- |
81−-- Unify two types, updating the current substitution
82−--
83−unifyTypes :: Type -> Type -> UnifyT Type Check ()
84−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $
85− unifyTypes' t1 t2
86− where
87− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
88− unifyTypes' (TUnknown u) t = u =:= t
89− unifyTypes' t (TUnknown u) = u =:= t
90− unifyTypes' (SaturatedTypeSynonym name args) ty = do
91− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
92− ty1 `unifyTypes` ty
93− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
94− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
95− case (sc1, sc2) of
96− (Just sc1', Just sc2') -> do
97− sko <- newSkolemConstant
98− let sk1 = skolemize ident1 sko sc1' ty1
99− let sk2 = skolemize ident2 sko sc2' ty2
100− sk1 `unifyTypes` sk2
101− _ -> throwError (prettyPrintType ty1)
102− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
103− sko <- newSkolemConstant
104− let sk = skolemize ident sko sc ty1
105− sk `unifyTypes` ty2
106− unifyTypes' ForAll{} _ = throwError "Skolem variable scope is unspecified"
107− unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
108− unifyTypes' (Object row1) (Object row2) = row1 =?= row2
109− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
110− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
111− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (c1 == c2)
112− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
113− t3 `unifyTypes` t5
114− t4 `unifyTypes` t6
115− unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
116− unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
117− unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
118− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
119− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
120− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
121−
122−-- |
123−-- Unify two rows, updating the current substitution
124−--
125−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
126−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
127−-- error.
128−--
129−unifyRows :: Type -> Type -> UnifyT Type Check ()
130−unifyRows r1 r2 =
131− let
132− (s1, r1') = rowToList r1
133− (s2, r2') = rowToList r2
134− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
135− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
136− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
137− in do
138− forM_ int (uncurry (=?=))
139− unifyRows' sd1 r1' sd2 r2'
140− where
141− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
142− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
143− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
144− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
145− occursCheck un ty
146− forM_ row $ \(_, t) -> occursCheck un t
147− u' <- fresh
148− u =?= RCons name ty u'
149− unifyRows' row r others u'
150− unifyRows' [] REmpty [] REmpty = return ()
151− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
152− unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
153− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")."
154−
155−-- |
156−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
157−-- type class dictionaries and type annotations.
158−--
159−typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
160−typesOf mainModuleName moduleName vals = do
161− tys <- fmap tidyUp . liftUnify $ do
162− let
163− -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
164− es = map isTyped vals
165− -- Filter the typed and untyped declarations
166− typed = filter (isJust . snd . snd) es
167− untyped = filter (isNothing . snd . snd) es
168− -- Make a map of names to typed declarations
169− typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
170− -- Create fresh unification variables for the types of untyped declarations
171− untypedNames <- replicateM (length untyped) fresh
172− let
173− -- Make a map of names to the unification variables of untyped declarations
174− untypedDict = zip (map fst untyped) untypedNames
175− -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
176− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
177− forM es $ \e@(_, (val, _)) -> do
178− -- If the declaration is a function, it has access to other values in the binding group.
179− -- If not, the generated code might fail at runtime since those values might be undefined.
180− let dict' = if isFunction val then dict else M.empty
181− triple@(_, (val', ty)) <- case e of
182− -- Typed declarations
183− (ident, (val', Just (ty, checkType))) -> do
184− -- Kind check
185− kind <- liftCheck $ kindOf moduleName ty
186− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
187− -- Check the type with the new names in scope
188− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
189− val'' <- bindNames dict' $ if checkType
190− then TypedValue True <$> check val' ty' <*> pure ty'
191− else return (TypedValue False val' ty')
192− return (ident, (val'', ty'))
193− -- Untyped declarations
194− (ident, (val', Nothing)) -> do
195− -- Infer the type with the new names in scope
196− TypedValue _ val'' ty <- bindNames dict' $ infer val'
197− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
198− return (ident, (TypedValue True val'' ty, ty))
199− -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
200− when (Just moduleName == mainModuleName && fst e == Ident "main") $ do
201− [eff, a] <- replicateM 2 fresh
202− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
203− -- Make sure unification variables do not escape
204− escapeCheck val' ty
205− return triple
206− forM tys $ \(ident, (val, ty)) -> do
207− -- Replace type class dictionary placeholders with actual dictionaries
208− val' <- replaceTypeClassDictionaries moduleName val
209− -- Check skolem variables did not escape their scope
210− skolemEscapeCheck val'
211− -- Remove type synonyms placeholders, remove duplicate row fields, and replace
212− -- top-level unification variables with named type variables.
213− let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
214− ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
215− return (ident, (val'', ty'))
216− where
217− -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
218− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
219−
220−-- |
221−-- Check if a value introduces a function
222−--
223−isFunction :: Value -> Bool
224−isFunction (Abs _ _) = True
225−isFunction (TypedValue _ val _) = isFunction val
226−isFunction _ = False
227−
228−-- |
229−-- Check if a value contains a type annotation
230−--
231−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
232−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
233−isTyped (name, value) = (name, (value, Nothing))
234−
235−-- |
236−-- Map a function over type annotations appearing inside a value
237−--
238−overTypes :: (Type -> Type) -> Value -> Value
239−overTypes f = everywhere (mkT f)
240−
241−-- |
242−-- Replace type class dictionary placeholders with inferred type class dictionaries
243−--
244−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
245−replaceTypeClassDictionaries mn = everywhereM' (mkM go)
246− where
247− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
248− go other = return other
249−
250−-- |
251−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
252−-- return a type class dictionary reference.
253−--
254−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Check Value
255−entails moduleName context goal@(className, tys) = do
256− env <- getEnv
257− case go env goal of
258− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ intercalate ", " (map prettyPrintType tys)
259− (dict : _) -> return dict
260− where
261− go env (className', tys') =
262− [ mkDictionary (canonicalizeDictionary tcd) args
263− | tcd <- context
264− -- Choose type class dictionaries in scope in the current module
265− , filterModule tcd
266− -- Make sure the type class name matches the one we are trying to satisfy
267− , className' == tcdClassName tcd
268− -- Make sure the type unifies with the type in the type instance definition
269− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
270− -- Solve any necessary subgoals
271− , args <- solveSubgoals env subst (tcdDependencies tcd) ]
272− -- Create dictionaries for subgoals which still need to be solved by calling go recursively
273− -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
274− -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
275− solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [Value]]
276− solveSubgoals _ _ Nothing = return Nothing
277− solveSubgoals env subst (Just subgoals) = do
278− dict <- mapM (go env . second (map (replaceAllTypeVars subst))) subgoals
279− return $ Just dict
280− -- Make a dictionary from subgoal dictionaries by applying the correct function
281− mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
282− mkDictionary fnName Nothing = Var fnName
283− mkDictionary fnName (Just []) = App (Var fnName) (ObjectLiteral [])
284− mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
285− -- Filter out type dictionaries which are in scope in the current module
286− filterModule :: TypeClassDictionaryInScope -> Bool
287− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
288− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
289− filterModule _ = False
290− canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
291− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
292− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
293− -- Ensure that a substitution is valid
294− verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
295− verifySubstitution subst = do
296− let grps = groupBy ((==) `on` fst) subst
297− guard (all ((==) 1 . length . nubBy ((==) `on` snd)) grps)
298− return $ map head grps
299−
300−-- |
301−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
302−-- and return a substitution from type variables to types which makes the type heads unify.
303−--
304−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
305−typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
306−typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
307−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
308−typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
309−typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
310−typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
311−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
312− Left _ -> Nothing
313− Right t1 -> typeHeadsAreEqual m e t1 t2
314−typeHeadsAreEqual _ _ _ _ = Nothing
315−
316−-- |
317−-- Ensure unsolved unification variables do not escape
318−--
319−escapeCheck :: Value -> Type -> UnifyT Type Check ()
320−escapeCheck value ty = do
321− subst <- unifyCurrentSubstitution <$> UnifyT get
322− let visibleUnknowns = nub $ unknowns $ subst $? ty
323− let allUnknowns = findAllTypes value
324− forM_ allUnknowns $ \t -> do
325− let unsolvedUnknowns = nub . unknowns $ subst $? t
326− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
327−
328−-- |
329−-- Find all type annotations occuring inside a value
330−--
331−findAllTypes :: Value -> [Type]
332−findAllTypes = everything (++) (mkQ [] go)
333− where
334− go (TypedValue _ _ ty) = [ty]
335− go _ = []
336−
337−-- |
338−-- Ensure skolem variables do not escape their scope
339−--
340−skolemEscapeCheck :: Value -> Check ()
341−skolemEscapeCheck (TypedValue False _ _) = return ()
342−skolemEscapeCheck root@TypedValue{} =
343− -- Every skolem variable is created when a ForAll type is skolemized.
344− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
345− -- field of the ForAll constructor.
346− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
347− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
348− -- an escaped skolem variable.
349− case everythingWithContext [] (++) (mkQ ((,) []) go) root of
350− [] -> return ()
351− ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
352− where
353− go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
354− go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
355− go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
356− (sco : _) -> ([(findBindingScope sco, val)], scos)
357− _ -> ([], scos)
358− where
359− collectSkolems :: Type -> [SkolemScope]
360− collectSkolems = nub . everything (++) (mkQ [] collect)
361− where
362− collect (Skolem _ scope) = [scope]
363− collect _ = []
364− go _ scos = ([], scos)
365− findBindingScope :: SkolemScope -> Maybe Value
366− findBindingScope sco = something (mkQ Nothing go') root
367− where
368− go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
369− go' _ = Nothing
370−skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
371−
372−-- |
373−-- Ensure a row contains no duplicate labels
374−--
375−setify :: Type -> Type
376−setify = rowFromList . first (M.toList . M.fromList) . rowToList
377−
378−-- |
379−-- \"Setify\" all rows occuring inside a value
380−--
381−setifyAll :: (D.Data d) => d -> d
382−setifyAll = everywhere (mkT setify)
383−
384−-- |
385−-- Replace outermost unsolved unification variables with named type variables
386−--
387−varIfUnknown :: Type -> Type
388−varIfUnknown ty =
389− let unks = nub $ unknowns ty
390− toName = (:) 't' . show
391− ty' = everywhere (mkT typeToVar) ty
392− typeToVar :: Type -> Type
393− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
394− typeToVar t = t
395− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
396−
397−-- |
398−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
399−-- or TypeClassDictionary values.
400−--
401−-- This is necessary during type checking to avoid unifying a polymorphic type with a
402−-- unification variable.
403−--
404−instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
405−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
406− ty' <- replaceVarWithUnknown ident ty
407− instantiatePolyTypeWithUnknowns val ty'
408−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
409− dicts <- getTypeClassDictionaries
410− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
411− return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
412−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
413−
414−-- |
415−-- Replace a single type variable with a new unification variable
416−--
417−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
418−replaceVarWithUnknown ident ty = do
419− tu <- fresh
420− return $ replaceTypeVars ident tu ty
421−
422−-- |
423−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
424−-- better error messages during unification.
425−--
426−replaceAllTypeSynonyms' :: (D.Data d) => Environment -> d -> Either String d
427−replaceAllTypeSynonyms' env d =
428− let
429− syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
430− in
431− saturateAllTypeSynonyms syns d
432−
433−replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
434−replaceAllTypeSynonyms d = do
435− env <- getEnv
436− either throwError return $ replaceAllTypeSynonyms' env d
437−
438−-- |
439−-- \"Desaturate\" @SaturatedTypeSynonym@s
440−--
441−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
442−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
443− where
444− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
445− replaceSaturatedTypeSynonym t = t
446−
447−-- |
448−-- Replace a type synonym and its arguments with the aliased type
449−--
450−expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
451−expandTypeSynonym' env name args =
452− case M.lookup name (typeSynonyms env) of
453− Just (synArgs, body) -> do
454− let repl = replaceAllTypeVars (zip synArgs args) body
455− replaceAllTypeSynonyms' env repl
456− Nothing -> error "Type synonym was not defined"
457−
458−expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
459−expandTypeSynonym name args = do
460− env <- getEnv
461− either throwError return $ expandTypeSynonym' env name args
462−
463−-- |
464−-- Ensure a set of property names and value does not contain duplicate labels
465−--
466−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
467−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
468−
469−-- |
470−-- Infer a type for a value, rethrowing any error to provide a more useful error message
471−--
472−infer :: Value -> UnifyT Type Check Value
473−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
474−
475−-- |
476−-- Infer a type for a value
477−--
478−infer' :: Value -> UnifyT Type Check Value
479−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
480−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
481−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
482−infer' (ArrayLiteral vals) = do
483− ts <- mapM infer vals
484− els <- fresh
485− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
486− return $ TypedValue True (ArrayLiteral ts) els
487−infer' (ObjectLiteral ps) = do
488− ensureNoDuplicateProperties ps
489− ts <- mapM (infer . snd) ps
490− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
491− ty = Object $ rowFromList (fields, REmpty)
492− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
493−infer' (ObjectUpdate o ps) = do
494− ensureNoDuplicateProperties ps
495− row <- fresh
496− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
497− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
498− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
499− let oldTy = Object $ rowFromList (oldTys, row)
500− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
501− return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
502−infer' (Accessor prop val) = do
503− typed@(TypedValue _ _ objTy) <- infer val
504− propTy <- inferProperty objTy prop
505− case propTy of
506− Nothing -> do
507− field <- fresh
508− rest <- fresh
509− _ <- subsumes Nothing objTy (Object (RCons prop field rest))
510− return $ TypedValue True (Accessor prop typed) field
511− Just ty -> return $ TypedValue True (Accessor prop typed) ty
512−infer' (Abs (Left arg) ret) = do
513− ty <- fresh
514− Just moduleName <- checkCurrentModule <$> get
515− bindLocalVariables moduleName [(arg, ty)] $ do
516− body@(TypedValue _ _ bodyTy) <- infer' ret
517− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
518−infer' (Abs (Right _) _) = error "Binder was not desugared"
519−infer' (App f arg) = do
520− f'@(TypedValue _ _ ft) <- infer f
521− (ret, app) <- checkFunctionApplication f' ft arg
522− return $ TypedValue True app ret
523−infer' (Var var) = do
524− Just moduleName <- checkCurrentModule <$> get
525− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
526− case ty of
527− ConstrainedType constraints ty' -> do
528− dicts <- getTypeClassDictionaries
529− return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) constraints)) ty'
530− _ -> return $ TypedValue True (Var var) ty
531−infer' v@(Constructor c) = do
532− env <- getEnv
533− case M.lookup c (dataConstructors env) of
534− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
535− Just ty -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
536− return $ TypedValue True v ty'
537−infer' (Case vals binders) = do
538− ts <- mapM infer vals
539− ret <- fresh
540− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
541− return $ TypedValue True (Case ts binders') ret
542−infer' (IfThenElse cond th el) = do
543− cond' <- check cond tyBoolean
544− v2@(TypedValue _ _ t2) <- infer th
545− v3@(TypedValue _ _ t3) <- infer el
546− t2 =?= t3
547− return $ TypedValue True (IfThenElse cond' v2 v3) t2
548−infer' (TypedValue checkType val ty) = do
549− Just moduleName <- checkCurrentModule <$> get
550− kind <- liftCheck $ kindOf moduleName ty
551− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
552− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
553− val' <- if checkType then check val ty' else return val
554− return $ TypedValue True val' ty'
555−infer' _ = error "Invalid argument to infer"
556−
557−-- |
558−-- Infer the type of a property inside a record with a given type
559−--
560−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
561−inferProperty (Object row) prop = do
562− let (props, _) = rowToList row
563− return $ lookup prop props
564−inferProperty (SaturatedTypeSynonym name args) prop = do
565− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
566− inferProperty replaced prop
567−inferProperty (ForAll ident ty _) prop = do
568− replaced <- replaceVarWithUnknown ident ty
569− inferProperty replaced prop
570−inferProperty _ _ = return Nothing
571−
572−-- |
573−-- Infer the types of variables brought into scope by a binder
574−--
575−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
576−inferBinder _ NullBinder = return M.empty
577−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
578−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
579−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
580−inferBinder val (VarBinder name) = return $ M.singleton name val
581−inferBinder val (ConstructorBinder ctor binders) = do
582− env <- getEnv
583− case M.lookup ctor (dataConstructors env) of
584− Just ty -> do
585− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contains constraints") ty
586− go binders fn
587− where
588− go [] ty' = do
589− _ <- subsumes Nothing val ty'
590− return M.empty
591− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
592− M.union <$> inferBinder obj binder <*> go binders' ret
593− go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
594− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
595−inferBinder val (ObjectBinder props) = do
596− row <- fresh
597− rest <- fresh
598− m1 <- inferRowProperties row rest props
599− val =?= Object row
600− return m1
601− where
602− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
603− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
604− inferRowProperties nrow row ((name, binder):binders) = do
605− propTy <- fresh
606− m1 <- inferBinder propTy binder
607− m2 <- inferRowProperties nrow (RCons name propTy row) binders
608− return $ m1 `M.union` m2
609−inferBinder val (ArrayBinder binders) = do
610− el <- fresh
611− m1 <- M.unions <$> mapM (inferBinder el) binders
612− val =?= TypeApp tyArray el
613− return m1
614−inferBinder val (ConsBinder headBinder tailBinder) = do
615− el <- fresh
616− m1 <- inferBinder el headBinder
617− m2 <- inferBinder val tailBinder
618− val =?= TypeApp tyArray el
619− return $ m1 `M.union` m2
620−inferBinder val (NamedBinder name binder) = do
621− m <- inferBinder val binder
622− return $ M.insert name val m
623−
624−-- |
625−-- Check the types of the return values in a set of binders in a case statement
626−--
627−checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
628−checkBinders _ _ [] = return []
629−checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
630− Just moduleName <- checkCurrentModule <$> get
631− m1 <- M.unions <$> zipWithM inferBinder nvals binders
632− r <- bindLocalVariables moduleName (M.toList m1) $ do
633− val' <- TypedValue True <$> check val ret <*> pure ret
634− case grd of
635− Nothing -> return $ CaseAlternative binders Nothing val'
636− Just g -> do
637− g' <- check g tyBoolean
638− return $ CaseAlternative binders (Just g') val'
639− rs <- checkBinders nvals ret bs
640− return $ r : rs
641−
642−-- |
643−-- Generate a new skolem constant
644−--
645−newSkolemConstant :: UnifyT Type Check Int
646−newSkolemConstant = runUnknown <$> fresh'
647−
648−-- |
649−-- Generate a new skolem scope
650−--
651−newSkolemScope :: UnifyT Type Check SkolemScope
652−newSkolemScope = SkolemScope . runUnknown <$> fresh'
653−
654−-- |
655−-- Skolemize a type variable by replacing its instances with fresh skolem constants
656−--
657−skolemize :: String -> Int -> SkolemScope -> Type -> Type
658−skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
659−
660−-- |
661−-- Introduce skolem scope at every occurence of a ForAll
662−--
663−introduceSkolemScope :: Type -> UnifyT Type Check Type
664−introduceSkolemScope = everywhereM (mkM go)
665− where
666− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
667− go other = return other
668−
669−-- |
670−-- Check the type of a value, rethrowing errors to provide a better error message
671−--
672−check :: Value -> Type -> UnifyT Type Check Value
673−check val ty = rethrow errorMessage $ check' val ty
674− where
675− errorMessage msg =
676− "Error checking type of term " ++
677− prettyPrintValue val ++
678− " against type " ++
679− prettyPrintType ty ++
680− ":\n" ++
681− msg
682−
683−-- |
684−-- Check the type of a value
685−--
686−check' :: Value -> Type -> UnifyT Type Check Value
687−check' val (ForAll ident ty _) = do
688− scope <- newSkolemScope
689− sko <- newSkolemConstant
690− let sk = skolemize ident sko scope ty
691− val' <- check val sk
692− return $ TypedValue True val' (ForAll ident ty (Just scope))
693−check' val t@(ConstrainedType constraints ty) = do
694− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
695− n <- liftCheck freshDictionaryName
696− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
697− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
698− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
699− constraints) $ check val ty
700− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
701−check' val (SaturatedTypeSynonym name args) = do
702− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
703− val' <- check val ty
704− return $ TypedValue True val' ty
705−check' val u@(TUnknown _) = do
706− val'@(TypedValue _ _ ty) <- infer val
707− -- Don't unify an unknown with an inferred polytype
708− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
709− ty' =?= u
710− return $ TypedValue True val'' ty'
711−check' v@(NumericLiteral _) t | t == tyNumber =
712− return $ TypedValue True v t
713−check' v@(StringLiteral _) t | t == tyString =
714− return $ TypedValue True v t
715−check' v@(BooleanLiteral _) t | t == tyBoolean =
716− return $ TypedValue True v t
717−check' (ArrayLiteral vals) t@(TypeApp a ty) | a == tyArray = do
718− array <- ArrayLiteral <$> forM vals (`check` ty)
719− return $ TypedValue True array t
720−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
721− Just moduleName <- checkCurrentModule <$> get
722− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
723− return $ TypedValue True (Abs (Left arg) ret') ty
724−check' (Abs (Right _) _) _ = error "Binder was not desugared"
725−check' (App f arg) ret = do
726− f'@(TypedValue _ _ ft) <- infer f
727− (ret', app) <- checkFunctionApplication f' ft arg
728− _ <- subsumes Nothing ret' ret
729− return $ TypedValue True app ret
730−check' v@(Var var) ty = do
731− Just moduleName <- checkCurrentModule <$> get
732− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
733− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
734− v' <- subsumes (Just v) repl ty'
735− case v' of
736− Nothing -> throwError "Unable to check type subsumption"
737− Just v'' -> return $ TypedValue True v'' ty'
738−check' (TypedValue checkType val ty1) ty2 = do
739− Just moduleName <- checkCurrentModule <$> get
740− kind <- liftCheck $ kindOf moduleName ty1
741− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
742− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
743− val' <- subsumes (Just val) ty1' ty2
744− case val' of
745− Nothing -> throwError "Unable to check type subsumption"
746− Just val'' -> do
747− val''' <- if checkType then check val'' ty1 else return val''
748− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
749−check' (Case vals binders) ret = do
750− vals' <- mapM infer vals
751− let ts = map (\(TypedValue _ _ t) -> t) vals'
752− binders' <- checkBinders ts ret binders
753− return $ TypedValue True (Case vals' binders') ret
754−check' (IfThenElse cond th el) ty = do
755− cond' <- check cond tyBoolean
756− th' <- check th ty
757− el' <- check el ty
758− return $ TypedValue True (IfThenElse cond' th' el') ty
759−check' (ObjectLiteral ps) t@(Object row) = do
760− ensureNoDuplicateProperties ps
761− ps' <- checkProperties ps row False
762− return $ TypedValue True (ObjectLiteral ps') t
763−check' (ObjectUpdate obj ps) t@(Object row) = do
764− ensureNoDuplicateProperties ps
765− us <- zip (map fst ps) <$> replicateM (length ps) fresh
766− let (propsToCheck, rest) = rowToList row
767− propsToRemove = map fst ps
768− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
769− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
770− ps' <- checkProperties ps row True
771− return $ TypedValue True (ObjectUpdate obj' ps') t
772−check' (Accessor prop val) ty = do
773− rest <- fresh
774− val' <- check val (Object (RCons prop ty rest))
775− return $ TypedValue True (Accessor prop val') ty
776−check' (Constructor c) ty = do
777− env <- getEnv
778− case M.lookup c (dataConstructors env) of
779− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
780− Just ty1 -> do
781− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
782− _ <- subsumes Nothing repl ty
783− return $ TypedValue True (Constructor c) ty
784−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
785−
786−-- |
787−-- Check the type of a collection of named record fields
788−--
789−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
790−--
791−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
792−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
793− go [] [] REmpty = return []
794− go [] [] u@(TUnknown _) = do u =?= REmpty
795− return []
796− go [] [] (Skolem _ _) | lax = return []
797− go [] ((p, _): _) _ | lax = return []
798− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
799− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
800− go ((p,v):ps') [] u@(TUnknown _) = do
801− v'@(TypedValue _ _ ty) <- infer v
802− rest <- fresh
803− u =?= RCons p ty rest
804− ps'' <- go ps' [] rest
805− return $ (p, v') : ps''
806− go ((p,v):ps') ts r =
807− case lookup p ts of
808− Nothing -> do
809− v'@(TypedValue _ _ ty) <- infer v
810− rest <- fresh
811− r =?= RCons p ty rest
812− ps'' <- go ps' ts rest
813− return $ (p, v') : ps''
814− Just ty -> do
815− v' <- check v ty
816− ps'' <- go ps' (delete (p, ty) ts) r
817− return $ (p, v') : ps''
818− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
819−
820−-- |
821−-- Check the type of a function application, rethrowing errors to provide a better error message
822−--
823−checkFunctionApplication :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
824−checkFunctionApplication fn fnTy arg = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg
825− where
826− errorMessage msg = "Error applying function of type "
827− ++ prettyPrintType fnTy
828− ++ " to argument " ++ prettyPrintValue arg
829− ++ ":\n" ++ msg
830−
831−-- |
832−-- Check the type of a function application
833−--
834−checkFunctionApplication' :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
835−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg = do
836− tyFunction' =?= tyFunction
837− arg' <- check arg argTy
838− return (retTy, App fn arg')
839−checkFunctionApplication' fn (ForAll ident ty _) arg = do
840− replaced <- replaceVarWithUnknown ident ty
841− checkFunctionApplication fn replaced arg
842−checkFunctionApplication' fn u@(TUnknown _) arg = do
843− arg' <- do
844− TypedValue _ arg' t <- infer arg
845− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
846− return $ TypedValue True arg'' t'
847− let ty = (\(TypedValue _ _ t) -> t) arg'
848− ret <- fresh
849− u =?= function ty ret
850− return (ret, App fn arg')
851−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg = do
852− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
853− checkFunctionApplication fn ty arg
854−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg = do
855− dicts <- getTypeClassDictionaries
856− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg
857−checkFunctionApplication' _ fnTy arg = throwError $ "Cannot apply a function of type "
858− ++ prettyPrintType fnTy
859− ++ " to argument " ++ prettyPrintValue arg
860−
861−-- |
862−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
863−--
864−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
865−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
866− where
867− errorMessage msg = "Error checking that type "
868− ++ prettyPrintType ty1
869− ++ " subsumes type "
870− ++ prettyPrintType ty2
871− ++ ":\n" ++ msg
872−
873−-- |
874−-- Check whether one type subsumes another
875−--
876−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
877−subsumes' val (ForAll ident ty1 _) ty2 = do
878− replaced <- replaceVarWithUnknown ident ty1
879− subsumes val replaced ty2
880−subsumes' val ty1 (ForAll ident ty2 sco) =
881− case sco of
882− Just sco' -> do
883− sko <- newSkolemConstant
884− let sk = skolemize ident sko sco' ty2
885− subsumes val ty1 sk
886− Nothing -> throwError "Skolem variable scope is unspecified"
887−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
888− _ <- subsumes Nothing arg2 arg1
889− _ <- subsumes Nothing ret1 ret2
890− return val
891−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
892− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
893− subsumes val ty1 ty2
894−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
895− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
896− subsumes val ty1 ty2
897−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
898− dicts <- getTypeClassDictionaries
899− _ <- subsumes' Nothing ty1 ty2
900− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
901−subsumes' val (Object r1) (Object r2) = do
902− let
903− (ts1, r1') = rowToList r1
904− (ts2, r2') = rowToList r2
905− ts1' = sortBy (comparing fst) ts1
906− ts2' = sortBy (comparing fst) ts2
907− go ts1' ts2' r1' r2'
908− return val
909− where
910− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
911− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
912− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
913− | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
914− go ts1 ts2 r1' r2'
915− | p1 < p2 = do rest <- fresh
916− r2' =?= RCons p1 ty1 rest
917− go ts1 ((p2, ty2) : ts2) r1' rest
918− | otherwise = do rest <- fresh
919− r1' =?= RCons p2 ty2 rest
920− go ((p1, ty1) : ts1) ts2 rest r2'
921−subsumes' val ty1 ty2@(Object _) = subsumes val ty2 ty1
922−subsumes' val ty1 ty2 = do
923− ty1 =?= ty2
924− return val
925−