@@ -0,0 +1,991 @@
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' 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
109+ env <- getEnv
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
113+ t3 `unifyTypes` t5
114+ t4 `unifyTypes` t6
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 ++ "."
121+
122+-- |
123+-- Unify two rows, updating the current substitution
124+--
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
127+-- error.
128+--
129+unifyRows :: Type -> Type -> UnifyT Check ()
130+unifyRows r1 r2 =
131+ let
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 ]
137+ in do
138+ forM_ int (uncurry (?=))
139+ unifyRows' sd1 r1' sd2 r2'
140+ where
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
145+ occursCheck un ty
146+ forM_ row $ \(_, t) -> occursCheck un t
147+ u' <- fresh
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)) ++ "."
154+
155+-- |
156+-- Ensure type constructors are equal after canonicalization
157+--
158+typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
159+typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
160+
161+-- |
162+-- Infer the types of multiple mutually-recursive values, and return elaborated values including
163+-- type class dictionaries and type annotations.
164+--
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)
175+ forM es $ \e -> do
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
190+ escapeCheck val ty
191+ return triple
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))
197+
198+-- |
199+-- Check if a value contains a type annotation
200+--
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))
204+
205+-- |
206+-- Map a function over type annotations appearing inside a value
207+--
208+overTypes :: (Type -> Type) -> Value -> Value
209+overTypes f = everywhere (mkT f)
210+
211+-- |
212+-- Replace type class dictionary placeholders with inferred type class dictionaries
213+--
214+replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
215+replaceTypeClassDictionaries mn = everywhereM (mkM go)
216+ where
217+ go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
218+ go other = return other
219+
220+-- |
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.
223+--
224+entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
225+entails moduleName context goal@(className, ty) = do
226+ env <- getEnv
227+ case go env goal of
228+ [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
229+ (dict : _) -> return dict
230+ where
231+ go env (className', ty') =
232+ [ mkDictionary (canonicalizeDictionary tcd) args
233+ | tcd <- context
234+ , filterModule tcd
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)
241+ return $ Just dict
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
248+
249+-- |
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.
252+--
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
263+
264+-- |
265+-- Ensure unsolved unification variables do not escape
266+--
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
275+
276+-- |
277+-- Find all type annotations occuring inside a value
278+--
279+findAllTypes :: Value -> [Type]
280+findAllTypes = everything (++) (mkQ [] go)
281+ where
282+ go (TypedValue _ _ ty) = [ty]
283+ go _ = []
284+
285+-- |
286+-- Ensure skolem variables do not escape their scope
287+--
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."
293+ where
294+ findSkolems (Skolem _) = return ()
295+ findSkolems _ = mzero
296+
297+-- |
298+-- Ensure a row contains no duplicate labels
299+--
300+setify :: Type -> Type
301+setify = rowFromList . first (M.toList . M.fromList) . rowToList
302+
303+-- |
304+-- \"Setify\" all rows occuring inside a value
305+--
306+setifyAll :: (D.Data d) => d -> d
307+setifyAll = everywhere (mkT setify)
308+
309+-- |
310+-- Replace outermost unsolved unification variables with named type variables
311+--
312+varIfUnknown :: Type -> Type
313+varIfUnknown ty =
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)
319+ typeToVar t = t
320+ in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
321+
322+-- |
323+-- Replace named type variables with types
324+--
325+replaceAllTypeVars :: (D.Data d) => [(String, Type)] -> d -> d
326+replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
327+
328+-- |
329+-- Replace named type variables with new unification variables
330+--
331+replaceAllVarsWithUnknowns :: Type -> UnifyT Check Type
332+replaceAllVarsWithUnknowns (ForAll ident ty) = replaceVarWithUnknown ident ty >>= replaceAllVarsWithUnknowns
333+replaceAllVarsWithUnknowns ty = return ty
334+
335+-- |
336+-- Replace a single type variable with a new unification variable
337+--
338+replaceVarWithUnknown :: String -> Type -> UnifyT Check Type
339+replaceVarWithUnknown ident ty = do
340+ tu <- fresh
341+ return $ replaceTypeVars ident tu $ ty
342+
343+-- |
344+-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
345+-- better error messages during unification.
346+--
347+replaceAllTypeSynonyms :: (Functor m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
348+replaceAllTypeSynonyms d = do
349+ env <- getEnv
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
353+
354+-- |
355+-- \"Desaturate\" @SaturatedTypeSynonym@s
356+--
357+desaturateAllTypeSynonyms :: (D.Data d) => d -> d
358+desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
359+ where
360+ replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
361+ replaceSaturatedTypeSynonym t = t
362+
363+-- |
364+-- Replace a type synonym and its arguments with the aliased type
365+--
366+expandTypeSynonym :: Qualified ProperName -> [Type] -> UnifyT Check Type
367+expandTypeSynonym name args = do
368+ env <- getEnv
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"
373+
374+-- |
375+-- Ensure a set of property names and value does not contain duplicate labels
376+--
377+ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
378+ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
379+
380+-- |
381+-- Infer a type for a value, rethrowing any error to provide a more useful error message
382+--
383+infer :: Value -> UnifyT Check Value
384+infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
385+
386+-- |
387+-- Infer a type for a value
388+--
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
395+ els <- fresh
396+ forM_ ts $ \(TypedValue _ _ t) -> els ?= TypeApp Array t
397+ return $ TypedValue True (ArrayLiteral ts) els
398+infer' (Unary op val) = do
399+ v <- infer val
400+ inferUnary op v
401+infer' (Binary op left right) = do
402+ v1 <- infer left
403+ v2 <- infer right
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
413+ row <- fresh
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
420+ el <- fresh
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
427+ case propTy of
428+ Nothing -> do
429+ field <- fresh
430+ rest <- fresh
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
442+ ret <- fresh
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
449+ case ty' of
450+ ConstrainedType constraints _ -> do
451+ env <- getEnv
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
456+ ret <- fresh
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
461+ env <- getEnv
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
469+ ret <- fresh
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
476+ t2 ?= t3
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"
486+
487+-- |
488+-- Infer the type of a property inside a record with a given type
489+--
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
501+
502+-- |
503+-- Infer the type of a unary operator application
504+--
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
509+ valTy' ?= valTy
510+ return $ TypedValue True (Unary op val) resTy
511+inferUnary _ _ = error "Invalid arguments to inferUnary"
512+
513+-- |
514+-- Check the type of a unary operator application
515+--
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
520+ res ?= resTy
521+ val' <- check val valTy
522+ return $ Unary op val'
523+
524+-- |
525+-- Built-in unary operators
526+--
527+unaryOps :: [(UnaryOperator, (Type, Type))]
528+unaryOps = [ (Negate, (Number, Number))
529+ , (Not, (Boolean, Boolean))
530+ , (BitwiseNot, (Number, Number))
531+ ]
532+
533+-- |
534+-- Infer the type of a binary operator application
535+--
536+inferBinary :: BinaryOperator -> Value -> Value -> UnifyT Check Value
537+inferBinary op left@(TypedValue _ _ leftTy) right@(TypedValue _ _ rightTy) | isEqualityTest op = do
538+ leftTy ?= rightTy
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
543+ leftTy ?= valTy
544+ rightTy ?= valTy
545+ return $ TypedValue True (Binary op left right) resTy
546+inferBinary _ _ _ = error "Invalid arguments to inferBinary"
547+
548+-- |
549+-- Check the type of a binary operator application
550+--
551+checkBinary :: BinaryOperator -> Value -> Value -> Type -> UnifyT Check Value
552+checkBinary op left right res | isEqualityTest op = do
553+ res ?= Boolean
554+ left'@(TypedValue _ _ t1) <- infer left
555+ right'@(TypedValue _ _ t2) <- infer right
556+ t1 ?= t2
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
561+ res ?= resTy
562+ left' <- check left valTy
563+ right' <- check right valTy
564+ return $ Binary op left' right'
565+
566+-- |
567+-- Check if a @BinaryOperator@ is an equality test
568+--
569+isEqualityTest :: BinaryOperator -> Bool
570+isEqualityTest EqualTo = True
571+isEqualityTest NotEqualTo = True
572+isEqualityTest _ = False
573+
574+-- |
575+-- Built-in binary operators
576+--
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))
596+ ]
597+
598+-- |
599+-- Infer the types of variables brought into scope by a binder
600+--
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
608+ env <- getEnv
609+ Just moduleName <- checkCurrentModule <$> get
610+ case M.lookup (qualify moduleName ctor) (dataConstructors env) of
611+ Just (ty, _) -> do
612+ _ <- subsumes Nothing ty val
613+ return M.empty
614+ _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
615+inferBinder val (UnaryBinder ctor binder) = do
616+ env <- getEnv
617+ Just moduleName <- checkCurrentModule <$> get
618+ case M.lookup (qualify moduleName ctor) (dataConstructors env) of
619+ Just (ty, _) -> do
620+ fn <- replaceAllVarsWithUnknowns ty
621+ case fn of
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
628+ row <- fresh
629+ rest <- fresh
630+ m1 <- inferRowProperties row rest props
631+ val ?= Object row
632+ return m1
633+ where
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
637+ propTy <- fresh
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
642+ el <- fresh
643+ m1 <- M.unions <$> mapM (inferBinder el) binders
644+ val ?= TypeApp Array el
645+ return m1
646+inferBinder val (ConsBinder headBinder tailBinder) = do
647+ el <- fresh
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
655+
656+-- |
657+-- Check the types of the return values in a set of binders in a case statement
658+--
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
666+ case grd of
667+ Nothing -> return (binders, Nothing, val')
668+ Just g -> do
669+ g' <- check g Boolean
670+ return (binders, Just g', val')
671+ rs <- checkBinders nvals ret bs
672+ return $ r : rs
673+
674+-- |
675+-- Check that a local variable name is not already used
676+--
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."
683+ _ -> return ()
684+
685+-- |
686+-- Check the type of the return values of a statement, returning whether or not the statement returns on
687+-- all code paths
688+--
689+checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Check (Bool, M.Map Ident Type, Statement)
690+checkStatement mass _ (VariableIntroduction name val) = do
691+ assignVariable name
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')
717+
718+-- |
719+-- Check the type of an if-then-else statement
720+--
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'))
731+
732+-- |
733+-- Check the type of an else statement
734+--
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
740+
741+-- |
742+-- Check the type of the return value of a block of statements
743+--
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"
752+ (False, ss') -> do
753+ (b, m, ss'') <- checkBlock mass1 ret ss'
754+ return (b, m, s':ss'')
755+
756+-- |
757+-- Skolemize a type variable by replacing its instances with fresh skolem constants
758+--
759+skolemize :: String -> Type -> UnifyT Check Type
760+skolemize ident ty = do
761+ tsk <- Skolem . runUnknown <$> fresh'
762+ return $ replaceTypeVars ident tsk ty
763+
764+-- |
765+-- Check the type of a value, rethrowing errors to provide a better error message
766+--
767+check :: Value -> Type -> UnifyT Check Value
768+check val ty = rethrow errorMessage $ check' val ty
769+ where
770+ errorMessage msg =
771+ "Error checking type of term " ++
772+ prettyPrintValue val ++
773+ " against type " ++
774+ prettyPrintType ty ++
775+ ":\n" ++
776+ msg
777+
778+-- |
779+-- Check the type of a value
780+--
781+check' :: Value -> Type -> UnifyT Check Value
782+check' val (ForAll idents ty) = do
783+ sk <- skolemize idents ty
784+ check val sk
785+check' val (ConstrainedType constraints ty) = do
786+ env <- getEnv
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)) $
794+ check val ty
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
800+ ty' ?= u
801+ return val'
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
820+ return $ app
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
826+ case v' of
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
834+ case val' of
835+ Nothing -> throwError "Unable to check type subsumption"
836+ Just val'' -> do
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
846+ th' <- check th ty
847+ el' <- check el ty
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
863+ rest <- fresh
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
869+ return $ Block ss'
870+check' (Constructor c) ty = do
871+ env <- getEnv
872+ Just moduleName <- checkCurrentModule <$> get
873+ case M.lookup (qualify moduleName c) (dataConstructors env) of
874+ Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
875+ Just (ty1, _) -> do
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
881+ check val ty
882+check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
883+
884+-- |
885+-- Check the type of a collection of named record fields
886+--
887+-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
888+--
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
893+ return []
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
900+ rest <- fresh
901+ u ?= RCons p ty rest
902+ ps'' <- go ps' [] rest
903+ return $ (p, v') : ps''
904+ go ((p,v):ps') ts r =
905+ case lookup p ts of
906+ Nothing -> do
907+ v'@(TypedValue _ _ ty) <- infer v
908+ rest <- fresh
909+ r ?= RCons p ty rest
910+ ps'' <- go ps' ts rest
911+ return $ (p, v') : ps''
912+ Just ty -> do
913+ v' <- check v ty
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)
917+
918+-- |
919+-- Check the type of a function application, rethrowing errors to provide a better error message
920+--
921+checkFunctionApplication :: Value -> Type -> [Value] -> Type -> UnifyT Check Value
922+checkFunctionApplication fn fnTy args ret = rethrow errorMessage $ checkFunctionApplication' fn fnTy args ret
923+ where
924+ errorMessage msg = "Error applying function of type "
925+ ++ prettyPrintType fnTy
926+ ++ " to arguments " ++ intercalate ", " (map prettyPrintValue args)
927+ ++ ":\n" ++ msg
928+
929+-- |
930+-- Check the type of a function application
931+--
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
950+ env <- getEnv
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 ++ "."
958+
959+-- |
960+-- Check whether one type subsumes another, rethrowing errors to provide a better error message
961+--
962+subsumes :: Maybe Value -> Type -> Type -> UnifyT Check (Maybe Value)
963+subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
964+ where
965+ errorMessage msg = "Error checking that type "
966+ ++ prettyPrintType ty1
967+ ++ " subsumes type "
968+ ++ prettyPrintType ty2
969+ ++ ":\n" ++ msg
970+
971+-- |
972+-- Check whether one type subsumes another
973+--
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
981+ return val
982+subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
983+ env <- getEnv
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
989+ ty1 ?= ty2
990+ return val
991+