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