@@ -1,991 +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' Number Number = return ()
99− unifyTypes' String String = return ()
100− unifyTypes' Boolean Boolean = return ()
101− unifyTypes' Array Array = return ()
102− unifyTypes' (Object row1) (Object row2) = row1 ?= row2
103− unifyTypes' (Function args1 ret1) (Function args2 ret2) = do
104− guardWith "Function applied to incorrect number of args" $ length args1 == length args2
105− zipWithM_ unifyTypes args1 args2
106− ret1 `unifyTypes` ret2
107− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
108− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
110− Just moduleName <- checkCurrentModule <$> get
111− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
112− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
115− unifyTypes' (Skolem s1) (Skolem s2) | s1 == s2 = return ()
116− unifyTypes' r1@(RCons _ _ _) r2 = unifyRows r1 r2
117− unifyTypes' r1 r2@(RCons _ _ _) = unifyRows r1 r2
118− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
119− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
120− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
123−-- Unify two rows, updating the current substitution
125−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
126−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
129−unifyRows :: Type -> Type -> UnifyT Check ()
132− (s1, r1') = rowToList r1
133− (s2, r2') = rowToList r2
134− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
135− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
136− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
138− forM_ int (uncurry (?=))
139− unifyRows' sd1 r1' sd2 r2'
141− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Check ()
142− unifyRows' [] (TUnknown u) sd r = replace u (rowFromList (sd, r))
143− unifyRows' sd r [] (TUnknown u) = replace u (rowFromList (sd, r))
144− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
146− forM_ row $ \(_, t) -> occursCheck un t
148− u ?= RCons name ty u'
149− unifyRows' row r others u'
150− unifyRows' [] REmpty [] REmpty = return ()
151− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
152− unifyRows' [] (Skolem s1) [] (Skolem s2) | s1 == s2 = return ()
153− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify " ++ prettyPrintRow (rowFromList (sd3, r3)) ++ " with " ++ prettyPrintRow (rowFromList (sd4, r4)) ++ "."
156−-- Ensure type constructors are equal after canonicalization
158−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
159−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
162−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
163−-- type class dictionaries and type annotations.
165−typesOf :: ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
166−typesOf moduleName vals = do
167− tys <- liftUnify $ do
168− let es = map isTyped vals
169− typed = filter (isJust . snd . snd) es
170− untyped = filter (isNothing . snd . snd) es
171− typedDict = map (\(ident, (_, Just ty)) -> (ident, ty)) typed
172− untypedNames <- replicateM (length untyped) fresh
173− let untypedDict = zip (map fst untyped) untypedNames
174− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ (map (id *** fst) typedDict) ++ untypedDict)
176− triple@(_, (val, ty)) <- case e of
177− (ident, (val, Just (ty, checkType))) -> do
178− kind <- liftCheck $ kindOf moduleName ty
179− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
180− ty' <- replaceAllTypeSynonyms ty
181− val' <- bindNames dict $ if checkType then check val ty' else return val
182− return (ident, (val', ty'))
183− (ident, (val, Nothing)) -> do
184− TypedValue _ val' ty <- bindNames dict $ infer val
185− ty ?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
186− return (ident, (val', ty))
187− when (moduleName == ModuleName (ProperName "Main") && fst e == Ident "main") $ do
188− [eff, a] <- replicateM 2 fresh
189− ty ?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName (ProperName "Eff"))) (ProperName "Eff"))) eff) a
192− forM_ tys $ skolemEscapeCheck . snd . snd
193− forM tys $ \(ident, (val, ty)) -> do
194− val' <- replaceTypeClassDictionaries moduleName val
195− return (ident, (overTypes (desaturateAllTypeSynonyms . setifyAll) $ val'
196− , varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty))
199−-- Check if a value contains a type annotation
201−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
202−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
203−isTyped (name, value) = (name, (value, Nothing))
206−-- Map a function over type annotations appearing inside a value
208−overTypes :: (Type -> Type) -> Value -> Value
209−overTypes f = everywhere (mkT f)
212−-- Replace type class dictionary placeholders with inferred type class dictionaries
214−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
215−replaceTypeClassDictionaries mn = everywhereM (mkM go)
217− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
218− go other = return other
221−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
222−-- return a type class dictionary reference.
224−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
225−entails moduleName context goal@(className, ty) = do
228− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
229− (dict : _) -> return dict
231− go env (className', ty') =
232− [ mkDictionary (canonicalizeDictionary tcd) args
235− , typeConstructorsAreEqual env moduleName className' (tcdClassName tcd)
236− , subst <- maybeToList $ typeHeadsAreEqual moduleName env ty' (tcdInstanceType tcd)
237− , args <- solveSubgoals env subst (tcdDependencies tcd) ]
238− solveSubgoals _ _ Nothing = return Nothing
239− solveSubgoals env subst (Just subgoals) = do
240− dict <- mapM (go env) (replaceAllTypeVars subst subgoals)
242− mkDictionary fnName args = maybe id (flip App) args $ (Var fnName)
243− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
244− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
245− filterModule _ = False
246− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
247− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
250−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
251−-- and return a substitution from type variables to types which makes the type heads unify.
253−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
254−typeHeadsAreEqual _ _ String String = Just []
255−typeHeadsAreEqual _ _ Number Number = Just []
256−typeHeadsAreEqual _ _ Boolean Boolean = Just []
257−typeHeadsAreEqual _ _ (Skolem s1) (Skolem s2) | s1 == s2 = Just []
258−typeHeadsAreEqual _ _ Array Array = Just []
259−typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | typeConstructorsAreEqual e m c1 c2 = Just []
260−typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
261−typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
262−typeHeadsAreEqual _ _ _ _ = Nothing
265−-- Ensure unsolved unification variables do not escape
267−escapeCheck :: Value -> Type -> UnifyT Check ()
268−escapeCheck value ty = do
269− subst <- unifyCurrentSubstitution <$> UnifyT get
270− let visibleUnknowns = nub $ unknowns $ runSubstitution subst ty
271− let allUnknowns = findAllTypes value
272− forM_ allUnknowns $ \t -> do
273− let unsolvedUnknowns = nub . unknowns $ runSubstitution subst t
274− guardWith ("Escape check fails" ++ show ( runSubstitution subst ty, runSubstitution subst t)) $ null $ unsolvedUnknowns \\ visibleUnknowns
277−-- Find all type annotations occuring inside a value
279−findAllTypes :: Value -> [Type]
280−findAllTypes = everything (++) (mkQ [] go)
282− go (TypedValue _ _ ty) = [ty]
286−-- Ensure skolem variables do not escape their scope
288−skolemEscapeCheck :: Type -> Check ()
289−skolemEscapeCheck ty =
290− case something (mkQ Nothing findSkolems) ty of
291− Nothing -> return ()
292− Just _ -> throwError $ "Skolem variables cannot escape. Consider adding a type signature."
294− findSkolems (Skolem _) = return ()
295− findSkolems _ = mzero
298−-- Ensure a row contains no duplicate labels
300−setify :: Type -> Type
301−setify = rowFromList . first (M.toList . M.fromList) . rowToList
304−-- \"Setify\" all rows occuring inside a value
306−setifyAll :: (D.Data d) => d -> d
307−setifyAll = everywhere (mkT setify)
310−-- Replace outermost unsolved unification variables with named type variables
312−varIfUnknown :: Type -> Type
314− let unks = nub $ unknowns ty
315− toName = (:) 't' . show
316− ty' = everywhere (mkT typeToVar) $ ty
317− typeToVar :: Type -> Type
318− typeToVar (TUnknown (TypedUnknown (Unknown u))) = TypeVar (toName u)
320− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
323−-- Replace named type variables with types
325−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
326−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
329−-- Replace named type variables with new unification variables
331−replaceAllVarsWithUnknowns :: Type -> UnifyT Check Type
332−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
333−replaceAllVarsWithUnknowns ty = return ty
336−-- Replace a single type variable with a new unification variable
338−replaceVarWithUnknown :: String -> Type -> UnifyT Check Type
339−replaceVarWithUnknown ident ty = do
341− return $ replaceTypeVars ident tu $ ty
344−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
345−-- better error messages during unification.
347−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
348−replaceAllTypeSynonyms d = do
350− Just moduleName <- checkCurrentModule <$> get
351− let syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
352− either throwError return $ saturateAllTypeSynonyms env moduleName syns d
355−-- \"Desaturate\" @SaturatedTypeSynonym@s
357−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
358−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
360− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
361− replaceSaturatedTypeSynonym t = t
364−-- Replace a type synonym and its arguments with the aliased type
366−expandTypeSynonym :: Qualified ProperName -> [Type] -> UnifyT Check Type
367−expandTypeSynonym name args = do
369− Just moduleName <- checkCurrentModule <$> get
370− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
371− Just (synArgs, body) -> return $ replaceAllTypeVars (zip synArgs args) body
372− Nothing -> error "Type synonym was not defined"
375−-- Ensure a set of property names and value does not contain duplicate labels
377−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
378−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
381−-- Infer a type for a value, rethrowing any error to provide a more useful error message
383−infer :: Value -> UnifyT Check Value
384−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
387−-- Infer a type for a value
389−infer' :: Value -> UnifyT Check Value
390−infer' v@(NumericLiteral _) = return $ TypedValue True v Number
391−infer' v@(StringLiteral _) = return $ TypedValue True v String
392−infer' v@(BooleanLiteral _) = return $ TypedValue True v Boolean
393−infer' (ArrayLiteral vals) = do
394− ts <- mapM infer vals
396− forM_ ts $ \(TypedValue _ _ t) -> els ?= TypeApp Array t
397− return $ TypedValue True (ArrayLiteral ts) els
398−infer' (Unary op val) = do
401−infer' (Binary op left right) = do
404− inferBinary op v1 v2
405−infer' (ObjectLiteral ps) = do
406− ensureNoDuplicateProperties ps
407− ts <- mapM (infer . snd) ps
408− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
409− ty = Object $ rowFromList (fields, REmpty)
410− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
411−infer' (ObjectUpdate o ps) = do
412− ensureNoDuplicateProperties ps
414− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
415− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
416− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
417− o' <- check o $ Object $ rowFromList (oldTys, row)
418− return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
419−infer' (Indexer index val) = do
421− index' <- check index Number
422− val' <- check val (TypeApp Array el)
423− return $ TypedValue True (Indexer (TypedValue True index' Number) (TypedValue True val' (TypeApp Array el))) el
424−infer' (Accessor prop val) = do
425− typed@(TypedValue _ _ objTy) <- infer val
426− propTy <- inferProperty objTy prop
431− _ <- subsumes Nothing objTy (Object (RCons prop field rest))
432− return $ TypedValue True (Accessor prop typed) field
433− Just ty -> return $ TypedValue True (Accessor prop typed) ty
434−infer' (Abs args ret) = do
435− ts <- replicateM (length args) fresh
436− Just moduleName <- checkCurrentModule <$> get
437− bindLocalVariables moduleName (zip args ts) $ do
438− body@(TypedValue _ _ bodyTy) <- infer' ret
439− return $ TypedValue True (Abs args body) $ Function ts bodyTy
440−infer' (App f args) = do
441− f'@(TypedValue _ _ ft) <- infer f
443− app <- checkFunctionApplication f' ft args ret
444− return $ TypedValue True app ret
445−infer' (Var var) = do
446− Just moduleName <- checkCurrentModule <$> get
447− ty <- lookupVariable moduleName var
448− ty' <- replaceAllTypeSynonyms ty
450− ConstrainedType constraints _ -> do
452− dicts <- getTypeClassDictionaries
453− return $ TypedValue True (App (Var var) (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) ty'
454− _ -> return $ TypedValue True (Var var) ty'
455−infer' (Block ss) = do
457− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
458− guardWith "Block is missing a return statement" allCodePathsReturn
459− return $ TypedValue True (Block ss') ret
460−infer' v@(Constructor c) = do
462− Just moduleName <- checkCurrentModule <$> get
463− case M.lookup (qualify moduleName c) (dataConstructors env) of
464− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
465− Just (ty, _) -> do ty' <- replaceAllTypeSynonyms ty
466− return $ TypedValue True v ty'
467−infer' (Case vals binders) = do
468− ts <- mapM infer vals
470− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
471− return $ TypedValue True (Case ts binders') ret
472−infer' (IfThenElse cond th el) = do
473− cond' <- check cond Boolean
474− v2@(TypedValue _ _ t2) <- infer th
475− v3@(TypedValue _ _ t3) <- infer el
477− return $ TypedValue True (IfThenElse cond' v2 v3) t2
478−infer' (TypedValue checkType val ty) = do
479− Just moduleName <- checkCurrentModule <$> get
480− kind <- liftCheck $ kindOf moduleName ty
481− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
482− ty' <- replaceAllTypeSynonyms ty
483− val' <- if checkType then check val ty' else return val
484− return $ TypedValue True val' ty
485−infer' _ = error "Invalid argument to infer"
488−-- Infer the type of a property inside a record with a given type
490−inferProperty :: Type -> String -> UnifyT Check (Maybe Type)
491−inferProperty (Object row) prop = do
492− let (props, _) = rowToList row
493− return $ lookup prop props
494−inferProperty (SaturatedTypeSynonym name args) prop = do
495− replaced <- expandTypeSynonym name args
496− inferProperty replaced prop
497−inferProperty (ForAll ident ty) prop = do
498− replaced <- replaceVarWithUnknown ident ty
499− inferProperty replaced prop
500−inferProperty _ _ = return Nothing
503−-- Infer the type of a unary operator application
505−inferUnary :: UnaryOperator -> Value -> UnifyT Check Value
506−inferUnary op (TypedValue _ val valTy) =
507− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
508− (valTy', resTy) -> do
510− return $ TypedValue True (Unary op val) resTy
511−inferUnary _ _ = error "Invalid arguments to inferUnary"
514−-- Check the type of a unary operator application
516−checkUnary :: UnaryOperator -> Value -> Type -> UnifyT Check Value
517−checkUnary op val res =
518− case fromMaybe (error "Invalid operator") $ lookup op unaryOps of
519− (valTy, resTy) -> do
521− val' <- check val valTy
522− return $ Unary op val'
525−-- Built-in unary operators
527−unaryOps :: [(UnaryOperator, (Type, Type))]
528−unaryOps = [ (Negate, (Number, Number))
529− , (Not, (Boolean, Boolean))
530− , (BitwiseNot, (Number, Number))
534−-- Infer the type of a binary operator application
536−inferBinary :: BinaryOperator -> Value -> Value -> UnifyT Check Value
537−inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) | isEqualityTest op = do
539− return $ TypedValue True (Binary op left right) Boolean
540−inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) =
541− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
542− (valTy, resTy) -> do
545− return $ TypedValue True (Binary op left right) resTy
546−inferBinary _ _ _ = error "Invalid arguments to inferBinary"
549−-- Check the type of a binary operator application
551−checkBinary :: BinaryOperator -> Value -> Value -> Type -> UnifyT Check Value
552−checkBinary op left right res | isEqualityTest op = do
554− left'@(TypedValue _ _ t1) <- infer left
555− right'@(TypedValue _ _ t2) <- infer right
557− return $ Binary op left' right'
558−checkBinary op left right res =
559− case fromMaybe (error "Invalid operator") $ lookup op binaryOps of
560− (valTy, resTy) -> do
562− left' <- check left valTy
563− right' <- check right valTy
564− return $ Binary op left' right'
567−-- Check if a @BinaryOperator@ is an equality test
569−isEqualityTest :: BinaryOperator -> Bool
570−isEqualityTest EqualTo = True
571−isEqualityTest NotEqualTo = True
572−isEqualityTest _ = False
575−-- Built-in binary operators
577−binaryOps :: [(BinaryOperator, (Type, Type))]
578−binaryOps = [ (Add, (Number, Number))
579− , (Subtract, (Number, Number))
580− , (Multiply, (Number, Number))
581− , (Divide, (Number, Number))
582− , (Modulus, (Number, Number))
583− , (BitwiseAnd, (Number, Number))
584− , (BitwiseOr, (Number, Number))
585− , (BitwiseXor, (Number, Number))
586− , (ShiftRight, (Number, Number))
587− , (ZeroFillShiftRight, (Number, Number))
588− , (And, (Boolean, Boolean))
589− , (Or, (Boolean, Boolean))
590− , (Concat, (String, String))
591− , (Modulus, (Number, Number))
592− , (LessThan, (Number, Boolean))
593− , (LessThanOrEqualTo, (Number, Boolean))
594− , (GreaterThan, (Number, Boolean))
595− , (GreaterThanOrEqualTo, (Number, Boolean))
599−-- Infer the types of variables brought into scope by a binder
601−inferBinder :: Type -> Binder -> UnifyT Check (M.Map Ident Type)
602−inferBinder _ NullBinder = return M.empty
603−inferBinder val (StringBinder _) = val ?= String >> return M.empty
604−inferBinder val (NumberBinder _) = val ?= Number >> return M.empty
605−inferBinder val (BooleanBinder _) = val ?= Boolean >> return M.empty
606−inferBinder val (VarBinder name) = return $ M.singleton name val
607−inferBinder val (NullaryBinder ctor) = do
609− Just moduleName <- checkCurrentModule <$> get
610− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
612− _ <- subsumes Nothing ty val
614− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
615−inferBinder val (UnaryBinder ctor binder) = do
617− Just moduleName <- checkCurrentModule <$> get
618− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
620− fn <- replaceAllVarsWithUnknowns ty
622− Function [obj] ret -> do
623− _ <- subsumes Nothing val ret
624− inferBinder obj binder
625− _ -> throwError $ "Constructor " ++ show ctor ++ " is not a unary constructor"
626− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
627−inferBinder val (ObjectBinder props) = do
630− m1 <- inferRowProperties row rest props
634− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Check (M.Map Ident Type)
635− inferRowProperties nrow row [] = nrow ?= row >> return M.empty
636− inferRowProperties nrow row ((name, binder):binders) = do
638− m1 <- inferBinder propTy binder
639− m2 <- inferRowProperties nrow (RCons name propTy row) binders
640− return $ m1 `M.union` m2
641−inferBinder val (ArrayBinder binders) = do
643− m1 <- M.unions <$> mapM (inferBinder el) binders
644− val ?= TypeApp Array el
646−inferBinder val (ConsBinder headBinder tailBinder) = do
648− m1 <- inferBinder el headBinder
649− m2 <- inferBinder val tailBinder
650− val ?= TypeApp Array el
651− return $ m1 `M.union` m2
652−inferBinder val (NamedBinder name binder) = do
653− m <- inferBinder val binder
654− return $ M.insert name val m
657−-- Check the types of the return values in a set of binders in a case statement
659−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Check [([Binder], Maybe Guard, Value)]
660−checkBinders _ _ [] = return []
661−checkBinders nvals ret ((binders, grd, val):bs) = do
662− Just moduleName <- checkCurrentModule <$> get
663− m1 <- M.unions <$> zipWithM inferBinder nvals binders
664− r <- bindLocalVariables moduleName (M.toList m1) $ do
665− val' <- check val ret
667− Nothing -> return (binders, Nothing, val')
669− g' <- check g Boolean
670− return (binders, Just g', val')
671− rs <- checkBinders nvals ret bs
675−-- Check that a local variable name is not already used
677−assignVariable :: Ident -> UnifyT Check ()
678−assignVariable name = do
679− env <- checkEnv <$> get
680− Just moduleName <- checkCurrentModule <$> get
681− case M.lookup (moduleName, name) (names env) of
682− Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
686−-- Check the type of the return values of a statement, returning whether or not the statement returns on
689−checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Check (Bool, M.Map Ident Type, Statement)
690−checkStatement mass _ (VariableIntroduction name val) = do
692− val'@(TypedValue _ _ t) <- infer val
693− return (False, M.insert name t mass, VariableIntroduction name val')
694−checkStatement mass _ (Assignment ident val) = do
695− val'@(TypedValue _ _ t) <- infer val
696− case M.lookup ident mass of
697− Nothing -> throwError $ "No local variable with name " ++ show ident
698− Just ty -> do t ?= ty
699− return (False, mass, Assignment ident val')
700−checkStatement mass ret (While val inner) = do
701− val' <- check val Boolean
702− (allCodePathsReturn, _, inner') <- checkBlock mass ret inner
703− return (allCodePathsReturn, mass, While val' inner')
704−checkStatement mass ret (If ifst) = do
705− (allCodePathsReturn, ifst') <- checkIfStatement mass ret ifst
706− return (allCodePathsReturn, mass, If ifst')
707−checkStatement mass ret (For ident start end inner) = do
708− Just moduleName <- checkCurrentModule <$> get
709− assignVariable ident
710− start' <- check start Number
711− end' <- check end Number
712− (allCodePathsReturn, _, inner') <- bindLocalVariables moduleName [(ident, Number)] $ checkBlock mass ret inner
713− return (allCodePathsReturn, mass, For ident start' end' inner')
714−checkStatement mass ret (Return val) = do
715− val' <- check val ret
716− return (True, mass, Return val')
719−-- Check the type of an if-then-else statement
721−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> UnifyT Check (Bool, IfStatement)
722−checkIfStatement mass ret (IfStatement val thens Nothing) = do
723− val' <- check val Boolean
724− (_, _, thens') <- checkBlock mass ret thens
725− return (False, IfStatement val' thens' Nothing)
726−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
727− val' <- check val Boolean
728− (allCodePathsReturn1, _, thens') <- checkBlock mass ret thens
729− (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
730− return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
733−-- Check the type of an else statement
735−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> UnifyT Check (Bool, ElseStatement)
736−checkElseStatement mass ret (Else elses) = do
737− (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
738− return (allCodePathsReturn, Else elses')
739−checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
742−-- Check the type of the return value of a block of statements
744−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> UnifyT Check (Bool, M.Map Ident Type, [Statement])
745−checkBlock mass _ [] = return (False, mass, [])
746−checkBlock mass ret (s:ss) = do
747− Just moduleName <- checkCurrentModule <$> get
748− (b1, mass1, s') <- checkStatement mass ret s
749− bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
750− (True, []) -> return (True, mass1, [s'])
751− (True, _) -> throwError "Unreachable code"
753− (b, m, ss'') <- checkBlock mass1 ret ss'
754− return (b, m, s':ss'')
757−-- Skolemize a type variable by replacing its instances with fresh skolem constants
759−skolemize :: String -> Type -> UnifyT Check Type
760−skolemize ident ty = do
761− tsk <- Skolem . runUnknown <$> fresh'
762− return $ replaceTypeVars ident tsk ty
765−-- Check the type of a value, rethrowing errors to provide a better error message
767−check :: Value -> Type -> UnifyT Check Value
768−check val ty = rethrow errorMessage $ check' val ty
771− "Error checking type of term " ++
772− prettyPrintValue val ++
774− prettyPrintType ty ++
779−-- Check the type of a value
781−check' :: Value -> Type -> UnifyT Check Value
782−check' val (ForAll idents ty) = do
783− sk <- skolemize idents ty
785−check' val (ConstrainedType constraints ty) = do
787− Just moduleName <- checkCurrentModule <$> get
788− dictNames <- flip mapM constraints $ \(Qualified _ (ProperName className), _) -> do
789− n <- liftCheck freshDictionaryName
790− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
791− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
792− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
793− (qualifyAllUnqualifiedNames moduleName env constraints)) $
795− return $ Abs dictNames val'
796−check' val u@(TUnknown _) = do
797− val'@(TypedValue _ _ ty) <- infer val
798− -- Don't unify an unknown with an inferred polytype
799− ty' <- replaceAllVarsWithUnknowns ty
802−check' v@(NumericLiteral _) Number = return v
803−check' v@(StringLiteral _) String = return v
804−check' v@(BooleanLiteral _) Boolean = return v
805−check' (Unary op val) ty = checkUnary op val ty
806−check' (Binary op left right) ty = checkBinary op left right ty
807−check' (ArrayLiteral vals) (TypeApp Array ty) = ArrayLiteral <$> forM vals (\val -> check val ty)
808−check' (Indexer index vals) ty = do
809− index' <- check index Number
810− vals' <- check vals (TypeApp Array ty)
811− return $ Indexer index' vals'
812−check' (Abs args ret) (Function argTys retTy) = do
813− Just moduleName <- checkCurrentModule <$> get
814− guardWith "Incorrect number of function arguments" (length args == length argTys)
815− ret' <- bindLocalVariables moduleName (zip args argTys) $ check ret retTy
816− return $ Abs args ret'
817−check' (App f args) ret = do
818− f'@(TypedValue _ _ ft) <- infer f
819− app <- checkFunctionApplication f' ft args ret
821−check' v@(Var var) ty = do
822− Just moduleName <- checkCurrentModule <$> get
823− ty1 <- lookupVariable moduleName var
824− repl <- replaceAllTypeSynonyms ty1
825− v' <- subsumes (Just v) repl ty
827− Nothing -> throwError "Unable to check type subsumption"
828− Just v'' -> return v''
829−check' (TypedValue checkType val ty1) ty2 = do
830− Just moduleName <- checkCurrentModule <$> get
831− kind <- liftCheck $ kindOf moduleName ty1
832− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
833− val' <- subsumes (Just val) ty1 ty2
835− Nothing -> throwError "Unable to check type subsumption"
837− val''' <- if checkType then check val'' ty1 else return val''
838− return $ TypedValue True val''' ty1
839−check' (Case vals binders) ret = do
840− vals' <- mapM infer vals
841− let ts = map (\(TypedValue _ _ t) -> t) vals'
842− binders' <- checkBinders ts ret binders
843− return $ Case vals' binders'
844−check' (IfThenElse cond th el) ty = do
845− cond' <- check cond Boolean
848− return $ IfThenElse cond' th' el'
849−check' (ObjectLiteral ps) (Object row) = do
850− ensureNoDuplicateProperties ps
851− ps' <- checkProperties ps row False
852− return $ ObjectLiteral ps'
853−check' (ObjectUpdate obj ps) (Object row) = do
854− ensureNoDuplicateProperties ps
855− us <- zip (map fst ps) <$> replicateM (length ps) fresh
856− let (propsToCheck, rest) = rowToList row
857− propsToRemove = map fst ps
858− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
859− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
860− ps' <- checkProperties ps row True
861− return $ ObjectUpdate obj' ps'
862−check' (Accessor prop val) ty = do
864− val' <- check val (Object (RCons prop ty rest))
865− return $ Accessor prop val'
866−check' (Block ss) ret = do
867− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
868− guardWith "Block is missing a return statement" allCodePathsReturn
870−check' (Constructor c) ty = do
872− Just moduleName <- checkCurrentModule <$> get
873− case M.lookup (qualify moduleName c) (dataConstructors env) of
874− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
876− repl <- replaceAllTypeSynonyms ty1
877− _ <- subsumes Nothing repl ty
878− return $ Constructor c
879−check' val (SaturatedTypeSynonym name args) = do
880− ty <- expandTypeSynonym name args
882−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
885−-- Check the type of a collection of named record fields
887−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
889−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Check [(String, Value)]
890−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
891− go [] [] REmpty = return []
892− go [] [] u@(TUnknown _) = do u ?= REmpty
894− go [] [] (Skolem _) | lax = return []
895− go [] ((p, _): _) _ | lax = return []
896− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
897− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
898− go ((p,v):ps') [] u@(TUnknown _) = do
899− v'@(TypedValue _ _ ty) <- infer v
901− u ?= RCons p ty rest
902− ps'' <- go ps' [] rest
903− return $ (p, v') : ps''
904− go ((p,v):ps') ts r =
907− v'@(TypedValue _ _ ty) <- infer v
909− r ?= RCons p ty rest
910− ps'' <- go ps' ts rest
911− return $ (p, v') : ps''
914− ps'' <- go ps' (delete (p, ty) ts) r
915− return $ (p, v') : ps''
916− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
919−-- Check the type of a function application, rethrowing errors to provide a better error message
921−checkFunctionApplication :: Value -> Type -> [Value] -> Type -> UnifyT Check Value
922−checkFunctionApplication fn fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy args ret
924− errorMessage msg = "Error applying function of type "
925− ++ prettyPrintType fnTy
926− ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
930−-- Check the type of a function application
932−checkFunctionApplication' :: Value -> Type -> [Value] -> Type -> UnifyT Check Value
933−checkFunctionApplication' fn (Function argTys retTy) args ret = do
934− guardWith "Incorrect number of function arguments" (length args == length argTys)
935− args' <- zipWithM check args argTys
936− _ <- subsumes Nothing retTy ret
937− return $ App fn args'
938−checkFunctionApplication' fn (ForAll ident ty) args ret = do
939− replaced <- replaceVarWithUnknown ident ty
940− checkFunctionApplication fn replaced args ret
941−checkFunctionApplication' fn u@(TUnknown _) args ret = do
942− args' <- mapM (\arg -> infer arg >>= \(TypedValue _ v t) -> TypedValue True v <$> replaceAllVarsWithUnknowns t) args
943− let tys = map (\(TypedValue _ _ t) -> t) args'
944− u ?= Function tys ret
945− return $ App fn args'
946−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) args ret = do
947− ty <- expandTypeSynonym name tyArgs
948− checkFunctionApplication fn ty args ret
949−checkFunctionApplication' fn (ConstrainedType constraints fnTy) args ret = do
951− dicts <- getTypeClassDictionaries
952− Just moduleName <- checkCurrentModule <$> get
953− checkFunctionApplication' (App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy args ret
954−checkFunctionApplication' _ fnTy args ret = throwError $ "Applying a function of type "
955− ++ prettyPrintType fnTy
956− ++ " to argument(s) " ++ intercalate ", " (map prettyPrintValue args)
957− ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
960−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
962−subsumes :: Maybe Value -> Type -> Type -> UnifyT Check (Maybe Value)
963−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
965− errorMessage msg = "Error checking that type "
966− ++ prettyPrintType ty1
967− ++ " subsumes type "
968− ++ prettyPrintType ty2
972−-- Check whether one type subsumes another
974−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Check (Maybe Value)
975−subsumes' val (ForAll ident ty1) ty2 = do
976− replaced <- replaceVarWithUnknown ident ty1
977− subsumes val replaced ty2
978−subsumes' val (Function args1 ret1) (Function args2 ret2) = do
979− zipWithM_ (subsumes Nothing) args2 args1
980− subsumes Nothing ret1 ret2
982−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
984− dicts <- getTypeClassDictionaries
985− Just moduleName <- checkCurrentModule <$> get
986− _ <- subsumes' Nothing ty1 ty2
987− return . Just $ App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
988−subsumes' val ty1 ty2 = do