@@ -1,985 +0,0 @@
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− (mkM, everywhereM, everything, mkT, something, everywhere, mkQ)
50−import Language.PureScript.Values
51−import Language.PureScript.Types
52−import Language.PureScript.Kinds
53−import Language.PureScript.Names
54−import Language.PureScript.TypeChecker.Monad
55−import Language.PureScript.TypeChecker.Kinds
56−import Language.PureScript.TypeChecker.Synonyms
57−import Language.PureScript.Pretty
59−import Control.Monad.State
60−import Control.Monad.Error
61−import Control.Monad.Reader
62−import Control.Monad.Unify
64−import Control.Applicative
65−import Control.Arrow (Arrow(..))
67−import qualified Data.Map as M
68−import Data.Function (on)
70−instance Unifiable Check Type where
72− isUnknown (TUnknown u) = Just u
73− isUnknown _ = Nothing
77−-- Unify two types, updating the current substitution
79−unifyTypes :: Type -> Type -> UnifyT Check ()
80−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
83− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
84− unifyTypes' (TUnknown u) t = replace u t
85− unifyTypes' t (TUnknown u) = replace u t
86− unifyTypes' (SaturatedTypeSynonym name args) ty = do
87− ty1 <- expandTypeSynonym name args
89− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
90− unifyTypes' (ForAll ident1 ty1) (ForAll ident2 ty2) = do
91− sk <- skolemize ident1 ty1
92− replaced <- replaceVarWithUnknown ident2 ty2
93− sk `unifyTypes` replaced
94− unifyTypes' (ForAll ident ty1) ty2 = do
95− sk <- skolemize ident ty1
97− unifyTypes' ty f@(ForAll _ _) = f `unifyTypes` ty
98− unifyTypes' (Object row1) (Object row2) = row1 ?= row2
99− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
100− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
102− Just moduleName <- checkCurrentModule <$> get
103− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
104− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
107− unifyTypes' (Skolem s1) (Skolem s2) | s1 == s2 = return ()
108− unifyTypes' r1@(RCons _ _ _) r2 = unifyRows r1 r2
109− unifyTypes' r1 r2@(RCons _ _ _) = unifyRows r1 r2
110− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
111− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
112− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
115−-- Unify two rows, updating the current substitution
117−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
118−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
121−unifyRows :: Type -> Type -> UnifyT Check ()
124− (s1, r1') = rowToList r1
125− (s2, r2') = rowToList r2
126− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
127− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
128− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
130− forM_ int (uncurry (?=))
131− unifyRows' sd1 r1' sd2 r2'
133− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Check ()
134− unifyRows' [] (TUnknown u) sd r = replace u (rowFromList (sd, r))
135− unifyRows' sd r [] (TUnknown u) = replace u (rowFromList (sd, r))
136− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
138− forM_ row $ \(_, t) -> occursCheck un t
140− u ?= RCons name ty u'
141− unifyRows' row r others u'
142− unifyRows' [] REmpty [] REmpty = return ()
143− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
144− unifyRows' [] (Skolem s1) [] (Skolem s2) | s1 == s2 = return ()
145− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
148−-- Ensure type constructors are equal after canonicalization
150−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
151−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
154−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
155−-- type class dictionaries and type annotations.
157−typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
158−typesOf moduleName vals = do
159− tys <- liftUnify $ do
160− let es = map isTyped vals
161− typed = filter (isJust . snd . snd) es
162− untyped = filter (isNothing . snd . snd) es
163− typedDict = map (\(ident, (_, Just ty)) -> (ident, ty)) typed
164− untypedNames <- replicateM (length untyped) fresh
165− let untypedDict = zip (map fst untyped) untypedNames
166− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ (map (id *** fst) typedDict) ++ untypedDict)
168− triple@(_, (val, ty)) <- case e of
169− (ident, (val, Just (ty, checkType))) -> do
170− kind <- liftCheck $ kindOf moduleName ty
171− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
172− ty' <- replaceAllTypeSynonyms ty
173− val' <- bindNames dict $ if checkType then check val ty' else return val
174− return (ident, (val', ty'))
175− (ident, (val, Nothing)) -> do
176− TypedValue _ val' ty <- bindNames dict $ infer val
177− ty ?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
178− return (ident, (val', ty))
179− when (moduleName == ModuleName (ProperName "Main") && fst e == Ident "main") $ do
180− [eff, a] <- replicateM 2 fresh
181− ty ?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName (ProperName "Eff"))) (ProperName "Eff"))) eff) a
184− forM_ tys $ skolemEscapeCheck . snd . snd
185− forM tys $ \(ident, (val, ty)) -> do
186− val' <- replaceTypeClassDictionaries moduleName val
187− return (ident, (overTypes (desaturateAllTypeSynonyms . setifyAll) $ val'
188− , varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty))
191−-- Check if a value contains a type annotation
193−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
194−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
195−isTyped (name, value) = (name, (value, Nothing))
198−-- Map a function over type annotations appearing inside a value
200−overTypes :: (Type -> Type) -> Value -> Value
201−overTypes f = everywhere (mkT f)
204−-- Replace type class dictionary placeholders with inferred type class dictionaries
206−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
207−replaceTypeClassDictionaries mn = everywhereM (mkM go)
209− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
210− go other = return other
213−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
214−-- return a type class dictionary reference.
216−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
217−entails moduleName context goal@(className, ty) = do
220− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
221− (dict : _) -> return dict
223− go env (className', ty') =
224− [ mkDictionary (canonicalizeDictionary tcd) args
227− , typeConstructorsAreEqual env moduleName className' (tcdClassName tcd)
228− , subst <- maybeToList $ typeHeadsAreEqual moduleName env ty' (tcdInstanceType tcd)
229− , args <- solveSubgoals env subst (tcdDependencies tcd) ]
230− solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, Type)] -> [Maybe [Value]]
231− solveSubgoals _ _ Nothing = return Nothing
232− solveSubgoals env subst (Just subgoals) = do
233− dict <- mapM (go env) (replaceAllTypeVars subst subgoals)
235− mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
236− mkDictionary fnName Nothing = Var fnName
237− mkDictionary fnName (Just dicts) = foldr (flip App) (Var fnName) dicts
238− filterModule :: TypeClassDictionaryInScope -> Bool
239− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
240− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
241− filterModule _ = False
242− canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
243− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
244− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
247−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
248−-- and return a substitution from type variables to types which makes the type heads unify.
250−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
251−typeHeadsAreEqual _ _ (Skolem s1) (Skolem s2) | s1 == s2 = Just []
252−typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | typeConstructorsAreEqual e m c1 c2 = Just []
253−typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
254−typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
255−typeHeadsAreEqual _ _ _ _ = Nothing
258−-- Ensure unsolved unification variables do not escape
260−escapeCheck :: Value -> Type -> UnifyT Check ()
261−escapeCheck value ty = do
262− subst <- unifyCurrentSubstitution <$> UnifyT get
263− let visibleUnknowns = nub $ unknowns $ runSubstitution subst ty
264− let allUnknowns = findAllTypes value
265− forM_ allUnknowns $ \t -> do
266− let unsolvedUnknowns = nub . unknowns $ runSubstitution subst t
267− guardWith ("Escape check fails" ++ show ( runSubstitution subst ty, runSubstitution subst t)) $ null $ unsolvedUnknowns \\ visibleUnknowns
270−-- Find all type annotations occuring inside a value
272−findAllTypes :: Value -> [Type]
273−findAllTypes = everything (++) (mkQ [] go)
275− go (TypedValue _ _ ty) = [ty]
279−-- Ensure skolem variables do not escape their scope
281−skolemEscapeCheck :: Type -> Check ()
282−skolemEscapeCheck ty =
283− case something (mkQ Nothing findSkolems) ty of
284− Nothing -> return ()
285− Just _ -> throwError $ "Skolem variables cannot escape. Consider adding a type signature."
287− findSkolems (Skolem _) = return ()
288− findSkolems _ = mzero
291−-- Ensure a row contains no duplicate labels
293−setify :: Type -> Type
294−setify = rowFromList . first (M.toList . M.fromList) . rowToList
297−-- \"Setify\" all rows occuring inside a value
299−setifyAll :: (D.Data d) => d -> d
300−setifyAll = everywhere (mkT setify)
303−-- Replace outermost unsolved unification variables with named type variables
305−varIfUnknown :: Type -> Type
307− let unks = nub $ unknowns ty
308− toName = (:) 't' . show
309− ty' = everywhere (mkT typeToVar) $ ty
310− typeToVar :: Type -> Type
311− typeToVar (TUnknown (TypedUnknown (Unknown u))) = TypeVar (toName u)
313− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
316−-- Replace named type variables with types
318−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
319−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
322−-- Replace named type variables with new unification variables
324−replaceAllVarsWithUnknowns :: Type -> UnifyT Check Type
325−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
326−replaceAllVarsWithUnknowns ty = return ty
329−-- Replace a single type variable with a new unification variable
331−replaceVarWithUnknown :: String -> Type -> UnifyT Check Type
332−replaceVarWithUnknown ident ty = do
334− return $ replaceTypeVars ident tu $ ty
337−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
338−-- better error messages during unification.
340−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
341−replaceAllTypeSynonyms d = do
343− Just moduleName <- checkCurrentModule <$> get
344− let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
345− either throwError return $ saturateAllTypeSynonyms env moduleName syns d
348−-- \"Desaturate\" @SaturatedTypeSynonym@s
350−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
351−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
353− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
354− replaceSaturatedTypeSynonym t = t
357−-- Replace a type synonym and its arguments with the aliased type
359−expandTypeSynonym :: Qualified ProperName -> [Type] -> UnifyT Check Type
360−expandTypeSynonym name args = do
362− Just moduleName <- checkCurrentModule <$> get
363− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
364− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
365− Nothing -> error "Type synonym was not defined"
368−-- Ensure a set of property names and value does not contain duplicate labels
370−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
371−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
374−-- Infer a type for a value, rethrowing any error to provide a more useful error message
376−infer :: Value -> UnifyT Check Value
377−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
380−-- Infer a type for a value
382−infer' :: Value -> UnifyT Check Value
383−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
384−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
385−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
386−infer' (ArrayLiteral vals) = do
387− ts <- mapM infer vals
389− forM_ ts $ \(TypedValue _ _ t) -> els ?= TypeApp tyArray t
390− return $ TypedValue True (ArrayLiteral ts) els
391−infer' (Unary op val) = do
394−infer' (Binary op left right) = do
397− inferBinary op v1 v2
398−infer' (ObjectLiteral ps) = do
399− ensureNoDuplicateProperties ps
400− ts <- mapM (infer . snd) ps
401− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
402− ty = Object $ rowFromList (fields, REmpty)
403− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
404−infer' (ObjectUpdate o ps) = do
405− ensureNoDuplicateProperties ps
407− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
408− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
409− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
410− o' <- check o $ Object $ rowFromList (oldTys, row)
411− return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
412−infer' (Indexer index val) = do
414− index' <- check index tyNumber
415− val' <- check val (TypeApp tyArray el)
416− return $ TypedValue True (Indexer (TypedValue True index' tyNumber) (TypedValue True val' (TypeApp tyArray el))) el
417−infer' (Accessor prop val) = do
418− typed@(TypedValue _ _ objTy) <- infer val
419− propTy <- inferProperty objTy prop
424− _ <- subsumes Nothing objTy (Object (RCons prop field rest))
425− return $ TypedValue True (Accessor prop typed) field
426− Just ty -> return $ TypedValue True (Accessor prop typed) ty
427−infer' (Abs arg ret) = do
429− Just moduleName <- checkCurrentModule <$> get
430− bindLocalVariables moduleName [(arg, ty)] $ do
431− body@(TypedValue _ _ bodyTy) <- infer' ret
432− return $ TypedValue True (Abs arg body) $ function ty bodyTy
433−infer' (App f arg) = do
434− f'@(TypedValue _ _ ft) <- infer f
436− app <- checkFunctionApplication f' ft arg ret
437− return $ TypedValue True app ret
438−infer' (Var var) = do
439− Just moduleName <- checkCurrentModule <$> get
440− ty <- lookupVariable moduleName var
441− ty' <- replaceAllTypeSynonyms ty
443− ConstrainedType constraints _ -> do
445− dicts <- getTypeClassDictionaries
446− return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) ty'
447− _ -> return $ TypedValue True (Var var) ty'
448−infer' (Block ss) = do
450− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
451− guardWith "Block is missing a return statement" allCodePathsReturn
452− return $ TypedValue True (Block ss') ret
453−infer' v@(Constructor c) = do
455− Just moduleName <- checkCurrentModule <$> get
456− case M.lookup (qualify moduleName c) (dataConstructors env) of
457− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
458− Just (ty, _) -> do ty' <- replaceAllTypeSynonyms ty
459− return $ TypedValue True v ty'
460−infer' (Case vals binders) = do
461− ts <- mapM infer vals
463− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
464− return $ TypedValue True (Case ts binders') ret
465−infer' (IfThenElse cond th el) = do
466− cond' <- check cond tyBoolean
467− v2@(TypedValue _ _ t2) <- infer th
468− v3@(TypedValue _ _ t3) <- infer el
470− return $ TypedValue True (IfThenElse cond' v2 v3) t2
471−infer' (TypedValue checkType val ty) = do
472− Just moduleName <- checkCurrentModule <$> get
473− kind <- liftCheck $ kindOf moduleName ty
474− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
475− ty' <- replaceAllTypeSynonyms ty
476− val' <- if checkType then check val ty' else return val
477− return $ TypedValue True val' ty
478−infer' _ = error "Invalid argument to infer"
481−-- Infer the type of a property inside a record with a given type
483−inferProperty :: Type -> String -> UnifyT Check (Maybe Type)
484−inferProperty (Object row) prop = do
485− let (props, _) = rowToList row
486− return $ lookup prop props
487−inferProperty (SaturatedTypeSynonym name args) prop = do
488− replaced <- expandTypeSynonym name args
489− inferProperty replaced prop
490−inferProperty (ForAll ident ty) prop = do
491− replaced <- replaceVarWithUnknown ident ty
492− inferProperty replaced prop
493−inferProperty _ _ = return Nothing
496−-- Infer the type of a unary operator application
498−inferUnary :: UnaryOperator -> Value -> UnifyT Check Value
499−inferUnary op (TypedValue _ val valTy) =
500− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
501− (valTy', resTy) -> do
503− return $ TypedValue True (Unary op val) resTy
504−inferUnary _ _ = error "Invalid arguments to inferUnary"
507−-- Check the type of a unary operator application
509−checkUnary :: UnaryOperator -> Value -> Type -> UnifyT Check Value
510−checkUnary op val res =
511− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
512− (valTy, resTy) -> do
514− val' <- check val valTy
515− return $ Unary op val'
518−-- Built-in unary operators
520−unaryOps :: [(UnaryOperator, (Type, Type))]
521−unaryOps = [ (Negate, (tyNumber, tyNumber))
522− , (Not, (tyBoolean, tyBoolean))
523− , (BitwiseNot, (tyNumber, tyNumber))
527−-- Infer the type of a binary operator application
529−inferBinary :: BinaryOperator -> Value -> Value -> UnifyT Check Value
530−inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) | isEqualityTest op = do
532− return $ TypedValue True (Binary op left right) tyBoolean
533−inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) =
534− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
535− (valTy, resTy) -> do
538− return $ TypedValue True (Binary op left right) resTy
539−inferBinary _ _ _ = error "Invalid arguments to inferBinary"
542−-- Check the type of a binary operator application
544−checkBinary :: BinaryOperator -> Value -> Value -> Type -> UnifyT Check Value
545−checkBinary op left right res | isEqualityTest op = do
547− left'@(TypedValue _ _ t1) <- infer left
548− right'@(TypedValue _ _ t2) <- infer right
550− return $ Binary op left' right'
551−checkBinary op left right res =
552− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
553− (valTy, resTy) -> do
555− left' <- check left valTy
556− right' <- check right valTy
557− return $ Binary op left' right'
560−-- Check if a @BinaryOperator@ is an equality test
562−isEqualityTest :: BinaryOperator -> Bool
563−isEqualityTest EqualTo = True
564−isEqualityTest NotEqualTo = True
565−isEqualityTest _ = False
568−-- Built-in binary operators
570−binaryOps :: [(BinaryOperator, (Type, Type))]
571−binaryOps = [ (Add, (tyNumber, tyNumber))
572− , (Subtract, (tyNumber, tyNumber))
573− , (Multiply, (tyNumber, tyNumber))
574− , (Divide, (tyNumber, tyNumber))
575− , (Modulus, (tyNumber, tyNumber))
576− , (BitwiseAnd, (tyNumber, tyNumber))
577− , (BitwiseOr, (tyNumber, tyNumber))
578− , (BitwiseXor, (tyNumber, tyNumber))
579− , (ShiftRight, (tyNumber, tyNumber))
580− , (ZeroFillShiftRight, (tyNumber, tyNumber))
581− , (And, (tyBoolean, tyBoolean))
582− , (Or, (tyBoolean, tyBoolean))
583− , (Concat, (tyString, tyString))
584− , (Modulus, (tyNumber, tyNumber))
585− , (LessThan, (tyNumber, tyBoolean))
586− , (LessThanOrEqualTo, (tyNumber, tyBoolean))
587− , (GreaterThan, (tyNumber, tyBoolean))
588− , (GreaterThanOrEqualTo, (tyNumber, tyBoolean))
592−-- Infer the types of variables brought into scope by a binder
594−inferBinder :: Type -> Binder -> UnifyT Check (M.Map Ident Type)
595−inferBinder _ NullBinder = return M.empty
596−inferBinder val (StringBinder _) = val ?= tyString >> return M.empty
597−inferBinder val (NumberBinder _) = val ?= tyNumber >> return M.empty
598−inferBinder val (BooleanBinder _) = val ?= tyBoolean >> return M.empty
599−inferBinder val (VarBinder name) = return $ M.singleton name val
600−inferBinder val (NullaryBinder ctor) = do
602− Just moduleName <- checkCurrentModule <$> get
603− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
605− _ <- subsumes Nothing ty val
607− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
608−inferBinder val (UnaryBinder ctor binder) = do
610− Just moduleName <- checkCurrentModule <$> get
611− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
613− fn <- replaceAllVarsWithUnknowns ty
615− TypeApp (TypeApp t obj) ret | t == tyFunction -> do
616− _ <- subsumes Nothing val ret
617− inferBinder obj binder
618− _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
619− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
620−inferBinder val (ObjectBinder props) = do
623− m1 <- inferRowProperties row rest props
627− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Check (M.Map Ident Type)
628− inferRowProperties nrow row [] = nrow ?= row >> return M.empty
629− inferRowProperties nrow row ((name, binder):binders) = do
631− m1 <- inferBinder propTy binder
632− m2 <- inferRowProperties nrow (RCons name propTy row) binders
633− return $ m1 `M.union` m2
634−inferBinder val (ArrayBinder binders) = do
636− m1 <- M.unions <$> mapM (inferBinder el) binders
637− val ?= TypeApp tyArray el
639−inferBinder val (ConsBinder headBinder tailBinder) = do
641− m1 <- inferBinder el headBinder
642− m2 <- inferBinder val tailBinder
643− val ?= TypeApp tyArray el
644− return $ m1 `M.union` m2
645−inferBinder val (NamedBinder name binder) = do
646− m <- inferBinder val binder
647− return $ M.insert name val m
650−-- Check the types of the return values in a set of binders in a case statement
652−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Check [([Binder], Maybe Guard, Value)]
653−checkBinders _ _ [] = return []
654−checkBinders nvals ret ((binders, grd, val):bs) = do
655− Just moduleName <- checkCurrentModule <$> get
656− m1 <- M.unions <$> zipWithM inferBinder nvals binders
657− r <- bindLocalVariables moduleName (M.toList m1) $ do
658− val' <- check val ret
660− Nothing -> return (binders, Nothing, val')
662− g' <- check g tyBoolean
663− return (binders, Just g', val')
664− rs <- checkBinders nvals ret bs
668−-- Check that a local variable name is not already used
670−assignVariable :: Ident -> UnifyT Check ()
671−assignVariable name = do
672− env <- checkEnv <$> get
673− Just moduleName <- checkCurrentModule <$> get
674− case M.lookup (moduleName, name) (names env) of
675− Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
679−-- Check the type of the return values of a statement, returning whether or not the statement returns on
682−checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Check (Bool, M.Map Ident Type, Statement)
683−checkStatement mass _ (VariableIntroduction name val) = do
685− val'@(TypedValue _ _ t) <- infer val
686− return (False, M.insert name t mass, VariableIntroduction name val')
687−checkStatement mass _ (Assignment ident val) = do
688− val'@(TypedValue _ _ t) <- infer val
689− case M.lookup ident mass of
690− Nothing -> throwError $ "No local variable with name " ++ show ident
691− Just ty -> do t ?= ty
692− return (False, mass, Assignment ident val')
693−checkStatement mass ret (While val inner) = do
694− val' <- check val tyBoolean
695− (allCodePathsReturn, _, inner') <- checkBlock mass ret inner
696− return (allCodePathsReturn, mass, While val' inner')
697−checkStatement mass ret (If ifst) = do
698− (allCodePathsReturn, ifst') <- checkIfStatement mass ret ifst
699− return (allCodePathsReturn, mass, If ifst')
700−checkStatement mass ret (For ident start end inner) = do
701− Just moduleName <- checkCurrentModule <$> get
702− assignVariable ident
703− start' <- check start tyNumber
704− end' <- check end tyNumber
705− (allCodePathsReturn, _, inner') <- bindLocalVariables moduleName [(ident, tyNumber)] $ checkBlock mass ret inner
706− return (allCodePathsReturn, mass, For ident start' end' inner')
707−checkStatement mass ret (Return val) = do
708− val' <- check val ret
709− return (True, mass, Return val')
712−-- Check the type of an if-then-else statement
714−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> UnifyT Check (Bool, IfStatement)
715−checkIfStatement mass ret (IfStatement val thens Nothing) = do
716− val' <- check val tyBoolean
717− (_, _, thens') <- checkBlock mass ret thens
718− return (False, IfStatement val' thens' Nothing)
719−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
720− val' <- check val tyBoolean
721− (allCodePathsReturn1, _, thens') <- checkBlock mass ret thens
722− (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
723− return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
726−-- Check the type of an else statement
728−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> UnifyT Check (Bool, ElseStatement)
729−checkElseStatement mass ret (Else elses) = do
730− (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
731− return (allCodePathsReturn, Else elses')
732−checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
735−-- Check the type of the return value of a block of statements
737−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> UnifyT Check (Bool, M.Map Ident Type, [Statement])
738−checkBlock mass _ [] = return (False, mass, [])
739−checkBlock mass ret (s:ss) = do
740− Just moduleName <- checkCurrentModule <$> get
741− (b1, mass1, s') <- checkStatement mass ret s
742− bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
743− (True, []) -> return (True, mass1, [s'])
744− (True, _) -> throwError "Unreachable code"
746− (b, m, ss'') <- checkBlock mass1 ret ss'
747− return (b, m, s':ss'')
750−-- Skolemize a type variable by replacing its instances with fresh skolem constants
752−skolemize :: String -> Type -> UnifyT Check Type
753−skolemize ident ty = do
754− tsk <- Skolem . runUnknown <$> fresh'
755− return $ replaceTypeVars ident tsk ty
758−-- Check the type of a value, rethrowing errors to provide a better error message
760−check :: Value -> Type -> UnifyT Check Value
761−check val ty = rethrow errorMessage $ check' val ty
764− "Error checking type of term " ++
765− prettyPrintValue val ++
767− prettyPrintType ty ++
772−-- Check the type of a value
774−check' :: Value -> Type -> UnifyT Check Value
775−check' val (ForAll idents ty) = do
776− sk <- skolemize idents ty
778−check' val (ConstrainedType constraints ty) = do
780− Just moduleName <- checkCurrentModule <$> get
781− dictNames <- flip mapM constraints $ \(Qualified _ (ProperName className), _) -> do
782− n <- liftCheck freshDictionaryName
783− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
784− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
785− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
786− (qualifyAllUnqualifiedNames moduleName env constraints)) $
788− return $ foldr Abs val' dictNames
789−check' val u@(TUnknown _) = do
790− val'@(TypedValue _ _ ty) <- infer val
791− -- Don't unify an unknown with an inferred polytype
792− ty' <- replaceAllVarsWithUnknowns ty
795−check' v@(NumericLiteral _) t | t == tyNumber = return v
796−check' v@(StringLiteral _) t | t == tyString = return v
797−check' v@(BooleanLiteral _) t | t == tyBoolean = return v
798−check' (Unary op val) ty = checkUnary op val ty
799−check' (Binary op left right) ty = checkBinary op left right ty
800−check' (ArrayLiteral vals) (TypeApp a ty) | a == tyArray = ArrayLiteral <$> forM vals (\val -> check val ty)
801−check' (Indexer index vals) ty = do
802− index' <- check index tyNumber
803− vals' <- check vals (TypeApp tyArray ty)
804− return $ Indexer index' vals'
805−check' (Abs arg ret) (TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
806− Just moduleName <- checkCurrentModule <$> get
807− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
808− return $ Abs arg ret'
809−check' (App f arg) ret = do
810− f'@(TypedValue _ _ ft) <- infer f
811− app <- checkFunctionApplication f' ft arg ret
813−check' v@(Var var) ty = do
814− Just moduleName <- checkCurrentModule <$> get
815− ty1 <- lookupVariable moduleName var
816− repl <- replaceAllTypeSynonyms ty1
817− v' <- subsumes (Just v) repl ty
819− Nothing -> throwError "Unable to check type subsumption"
820− Just v'' -> return v''
821−check' (TypedValue checkType val ty1) ty2 = do
822− Just moduleName <- checkCurrentModule <$> get
823− kind <- liftCheck $ kindOf moduleName ty1
824− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
825− val' <- subsumes (Just val) ty1 ty2
827− Nothing -> throwError "Unable to check type subsumption"
829− val''' <- if checkType then check val'' ty1 else return val''
830− return $ TypedValue True val''' ty1
831−check' (Case vals binders) ret = do
832− vals' <- mapM infer vals
833− let ts = map (\(TypedValue _ _ t) -> t) vals'
834− binders' <- checkBinders ts ret binders
835− return $ Case vals' binders'
836−check' (IfThenElse cond th el) ty = do
837− cond' <- check cond tyBoolean
840− return $ IfThenElse cond' th' el'
841−check' (ObjectLiteral ps) (Object row) = do
842− ensureNoDuplicateProperties ps
843− ps' <- checkProperties ps row False
844− return $ ObjectLiteral ps'
845−check' (ObjectUpdate obj ps) (Object row) = do
846− ensureNoDuplicateProperties ps
847− us <- zip (map fst ps) <$> replicateM (length ps) fresh
848− let (propsToCheck, rest) = rowToList row
849− propsToRemove = map fst ps
850− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
851− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
852− ps' <- checkProperties ps row True
853− return $ ObjectUpdate obj' ps'
854−check' (Accessor prop val) ty = do
856− val' <- check val (Object (RCons prop ty rest))
857− return $ Accessor prop val'
858−check' (Block ss) ret = do
859− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
860− guardWith "Block is missing a return statement" allCodePathsReturn
862−check' (Constructor c) ty = do
864− Just moduleName <- checkCurrentModule <$> get
865− case M.lookup (qualify moduleName c) (dataConstructors env) of
866− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
868− repl <- replaceAllTypeSynonyms ty1
869− _ <- subsumes Nothing repl ty
870− return $ Constructor c
871−check' val (SaturatedTypeSynonym name args) = do
872− ty <- expandTypeSynonym name args
874−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
877−-- Check the type of a collection of named record fields
879−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
881−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Check [(String, Value)]
882−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
883− go [] [] REmpty = return []
884− go [] [] u@(TUnknown _) = do u ?= REmpty
886− go [] [] (Skolem _) | lax = return []
887− go [] ((p, _): _) _ | lax = return []
888− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
889− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
890− go ((p,v):ps') [] u@(TUnknown _) = do
891− v'@(TypedValue _ _ ty) <- infer v
893− u ?= RCons p ty rest
894− ps'' <- go ps' [] rest
895− return $ (p, v') : ps''
896− go ((p,v):ps') ts r =
899− v'@(TypedValue _ _ ty) <- infer v
901− r ?= RCons p ty rest
902− ps'' <- go ps' ts rest
903− return $ (p, v') : ps''
906− ps'' <- go ps' (delete (p, ty) ts) r
907− return $ (p, v') : ps''
908− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
911−-- Check the type of a function application, rethrowing errors to provide a better error message
913−checkFunctionApplication :: Value -> Type -> Value -> Type -> UnifyT Check Value
914−checkFunctionApplication fn fnTy arg ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg ret
916− errorMessage msg = "Error applying function of type "
917− ++ prettyPrintType fnTy
918− ++ " to argument " ++ prettyPrintValue arg
922−-- Check the type of a function application
924−checkFunctionApplication' :: Value -> Type -> Value -> Type -> UnifyT Check Value
925−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
926− tyFunction' ?= tyFunction
927− arg' <- check arg argTy
928− _ <- subsumes Nothing retTy ret
929− return $ App fn arg'
930−checkFunctionApplication' fn (ForAll ident ty) arg ret = do
931− replaced <- replaceVarWithUnknown ident ty
932− checkFunctionApplication fn replaced arg ret
933−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
935− TypedValue _ v t <- infer arg
936− TypedValue True v <$> replaceAllVarsWithUnknowns t
937− let ty = (\(TypedValue _ _ t) -> t) arg'
938− u ?= function ty ret
939− return $ App fn arg'
940−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
941− ty <- expandTypeSynonym name tyArgs
942− checkFunctionApplication fn ty arg ret
943−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
945− dicts <- getTypeClassDictionaries
946− Just moduleName <- checkCurrentModule <$> get
947− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy arg ret
948−checkFunctionApplication' _ fnTy arg ret = throwError $ "Applying a function of type "
949− ++ prettyPrintType fnTy
950− ++ " to argument(s) " ++ prettyPrintValue arg
951− ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
954−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
956−subsumes :: Maybe Value -> Type -> Type -> UnifyT Check (Maybe Value)
957−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
959− errorMessage msg = "Error checking that type "
960− ++ prettyPrintType ty1
961− ++ " subsumes type "
962− ++ prettyPrintType ty2
966−-- Check whether one type subsumes another
968−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Check (Maybe Value)
969−subsumes' val (ForAll ident ty1) ty2 = do
970− replaced <- replaceVarWithUnknown ident ty1
971− subsumes val replaced ty2
972−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
973− subsumes Nothing arg2 arg1
974− subsumes Nothing ret1 ret2
976−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
978− dicts <- getTypeClassDictionaries
979− Just moduleName <- checkCurrentModule <$> get
980− _ <- subsumes' Nothing ty1 ty2
981− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
982−subsumes' val ty1 ty2 = do