@@ -1,984 +0,0 @@
1−-----------------------------------------------------------------------------
2−--
3−-- Module : Language.PureScript.TypeChecker.Types
4−-- Copyright : (c) Phil Freeman 2013
5−-- License : MIT
6−--
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
9−-- Portability :
10−--
11−-- |
12−-- This module implements the type checker
13−--
14−-----------------------------------------------------------------------------
15−
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE DeriveDataTypeable #-}
18−{-# LANGUAGE FlexibleContexts #-}
19−{-# LANGUAGE MultiParamTypeClasses #-}
20−
21−module Language.PureScript.TypeChecker.Types (
22− typesOf
23−) where
24−
25−{-
26− The following functions represent the corresponding type checking judgements:
27−
28− infer
29− Synthesize a type for a value
30−
31− check
32− Check a value has a given type
33−
34− checkProperties
35− Check an object with a given type contains specified properties
36−
37− checkFunctionApplication
38− Check a function of a given type returns a value of another type when applied to its arguments
39−
40− subsumes
41− Check a type subsumes another type
42−-}
43−
44−import Data.List
45−import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46−import qualified Data.Data as D
47−import Data.Generics
48− (mkM, everywhereM, everything, mkT, something, everywhere, mkQ)
49−
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
58−
59−import Control.Monad.State
60−import Control.Monad.Error
61−import Control.Monad.Reader
62−import Control.Monad.Unify
63−
64−import Control.Applicative
65−import Control.Arrow (Arrow(..))
66−
67−import qualified Data.Map as M
68−import Data.Function (on)
69−
70−instance Unifiable Check Type where
71− unknown = TUnknown
72− isUnknown (TUnknown u) = Just u
73− isUnknown _ = Nothing
74− (?=) = unifyTypes
75−
76−-- |
77−-- Unify two types, updating the current substitution
78−--
79−unifyTypes :: Type -> Type -> UnifyT Check ()
80−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
81− unifyTypes' t1 t2
82− where
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
88− ty1 `unifyTypes` ty
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
96− sk `unifyTypes` ty2
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
101− env <- getEnv
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
105− t3 `unifyTypes` t5
106− t4 `unifyTypes` t6
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 ++ "."
113−
114−-- |
115−-- Unify two rows, updating the current substitution
116−--
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
119−-- error.
120−--
121−unifyRows :: Type -> Type -> UnifyT Check ()
122−unifyRows r1 r2 =
123− let
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 ]
129− in do
130− forM_ int (uncurry (?=))
131− unifyRows' sd1 r1' sd2 r2'
132− where
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
137− occursCheck un ty
138− forM_ row $ \(_, t) -> occursCheck un t
139− u' <- fresh
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)) ++ "."
146−
147−-- |
148−-- Ensure type constructors are equal after canonicalization
149−--
150−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
151−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
152−
153−-- |
154−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
155−-- type class dictionaries and type annotations.
156−--
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)
167− forM es $ \e -> do
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
182− escapeCheck val ty
183− return triple
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))
189−
190−-- |
191−-- Check if a value contains a type annotation
192−--
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))
196−
197−-- |
198−-- Map a function over type annotations appearing inside a value
199−--
200−overTypes :: (Type -> Type) -> Value -> Value
201−overTypes f = everywhere (mkT f)
202−
203−-- |
204−-- Replace type class dictionary placeholders with inferred type class dictionaries
205−--
206−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
207−replaceTypeClassDictionaries mn = everywhereM (mkM go)
208− where
209− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
210− go other = return other
211−
212−-- |
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.
215−--
216−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
217−entails moduleName context goal@(className, ty) = do
218− env <- getEnv
219− case go env goal of
220− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
221− (dict : _) -> return dict
222− where
223− go env (className', ty') =
224− [ mkDictionary (canonicalizeDictionary tcd) args
225− | tcd <- context
226− , filterModule tcd
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)
234− return $ Just dict
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
245−
246−-- |
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.
249−--
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
256−
257−-- |
258−-- Ensure unsolved unification variables do not escape
259−--
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
268−
269−-- |
270−-- Find all type annotations occuring inside a value
271−--
272−findAllTypes :: Value -> [Type]
273−findAllTypes = everything (++) (mkQ [] go)
274− where
275− go (TypedValue _ _ ty) = [ty]
276− go _ = []
277−
278−-- |
279−-- Ensure skolem variables do not escape their scope
280−--
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."
286− where
287− findSkolems (Skolem _) = return ()
288− findSkolems _ = mzero
289−
290−-- |
291−-- Ensure a row contains no duplicate labels
292−--
293−setify :: Type -> Type
294−setify = rowFromList . first (M.toList . M.fromList) . rowToList
295−
296−-- |
297−-- \"Setify\" all rows occuring inside a value
298−--
299−setifyAll :: (D.Data d) => d -> d
300−setifyAll = everywhere (mkT setify)
301−
302−-- |
303−-- Replace outermost unsolved unification variables with named type variables
304−--
305−varIfUnknown :: Type -> Type
306−varIfUnknown ty =
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)
312− typeToVar t = t
313− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
314−
315−-- |
316−-- Replace named type variables with types
317−--
318−replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
319−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
320−
321−-- |
322−-- Replace named type variables with new unification variables
323−--
324−replaceAllVarsWithUnknowns :: Type -> UnifyT Check Type
325−replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
326−replaceAllVarsWithUnknowns ty = return ty
327−
328−-- |
329−-- Replace a single type variable with a new unification variable
330−--
331−replaceVarWithUnknown :: String -> Type -> UnifyT Check Type
332−replaceVarWithUnknown ident ty = do
333− tu <- fresh
334− return $ replaceTypeVars ident tu $ ty
335−
336−-- |
337−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
338−-- better error messages during unification.
339−--
340−replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
341−replaceAllTypeSynonyms d = do
342− env <- getEnv
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
346−
347−-- |
348−-- \"Desaturate\" @SaturatedTypeSynonym@s
349−--
350−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
351−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
352− where
353− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
354− replaceSaturatedTypeSynonym t = t
355−
356−-- |
357−-- Replace a type synonym and its arguments with the aliased type
358−--
359−expandTypeSynonym :: Qualified ProperName -> [Type] -> UnifyT Check Type
360−expandTypeSynonym name args = do
361− env <- getEnv
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"
366−
367−-- |
368−-- Ensure a set of property names and value does not contain duplicate labels
369−--
370−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
371−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
372−
373−-- |
374−-- Infer a type for a value, rethrowing any error to provide a more useful error message
375−--
376−infer :: Value -> UnifyT Check Value
377−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
378−
379−-- |
380−-- Infer a type for a value
381−--
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
388− els <- fresh
389− forM_ ts $ \(TypedValue _ _ t) -> els ?= TypeApp tyArray t
390− return $ TypedValue True (ArrayLiteral ts) els
391−infer' (Unary op val) = do
392− v <- infer val
393− inferUnary op v
394−infer' (Binary op left right) = do
395− v1 <- infer left
396− v2 <- infer right
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
406− row <- fresh
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
413− el <- fresh
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
420− case propTy of
421− Nothing -> do
422− field <- fresh
423− rest <- fresh
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
428− ty <- fresh
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
435− ret <- fresh
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
442− case ty' of
443− ConstrainedType constraints _ -> do
444− env <- getEnv
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
449− ret <- fresh
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
454− env <- getEnv
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
462− ret <- fresh
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
469− t2 ?= t3
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"
479−
480−-- |
481−-- Infer the type of a property inside a record with a given type
482−--
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
494−
495−-- |
496−-- Infer the type of a unary operator application
497−--
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
502− valTy' ?= valTy
503− return $ TypedValue True (Unary op val) resTy
504−inferUnary _ _ = error "Invalid arguments to inferUnary"
505−
506−-- |
507−-- Check the type of a unary operator application
508−--
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
513− res ?= resTy
514− val' <- check val valTy
515− return $ Unary op val'
516−
517−-- |
518−-- Built-in unary operators
519−--
520−unaryOps :: [(UnaryOperator, (Type, Type))]
521−unaryOps = [ (Negate, (tyNumber, tyNumber))
522− , (Not, (tyBoolean, tyBoolean))
523− , (BitwiseNot, (tyNumber, tyNumber))
524− ]
525−
526−-- |
527−-- Infer the type of a binary operator application
528−--
529−inferBinary :: BinaryOperator -> Value -> Value -> UnifyT Check Value
530−inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) | isEqualityTest op = do
531− leftTy ?= rightTy
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
536− leftTy ?= valTy
537− rightTy ?= valTy
538− return $ TypedValue True (Binary op left right) resTy
539−inferBinary _ _ _ = error "Invalid arguments to inferBinary"
540−
541−-- |
542−-- Check the type of a binary operator application
543−--
544−checkBinary :: BinaryOperator -> Value -> Value -> Type -> UnifyT Check Value
545−checkBinary op left right res | isEqualityTest op = do
546− res ?= tyBoolean
547− left'@(TypedValue _ _ t1) <- infer left
548− right'@(TypedValue _ _ t2) <- infer right
549− t1 ?= t2
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
554− res ?= resTy
555− left' <- check left valTy
556− right' <- check right valTy
557− return $ Binary op left' right'
558−
559−-- |
560−-- Check if a @BinaryOperator@ is an equality test
561−--
562−isEqualityTest :: BinaryOperator -> Bool
563−isEqualityTest EqualTo = True
564−isEqualityTest NotEqualTo = True
565−isEqualityTest _ = False
566−
567−-- |
568−-- Built-in binary operators
569−--
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))
589− ]
590−
591−-- |
592−-- Infer the types of variables brought into scope by a binder
593−--
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
601− env <- getEnv
602− Just moduleName <- checkCurrentModule <$> get
603− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
604− Just (ty, _) -> do
605− _ <- subsumes Nothing ty val
606− return M.empty
607− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
608−inferBinder val (UnaryBinder ctor binder) = do
609− env <- getEnv
610− Just moduleName <- checkCurrentModule <$> get
611− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
612− Just (ty, _) -> do
613− fn <- replaceAllVarsWithUnknowns ty
614− case fn of
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
621− row <- fresh
622− rest <- fresh
623− m1 <- inferRowProperties row rest props
624− val ?= Object row
625− return m1
626− where
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
630− propTy <- fresh
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
635− el <- fresh
636− m1 <- M.unions <$> mapM (inferBinder el) binders
637− val ?= TypeApp tyArray el
638− return m1
639−inferBinder val (ConsBinder headBinder tailBinder) = do
640− el <- fresh
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
648−
649−-- |
650−-- Check the types of the return values in a set of binders in a case statement
651−--
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
659− case grd of
660− Nothing -> return (binders, Nothing, val')
661− Just g -> do
662− g' <- check g tyBoolean
663− return (binders, Just g', val')
664− rs <- checkBinders nvals ret bs
665− return $ r : rs
666−
667−-- |
668−-- Check that a local variable name is not already used
669−--
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."
676− _ -> return ()
677−
678−-- |
679−-- Check the type of the return values of a statement, returning whether or not the statement returns on
680−-- all code paths
681−--
682−checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Check (Bool, M.Map Ident Type, Statement)
683−checkStatement mass _ (VariableIntroduction name val) = do
684− assignVariable name
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')
710−
711−-- |
712−-- Check the type of an if-then-else statement
713−--
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'))
724−
725−-- |
726−-- Check the type of an else statement
727−--
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
733−
734−-- |
735−-- Check the type of the return value of a block of statements
736−--
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"
745− (False, ss') -> do
746− (b, m, ss'') <- checkBlock mass1 ret ss'
747− return (b, m, s':ss'')
748−
749−-- |
750−-- Skolemize a type variable by replacing its instances with fresh skolem constants
751−--
752−skolemize :: String -> Type -> UnifyT Check Type
753−skolemize ident ty = do
754− tsk <- Skolem . runUnknown <$> fresh'
755− return $ replaceTypeVars ident tsk ty
756−
757−-- |
758−-- Check the type of a value, rethrowing errors to provide a better error message
759−--
760−check :: Value -> Type -> UnifyT Check Value
761−check val ty = rethrow errorMessage $ check' val ty
762− where
763− errorMessage msg =
764− "Error checking type of term " ++
765− prettyPrintValue val ++
766− " against type " ++
767− prettyPrintType ty ++
768− ":\n" ++
769− msg
770−
771−-- |
772−-- Check the type of a value
773−--
774−check' :: Value -> Type -> UnifyT Check Value
775−check' val (ForAll idents ty) = do
776− sk <- skolemize idents ty
777− check val sk
778−check' val (ConstrainedType constraints ty) = do
779− env <- getEnv
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)) $
787− check val ty
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
793− ty' ?= u
794− return val'
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
812− return $ app
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
818− case v' of
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
826− case val' of
827− Nothing -> throwError "Unable to check type subsumption"
828− Just val'' -> do
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
838− th' <- check th ty
839− el' <- check el ty
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
855− rest <- fresh
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
861− return $ Block ss'
862−check' (Constructor c) ty = do
863− env <- getEnv
864− Just moduleName <- checkCurrentModule <$> get
865− case M.lookup (qualify moduleName c) (dataConstructors env) of
866− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
867− Just (ty1, _) -> do
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
873− check val ty
874−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
875−
876−-- |
877−-- Check the type of a collection of named record fields
878−--
879−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
880−--
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
885− return []
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
892− rest <- fresh
893− u ?= RCons p ty rest
894− ps'' <- go ps' [] rest
895− return $ (p, v') : ps''
896− go ((p,v):ps') ts r =
897− case lookup p ts of
898− Nothing -> do
899− v'@(TypedValue _ _ ty) <- infer v
900− rest <- fresh
901− r ?= RCons p ty rest
902− ps'' <- go ps' ts rest
903− return $ (p, v') : ps''
904− Just ty -> do
905− v' <- check v ty
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)
909−
910−-- |
911−-- Check the type of a function application, rethrowing errors to provide a better error message
912−--
913−checkFunctionApplication :: Value -> Type -> Value -> Type -> UnifyT Check Value
914−checkFunctionApplication fn fnTy arg ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg ret
915− where
916− errorMessage msg = "Error applying function of type "
917− ++ prettyPrintType fnTy
918− ++ " to argument " ++ prettyPrintValue arg
919− ++ ":\n" ++ msg
920−
921−-- |
922−-- Check the type of a function application
923−--
924−checkFunctionApplication' :: Value -> Type -> Value -> Type -> UnifyT Check Value
925−checkFunctionApplication' fn (TypeApp (TypeApp t argTy) retTy) arg ret | t == tyFunction = do
926− arg' <- check arg argTy
927− _ <- subsumes Nothing retTy ret
928− return $ App fn arg'
929−checkFunctionApplication' fn (ForAll ident ty) arg ret = do
930− replaced <- replaceVarWithUnknown ident ty
931− checkFunctionApplication fn replaced arg ret
932−checkFunctionApplication' fn u@(TUnknown _) arg ret = do
933− arg' <- do
934− TypedValue _ v t <- infer arg
935− TypedValue True v <$> replaceAllVarsWithUnknowns t
936− let ty = (\(TypedValue _ _ t) -> t) arg'
937− u ?= function ty ret
938− return $ App fn arg'
939−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg ret = do
940− ty <- expandTypeSynonym name tyArgs
941− checkFunctionApplication fn ty arg ret
942−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg ret = do
943− env <- getEnv
944− dicts <- getTypeClassDictionaries
945− Just moduleName <- checkCurrentModule <$> get
946− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy arg ret
947−checkFunctionApplication' _ fnTy arg ret = throwError $ "Applying a function of type "
948− ++ prettyPrintType fnTy
949− ++ " to argument(s) " ++ prettyPrintValue arg
950− ++ " does not yield a value of type " ++ prettyPrintType ret ++ "."
951−
952−-- |
953−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
954−--
955−subsumes :: Maybe Value -> Type -> Type -> UnifyT Check (Maybe Value)
956−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
957− where
958− errorMessage msg = "Error checking that type "
959− ++ prettyPrintType ty1
960− ++ " subsumes type "
961− ++ prettyPrintType ty2
962− ++ ":\n" ++ msg
963−
964−-- |
965−-- Check whether one type subsumes another
966−--
967−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Check (Maybe Value)
968−subsumes' val (ForAll ident ty1) ty2 = do
969− replaced <- replaceVarWithUnknown ident ty1
970− subsumes val replaced ty2
971−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
972− subsumes Nothing arg2 arg1
973− subsumes Nothing ret1 ret2
974− return val
975−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
976− env <- getEnv
977− dicts <- getTypeClassDictionaries
978− Just moduleName <- checkCurrentModule <$> get
979− _ <- subsumes' Nothing ty1 ty2
980− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
981−subsumes' val ty1 ty2 = do
982− ty1 ?= ty2
983− return val
984−