@@ -1,953 +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 FlexibleContexts #-}
18−{-# LANGUAGE MultiParamTypeClasses #-}
20−module Language.PureScript.TypeChecker.Types (
25− The following functions represent the corresponding type checking judgements:
28− Synthesize a type for a value
31− Check a value has a given type
34− Check an object with a given type contains specified properties
36− checkFunctionApplication
37− Check a function of a given type returns a value of another type when applied to its arguments
40− Check a type subsumes another type
44−import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
45−import qualified Data.Data as D
47− (everythingWithContext, mkM, everywhereM, everything, mkT,
48− something, everywhere, mkQ)
49−import Data.Generics.Extras
51−import Language.PureScript.Values
52−import Language.PureScript.Types
53−import Language.PureScript.Kinds
54−import Language.PureScript.Names
55−import Language.PureScript.TypeChecker.Monad
56−import Language.PureScript.TypeChecker.Kinds
57−import Language.PureScript.TypeChecker.Synonyms
58−import Language.PureScript.Pretty
60−import Control.Monad.State
61−import Control.Monad.Error
62−import Control.Monad.Unify
64−import Control.Applicative
65−import Control.Arrow (Arrow(..))
67−import qualified Data.Map as M
68−import Data.Function (on)
69−import Data.Ord (comparing)
71−instance Partial Type where
73− isUnknown (TUnknown u) = Just u
74− isUnknown _ = Nothing
76−instance Unifiable Check Type where
80−-- Unify two types, updating the current substitution
82−unifyTypes :: Type -> Type -> UnifyT Type Check ()
83−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $
86− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
87− unifyTypes' (TUnknown u) t = u =:= t
88− unifyTypes' t (TUnknown u) = u =:= t
89− unifyTypes' (SaturatedTypeSynonym name args) ty = do
90− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
92− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
93− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
95− (Just sc1', Just sc2') -> do
96− sko <- newSkolemConstant
97− let sk1 = skolemize ident1 sko sc1' ty1
98− let sk2 = skolemize ident2 sko sc2' ty2
100− _ -> throwError (prettyPrintType ty1)
101− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
102− sko <- newSkolemConstant
103− let sk = skolemize ident sko sc ty1
105− unifyTypes' ForAll{} _ = throwError "Skolem variable scope is unspecified"
106− unifyTypes' ty f@ForAll{} = f `unifyTypes` ty
107− unifyTypes' (Object row1) (Object row2) = row1 =?= row2
108− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
109− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
111− Just moduleName <- checkCurrentModule <$> get
112− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (c1 == c2)
113− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
116− unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
117− unifyTypes' r1@RCons{} r2 = unifyRows r1 r2
118− unifyTypes' r1 r2@RCons{} = unifyRows r1 r2
119− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
120− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
121− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
124−-- Unify two rows, updating the current substitution
126−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
127−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
130−unifyRows :: Type -> Type -> UnifyT Type Check ()
133− (s1, r1') = rowToList r1
134− (s2, r2') = rowToList r2
135− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
136− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
137− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
139− forM_ int (uncurry (=?=))
140− unifyRows' sd1 r1' sd2 r2'
142− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
143− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
144− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
145− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
147− forM_ row $ \(_, t) -> occursCheck un t
149− u =?= RCons name ty u'
150− unifyRows' row r others u'
151− unifyRows' [] REmpty [] REmpty = return ()
152− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
153− unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
154− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")."
157−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
158−-- type class dictionaries and type annotations.
160−typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
161−typesOf mainModuleName moduleName vals = do
162− tys <- fmap tidyUp . liftUnify $ do
164− -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
165− es = map isTyped vals
166− -- Filter the typed and untyped declarations
167− typed = filter (isJust . snd . snd) es
168− untyped = filter (isNothing . snd . snd) es
169− -- Make a map of names to typed declarations
170− typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
171− -- Create fresh unification variables for the types of untyped declarations
172− untypedNames <- replicateM (length untyped) fresh
174− -- Make a map of names to the unification variables of untyped declarations
175− untypedDict = zip (map fst untyped) untypedNames
176− -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
177− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
178− forM es $ \e@(_, (val, _)) -> do
179− -- If the declaration is a function, it has access to other values in the binding group.
180− -- If not, the generated code might fail at runtime since those values might be undefined.
181− let dict' = if isFunction val then dict else M.empty
182− triple@(_, (val', ty)) <- case e of
183− -- Typed declarations
184− (ident, (val', Just (ty, checkType))) -> do
186− kind <- liftCheck $ kindOf moduleName ty
187− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
188− -- Check the type with the new names in scope
189− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
190− val'' <- bindNames dict' $ if checkType
191− then TypedValue True <$> check val' ty' <*> pure ty'
192− else return (TypedValue False val' ty')
193− return (ident, (val'', ty'))
194− -- Untyped declarations
195− (ident, (val', Nothing)) -> do
196− -- Infer the type with the new names in scope
197− TypedValue _ val'' ty <- bindNames dict' $ infer val'
198− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
199− return (ident, (TypedValue True val'' ty, ty))
200− -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
201− when (Just moduleName == mainModuleName && fst e == Ident "main") $ do
202− [eff, a] <- replicateM 2 fresh
203− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName [ProperName "Control", ProperName "Monad", ProperName "Eff"])) (ProperName "Eff"))) eff) a
204− -- Make sure unification variables do not escape
207− forM tys $ \(ident, (val, ty)) -> do
208− -- Replace type class dictionary placeholders with actual dictionaries
209− val' <- replaceTypeClassDictionaries moduleName val
210− -- Check skolem variables did not escape their scope
211− skolemEscapeCheck val'
212− -- Remove type synonyms placeholders, remove duplicate row fields, and replace
213− -- top-level unification variables with named type variables.
214− let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
215− ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
216− return (ident, (val'', ty'))
218− -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
219− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
222−-- Check if a value introduces a function
224−isFunction :: Value -> Bool
225−isFunction (Abs _ _) = True
226−isFunction (TypedValue _ val _) = isFunction val
230−-- Check if a value contains a type annotation
232−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
233−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
234−isTyped (name, value) = (name, (value, Nothing))
237−-- Map a function over type annotations appearing inside a value
239−overTypes :: (Type -> Type) -> Value -> Value
240−overTypes f = everywhere (mkT f)
243−-- Replace type class dictionary placeholders with inferred type class dictionaries
245−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
246−replaceTypeClassDictionaries mn = everywhereM' (mkM go)
248− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
249− go other = return other
252−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
253−-- return a type class dictionary reference.
255−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, [Type]) -> Check Value
256−entails moduleName context goal@(className, tys) = do
259− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ intercalate ", " (map prettyPrintType tys)
260− (dict : _) -> return dict
262− go env (className', tys') =
263− [ mkDictionary (canonicalizeDictionary tcd) args
265− -- Choose type class dictionaries in scope in the current module
267− -- Make sure the type class name matches the one we are trying to satisfy
268− , className' == tcdClassName tcd
269− -- Make sure the type unifies with the type in the type instance definition
270− , subst <- maybeToList . (>>= verifySubstitution) . fmap concat $ zipWithM (typeHeadsAreEqual moduleName env) tys' (tcdInstanceTypes tcd)
271− -- Solve any necessary subgoals
272− , args <- solveSubgoals env subst (tcdDependencies tcd) ]
273− -- Create dictionaries for subgoals which still need to be solved by calling go recursively
274− -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
275− -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
276− solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, [Type])] -> [Maybe [Value]]
277− solveSubgoals _ _ Nothing = return Nothing
278− solveSubgoals env subst (Just subgoals) = do
279− dict <- mapM (go env . second (map (replaceAllTypeVars subst))) subgoals
281− -- Make a dictionary from subgoal dictionaries by applying the correct function
282− mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
283− mkDictionary fnName Nothing = Var fnName
284− mkDictionary fnName (Just []) = App (Var fnName) (ObjectLiteral [])
285− mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
286− -- Filter out type dictionaries which are in scope in the current module
287− filterModule :: TypeClassDictionaryInScope -> Bool
288− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
289− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
290− filterModule _ = False
291− -- Resolve a type class dictionary in scope to an actual value by following any (TCDAlias) pointers
292− -- which originated from module imports
293− canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
294− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
295− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
296− -- Ensure that a substitution is valid
297− verifySubstitution :: [(String, Type)] -> Maybe [(String, Type)]
298− verifySubstitution subst = do
299− let grps = groupBy ((==) `on` fst) subst
300− guard (all ((==) 1 . length . nubBy ((==) `on` snd)) grps)
301− return $ map head grps
304−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
305−-- and return a substitution from type variables to types which makes the type heads unify.
307−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
308−typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
309−typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
310−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
311−typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | c1 == c2 = Just []
312−typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
313−typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
314−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e m name args of
316− Right t1 -> typeHeadsAreEqual m e t1 t2
317−typeHeadsAreEqual _ _ _ _ = Nothing
320−-- Ensure unsolved unification variables do not escape
322−escapeCheck :: Value -> Type -> UnifyT Type Check ()
323−escapeCheck value ty = do
324− subst <- unifyCurrentSubstitution <$> UnifyT get
325− let visibleUnknowns = nub $ unknowns $ subst $? ty
326− let allUnknowns = findAllTypes value
327− forM_ allUnknowns $ \t -> do
328− let unsolvedUnknowns = nub . unknowns $ subst $? t
329− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
332−-- Find all type annotations occuring inside a value
334−findAllTypes :: Value -> [Type]
335−findAllTypes = everything (++) (mkQ [] go)
337− go (TypedValue _ _ ty) = [ty]
341−-- Ensure skolem variables do not escape their scope
343−skolemEscapeCheck :: Value -> Check ()
344−skolemEscapeCheck (TypedValue False _ _) = return ()
345−skolemEscapeCheck root@TypedValue{} =
346− -- Every skolem variable is created when a ForAll type is skolemized.
347− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
348− -- field of the ForAll constructor.
349− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
350− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
351− -- an escaped skolem variable.
352− case everythingWithContext [] (++) (mkQ ((,) []) go) root of
354− ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
356− go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
357− go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
358− go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
359− (sco : _) -> ([(findBindingScope sco, val)], scos)
362− collectSkolems :: Type -> [SkolemScope]
363− collectSkolems = nub . everything (++) (mkQ [] collect)
365− collect (Skolem _ scope) = [scope]
367− go _ scos = ([], scos)
368− findBindingScope :: SkolemScope -> Maybe Value
369− findBindingScope sco = something (mkQ Nothing go') root
371− go' val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
373−skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
376−-- Ensure a row contains no duplicate labels
378−setify :: Type -> Type
379−setify = rowFromList . first (M.toList . M.fromList) . rowToList
382−-- \"Setify\" all rows occuring inside a value
384−setifyAll :: (D.Data d) => d -> d
385−setifyAll = everywhere (mkT setify)
388−-- Replace outermost unsolved unification variables with named type variables
390−varIfUnknown :: Type -> Type
392− let unks = nub $ unknowns ty
393− toName = (:) 't' . show
394− ty' = everywhere (mkT typeToVar) ty
395− typeToVar :: Type -> Type
396− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
398− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
401−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
402−-- or TypeClassDictionary values.
404−-- This is necessary during type checking to avoid unifying a polymorphic type with a
405−-- unification variable.
407−instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
408−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
409− ty' <- replaceVarWithUnknown ident ty
410− instantiatePolyTypeWithUnknowns val ty'
411−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
413− Just moduleName <- checkCurrentModule <$> get
414− dicts <- getTypeClassDictionaries
415− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
416− return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
417−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
420−-- Replace a single type variable with a new unification variable
422−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
423−replaceVarWithUnknown ident ty = do
425− return $ replaceTypeVars ident tu ty
428−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
429−-- better error messages during unification.
431−replaceAllTypeSynonyms' :: (D.Data d) => Environment -> ModuleName -> d -> Either String d
432−replaceAllTypeSynonyms' env moduleName d =
434− syns = map (\(name, (args, _)) -> (name, length args)) . M.toList $ typeSynonyms env
436− saturateAllTypeSynonyms env moduleName syns d
438−replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
439−replaceAllTypeSynonyms d = do
441− Just moduleName <- checkCurrentModule <$> get
442− either throwError return $ replaceAllTypeSynonyms' env moduleName d
445−-- \"Desaturate\" @SaturatedTypeSynonym@s
447−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
448−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
450− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
451− replaceSaturatedTypeSynonym t = t
454−-- Replace a type synonym and its arguments with the aliased type
456−expandTypeSynonym' :: Environment -> ModuleName -> Qualified ProperName -> [Type] -> Either String Type
457−expandTypeSynonym' env moduleName name args =
458− case M.lookup name (typeSynonyms env) of
459− Just (synArgs, body) -> do
460− let repl = replaceAllTypeVars (zip synArgs args) body
461− replaceAllTypeSynonyms' env moduleName repl
462− Nothing -> error "Type synonym was not defined"
464−expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
465−expandTypeSynonym name args = do
467− Just moduleName <- checkCurrentModule <$> get
468− either throwError return $ expandTypeSynonym' env moduleName name args
471−-- Ensure a set of property names and value does not contain duplicate labels
473−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
474−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
477−-- Infer a type for a value, rethrowing any error to provide a more useful error message
479−infer :: Value -> UnifyT Type Check Value
480−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
483−-- Infer a type for a value
485−infer' :: Value -> UnifyT Type Check Value
486−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
487−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
488−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
489−infer' (ArrayLiteral vals) = do
490− ts <- mapM infer vals
492− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
493− return $ TypedValue True (ArrayLiteral ts) els
494−infer' (ObjectLiteral ps) = do
495− ensureNoDuplicateProperties ps
496− ts <- mapM (infer . snd) ps
497− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
498− ty = Object $ rowFromList (fields, REmpty)
499− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
500−infer' (ObjectUpdate o ps) = do
501− ensureNoDuplicateProperties ps
503− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
504− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
505− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
506− let oldTy = Object $ rowFromList (oldTys, row)
507− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
508− return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
509−infer' (Accessor prop val) = do
510− typed@(TypedValue _ _ objTy) <- infer val
511− propTy <- inferProperty objTy prop
516− _ <- subsumes Nothing objTy (Object (RCons prop field rest))
517− return $ TypedValue True (Accessor prop typed) field
518− Just ty -> return $ TypedValue True (Accessor prop typed) ty
519−infer' (Abs (Left arg) ret) = do
521− Just moduleName <- checkCurrentModule <$> get
522− bindLocalVariables moduleName [(arg, ty)] $ do
523− body@(TypedValue _ _ bodyTy) <- infer' ret
524− return $ TypedValue True (Abs (Left arg) body) $ function ty bodyTy
525−infer' (Abs (Right _) _) = error "Binder was not desugared"
526−infer' (App f arg) = do
527− f'@(TypedValue _ _ ft) <- infer f
528− (ret, app) <- checkFunctionApplication f' ft arg
529− return $ TypedValue True app ret
530−infer' (Var var) = do
531− Just moduleName <- checkCurrentModule <$> get
532− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
534− ConstrainedType constraints ty' -> do
536− dicts <- getTypeClassDictionaries
537− return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) constraints)) ty'
538− _ -> return $ TypedValue True (Var var) ty
539−infer' v@(Constructor c) = do
541− Just moduleName <- checkCurrentModule <$> get
542− case M.lookup c (dataConstructors env) of
543− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
544− Just ty -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
545− return $ TypedValue True v ty'
546−infer' (Case vals binders) = do
547− ts <- mapM infer vals
549− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
550− return $ TypedValue True (Case ts binders') ret
551−infer' (IfThenElse cond th el) = do
552− cond' <- check cond tyBoolean
553− v2@(TypedValue _ _ t2) <- infer th
554− v3@(TypedValue _ _ t3) <- infer el
556− return $ TypedValue True (IfThenElse cond' v2 v3) t2
557−infer' (TypedValue checkType val ty) = do
558− Just moduleName <- checkCurrentModule <$> get
559− kind <- liftCheck $ kindOf moduleName ty
560− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
561− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
562− val' <- if checkType then check val ty' else return val
563− return $ TypedValue True val' ty'
564−infer' _ = error "Invalid argument to infer"
567−-- Infer the type of a property inside a record with a given type
569−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
570−inferProperty (Object row) prop = do
571− let (props, _) = rowToList row
572− return $ lookup prop props
573−inferProperty (SaturatedTypeSynonym name args) prop = do
574− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
575− inferProperty replaced prop
576−inferProperty (ForAll ident ty _) prop = do
577− replaced <- replaceVarWithUnknown ident ty
578− inferProperty replaced prop
579−inferProperty _ _ = return Nothing
582−-- Infer the types of variables brought into scope by a binder
584−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
585−inferBinder _ NullBinder = return M.empty
586−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
587−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
588−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
589−inferBinder val (VarBinder name) = return $ M.singleton name val
590−inferBinder val (ConstructorBinder ctor binders) = do
592− Just moduleName <- checkCurrentModule <$> get
593− case M.lookup ctor (dataConstructors env) of
595− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contains constraints") ty
599− subsumes Nothing val ty'
601− go (binder : binders') (TypeApp (TypeApp t obj) ret) | t == tyFunction =
602− M.union <$> inferBinder obj binder <*> go binders' ret
603− go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
604− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
605−inferBinder val (ObjectBinder props) = do
608− m1 <- inferRowProperties row rest props
612− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
613− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
614− inferRowProperties nrow row ((name, binder):binders) = do
616− m1 <- inferBinder propTy binder
617− m2 <- inferRowProperties nrow (RCons name propTy row) binders
618− return $ m1 `M.union` m2
619−inferBinder val (ArrayBinder binders) = do
621− m1 <- M.unions <$> mapM (inferBinder el) binders
622− val =?= TypeApp tyArray el
624−inferBinder val (ConsBinder headBinder tailBinder) = do
626− m1 <- inferBinder el headBinder
627− m2 <- inferBinder val tailBinder
628− val =?= TypeApp tyArray el
629− return $ m1 `M.union` m2
630−inferBinder val (NamedBinder name binder) = do
631− m <- inferBinder val binder
632− return $ M.insert name val m
635−-- Check the types of the return values in a set of binders in a case statement
637−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Type Check [([Binder], Maybe Guard, Value)]
638−checkBinders _ _ [] = return []
639−checkBinders nvals ret ((binders, grd, val):bs) = do
640− Just moduleName <- checkCurrentModule <$> get
641− m1 <- M.unions <$> zipWithM inferBinder nvals binders
642− r <- bindLocalVariables moduleName (M.toList m1) $ do
643− val' <- TypedValue True <$> check val ret <*> pure ret
645− Nothing -> return (binders, Nothing, val')
647− g' <- check g tyBoolean
648− return (binders, Just g', val')
649− rs <- checkBinders nvals ret bs
653−-- Check that a local variable name is not already used
655−assignVariable :: Ident -> UnifyT Type Check ()
656−assignVariable name = do
657− env <- checkEnv <$> get
658− Just moduleName <- checkCurrentModule <$> get
659− case M.lookup (moduleName, name) (names env) of
660− Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
664−-- Generate a new skolem constant
666−newSkolemConstant :: UnifyT Type Check Int
667−newSkolemConstant = runUnknown <$> fresh'
670−-- Generate a new skolem scope
672−newSkolemScope :: UnifyT Type Check SkolemScope
673−newSkolemScope = SkolemScope . runUnknown <$> fresh'
676−-- Skolemize a type variable by replacing its instances with fresh skolem constants
678−skolemize :: String -> Int -> SkolemScope -> Type -> Type
679−skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
682−-- Introduce skolem scope at every occurence of a ForAll
684−introduceSkolemScope :: Type -> UnifyT Type Check Type
685−introduceSkolemScope = everywhereM (mkM go)
687− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
688− go other = return other
691−-- Check the type of a value, rethrowing errors to provide a better error message
693−check :: Value -> Type -> UnifyT Type Check Value
694−check val ty = rethrow errorMessage $ check' val ty
697− "Error checking type of term " ++
698− prettyPrintValue val ++
700− prettyPrintType ty ++
705−-- Check the type of a value
707−check' :: Value -> Type -> UnifyT Type Check Value
708−check' val (ForAll ident ty _) = do
709− scope <- newSkolemScope
710− sko <- newSkolemConstant
711− let sk = skolemize ident sko scope ty
712− val' <- check val sk
713− return $ TypedValue True val' (ForAll ident ty (Just scope))
714−check' val t@(ConstrainedType constraints ty) = do
716− Just moduleName <- checkCurrentModule <$> get
717− dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
718− n <- liftCheck freshDictionaryName
719− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
720− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
721− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
722− constraints) $ check val ty
723− return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
724−check' val (SaturatedTypeSynonym name args) = do
725− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
726− val' <- check val ty
727− return $ TypedValue True val' ty
728−check' val u@(TUnknown _) = do
729− val'@(TypedValue _ _ ty) <- infer val
730− -- Don't unify an unknown with an inferred polytype
731− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
733− return $ TypedValue True val'' ty'
734−check' v@(NumericLiteral _) t | t == tyNumber =
735− return $ TypedValue True v t
736−check' v@(StringLiteral _) t | t == tyString =
737− return $ TypedValue True v t
738−check' v@(BooleanLiteral _) t | t == tyBoolean =
739− return $ TypedValue True v t
740−check' (ArrayLiteral vals) t@(TypeApp a ty) | a == tyArray = do
741− array <- ArrayLiteral <$> forM vals (`check` ty)
742− return $ TypedValue True array t
743−check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
744− Just moduleName <- checkCurrentModule <$> get
745− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
746− return $ TypedValue True (Abs (Left arg) ret') ty
747−check' (Abs (Right _) _) _ = error "Binder was not desugared"
748−check' (App f arg) ret = do
749− f'@(TypedValue _ _ ft) <- infer f
750− (ret', app) <- checkFunctionApplication f' ft arg
751− subsumes Nothing ret' ret
752− return $ TypedValue True app ret
753−check' v@(Var var) ty = do
754− Just moduleName <- checkCurrentModule <$> get
755− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
756− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
757− v' <- subsumes (Just v) repl ty'
759− Nothing -> throwError "Unable to check type subsumption"
760− Just v'' -> return $ TypedValue True v'' ty'
761−check' (TypedValue checkType val ty1) ty2 = do
762− Just moduleName <- checkCurrentModule <$> get
763− kind <- liftCheck $ kindOf moduleName ty1
764− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
765− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
766− val' <- subsumes (Just val) ty1' ty2
768− Nothing -> throwError "Unable to check type subsumption"
770− val''' <- if checkType then check val'' ty1 else return val''
771− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
772−check' (Case vals binders) ret = do
773− vals' <- mapM infer vals
774− let ts = map (\(TypedValue _ _ t) -> t) vals'
775− binders' <- checkBinders ts ret binders
776− return $ TypedValue True (Case vals' binders') ret
777−check' (IfThenElse cond th el) ty = do
778− cond' <- check cond tyBoolean
781− return $ TypedValue True (IfThenElse cond' th' el') ty
782−check' (ObjectLiteral ps) t@(Object row) = do
783− ensureNoDuplicateProperties ps
784− ps' <- checkProperties ps row False
785− return $ TypedValue True (ObjectLiteral ps') t
786−check' (ObjectUpdate obj ps) t@(Object row) = do
787− ensureNoDuplicateProperties ps
788− us <- zip (map fst ps) <$> replicateM (length ps) fresh
789− let (propsToCheck, rest) = rowToList row
790− propsToRemove = map fst ps
791− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
792− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
793− ps' <- checkProperties ps row True
794− return $ TypedValue True (ObjectUpdate obj' ps') t
795−check' (Accessor prop val) ty = do
797− val' <- check val (Object (RCons prop ty rest))
798− return $ TypedValue True (Accessor prop val') ty
799−check' (Constructor c) ty = do
801− Just moduleName <- checkCurrentModule <$> get
802− case M.lookup c (dataConstructors env) of
803− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
805− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
806− _ <- subsumes Nothing repl ty
807− return $ TypedValue True (Constructor c) ty
808−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
811−-- Check the type of a collection of named record fields
813−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
815−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
816−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
817− go [] [] REmpty = return []
818− go [] [] u@(TUnknown _) = do u =?= REmpty
820− go [] [] (Skolem _ _) | lax = return []
821− go [] ((p, _): _) _ | lax = return []
822− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
823− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
824− go ((p,v):ps') [] u@(TUnknown _) = do
825− v'@(TypedValue _ _ ty) <- infer v
827− u =?= RCons p ty rest
828− ps'' <- go ps' [] rest
829− return $ (p, v') : ps''
830− go ((p,v):ps') ts r =
833− v'@(TypedValue _ _ ty) <- infer v
835− r =?= RCons p ty rest
836− ps'' <- go ps' ts rest
837− return $ (p, v') : ps''
840− ps'' <- go ps' (delete (p, ty) ts) r
841− return $ (p, v') : ps''
842− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
845−-- Check the type of a function application, rethrowing errors to provide a better error message
847−checkFunctionApplication :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
848−checkFunctionApplication fn fnTy arg = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg
850− errorMessage msg = "Error applying function of type "
851− ++ prettyPrintType fnTy
852− ++ " to argument " ++ prettyPrintValue arg
856−-- Check the type of a function application
858−checkFunctionApplication' :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
859−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg = do
860− tyFunction' =?= tyFunction
861− arg' <- check arg argTy
862− return (retTy, App fn arg')
863−checkFunctionApplication' fn (ForAll ident ty _) arg = do
864− replaced <- replaceVarWithUnknown ident ty
865− checkFunctionApplication fn replaced arg
866−checkFunctionApplication' fn u@(TUnknown _) arg = do
868− TypedValue _ arg' t <- infer arg
869− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
870− return $ TypedValue True arg'' t'
871− let ty = (\(TypedValue _ _ t) -> t) arg'
873− u =?= function ty ret
874− return (ret, App fn arg')
875−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg = do
876− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
877− checkFunctionApplication fn ty arg
878−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg = do
880− dicts <- getTypeClassDictionaries
881− Just moduleName <- checkCurrentModule <$> get
882− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) constraints)) fnTy arg
883−checkFunctionApplication' _ fnTy arg = throwError $ "Cannot apply a function of type "
884− ++ prettyPrintType fnTy
885− ++ " to argument " ++ prettyPrintValue arg
888−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
890−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
891−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
893− errorMessage msg = "Error checking that type "
894− ++ prettyPrintType ty1
895− ++ " subsumes type "
896− ++ prettyPrintType ty2
900−-- Check whether one type subsumes another
902−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
903−subsumes' val (ForAll ident ty1 _) ty2 = do
904− replaced <- replaceVarWithUnknown ident ty1
905− subsumes val replaced ty2
906−subsumes' val ty1 (ForAll ident ty2 sco) =
909− sko <- newSkolemConstant
910− let sk = skolemize ident sko sco' ty2
912− Nothing -> throwError "Skolem variable scope is unspecified"
913−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
914− subsumes Nothing arg2 arg1
915− subsumes Nothing ret1 ret2
917−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
918− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
919− subsumes val ty1 ty2
920−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
921− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
922− subsumes val ty1 ty2
923−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
925− dicts <- getTypeClassDictionaries
926− Just moduleName <- checkCurrentModule <$> get
927− _ <- subsumes' Nothing ty1 ty2
928− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) constraints)
929−subsumes' val (Object r1) (Object r2) = do
931− (ts1, r1') = rowToList r1
932− (ts2, r2') = rowToList r2
933− ts1' = sortBy (comparing fst) ts1
934− ts2' = sortBy (comparing fst) ts2
935− go ts1' ts2' r1' r2'
938− go [] ts2 r1' r2' = r1' =?= rowFromList (ts2, r2')
939− go ts1 [] r1' r2' = r2' =?= rowFromList (ts1, r1')
940− go ((p1, ty1) : ts1) ((p2, ty2) : ts2) r1' r2'
941− | p1 == p2 = do subsumes Nothing ty1 ty2
943− | p1 < p2 = do rest <- fresh
944− r2' =?= RCons p1 ty1 rest
945− go ts1 ((p2, ty2) : ts2) r1' rest
946− | p1 > p2 = do rest <- fresh
947− r1' =?= RCons p2 ty2 rest
948− go ((p1, ty1) : ts1) ts2 rest r2'
949−subsumes' val ty1 ty2@(Object _) = subsumes val ty2 ty1
950−subsumes' val ty1 ty2 = do