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