@@ -0,0 +1,1020 @@
1+-----------------------------------------------------------------------------
3+-- Module : Language.PureScript.TypeChecker.Types
4+-- Copyright : (c) Phil Freeman 2013
7+-- Maintainer : Phil Freeman <paf31@cantab.net>
8+-- Stability : experimental
12+-- This module implements the type checker
14+-----------------------------------------------------------------------------
16+{-# OPTIONS_GHC -fno-warn-orphans #-}
17+{-# LANGUAGE DeriveDataTypeable #-}
18+{-# LANGUAGE FlexibleContexts #-}
19+{-# LANGUAGE MultiParamTypeClasses #-}
21+module Language.PureScript.TypeChecker.Types (
26+ The following functions represent the corresponding type checking judgements:
29+ Synthesize a type for a value
32+ Check a value has a given type
35+ Check an object with a given type contains specified properties
37+ checkFunctionApplication
38+ Check a function of a given type returns a value of another type when applied to its arguments
41+ Check a type subsumes another type
45+import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46+import qualified Data.Data as D
48+ (everythingWithContext, mkM, everywhereM, everything, mkT,
49+ something, everywhere, mkQ)
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
60+import Control.Monad.State
61+import Control.Monad.Error
62+import Control.Monad.Reader
63+import Control.Monad.Unify
65+import Control.Applicative
66+import Control.Arrow (Arrow(..))
68+import qualified Data.Map as M
69+import Data.Function (on)
71+instance Partial Type where
73+ isUnknown (TUnknown u) = Just u
74+ isUnknown _ = Nothing
76+instance Unifiable Check Type where
80+-- Unify two types, updating the current substitution
82+unifyTypes :: Type -> Type -> UnifyT Type Check ()
83+unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
86+ unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
87+ unifyTypes' (TUnknown u) t = u =:= t
88+ unifyTypes' t (TUnknown u) = u =:= t
89+ unifyTypes' (SaturatedTypeSynonym name args) ty = do
90+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
92+ unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
93+ unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
95+ (Just sc1', Just sc2') -> do
96+ sko <- newSkolemConstant
97+ let sk1 = skolemize ident1 sko sc1' ty1
98+ let sk2 = skolemize ident2 sko sc2' ty2
100+ _ -> throwError (prettyPrintType ty1)
101+ unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
102+ sko <- newSkolemConstant
103+ let sk = skolemize ident sko sc ty1
105+ unifyTypes' (ForAll _ _ _) _ = throwError "Skolem variable scope is unspecified"
106+ unifyTypes' ty f@(ForAll _ _ _) = f `unifyTypes` ty
107+ unifyTypes' (Object row1) (Object row2) = row1 =?= row2
108+ unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
109+ unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
111+ Just moduleName <- checkCurrentModule <$> get
112+ guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
113+ unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
116+ unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
117+ unifyTypes' r1@(RCons _ _ _) r2 = unifyRows r1 r2
118+ unifyTypes' r1 r2@(RCons _ _ _) = unifyRows r1 r2
119+ unifyTypes' r1@REmpty r2 = unifyRows r1 r2
120+ unifyTypes' r1 r2@REmpty = unifyRows r1 r2
121+ unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
124+-- Unify two rows, updating the current substitution
126+-- Common labels are first identified, and unified. Remaining labels and types are unified with a
127+-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
130+unifyRows :: Type -> Type -> UnifyT Type Check ()
133+ (s1, r1') = rowToList r1
134+ (s2, r2') = rowToList r2
135+ int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
136+ sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
137+ sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
139+ forM_ int (uncurry (=?=))
140+ unifyRows' sd1 r1' sd2 r2'
142+ unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
143+ unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
144+ unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
145+ unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
147+ forM_ row $ \(_, t) -> occursCheck un t
149+ u =?= RCons name ty u'
150+ unifyRows' row r others u'
151+ unifyRows' [] REmpty [] REmpty = return ()
152+ unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
153+ unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
154+ unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
157+-- Ensure type constructors are equal after canonicalization
159+typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
160+typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
163+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
164+-- type class dictionaries and type annotations.
166+typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
167+typesOf moduleName vals = do
168+ tys <- fmap tidyUp . liftUnify $ do
170+ -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
171+ es = map isTyped vals
172+ -- Filter the typed and untyped declarations
173+ typed = filter (isJust . snd . snd) es
174+ untyped = filter (isNothing . snd . snd) es
175+ -- Make a map of names to typed declarations
176+ typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
177+ -- Create fresh unification variables for the types of untyped declarations
178+ untypedNames <- replicateM (length untyped) fresh
180+ -- Make a map of names to the unification variables of untyped declarations
181+ untypedDict = zip (map fst untyped) untypedNames
182+ -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
183+ dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
184+ forM es $ \e@(_, (val, _)) -> do
185+ -- If the declaration is a function, it has access to other values in the binding group.
186+ -- If not, the generated code might fail at runtime since those values might be undefined.
187+ let dict' = if isFunction val then dict else M.empty
188+ triple@(_, (val, ty)) <- case e of
189+ -- Typed declarations
190+ (ident, (val, Just (ty, checkType))) -> do
192+ kind <- liftCheck $ kindOf moduleName ty
193+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
194+ -- Check the type with the new names in scope
195+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
196+ val' <- bindNames dict' $ if checkType
197+ then TypedValue True <$> check val ty' <*> pure ty'
198+ else return (TypedValue False val ty')
199+ return (ident, (val', ty'))
200+ -- Untyped declarations
201+ (ident, (val, Nothing)) -> do
202+ -- Infer the type with the new names in scope
203+ TypedValue _ val' ty <- bindNames dict' $ infer val
204+ ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
205+ return (ident, (TypedValue True val' ty, ty))
206+ -- If run-main is enabled, need to check that Main.main has type Eff eff a for some eff, a
207+ when (moduleName == ModuleName (ProperName "Main") && fst e == Ident "main") $ do
208+ [eff, a] <- replicateM 2 fresh
209+ ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName (ProperName "Eff"))) (ProperName "Eff"))) eff) a
210+ -- Make sure unification variables do not escape
213+ forM tys $ \(ident, (val, ty)) -> do
214+ -- Replace type class dictionary placeholders with actual dictionaries
215+ val' <- replaceTypeClassDictionaries moduleName val
216+ -- Check skolem variables did not escape their scope
217+ skolemEscapeCheck val'
218+ -- Remove type synonyms placeholders, remove duplicate row fields, and replace
219+ -- top-level unification variables with named type variables.
220+ let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
221+ ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
222+ return $ (ident, (val'', ty'))
224+ -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
225+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
228+-- Check if a value introduces a function
230+isFunction :: Value -> Bool
231+isFunction (Abs _ _) = True
232+isFunction (TypedValue _ val _) = isFunction val
236+-- Check if a value contains a type annotation
238+isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
239+isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
240+isTyped (name, value) = (name, (value, Nothing))
243+-- Map a function over type annotations appearing inside a value
245+overTypes :: (Type -> Type) -> Value -> Value
246+overTypes f = everywhere (mkT f)
249+-- Replace type class dictionary placeholders with inferred type class dictionaries
251+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
252+replaceTypeClassDictionaries mn = everywhereM (mkM go)
254+ go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
255+ go other = return other
258+-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
259+-- return a type class dictionary reference.
261+entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
262+entails moduleName context goal@(className, ty) = do
265+ [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
266+ (dict : _) -> return dict
268+ go env (className', ty') =
269+ [ mkDictionary (canonicalizeDictionary tcd) args
271+ -- Choose type class dictionaries in scope in the current module
273+ -- Make sure the type class name matches the one we are trying to satisfy
274+ , typeConstructorsAreEqual env moduleName className' (tcdClassName tcd)
275+ -- Make sure the type unifies with the type in the type instance definition
276+ , subst <- maybeToList $ typeHeadsAreEqual moduleName env ty' (tcdInstanceType tcd)
277+ -- Solve any necessary subgoals
278+ , args <- solveSubgoals env subst (tcdDependencies tcd) ]
279+ -- Create dictionaries for subgoals which still need to be solved by calling go recursively
280+ -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
281+ -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
282+ solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, Type)] -> [Maybe [Value]]
283+ solveSubgoals _ _ Nothing = return Nothing
284+ solveSubgoals env subst (Just subgoals) = do
285+ dict <- mapM (go env) (map (id *** replaceAllTypeVars subst) subgoals)
287+ -- Make a dictionary from subgoal dictionaries by applying the correct function
288+ mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
289+ mkDictionary fnName Nothing = Var fnName
290+ mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
291+ -- Filter out type dictionaries which are in scope in the current module
292+ filterModule :: TypeClassDictionaryInScope -> Bool
293+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
294+ filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
295+ filterModule _ = False
296+ -- Resolve a type class dictionary in scope to an actual value by following any (TCDAlias) pointers
297+ -- which originated from module imports
298+ canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
299+ canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
300+ canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
303+-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
304+-- and return a substitution from type variables to types which makes the type heads unify.
306+typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
307+typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
308+typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
309+typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
310+typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | typeConstructorsAreEqual e m c1 c2 = Just []
311+typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
312+typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
313+typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e m name args of
315+ Right t1 -> typeHeadsAreEqual m e t1 t2
316+typeHeadsAreEqual _ _ _ _ = Nothing
319+-- Ensure unsolved unification variables do not escape
321+escapeCheck :: Value -> Type -> UnifyT Type Check ()
322+escapeCheck value ty = do
323+ subst <- unifyCurrentSubstitution <$> UnifyT get
324+ let visibleUnknowns = nub $ unknowns $ subst $? ty
325+ let allUnknowns = findAllTypes value
326+ forM_ allUnknowns $ \t -> do
327+ let unsolvedUnknowns = nub . unknowns $ subst $? t
328+ guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
331+-- Find all type annotations occuring inside a value
333+findAllTypes :: Value -> [Type]
334+findAllTypes = everything (++) (mkQ [] go)
336+ go (TypedValue _ _ ty) = [ty]
340+-- Ensure skolem variables do not escape their scope
342+skolemEscapeCheck :: Value -> Check ()
343+skolemEscapeCheck (TypedValue False _ _) = return ()
344+skolemEscapeCheck root@(TypedValue _ _ _) =
345+ -- Every skolem variable is created when a ForAll type is skolemized.
346+ -- This determines the scope of that skolem variable, which is copied from the SkolemScope
347+ -- field of the ForAll constructor.
348+ -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
349+ -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
350+ -- an escaped skolem variable.
351+ case everythingWithContext [] (++) (mkQ ((,) []) go) root of
353+ ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
355+ go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
356+ go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
357+ go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
358+ (sco : _) -> ([(findBindingScope sco, val)], scos)
361+ collectSkolems :: Type -> [SkolemScope]
362+ collectSkolems = nub . everything (++) (mkQ [] collect)
364+ collect (Skolem _ scope) = [scope]
366+ go _ scos = ([], scos)
367+ findBindingScope :: SkolemScope -> Maybe Value
368+ findBindingScope sco = something (mkQ Nothing go) root
370+ go val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
372+skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
375+-- Ensure a row contains no duplicate labels
377+setify :: Type -> Type
378+setify = rowFromList . first (M.toList . M.fromList) . rowToList
381+-- \"Setify\" all rows occuring inside a value
383+setifyAll :: (D.Data d) => d -> d
384+setifyAll = everywhere (mkT setify)
387+-- Replace outermost unsolved unification variables with named type variables
389+varIfUnknown :: Type -> Type
391+ let unks = nub $ unknowns ty
392+ toName = (:) 't' . show
393+ ty' = everywhere (mkT typeToVar) $ ty
394+ typeToVar :: Type -> Type
395+ typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
397+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
400+-- Replace named type variables with types
402+replaceAllTypeVars :: [(String, Type)] -> Type -> Type
403+replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
406+-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
407+-- or TypeClassDictionary values.
409+-- This is necessary during type checking to avoid unifying a polymorphic type with a
410+-- unification variable.
412+instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
413+instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
414+ ty' <- replaceVarWithUnknown ident ty
415+ instantiatePolyTypeWithUnknowns val ty'
416+instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
418+ Just moduleName <- checkCurrentModule <$> get
419+ dicts <- getTypeClassDictionaries
420+ (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
421+ return (foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints)), ty')
422+instantiatePolyTypeWithUnknowns val ty = return (val, ty)
425+-- Replace a single type variable with a new unification variable
427+replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
428+replaceVarWithUnknown ident ty = do
430+ return $ replaceTypeVars ident tu $ ty
433+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
434+-- better error messages during unification.
436+replaceAllTypeSynonyms' :: (D.Data d) => Environment -> ModuleName -> d -> Either String d
437+replaceAllTypeSynonyms' env moduleName d =
439+ syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
441+ saturateAllTypeSynonyms env moduleName syns d
443+replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
444+replaceAllTypeSynonyms d = do
446+ Just moduleName <- checkCurrentModule <$> get
447+ either throwError return $ replaceAllTypeSynonyms' env moduleName d
450+-- \"Desaturate\" @SaturatedTypeSynonym@s
452+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
453+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
455+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
456+ replaceSaturatedTypeSynonym t = t
459+-- Replace a type synonym and its arguments with the aliased type
461+expandTypeSynonym' :: Environment -> ModuleName -> Qualified ProperName -> [Type] -> Either String Type
462+expandTypeSynonym' env moduleName name args =
463+ case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
464+ Just (synArgs, body) -> do
465+ let repl = replaceAllTypeVars (zip synArgs args) body
466+ replaceAllTypeSynonyms' env moduleName repl
467+ Nothing -> error "Type synonym was not defined"
469+expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
470+expandTypeSynonym name args = do
472+ Just moduleName <- checkCurrentModule <$> get
473+ either throwError return $ expandTypeSynonym' env moduleName name args
476+-- Ensure a set of property names and value does not contain duplicate labels
478+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
479+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
482+-- Infer a type for a value, rethrowing any error to provide a more useful error message
484+infer :: Value -> UnifyT Type Check Value
485+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
488+-- Infer a type for a value
490+infer' :: Value -> UnifyT Type Check Value
491+infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
492+infer' v@(StringLiteral _) = return $ TypedValue True v tyString
493+infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
494+infer' (ArrayLiteral vals) = do
495+ ts <- mapM infer vals
497+ forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
498+ return $ TypedValue True (ArrayLiteral ts) els
499+infer' (ObjectLiteral ps) = do
500+ ensureNoDuplicateProperties ps
501+ ts <- mapM (infer . snd) ps
502+ let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
503+ ty = Object $ rowFromList (fields, REmpty)
504+ return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
505+infer' (ObjectUpdate o ps) = do
506+ ensureNoDuplicateProperties ps
508+ newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
509+ let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
510+ oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
511+ let oldTy = Object $ rowFromList (oldTys, row)
512+ o' <- TypedValue True <$> check o oldTy <*> pure oldTy
513+ return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
514+infer' (Accessor prop val) = do
515+ typed@(TypedValue _ _ objTy) <- infer val
516+ propTy <- inferProperty objTy prop
521+ _ <- subsumes Nothing objTy (Object (RCons prop field rest))
522+ return $ TypedValue True (Accessor prop typed) field
523+ Just ty -> return $ TypedValue True (Accessor prop typed) ty
524+infer' (Abs arg ret) = do
526+ Just moduleName <- checkCurrentModule <$> get
527+ bindLocalVariables moduleName [(arg, ty)] $ do
528+ body@(TypedValue _ _ bodyTy) <- infer' ret
529+ return $ TypedValue True (Abs arg body) $ function ty bodyTy
530+infer' (App f arg) = do
531+ f'@(TypedValue _ _ ft) <- infer f
532+ (ret, app) <- checkFunctionApplication f' ft arg
533+ return $ TypedValue True app ret
534+infer' (Var var) = do
535+ Just moduleName <- checkCurrentModule <$> get
536+ ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
538+ ConstrainedType constraints ty' -> do
540+ dicts <- getTypeClassDictionaries
541+ return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) ty'
542+ _ -> return $ TypedValue True (Var var) ty
543+infer' (Block ss) = do
545+ (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
546+ guardWith "Block is missing a return statement" allCodePathsReturn
547+ return $ TypedValue True (Block ss') ret
548+infer' v@(Constructor c) = do
550+ Just moduleName <- checkCurrentModule <$> get
551+ case M.lookup (qualify moduleName c) (dataConstructors env) of
552+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
553+ Just (ty, _) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
554+ return $ TypedValue True v ty'
555+infer' (Case vals binders) = do
556+ ts <- mapM infer vals
558+ binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
559+ return $ TypedValue True (Case ts binders') ret
560+infer' (IfThenElse cond th el) = do
561+ cond' <- check cond tyBoolean
562+ v2@(TypedValue _ _ t2) <- infer th
563+ v3@(TypedValue _ _ t3) <- infer el
565+ return $ TypedValue True (IfThenElse cond' v2 v3) t2
566+infer' (TypedValue checkType val ty) = do
567+ Just moduleName <- checkCurrentModule <$> get
568+ kind <- liftCheck $ kindOf moduleName ty
569+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
570+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
571+ val' <- if checkType then check val ty' else return val
572+ return $ TypedValue True val' ty'
573+infer' _ = error "Invalid argument to infer"
576+-- Infer the type of a property inside a record with a given type
578+inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
579+inferProperty (Object row) prop = do
580+ let (props, _) = rowToList row
581+ return $ lookup prop props
582+inferProperty (SaturatedTypeSynonym name args) prop = do
583+ replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
584+ inferProperty replaced prop
585+inferProperty (ForAll ident ty _) prop = do
586+ replaced <- replaceVarWithUnknown ident ty
587+ inferProperty replaced prop
588+inferProperty _ _ = return Nothing
591+-- Infer the types of variables brought into scope by a binder
593+inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
594+inferBinder _ NullBinder = return M.empty
595+inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
596+inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
597+inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
598+inferBinder val (VarBinder name) = return $ M.singleton name val
599+inferBinder val (NullaryBinder ctor) = do
601+ Just moduleName <- checkCurrentModule <$> get
602+ case M.lookup (qualify moduleName ctor) (dataConstructors env) of
604+ _ <- subsumes Nothing ty val
606+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
607+inferBinder val (UnaryBinder ctor binder) = do
609+ Just moduleName <- checkCurrentModule <$> get
610+ case M.lookup (qualify moduleName ctor) (dataConstructors env) of
612+ (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contains constraints") ty
614+ TypeApp (TypeApp t obj) ret | t == tyFunction -> do
615+ _ <- subsumes Nothing val ret
616+ inferBinder obj binder
617+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
618+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
619+inferBinder val (ObjectBinder props) = do
622+ m1 <- inferRowProperties row rest props
626+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
627+ inferRowProperties nrow row [] = nrow =?= row >> return M.empty
628+ inferRowProperties nrow row ((name, binder):binders) = do
630+ m1 <- inferBinder propTy binder
631+ m2 <- inferRowProperties nrow (RCons name propTy row) binders
632+ return $ m1 `M.union` m2
633+inferBinder val (ArrayBinder binders) = do
635+ m1 <- M.unions <$> mapM (inferBinder el) binders
636+ val =?= TypeApp tyArray el
638+inferBinder val (ConsBinder headBinder tailBinder) = do
640+ m1 <- inferBinder el headBinder
641+ m2 <- inferBinder val tailBinder
642+ val =?= TypeApp tyArray el
643+ return $ m1 `M.union` m2
644+inferBinder val (NamedBinder name binder) = do
645+ m <- inferBinder val binder
646+ return $ M.insert name val m
649+-- Check the types of the return values in a set of binders in a case statement
651+checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Type Check [([Binder], Maybe Guard, Value)]
652+checkBinders _ _ [] = return []
653+checkBinders nvals ret ((binders, grd, val):bs) = do
654+ Just moduleName <- checkCurrentModule <$> get
655+ m1 <- M.unions <$> zipWithM inferBinder nvals binders
656+ r <- bindLocalVariables moduleName (M.toList m1) $ do
657+ val' <- TypedValue True <$> check val ret <*> pure ret
659+ Nothing -> return (binders, Nothing, val')
661+ g' <- check g tyBoolean
662+ return (binders, Just g', val')
663+ rs <- checkBinders nvals ret bs
667+-- Check that a local variable name is not already used
669+assignVariable :: Ident -> UnifyT Type Check ()
670+assignVariable name = do
671+ env <- checkEnv <$> get
672+ Just moduleName <- checkCurrentModule <$> get
673+ case M.lookup (moduleName, name) (names env) of
674+ Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
678+-- Check the type of the return values of a statement, returning whether or not the statement returns on
681+checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Type Check (Bool, M.Map Ident Type, Statement)
682+checkStatement mass _ (VariableIntroduction name val) = do
684+ val'@(TypedValue _ _ t) <- infer val
685+ return (False, M.insert name t mass, VariableIntroduction name val')
686+checkStatement mass _ (Assignment ident val) = do
687+ val'@(TypedValue _ _ t) <- infer val
688+ case M.lookup ident mass of
689+ Nothing -> throwError $ "No local variable with name " ++ show ident
690+ Just ty -> do t =?= ty
691+ return (False, mass, Assignment ident val')
692+checkStatement mass ret (While val inner) = do
693+ val' <- check val tyBoolean
694+ (allCodePathsReturn, _, inner') <- checkBlock mass ret inner
695+ return (allCodePathsReturn, mass, While val' inner')
696+checkStatement mass ret (If ifst) = do
697+ (allCodePathsReturn, ifst') <- checkIfStatement mass ret ifst
698+ return (allCodePathsReturn, mass, If ifst')
699+checkStatement mass ret (For ident start end inner) = do
700+ Just moduleName <- checkCurrentModule <$> get
701+ assignVariable ident
702+ start' <- check start tyNumber
703+ end' <- check end tyNumber
704+ (allCodePathsReturn, _, inner') <- bindLocalVariables moduleName [(ident, tyNumber)] $ checkBlock mass ret inner
705+ return (allCodePathsReturn, mass, For ident start' end' inner')
706+checkStatement mass ret (Return val) = do
707+ val' <- check val ret
708+ return (True, mass, Return (TypedValue True val' ret))
711+-- Check the type of an if-then-else statement
713+checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> UnifyT Type Check (Bool, IfStatement)
714+checkIfStatement mass ret (IfStatement val thens Nothing) = do
715+ val' <- check val tyBoolean
716+ (_, _, thens') <- checkBlock mass ret thens
717+ return (False, IfStatement val' thens' Nothing)
718+checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
719+ val' <- check val tyBoolean
720+ (allCodePathsReturn1, _, thens') <- checkBlock mass ret thens
721+ (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
722+ return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
725+-- Check the type of an else statement
727+checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> UnifyT Type Check (Bool, ElseStatement)
728+checkElseStatement mass ret (Else elses) = do
729+ (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
730+ return (allCodePathsReturn, Else elses')
731+checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
734+-- Check the type of the return value of a block of statements
736+checkBlock :: M.Map Ident Type -> Type -> [Statement] -> UnifyT Type Check (Bool, M.Map Ident Type, [Statement])
737+checkBlock mass _ [] = return (False, mass, [])
738+checkBlock mass ret (s:ss) = do
739+ Just moduleName <- checkCurrentModule <$> get
740+ (b1, mass1, s') <- checkStatement mass ret s
741+ bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
742+ (True, []) -> return (True, mass1, [s'])
743+ (True, _) -> throwError "Unreachable code"
745+ (b, m, ss'') <- checkBlock mass1 ret ss'
746+ return (b, m, s':ss'')
749+-- Generate a new skolem constant
751+newSkolemConstant :: UnifyT Type Check Int
752+newSkolemConstant = runUnknown <$> fresh'
755+-- Generate a new skolem scope
757+newSkolemScope :: UnifyT Type Check SkolemScope
758+newSkolemScope = SkolemScope . runUnknown <$> fresh'
761+-- Skolemize a type variable by replacing its instances with fresh skolem constants
763+skolemize :: String -> Int -> SkolemScope -> Type -> Type
764+skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
767+-- Introduce skolem scope at every occurence of a ForAll
769+introduceSkolemScope :: Type -> UnifyT Type Check Type
770+introduceSkolemScope = everywhereM (mkM go)
772+ go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
773+ go other = return other
776+-- Check the type of a value, rethrowing errors to provide a better error message
778+check :: Value -> Type -> UnifyT Type Check Value
779+check val ty = rethrow errorMessage $ check' val ty
782+ "Error checking type of term " ++
783+ prettyPrintValue val ++
785+ prettyPrintType ty ++
790+-- Check the type of a value
792+check' :: Value -> Type -> UnifyT Type Check Value
793+check' val t@(ForAll ident ty _) = do
794+ scope <- newSkolemScope
795+ sko <- newSkolemConstant
796+ let sk = skolemize ident sko scope ty
797+ val' <- check val sk
798+ return $ TypedValue True val' (ForAll ident ty (Just scope))
799+check' val t@(ConstrainedType constraints ty) = do
801+ Just moduleName <- checkCurrentModule <$> get
802+ dictNames <- flip mapM constraints $ \(Qualified _ (ProperName className), _) -> do
803+ n <- liftCheck freshDictionaryName
804+ return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
805+ val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
806+ TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
807+ (qualifyAllUnqualifiedNames moduleName env constraints)) $
809+ return $ TypedValue True (foldr Abs val' dictNames) t
810+check' val t@(SaturatedTypeSynonym name args) = do
811+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
812+ val' <- check val ty
813+ return $ TypedValue True val' ty
814+check' val u@(TUnknown _) = do
815+ val'@(TypedValue _ _ ty) <- infer val
816+ -- Don't unify an unknown with an inferred polytype
817+ (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
819+ return $ TypedValue True val'' ty'
820+check' v@(NumericLiteral _) t | t == tyNumber =
821+ return $ TypedValue True v t
822+check' v@(StringLiteral _) t | t == tyString =
823+ return $ TypedValue True v t
824+check' v@(BooleanLiteral _) t | t == tyBoolean =
825+ return $ TypedValue True v t
826+check' (ArrayLiteral vals) t@(TypeApp a ty) | a == tyArray = do
827+ arr <- ArrayLiteral <$> forM vals (\val -> check val ty)
828+ return $ TypedValue True arr t
829+check' (Abs arg ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
830+ Just moduleName <- checkCurrentModule <$> get
831+ ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
832+ return $ TypedValue True (Abs arg ret') ty
833+check' (App f arg) ret = do
834+ f'@(TypedValue _ _ ft) <- infer f
835+ (ret', app) <- checkFunctionApplication f' ft arg
836+ subsumes Nothing ret' ret
837+ return $ TypedValue True app ret
838+check' v@(Var var) ty = do
839+ Just moduleName <- checkCurrentModule <$> get
840+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
841+ ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
842+ v' <- subsumes (Just v) repl ty'
844+ Nothing -> throwError "Unable to check type subsumption"
845+ Just v'' -> return $ TypedValue True v'' ty'
846+check' (TypedValue checkType val ty1) ty2 = do
847+ Just moduleName <- checkCurrentModule <$> get
848+ kind <- liftCheck $ kindOf moduleName ty1
849+ guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
850+ val' <- subsumes (Just val) ty1 ty2
852+ Nothing -> throwError "Unable to check type subsumption"
854+ val''' <- if checkType then check val'' ty1 else return val''
855+ return $ TypedValue checkType (TypedValue True val''' ty1) ty2
856+check' (Case vals binders) ret = do
857+ vals' <- mapM infer vals
858+ let ts = map (\(TypedValue _ _ t) -> t) vals'
859+ binders' <- checkBinders ts ret binders
860+ return $ TypedValue True (Case vals' binders') ret
861+check' (IfThenElse cond th el) ty = do
862+ cond' <- check cond tyBoolean
865+ return $ TypedValue True (IfThenElse cond' th' el') ty
866+check' (ObjectLiteral ps) t@(Object row) = do
867+ ensureNoDuplicateProperties ps
868+ ps' <- checkProperties ps row False
869+ return $ TypedValue True (ObjectLiteral ps') t
870+check' (ObjectUpdate obj ps) t@(Object row) = do
871+ ensureNoDuplicateProperties ps
872+ us <- zip (map fst ps) <$> replicateM (length ps) fresh
873+ let (propsToCheck, rest) = rowToList row
874+ propsToRemove = map fst ps
875+ remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
876+ obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
877+ ps' <- checkProperties ps row True
878+ return $ TypedValue True (ObjectUpdate obj' ps') t
879+check' (Accessor prop val) ty = do
881+ val' <- check val (Object (RCons prop ty rest))
882+ return $ TypedValue True (Accessor prop val') ty
883+check' (Block ss) ret = do
884+ (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
885+ guardWith "Block is missing a return statement" allCodePathsReturn
886+ return $ TypedValue True (Block ss') ret
887+check' (Constructor c) ty = do
889+ Just moduleName <- checkCurrentModule <$> get
890+ case M.lookup (qualify moduleName c) (dataConstructors env) of
891+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
893+ repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
894+ _ <- subsumes Nothing repl ty
895+ return $ TypedValue True (Constructor c) ty
896+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
899+-- Check the type of a collection of named record fields
901+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
903+checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
904+checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
905+ go [] [] REmpty = return []
906+ go [] [] u@(TUnknown _) = do u =?= REmpty
908+ go [] [] (Skolem _ _) | lax = return []
909+ go [] ((p, _): _) _ | lax = return []
910+ | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
911+ go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
912+ go ((p,v):ps') [] u@(TUnknown _) = do
913+ v'@(TypedValue _ _ ty) <- infer v
915+ u =?= RCons p ty rest
916+ ps'' <- go ps' [] rest
917+ return $ (p, v') : ps''
918+ go ((p,v):ps') ts r =
921+ v'@(TypedValue _ _ ty) <- infer v
923+ r =?= RCons p ty rest
924+ ps'' <- go ps' ts rest
925+ return $ (p, v') : ps''
928+ ps'' <- go ps' (delete (p, ty) ts) r
929+ return $ (p, v') : ps''
930+ go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
933+-- Check the type of a function application, rethrowing errors to provide a better error message
935+checkFunctionApplication :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
936+checkFunctionApplication fn fnTy arg = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg
938+ errorMessage msg = "Error applying function of type "
939+ ++ prettyPrintType fnTy
940+ ++ " to argument " ++ prettyPrintValue arg
944+-- Check the type of a function application
946+checkFunctionApplication' :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
947+checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg = do
948+ tyFunction' =?= tyFunction
949+ arg' <- check arg argTy
950+ return (retTy, App fn arg')
951+checkFunctionApplication' fn (ForAll ident ty _) arg = do
952+ replaced <- replaceVarWithUnknown ident ty
953+ checkFunctionApplication fn replaced arg
954+checkFunctionApplication' fn u@(TUnknown _) arg = do
956+ TypedValue _ v t <- infer arg
957+ (v', t') <- instantiatePolyTypeWithUnknowns arg t
958+ return $ TypedValue True v' t'
959+ let ty = (\(TypedValue _ _ t) -> t) arg'
961+ u =?= function ty ret
962+ return (ret, App fn arg')
963+checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg = do
964+ ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
965+ checkFunctionApplication fn ty arg
966+checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg = do
968+ dicts <- getTypeClassDictionaries
969+ Just moduleName <- checkCurrentModule <$> get
970+ checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy arg
971+checkFunctionApplication' _ fnTy arg = throwError $ "Cannot apply a function of type "
972+ ++ prettyPrintType fnTy
973+ ++ " to argument " ++ prettyPrintValue arg
976+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
978+subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
979+subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
981+ errorMessage msg = "Error checking that type "
982+ ++ prettyPrintType ty1
983+ ++ " subsumes type "
984+ ++ prettyPrintType ty2
988+-- Check whether one type subsumes another
990+subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
991+subsumes' val (ForAll ident ty1 _) ty2 = do
992+ replaced <- replaceVarWithUnknown ident ty1
993+ subsumes val replaced ty2
994+subsumes' val ty1 (ForAll ident ty2 sco) =
997+ sko <- newSkolemConstant
998+ let sk = skolemize ident sko sco' ty2
1000+ Nothing -> throwError "Skolem variable scope is unspecified"
1001+subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1002+ subsumes Nothing arg2 arg1
1003+ subsumes Nothing ret1 ret2
1005+subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1006+ ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1007+ subsumes val ty1 ty2
1008+subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1009+ ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1010+ subsumes val ty1 ty2
1011+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1013+ dicts <- getTypeClassDictionaries
1014+ Just moduleName <- checkCurrentModule <$> get
1015+ _ <- subsumes' Nothing ty1 ty2
1016+ return . Just $ foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
1017+subsumes' val ty1 ty2 = do