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