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