@@ -0,0 +1,926 @@
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.Environment
60+import qualified Language.PureScript.Constants as C
61+
62+import Control.Monad.State
63+import Control.Monad.Error
64+import Control.Monad.Unify
65+
66+import Control.Applicative
67+import Control.Arrow (Arrow(..))
68+
69+import qualified Data.Map as M
70+import Data.Function (on)
71+import Data.Ord (comparing)
72+
73+instance Partial Type where
74+ unknown = TUnknown
75+ isUnknown (TUnknown u) = Just u
76+ isUnknown _ = Nothing
77+
78+instance Unifiable Check Type where
79+ (=?=) = unifyTypes
80+
81+-- |
82+-- Unify two types, updating the current substitution
83+--
84+unifyTypes :: Type -> Type -> UnifyT Type Check ()
85+unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $
86+ unifyTypes' t1 t2
87+ where
88+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
89+ unifyTypes' (TUnknown u) t = u =:= t
90+ unifyTypes' t (TUnknown u) = u =:= t
91+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
92+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
93+ ty1 `unifyTypes` ty
94+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
95+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
96+ case (sc1, sc2) of
97+ (Just sc1', Just sc2') -> do
98+ sko <- newSkolemConstant
99+ let sk1 = skolemize ident1 sko sc1' ty1
100+ let sk2 = skolemize ident2 sko sc2' ty2
101+ sk1 `unifyTypes` sk2
102+ _ -> throwError (prettyPrintType ty1)
103+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
104+ sko <- newSkolemConstant
105+ let sk = skolemize ident sko sc ty1
106+ sk `unifyTypes` ty2
107+ unifyTypes' ForAll{} _ = throwError "Skolem variable scope is unspecified"
108+ unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
109+ unifyTypes' (Object row1) (Object row2) = row1 =?= row2
110+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
111+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) =
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 C.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+ -- Ensure that a substitution is valid
292+ verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
293+ verifySubstitution subst = do
294+ let grps = groupBy ((==) `on` fst) subst
295+ guard (all ((==) 1 . length . nubBy ((==) `on` snd)) grps)
296+ return $ map head grps
297+
298+-- |
299+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
300+-- and return a substitution from type variables to types which makes the type heads unify.
301+--
302+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
303+typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
304+typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
305+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
306+typeHeadsAreEqual _ _ (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
307+typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
308+typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
309+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e name args of
310+ Left _ -> Nothing
311+ Right t1 -> typeHeadsAreEqual m e t1 t2
312+typeHeadsAreEqual _ _ _ _ = Nothing
313+
314+-- |
315+-- Ensure unsolved unification variables do not escape
316+--
317+escapeCheck :: Value -> Type -> UnifyT Type Check ()
318+escapeCheck value ty = do
319+ subst <- unifyCurrentSubstitution <$> UnifyT get
320+ let visibleUnknowns = nub $ unknowns $ subst $? ty
321+ let allUnknowns = findAllTypes value
322+ forM_ allUnknowns $ \t -> do
323+ let unsolvedUnknowns = nub . unknowns $ subst $? t
324+ guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
325+
326+-- |
327+-- Find all type annotations occuring inside a value
328+--
329+findAllTypes :: Value -> [Type]
330+findAllTypes = everything (++) (mkQ [] go)
331+ where
332+ go (TypedValue _ _ ty) = [ty]
333+ go _ = []
334+
335+-- |
336+-- Ensure skolem variables do not escape their scope
337+--
338+skolemEscapeCheck :: Value -> Check ()
339+skolemEscapeCheck (TypedValue False _ _) = return ()
340+skolemEscapeCheck root@TypedValue{} =
341+ -- Every skolem variable is created when a ForAll type is skolemized.
342+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
343+ -- field of the ForAll constructor.
344+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
345+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
346+ -- an escaped skolem variable.
347+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
348+ [] -> return ()
349+ ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
350+ where
351+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
352+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
353+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
354+ (sco : _) -> ([(findBindingScope sco, val)], scos)
355+ _ -> ([], scos)
356+ where
357+ collectSkolems :: Type -> [SkolemScope]
358+ collectSkolems = nub . everything (++) (mkQ [] collect)
359+ where
360+ collect (Skolem _ scope) = [scope]
361+ collect _ = []
362+ go _ scos = ([], scos)
363+ findBindingScope :: SkolemScope -> Maybe Value
364+ findBindingScope sco = something (mkQ Nothing go') root
365+ where
366+ go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
367+ go' _ = Nothing
368+skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
369+
370+-- |
371+-- Ensure a row contains no duplicate labels
372+--
373+setify :: Type -> Type
374+setify = rowFromList . first (M.toList . M.fromList) . rowToList
375+
376+-- |
377+-- \"Setify\" all rows occuring inside a value
378+--
379+setifyAll :: (D.Data d) => d -> d
380+setifyAll = everywhere (mkT setify)
381+
382+-- |
383+-- Replace outermost unsolved unification variables with named type variables
384+--
385+varIfUnknown :: Type -> Type
386+varIfUnknown ty =
387+ let unks = nub $ unknowns ty
388+ toName = (:) 't' . show
389+ ty' = everywhere (mkT typeToVar) ty
390+ typeToVar :: Type -> Type
391+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
392+ typeToVar t = t
393+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
394+
395+-- |
396+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
397+-- or TypeClassDictionary values.
398+--
399+-- This is necessary during type checking to avoid unifying a polymorphic type with a
400+-- unification variable.
401+--
402+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
403+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
404+ ty' <- replaceVarWithUnknown ident ty
405+ instantiatePolyTypeWithUnknowns val ty'
406+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
407+ dicts <- getTypeClassDictionaries
408+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
409+ return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
410+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
411+
412+-- |
413+-- Replace a single type variable with a new unification variable
414+--
415+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
416+replaceVarWithUnknown ident ty = do
417+ tu <- fresh
418+ return $ replaceTypeVars ident tu ty
419+
420+-- |
421+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
422+-- better error messages during unification.
423+--
424+replaceAllTypeSynonyms' :: (D.Data d) => Environment -> d -> Either String d
425+replaceAllTypeSynonyms' env d =
426+ let
427+ syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
428+ in
429+ saturateAllTypeSynonyms syns d
430+
431+replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
432+replaceAllTypeSynonyms d = do
433+ env <- getEnv
434+ either throwError return $ replaceAllTypeSynonyms' env d
435+
436+-- |
437+-- \"Desaturate\" @SaturatedTypeSynonym@s
438+--
439+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
440+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
441+ where
442+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
443+ replaceSaturatedTypeSynonym t = t
444+
445+-- |
446+-- Replace a type synonym and its arguments with the aliased type
447+--
448+expandTypeSynonym' :: Environment -> Qualified ProperName -> [Type] -> Either String Type
449+expandTypeSynonym' env name args =
450+ case M.lookup name (typeSynonyms env) of
451+ Just (synArgs, body) -> do
452+ let repl = replaceAllTypeVars (zip synArgs args) body
453+ replaceAllTypeSynonyms' env repl
454+ Nothing -> error "Type synonym was not defined"
455+
456+expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
457+expandTypeSynonym name args = do
458+ env <- getEnv
459+ either throwError return $ expandTypeSynonym' env name args
460+
461+-- |
462+-- Ensure a set of property names and value does not contain duplicate labels
463+--
464+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
465+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
466+
467+-- |
468+-- Infer a type for a value, rethrowing any error to provide a more useful error message
469+--
470+infer :: Value -> UnifyT Type Check Value
471+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
472+
473+-- |
474+-- Infer a type for a value
475+--
476+infer' :: Value -> UnifyT Type Check Value
477+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
478+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
479+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
480+infer' (ArrayLiteral vals) = do
481+ ts <- mapM infer vals
482+ els <- fresh
483+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
484+ return $ TypedValue True (ArrayLiteral ts) els
485+infer' (ObjectLiteral ps) = do
486+ ensureNoDuplicateProperties ps
487+ ts <- mapM (infer . snd) ps
488+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
489+ ty = Object $ rowFromList (fields, REmpty)
490+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
491+infer' (ObjectUpdate o ps) = do
492+ ensureNoDuplicateProperties ps
493+ row <- fresh
494+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
495+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
496+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
497+ let oldTy = Object $ rowFromList (oldTys, row)
498+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
499+ return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
500+infer' (Accessor prop val) = do
501+ typed@(TypedValue _ _ objTy) <- infer val
502+ propTy <- inferProperty objTy prop
503+ case propTy of
504+ Nothing -> do
505+ field <- fresh
506+ rest <- fresh
507+ _ <- subsumes Nothing objTy (Object (RCons prop field rest))
508+ return $ TypedValue True (Accessor prop typed) field
509+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
510+infer' (Abs (Left arg) ret) = do
511+ ty <- fresh
512+ Just moduleName <- checkCurrentModule <$> get
513+ bindLocalVariables moduleName [(arg, ty)] $ do
514+ body@(TypedValue _ _ bodyTy) <- infer' ret
515+ return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
516+infer' (Abs (Right _) _) = error "Binder was not desugared"
517+infer' (App f arg) = do
518+ f'@(TypedValue _ _ ft) <- infer f
519+ (ret, app) <- checkFunctionApplication f' ft arg Nothing
520+ return $ TypedValue True app ret
521+infer' (Var var) = do
522+ Just moduleName <- checkCurrentModule <$> get
523+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
524+ case ty of
525+ ConstrainedType constraints ty' -> do
526+ dicts <- getTypeClassDictionaries
527+ return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) constraints)) ty'
528+ _ -> return $ TypedValue True (Var var) ty
529+infer' v@(Constructor c) = do
530+ env <- getEnv
531+ case M.lookup c (dataConstructors env) of
532+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
533+ Just (_, ty) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
534+ return $ TypedValue True v ty'
535+infer' (Case vals binders) = do
536+ ts <- mapM infer vals
537+ ret <- fresh
538+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
539+ return $ TypedValue True (Case ts binders') ret
540+infer' (IfThenElse cond th el) = do
541+ cond' <- check cond tyBoolean
542+ v2@(TypedValue _ _ t2) <- infer th
543+ v3@(TypedValue _ _ t3) <- infer el
544+ t2 =?= t3
545+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
546+infer' (TypedValue checkType val ty) = do
547+ Just moduleName <- checkCurrentModule <$> get
548+ kind <- liftCheck $ kindOf moduleName ty
549+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
550+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
551+ val' <- if checkType then check val ty' else return val
552+ return $ TypedValue True val' ty'
553+infer' _ = error "Invalid argument to infer"
554+
555+-- |
556+-- Infer the type of a property inside a record with a given type
557+--
558+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
559+inferProperty (Object row) prop = do
560+ let (props, _) = rowToList row
561+ return $ lookup prop props
562+inferProperty (SaturatedTypeSynonym name args) prop = do
563+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
564+ inferProperty replaced prop
565+inferProperty (ForAll ident ty _) prop = do
566+ replaced <- replaceVarWithUnknown ident ty
567+ inferProperty replaced prop
568+inferProperty _ _ = return Nothing
569+
570+-- |
571+-- Infer the types of variables brought into scope by a binder
572+--
573+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
574+inferBinder _ NullBinder = return M.empty
575+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
576+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
577+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
578+inferBinder val (VarBinder name) = return $ M.singleton name val
579+inferBinder val (ConstructorBinder ctor binders) = do
580+ env <- getEnv
581+ case M.lookup ctor (dataConstructors env) of
582+ Just (_, ty) -> do
583+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contain constraints") ty
584+ fn' <- replaceAllTypeSynonyms fn
585+ go binders fn'
586+ where
587+ go [] ty' = do
588+ _ <- subsumes Nothing val ty'
589+ return M.empty
590+ go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
591+ M.union <$> inferBinder obj binder <*> go binders' ret
592+ go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
593+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
594+inferBinder val (ObjectBinder props) = do
595+ row <- fresh
596+ rest <- fresh
597+ m1 <- inferRowProperties row rest props
598+ val =?= Object row
599+ return m1
600+ where
601+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
602+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
603+ inferRowProperties nrow row ((name, binder):binders) = do
604+ propTy <- fresh
605+ m1 <- inferBinder propTy binder
606+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
607+ return $ m1 `M.union` m2
608+inferBinder val (ArrayBinder binders) = do
609+ el <- fresh
610+ m1 <- M.unions <$> mapM (inferBinder el) binders
611+ val =?= TypeApp tyArray el
612+ return m1
613+inferBinder val (ConsBinder headBinder tailBinder) = do
614+ el <- fresh
615+ m1 <- inferBinder el headBinder
616+ m2 <- inferBinder val tailBinder
617+ val =?= TypeApp tyArray el
618+ return $ m1 `M.union` m2
619+inferBinder val (NamedBinder name binder) = do
620+ m <- inferBinder val binder
621+ return $ M.insert name val m
622+
623+-- |
624+-- Check the types of the return values in a set of binders in a case statement
625+--
626+checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
627+checkBinders _ _ [] = return []
628+checkBinders nvals ret (CaseAlternative binders grd val : bs) = do
629+ Just moduleName <- checkCurrentModule <$> get
630+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
631+ r <- bindLocalVariables moduleName (M.toList m1) $ do
632+ val' <- TypedValue True <$> check val ret <*> pure ret
633+ case grd of
634+ Nothing -> return $ CaseAlternative binders Nothing val'
635+ Just g -> do
636+ g' <- check g tyBoolean
637+ return $ CaseAlternative binders (Just g') val'
638+ rs <- checkBinders nvals ret bs
639+ return $ r : rs
640+
641+-- |
642+-- Generate a new skolem constant
643+--
644+newSkolemConstant :: UnifyT Type Check Int
645+newSkolemConstant = runUnknown <$> fresh'
646+
647+-- |
648+-- Generate a new skolem scope
649+--
650+newSkolemScope :: UnifyT Type Check SkolemScope
651+newSkolemScope = SkolemScope . runUnknown <$> fresh'
652+
653+-- |
654+-- Skolemize a type variable by replacing its instances with fresh skolem constants
655+--
656+skolemize :: String -> Int -> SkolemScope -> Type -> Type
657+skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
658+
659+-- |
660+-- Introduce skolem scope at every occurence of a ForAll
661+--
662+introduceSkolemScope :: Type -> UnifyT Type Check Type
663+introduceSkolemScope = everywhereM (mkM go)
664+ where
665+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
666+ go other = return other
667+
668+-- |
669+-- Check the type of a value, rethrowing errors to provide a better error message
670+--
671+check :: Value -> Type -> UnifyT Type Check Value
672+check val ty = rethrow errorMessage $ check' val ty
673+ where
674+ errorMessage msg =
675+ "Error checking type of term " ++
676+ prettyPrintValue val ++
677+ " against type " ++
678+ prettyPrintType ty ++
679+ ":\n" ++
680+ msg
681+
682+-- |
683+-- Check the type of a value
684+--
685+check' :: Value -> Type -> UnifyT Type Check Value
686+check' val (ForAll ident ty _) = do
687+ scope <- newSkolemScope
688+ sko <- newSkolemConstant
689+ let sk = skolemize ident sko scope ty
690+ val' <- check val sk
691+ return $ TypedValue True val' (ForAll ident ty (Just scope))
692+check' val t@(ConstrainedType constraints ty) = do
693+ dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
694+ n <- liftCheck freshDictionaryName
695+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
696+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
697+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
698+ constraints) $ check val ty
699+ return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
700+check' val (SaturatedTypeSynonym name args) = do
701+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
702+ val' <- check val ty
703+ return $ TypedValue True val' ty
704+check' val u@(TUnknown _) = do
705+ val'@(TypedValue _ _ ty) <- infer val
706+ -- Don't unify an unknown with an inferred polytype
707+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
708+ ty' =?= u
709+ return $ TypedValue True val'' ty'
710+check' v@(NumericLiteral _) t | t == tyNumber =
711+ return $ TypedValue True v t
712+check' v@(StringLiteral _) t | t == tyString =
713+ return $ TypedValue True v t
714+check' v@(BooleanLiteral _) t | t == tyBoolean =
715+ return $ TypedValue True v t
716+check' (ArrayLiteral vals) t@(TypeApp a ty) = do
717+ a =?= tyArray
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+ (_, app) <- checkFunctionApplication f' ft arg (Just ret)
728+ return $ TypedValue True app ret
729+check' v@(Var var) ty = do
730+ Just moduleName <- checkCurrentModule <$> get
731+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
732+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
733+ v' <- subsumes (Just v) repl ty'
734+ case v' of
735+ Nothing -> throwError "Unable to check type subsumption"
736+ Just v'' -> return $ TypedValue True v'' ty'
737+check' (TypedValue checkType val ty1) ty2 = do
738+ Just moduleName <- checkCurrentModule <$> get
739+ kind <- liftCheck $ kindOf moduleName ty1
740+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
741+ ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
742+ val' <- subsumes (Just val) ty1' ty2
743+ case val' of
744+ Nothing -> throwError "Unable to check type subsumption"
745+ Just val'' -> do
746+ val''' <- if checkType then check val'' ty1 else return val''
747+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
748+check' (Case vals binders) ret = do
749+ vals' <- mapM infer vals
750+ let ts = map (\(TypedValue _ _ t) -> t) vals'
751+ binders' <- checkBinders ts ret binders
752+ return $ TypedValue True (Case vals' binders') ret
753+check' (IfThenElse cond th el) ty = do
754+ cond' <- check cond tyBoolean
755+ th' <- check th ty
756+ el' <- check el ty
757+ return $ TypedValue True (IfThenElse cond' th' el') ty
758+check' (ObjectLiteral ps) t@(Object row) = do
759+ ensureNoDuplicateProperties ps
760+ ps' <- checkProperties ps row False
761+ return $ TypedValue True (ObjectLiteral ps') t
762+check' (ObjectUpdate obj ps) t@(Object row) = do
763+ ensureNoDuplicateProperties ps
764+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
765+ let (propsToCheck, rest) = rowToList row
766+ propsToRemove = map fst ps
767+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
768+ obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
769+ ps' <- checkProperties ps row True
770+ return $ TypedValue True (ObjectUpdate obj' ps') t
771+check' (Accessor prop val) ty = do
772+ rest <- fresh
773+ val' <- check val (Object (RCons prop ty rest))
774+ return $ TypedValue True (Accessor prop val') ty
775+check' (Constructor c) ty = do
776+ env <- getEnv
777+ case M.lookup c (dataConstructors env) of
778+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
779+ Just (_, ty1) -> do
780+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
781+ _ <- subsumes Nothing repl ty
782+ return $ TypedValue True (Constructor c) ty
783+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
784+
785+-- |
786+-- Check the type of a collection of named record fields
787+--
788+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
789+--
790+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
791+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
792+ go [] [] REmpty = return []
793+ go [] [] u@(TUnknown _) = do u =?= REmpty
794+ return []
795+ go [] [] (Skolem _ _) | lax = return []
796+ go [] ((p, _): _) _ | lax = return []
797+ | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
798+ go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
799+ go ((p,v):ps') [] u@(TUnknown _) = do
800+ v'@(TypedValue _ _ ty) <- infer v
801+ rest <- fresh
802+ u =?= RCons p ty rest
803+ ps'' <- go ps' [] rest
804+ return $ (p, v') : ps''
805+ go ((p,v):ps') ts r =
806+ case lookup p ts of
807+ Nothing -> do
808+ v'@(TypedValue _ _ ty) <- infer v
809+ rest <- fresh
810+ r =?= RCons p ty rest
811+ ps'' <- go ps' ts rest
812+ return $ (p, v') : ps''
813+ Just ty -> do
814+ v' <- check v ty
815+ ps'' <- go ps' (delete (p, ty) ts) r
816+ return $ (p, v') : ps''
817+ go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
818+
819+-- |
820+-- Check the type of a function application, rethrowing errors to provide a better error message
821+--
822+checkFunctionApplication :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
823+checkFunctionApplication fn fnTy arg ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg ret
824+ where
825+ errorMessage msg = "Error applying function of type "
826+ ++ prettyPrintType fnTy
827+ ++ " to argument " ++ prettyPrintValue arg
828+ ++ ":\n" ++ msg
829+
830+-- |
831+-- Check the type of a function application
832+--
833+checkFunctionApplication' :: Value -> Type -> Value -> Maybe Type -> UnifyT Type Check (Type, Value)
834+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
835+ tyFunction' =?= tyFunction
836+ _ <- maybe (return Nothing) (subsumes Nothing retTy) ret
837+ subst <- unifyCurrentSubstitution <$> UnifyT get
838+ arg' <- check arg (subst $? argTy)
839+ return (retTy, App fn arg')
840+checkFunctionApplication' fn (ForAll ident ty _) arg ret = do
841+ replaced <- replaceVarWithUnknown ident ty
842+ checkFunctionApplication fn replaced arg ret
843+checkFunctionApplication' fn u@(TUnknown _) arg ret = do
844+ arg' <- do
845+ TypedValue _ arg' t <- infer arg
846+ (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
847+ return $ TypedValue True arg'' t'
848+ let ty = (\(TypedValue _ _ t) -> t) arg'
849+ ret' <- maybe fresh return ret
850+ u =?= function ty ret'
851+ return (ret', App fn arg')
852+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
853+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
854+ checkFunctionApplication fn ty arg ret
855+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
856+ dicts <- getTypeClassDictionaries
857+ checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg ret
858+checkFunctionApplication' _ fnTy arg _ = throwError $ "Cannot apply a function of type "
859+ ++ prettyPrintType fnTy
860+ ++ " to argument " ++ prettyPrintValue arg
861+
862+-- |
863+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
864+--
865+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
866+subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
867+ where
868+ errorMessage msg = "Error checking that type "
869+ ++ prettyPrintType ty1
870+ ++ " subsumes type "
871+ ++ prettyPrintType ty2
872+ ++ ":\n" ++ msg
873+
874+-- |
875+-- Check whether one type subsumes another
876+--
877+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
878+subsumes' val (ForAll ident ty1 _) ty2 = do
879+ replaced <- replaceVarWithUnknown ident ty1
880+ subsumes val replaced ty2
881+subsumes' val ty1 (ForAll ident ty2 sco) =
882+ case sco of
883+ Just sco' -> do
884+ sko <- newSkolemConstant
885+ let sk = skolemize ident sko sco' ty2
886+ subsumes val ty1 sk
887+ Nothing -> throwError "Skolem variable scope is unspecified"
888+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
889+ _ <- subsumes Nothing arg2 arg1
890+ _ <- subsumes Nothing ret1 ret2
891+ return val
892+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
893+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
894+ subsumes val ty1 ty2
895+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
896+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
897+ subsumes val ty1 ty2
898+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
899+ dicts <- getTypeClassDictionaries
900+ _ <- subsumes' Nothing ty1 ty2
901+ return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
902+subsumes' val (Object r1) (Object r2) = do
903+ let
904+ (ts1, r1') = rowToList r1
905+ (ts2, r2') = rowToList r2
906+ ts1' = sortBy (comparing fst) ts1
907+ ts2' = sortBy (comparing fst) ts2
908+ go ts1' ts2' r1' r2'
909+ return val
910+ where
911+ go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
912+ go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
913+ go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
914+ | p1 == p2 = do _ <- subsumes Nothing ty1 ty2
915+ go ts1 ts2 r1' r2'
916+ | p1 < p2 = do rest <- fresh
917+ r2' =?= RCons p1 ty1 rest
918+ go ts1 ((p2, ty2) : ts2) r1' rest
919+ | otherwise = do rest <- fresh
920+ r1' =?= RCons p2 ty2 rest
921+ go ((p1, ty1) : ts1) ts2 rest r2'
922+subsumes' val ty1 ty2@(Object _) = subsumes val ty2 ty1
923+subsumes' val ty1 ty2 = do
924+ ty1 =?= ty2
925+ return val
926+