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