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