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