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