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