@@ -1,1018 +0,0 @@
1−-----------------------------------------------------------------------------
3−-- Module : Language.PureScript.TypeChecker.Types
4−-- Copyright : (c) Phil Freeman 2013
7−-- Maintainer : Phil Freeman <paf31@cantab.net>
8−-- Stability : experimental
12−-- This module implements the type checker
14−-----------------------------------------------------------------------------
16−{-# OPTIONS_GHC -fno-warn-orphans #-}
17−{-# LANGUAGE DeriveDataTypeable #-}
18−{-# LANGUAGE FlexibleContexts #-}
19−{-# LANGUAGE MultiParamTypeClasses #-}
21−module Language.PureScript.TypeChecker.Types (
26− The following functions represent the corresponding type checking judgements:
29− Synthesize a type for a value
32− Check a value has a given type
35− Check an object with a given type contains specified properties
37− checkFunctionApplication
38− Check a function of a given type returns a value of another type when applied to its arguments
41− Check a type subsumes another type
45−import Data.Maybe (maybeToList, isNothing, isJust, fromMaybe)
46−import qualified Data.Data as D
48− (everythingWithContext, mkM, everywhereM, everything, mkT,
49− something, everywhere, mkQ)
50−import Data.Generics.Extras
52−import Language.PureScript.Values
53−import Language.PureScript.Types
54−import Language.PureScript.Kinds
55−import Language.PureScript.Names
56−import Language.PureScript.TypeChecker.Monad
57−import Language.PureScript.TypeChecker.Kinds
58−import Language.PureScript.TypeChecker.Synonyms
59−import Language.PureScript.Pretty
61−import Control.Monad.State
62−import Control.Monad.Error
63−import Control.Monad.Reader
64−import Control.Monad.Unify
66−import Control.Applicative
67−import Control.Arrow (Arrow(..))
69−import qualified Data.Map as M
70−import Data.Function (on)
72−instance Partial Type where
74− isUnknown (TUnknown u) = Just u
75− isUnknown _ = Nothing
77−instance Unifiable Check Type where
81−-- Unify two types, updating the current substitution
83−unifyTypes :: Type -> Type -> UnifyT Type Check ()
84−unifyTypes t1 t2 = rethrow (\e -> "Error unifying type " ++ prettyPrintType t1 ++ " with type " ++ prettyPrintType t2 ++ ":\n" ++ e) $ do
87− unifyTypes' (TUnknown u1) (TUnknown u2) | u1 == u2 = return ()
88− unifyTypes' (TUnknown u) t = u =:= t
89− unifyTypes' t (TUnknown u) = u =:= t
90− unifyTypes' (SaturatedTypeSynonym name args) ty = do
91− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ args
93− unifyTypes' ty s@(SaturatedTypeSynonym _ _) = s `unifyTypes` ty
94− unifyTypes' (ForAll ident1 ty1 sc1) (ForAll ident2 ty2 sc2) =
96− (Just sc1', Just sc2') -> do
97− sko <- newSkolemConstant
98− let sk1 = skolemize ident1 sko sc1' ty1
99− let sk2 = skolemize ident2 sko sc2' ty2
100− sk1 `unifyTypes` sk2
101− _ -> throwError (prettyPrintType ty1)
102− unifyTypes' (ForAll ident ty1 (Just sc)) ty2 = do
103− sko <- newSkolemConstant
104− let sk = skolemize ident sko sc ty1
106− unifyTypes' (ForAll _ _ _) _ = throwError "Skolem variable scope is unspecified"
107− unifyTypes' ty f@(ForAll _ _ _) = f `unifyTypes` ty
108− unifyTypes' (Object row1) (Object row2) = row1 =?= row2
109− unifyTypes' (TypeVar v1) (TypeVar v2) | v1 == v2 = return ()
110− unifyTypes' (TypeConstructor c1) (TypeConstructor c2) = do
112− Just moduleName <- checkCurrentModule <$> get
113− guardWith ("Cannot unify " ++ show c1 ++ " with " ++ show c2 ++ ".") (typeConstructorsAreEqual env moduleName c1 c2)
114− unifyTypes' (TypeApp t3 t4) (TypeApp t5 t6) = do
117− unifyTypes' (Skolem s1 _) (Skolem s2 _) | s1 == s2 = return ()
118− unifyTypes' r1@(RCons _ _ _) r2 = unifyRows r1 r2
119− unifyTypes' r1 r2@(RCons _ _ _) = unifyRows r1 r2
120− unifyTypes' r1@REmpty r2 = unifyRows r1 r2
121− unifyTypes' r1 r2@REmpty = unifyRows r1 r2
122− unifyTypes' t3 t4 = throwError $ "Cannot unify " ++ prettyPrintType t3 ++ " with " ++ prettyPrintType t4 ++ "."
125−-- Unify two rows, updating the current substitution
127−-- Common labels are first identified, and unified. Remaining labels and types are unified with a
128−-- trailing row unification variable, if appropriate, otherwise leftover labels result in a unification
131−unifyRows :: Type -> Type -> UnifyT Type Check ()
134− (s1, r1') = rowToList r1
135− (s2, r2') = rowToList r2
136− int = [ (t1, t2) | (name, t1) <- s1, (name', t2) <- s2, name == name' ]
137− sd1 = [ (name, t1) | (name, t1) <- s1, name `notElem` map fst s2 ]
138− sd2 = [ (name, t2) | (name, t2) <- s2, name `notElem` map fst s1 ]
140− forM_ int (uncurry (=?=))
141− unifyRows' sd1 r1' sd2 r2'
143− unifyRows' :: [(String, Type)] -> Type -> [(String, Type)] -> Type -> UnifyT Type Check ()
144− unifyRows' [] (TUnknown u) sd r = u =:= rowFromList (sd, r)
145− unifyRows' sd r [] (TUnknown u) = u =:= rowFromList (sd, r)
146− unifyRows' ((name, ty):row) r others u@(TUnknown un) = do
148− forM_ row $ \(_, t) -> occursCheck un t
150− u =?= RCons name ty u'
151− unifyRows' row r others u'
152− unifyRows' [] REmpty [] REmpty = return ()
153− unifyRows' [] (TypeVar v1) [] (TypeVar v2) | v1 == v2 = return ()
154− unifyRows' [] (Skolem s1 _) [] (Skolem s2 _) | s1 == s2 = return ()
155− unifyRows' sd3 r3 sd4 r4 = throwError $ "Cannot unify (" ++ prettyPrintRow (rowFromList (sd3, r3)) ++ ") with (" ++ prettyPrintRow (rowFromList (sd4, r4)) ++ ")."
158−-- Ensure type constructors are equal after canonicalization
160−typeConstructorsAreEqual :: Environment -> ModuleName -> Qualified ProperName -> Qualified ProperName -> Bool
161−typeConstructorsAreEqual env moduleName = (==) `on` canonicalizeType moduleName env
164−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
165−-- type class dictionaries and type annotations.
167−typesOf :: Maybe ModuleName -> ModuleName -> [(Ident, Value)] -> Check [(Ident, (Value, Type))]
168−typesOf mainModuleName moduleName vals = do
169− tys <- fmap tidyUp . liftUnify $ do
171− -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
172− es = map isTyped vals
173− -- Filter the typed and untyped declarations
174− typed = filter (isJust . snd . snd) es
175− untyped = filter (isNothing . snd . snd) es
176− -- Make a map of names to typed declarations
177− typedDict = map (\(ident, (_, Just (ty, _))) -> (ident, ty)) typed
178− -- Create fresh unification variables for the types of untyped declarations
179− untypedNames <- replicateM (length untyped) fresh
181− -- Make a map of names to the unification variables of untyped declarations
182− untypedDict = zip (map fst untyped) untypedNames
183− -- Create the dictionary of all name/type pairs, which will be added to the environment during type checking
184− dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, LocalVariable))) $ typedDict ++ untypedDict)
185− forM es $ \e@(_, (val, _)) -> do
186− -- If the declaration is a function, it has access to other values in the binding group.
187− -- If not, the generated code might fail at runtime since those values might be undefined.
188− let dict' = if isFunction val then dict else M.empty
189− triple@(_, (val, ty)) <- case e of
190− -- Typed declarations
191− (ident, (val, Just (ty, checkType))) -> do
193− kind <- liftCheck $ kindOf moduleName ty
194− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
195− -- Check the type with the new names in scope
196− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
197− val' <- bindNames dict' $ if checkType
198− then TypedValue True <$> check val ty' <*> pure ty'
199− else return (TypedValue False val ty')
200− return (ident, (val', ty'))
201− -- Untyped declarations
202− (ident, (val, Nothing)) -> do
203− -- Infer the type with the new names in scope
204− TypedValue _ val' ty <- bindNames dict' $ infer val
205− ty =?= fromMaybe (error "name not found in dictionary") (lookup ident untypedDict)
206− return (ident, (TypedValue True val' ty, ty))
207− -- If --main is enabled, need to check that `main` has type Eff eff a for some eff, a
208− when (Just moduleName == mainModuleName && fst e == Ident "main") $ do
209− [eff, a] <- replicateM 2 fresh
210− ty =?= TypeApp (TypeApp (TypeConstructor (Qualified (Just (ModuleName (ProperName "Eff"))) (ProperName "Eff"))) eff) a
211− -- Make sure unification variables do not escape
214− forM tys $ \(ident, (val, ty)) -> do
215− -- Replace type class dictionary placeholders with actual dictionaries
216− val' <- replaceTypeClassDictionaries moduleName val
217− -- Check skolem variables did not escape their scope
218− skolemEscapeCheck val'
219− -- Remove type synonyms placeholders, remove duplicate row fields, and replace
220− -- top-level unification variables with named type variables.
221− let val'' = overTypes (desaturateAllTypeSynonyms . setifyAll) val'
222− ty' = varIfUnknown . desaturateAllTypeSynonyms . setifyAll $ ty
223− return $ (ident, (val'', ty'))
225− -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
226− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
229−-- Check if a value introduces a function
231−isFunction :: Value -> Bool
232−isFunction (Abs _ _) = True
233−isFunction (TypedValue _ val _) = isFunction val
237−-- Check if a value contains a type annotation
239−isTyped :: (Ident, Value) -> (Ident, (Value, Maybe (Type, Bool)))
240−isTyped (name, TypedValue checkType value ty) = (name, (value, Just (ty, checkType)))
241−isTyped (name, value) = (name, (value, Nothing))
244−-- Map a function over type annotations appearing inside a value
246−overTypes :: (Type -> Type) -> Value -> Value
247−overTypes f = everywhere (mkT f)
250−-- Replace type class dictionary placeholders with inferred type class dictionaries
252−replaceTypeClassDictionaries :: ModuleName -> Value -> Check Value
253−replaceTypeClassDictionaries mn = everywhereM' (mkM go)
255− go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
256− go other = return other
259−-- Check that the current set of type class dictionaries entail the specified type class goal, and, if so,
260−-- return a type class dictionary reference.
262−entails :: ModuleName -> [TypeClassDictionaryInScope] -> (Qualified ProperName, Type) -> Check Value
263−entails moduleName context goal@(className, ty) = do
266− [] -> throwError $ "No " ++ show className ++ " instance found for " ++ prettyPrintType ty
267− (dict : _) -> return dict
269− go env (className', ty') =
270− [ mkDictionary (canonicalizeDictionary tcd) args
272− -- Choose type class dictionaries in scope in the current module
274− -- Make sure the type class name matches the one we are trying to satisfy
275− , typeConstructorsAreEqual env moduleName className' (tcdClassName tcd)
276− -- Make sure the type unifies with the type in the type instance definition
277− , subst <- maybeToList $ typeHeadsAreEqual moduleName env ty' (tcdInstanceType tcd)
278− -- Solve any necessary subgoals
279− , args <- solveSubgoals env subst (tcdDependencies tcd) ]
280− -- Create dictionaries for subgoals which still need to be solved by calling go recursively
281− -- E.g. the goal (Show a, Show b) => Show (Either a b) can be satisfied if the current type
282− -- unifies with Either a b, and we can satisfy the subgoals Show a and Show b recursively.
283− solveSubgoals :: Environment -> [(String, Type)] -> Maybe [(Qualified ProperName, Type)] -> [Maybe [Value]]
284− solveSubgoals _ _ Nothing = return Nothing
285− solveSubgoals env subst (Just subgoals) = do
286− dict <- mapM (go env) (map (id *** replaceAllTypeVars subst) subgoals)
288− -- Make a dictionary from subgoal dictionaries by applying the correct function
289− mkDictionary :: Qualified Ident -> Maybe [Value] -> Value
290− mkDictionary fnName Nothing = Var fnName
291− mkDictionary fnName (Just []) = App (Var fnName) (ObjectLiteral [])
292− mkDictionary fnName (Just dicts) = foldl App (Var fnName) dicts
293− -- Filter out type dictionaries which are in scope in the current module
294− filterModule :: TypeClassDictionaryInScope -> Bool
295− filterModule (TypeClassDictionaryInScope { tcdName = Qualified (Just mn) _ }) | mn == moduleName = True
296− filterModule (TypeClassDictionaryInScope { tcdName = Qualified Nothing _ }) = True
297− filterModule _ = False
298− -- Resolve a type class dictionary in scope to an actual value by following any (TCDAlias) pointers
299− -- which originated from module imports
300− canonicalizeDictionary :: TypeClassDictionaryInScope -> Qualified Ident
301− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDRegular, tcdName = nm }) = nm
302− canonicalizeDictionary (TypeClassDictionaryInScope { tcdType = TCDAlias nm }) = nm
305−-- Check whether the type heads of two types are equal (for the purposes of type class dictionary lookup),
306−-- and return a substitution from type variables to types which makes the type heads unify.
308−typeHeadsAreEqual :: ModuleName -> Environment -> Type -> Type -> Maybe [(String, Type)]
309−typeHeadsAreEqual _ _ (Skolem s1 _) (Skolem s2 _) | s1 == s2 = Just []
310−typeHeadsAreEqual _ _ (TypeVar v) t = Just [(v, t)]
311−typeHeadsAreEqual _ _ t (TypeVar v) = Just [(v, t)]
312−typeHeadsAreEqual m e (TypeConstructor c1) (TypeConstructor c2) | typeConstructorsAreEqual e m c1 c2 = Just []
313−typeHeadsAreEqual m e (TypeApp h1 (TypeVar v)) (TypeApp h2 arg) = (:) (v, arg) <$> typeHeadsAreEqual m e h1 h2
314−typeHeadsAreEqual m e t1@(TypeApp _ _) t2@(TypeApp _ (TypeVar _)) = typeHeadsAreEqual m e t2 t1
315−typeHeadsAreEqual m e (SaturatedTypeSynonym name args) t2 = case expandTypeSynonym' e m name args of
317− Right t1 -> typeHeadsAreEqual m e t1 t2
318−typeHeadsAreEqual _ _ _ _ = Nothing
321−-- Ensure unsolved unification variables do not escape
323−escapeCheck :: Value -> Type -> UnifyT Type Check ()
324−escapeCheck value ty = do
325− subst <- unifyCurrentSubstitution <$> UnifyT get
326− let visibleUnknowns = nub $ unknowns $ subst $? ty
327− let allUnknowns = findAllTypes value
328− forM_ allUnknowns $ \t -> do
329− let unsolvedUnknowns = nub . unknowns $ subst $? t
330− guardWith "Escape check fails" $ null $ unsolvedUnknowns \\ visibleUnknowns
333−-- Find all type annotations occuring inside a value
335−findAllTypes :: Value -> [Type]
336−findAllTypes = everything (++) (mkQ [] go)
338− go (TypedValue _ _ ty) = [ty]
342−-- Ensure skolem variables do not escape their scope
344−skolemEscapeCheck :: Value -> Check ()
345−skolemEscapeCheck (TypedValue False _ _) = return ()
346−skolemEscapeCheck root@(TypedValue _ _ _) =
347− -- Every skolem variable is created when a ForAll type is skolemized.
348− -- This determines the scope of that skolem variable, which is copied from the SkolemScope
349− -- field of the ForAll constructor.
350− -- We traverse the tree top-down, and collect any SkolemScopes introduced by ForAlls.
351− -- If a Skolem is encountered whose SkolemScope is not in the current list, we have found
352− -- an escaped skolem variable.
353− case everythingWithContext [] (++) (mkQ ((,) []) go) root of
355− ((binding, val) : _) -> throwError $ "Rigid/skolem type variable bound by " ++ maybe "<unknown>" prettyPrintValue binding ++ " has escaped at " ++ prettyPrintValue val
357− go :: Value -> [(SkolemScope, Value)] -> ([(Maybe Value, Value)], [(SkolemScope, Value)])
358− go val@(TypedValue _ _ (ForAll _ _ (Just sco))) scos = ([], (sco, val) : scos)
359− go val@(TypedValue _ _ ty) scos = case collectSkolems ty \\ map fst scos of
360− (sco : _) -> ([(findBindingScope sco, val)], scos)
363− collectSkolems :: Type -> [SkolemScope]
364− collectSkolems = nub . everything (++) (mkQ [] collect)
366− collect (Skolem _ scope) = [scope]
368− go _ scos = ([], scos)
369− findBindingScope :: SkolemScope -> Maybe Value
370− findBindingScope sco = something (mkQ Nothing go) root
372− go val@(TypedValue _ _ (ForAll _ _ (Just sco'))) | sco == sco' = Just val
374−skolemEscapeCheck val = throwError $ "Untyped value passed to skolemEscapeCheck: " ++ prettyPrintValue val
377−-- Ensure a row contains no duplicate labels
379−setify :: Type -> Type
380−setify = rowFromList . first (M.toList . M.fromList) . rowToList
383−-- \"Setify\" all rows occuring inside a value
385−setifyAll :: (D.Data d) => d -> d
386−setifyAll = everywhere (mkT setify)
389−-- Replace outermost unsolved unification variables with named type variables
391−varIfUnknown :: Type -> Type
393− let unks = nub $ unknowns ty
394− toName = (:) 't' . show
395− ty' = everywhere (mkT typeToVar) $ ty
396− typeToVar :: Type -> Type
397− typeToVar (TUnknown (Unknown u)) = TypeVar (toName u)
399− in mkForAll (sort . map (toName . runUnknown) $ unks) ty'
402−-- Replace named type variables with types
404−replaceAllTypeVars :: [(String, Type)] -> Type -> Type
405−replaceAllTypeVars = foldl' (\f (name, ty) -> replaceTypeVars name ty . f) id
408−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
409−-- or TypeClassDictionary values.
411−-- This is necessary during type checking to avoid unifying a polymorphic type with a
412−-- unification variable.
414−instantiatePolyTypeWithUnknowns :: Value -> Type -> UnifyT Type Check (Value, Type)
415−instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
416− ty' <- replaceVarWithUnknown ident ty
417− instantiatePolyTypeWithUnknowns val ty'
418−instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
420− Just moduleName <- checkCurrentModule <$> get
421− dicts <- getTypeClassDictionaries
422− (_, ty') <- instantiatePolyTypeWithUnknowns (error "Types under a constraint cannot themselves be constrained") ty
423− return (foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints)), ty')
424−instantiatePolyTypeWithUnknowns val ty = return (val, ty)
427−-- Replace a single type variable with a new unification variable
429−replaceVarWithUnknown :: String -> Type -> UnifyT Type Check Type
430−replaceVarWithUnknown ident ty = do
432− return $ replaceTypeVars ident tu $ ty
435−-- Replace fully applied type synonyms with the @SaturatedTypeSynonym@ data constructor, which helps generate
436−-- better error messages during unification.
438−replaceAllTypeSynonyms' :: (D.Data d) => Environment -> ModuleName -> d -> Either String d
439−replaceAllTypeSynonyms' env moduleName d =
441− syns = map (\((path, name), (args, _)) -> ((path, name), length args)) . M.toList $ typeSynonyms env
443− saturateAllTypeSynonyms env moduleName syns d
445−replaceAllTypeSynonyms :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => (D.Data d) => d -> m d
446−replaceAllTypeSynonyms d = do
448− Just moduleName <- checkCurrentModule <$> get
449− either throwError return $ replaceAllTypeSynonyms' env moduleName d
452−-- \"Desaturate\" @SaturatedTypeSynonym@s
454−desaturateAllTypeSynonyms :: (D.Data d) => d -> d
455−desaturateAllTypeSynonyms = everywhere (mkT replaceSaturatedTypeSynonym)
457− replaceSaturatedTypeSynonym (SaturatedTypeSynonym name args) = foldl TypeApp (TypeConstructor name) args
458− replaceSaturatedTypeSynonym t = t
461−-- Replace a type synonym and its arguments with the aliased type
463−expandTypeSynonym' :: Environment -> ModuleName -> Qualified ProperName -> [Type] -> Either String Type
464−expandTypeSynonym' env moduleName name args =
465− case M.lookup (canonicalizeType moduleName env name) (typeSynonyms env) of
466− Just (synArgs, body) -> do
467− let repl = replaceAllTypeVars (zip synArgs args) body
468− replaceAllTypeSynonyms' env moduleName repl
469− Nothing -> error "Type synonym was not defined"
471−expandTypeSynonym :: (Functor m, Monad m, MonadState CheckState m, MonadError String m) => Qualified ProperName -> [Type] -> m Type
472−expandTypeSynonym name args = do
474− Just moduleName <- checkCurrentModule <$> get
475− either throwError return $ expandTypeSynonym' env moduleName name args
478−-- Ensure a set of property names and value does not contain duplicate labels
480−ensureNoDuplicateProperties :: (MonadError String m) => [(String, Value)] -> m ()
481−ensureNoDuplicateProperties ps = guardWith "Duplicate property names" $ length (nub . map fst $ ps) == length ps
484−-- Infer a type for a value, rethrowing any error to provide a more useful error message
486−infer :: Value -> UnifyT Type Check Value
487−infer val = rethrow (\e -> "Error inferring type of term " ++ prettyPrintValue val ++ ":\n" ++ e) $ infer' val
490−-- Infer a type for a value
492−infer' :: Value -> UnifyT Type Check Value
493−infer' v@(NumericLiteral _) = return $ TypedValue True v tyNumber
494−infer' v@(StringLiteral _) = return $ TypedValue True v tyString
495−infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
496−infer' (ArrayLiteral vals) = do
497− ts <- mapM infer vals
499− forM_ ts $ \(TypedValue _ _ t) -> els =?= TypeApp tyArray t
500− return $ TypedValue True (ArrayLiteral ts) els
501−infer' (ObjectLiteral ps) = do
502− ensureNoDuplicateProperties ps
503− ts <- mapM (infer . snd) ps
504− let fields = zipWith (\name (TypedValue _ _ t) -> (name, t)) (map fst ps) ts
505− ty = Object $ rowFromList (fields, REmpty)
506− return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
507−infer' (ObjectUpdate o ps) = do
508− ensureNoDuplicateProperties ps
510− newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
511− let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
512− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
513− let oldTy = Object $ rowFromList (oldTys, row)
514− o' <- TypedValue True <$> check o oldTy <*> pure oldTy
515− return $ TypedValue True (ObjectUpdate o' newVals) $ Object $ rowFromList (newTys, row)
516−infer' (Accessor prop val) = do
517− typed@(TypedValue _ _ objTy) <- infer val
518− propTy <- inferProperty objTy prop
523− _ <- subsumes Nothing objTy (Object (RCons prop field rest))
524− return $ TypedValue True (Accessor prop typed) field
525− Just ty -> return $ TypedValue True (Accessor prop typed) ty
526−infer' (Abs arg ret) = do
528− Just moduleName <- checkCurrentModule <$> get
529− bindLocalVariables moduleName [(arg, ty)] $ do
530− body@(TypedValue _ _ bodyTy) <- infer' ret
531− return $ TypedValue True (Abs arg body) $ function ty bodyTy
532−infer' (App f arg) = do
533− f'@(TypedValue _ _ ft) <- infer f
534− (ret, app) <- checkFunctionApplication f' ft arg
535− return $ TypedValue True app ret
536−infer' (Var var) = do
537− Just moduleName <- checkCurrentModule <$> get
538− ty <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
540− ConstrainedType constraints ty' -> do
542− dicts <- getTypeClassDictionaries
543− return $ TypedValue True (foldl App (Var var) (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) ty'
544− _ -> return $ TypedValue True (Var var) ty
545−infer' (Block ss) = do
547− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
548− guardWith "Block is missing a return statement" allCodePathsReturn
549− return $ TypedValue True (Block ss') ret
550−infer' v@(Constructor c) = do
552− Just moduleName <- checkCurrentModule <$> get
553− case M.lookup (qualify moduleName c) (dataConstructors env) of
554− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
555− Just (ty, _) -> do ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
556− return $ TypedValue True v ty'
557−infer' (Case vals binders) = do
558− ts <- mapM infer vals
560− binders' <- checkBinders (map (\(TypedValue _ _ t) -> t) ts) ret binders
561− return $ TypedValue True (Case ts binders') ret
562−infer' (IfThenElse cond th el) = do
563− cond' <- check cond tyBoolean
564− v2@(TypedValue _ _ t2) <- infer th
565− v3@(TypedValue _ _ t3) <- infer el
567− return $ TypedValue True (IfThenElse cond' v2 v3) t2
568−infer' (TypedValue checkType val ty) = do
569− Just moduleName <- checkCurrentModule <$> get
570− kind <- liftCheck $ kindOf moduleName ty
571− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
572− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
573− val' <- if checkType then check val ty' else return val
574− return $ TypedValue True val' ty'
575−infer' _ = error "Invalid argument to infer"
578−-- Infer the type of a property inside a record with a given type
580−inferProperty :: Type -> String -> UnifyT Type Check (Maybe Type)
581−inferProperty (Object row) prop = do
582− let (props, _) = rowToList row
583− return $ lookup prop props
584−inferProperty (SaturatedTypeSynonym name args) prop = do
585− replaced <- introduceSkolemScope <=< expandTypeSynonym name $ args
586− inferProperty replaced prop
587−inferProperty (ForAll ident ty _) prop = do
588− replaced <- replaceVarWithUnknown ident ty
589− inferProperty replaced prop
590−inferProperty _ _ = return Nothing
593−-- Infer the types of variables brought into scope by a binder
595−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
596−inferBinder _ NullBinder = return M.empty
597−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
598−inferBinder val (NumberBinder _) = val =?= tyNumber >> return M.empty
599−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
600−inferBinder val (VarBinder name) = return $ M.singleton name val
601−inferBinder val (ConstructorBinder ctor binders) = do
603− Just moduleName <- checkCurrentModule <$> get
604− case M.lookup (qualify moduleName ctor) (dataConstructors env) of
606− (_, fn) <- instantiatePolyTypeWithUnknowns (error "Data constructor types cannot contains constraints") ty
610− subsumes Nothing val ty
612− go (binder : binders) (TypeApp (TypeApp t obj) ret) | t == tyFunction =
613− M.union <$> inferBinder obj binder <*> go binders ret
614− go _ _ = throwError $ "Wrong number of arguments to constructor " ++ show ctor
615− _ -> throwError $ "Constructor " ++ show ctor ++ " is not defined"
616−inferBinder val (ObjectBinder props) = do
619− m1 <- inferRowProperties row rest props
623− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
624− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
625− inferRowProperties nrow row ((name, binder):binders) = do
627− m1 <- inferBinder propTy binder
628− m2 <- inferRowProperties nrow (RCons name propTy row) binders
629− return $ m1 `M.union` m2
630−inferBinder val (ArrayBinder binders) = do
632− m1 <- M.unions <$> mapM (inferBinder el) binders
633− val =?= TypeApp tyArray el
635−inferBinder val (ConsBinder headBinder tailBinder) = do
637− m1 <- inferBinder el headBinder
638− m2 <- inferBinder val tailBinder
639− val =?= TypeApp tyArray el
640− return $ m1 `M.union` m2
641−inferBinder val (NamedBinder name binder) = do
642− m <- inferBinder val binder
643− return $ M.insert name val m
646−-- Check the types of the return values in a set of binders in a case statement
648−checkBinders :: [Type] -> Type -> [([Binder], Maybe Guard, Value)] -> UnifyT Type Check [([Binder], Maybe Guard, Value)]
649−checkBinders _ _ [] = return []
650−checkBinders nvals ret ((binders, grd, val):bs) = do
651− Just moduleName <- checkCurrentModule <$> get
652− m1 <- M.unions <$> zipWithM inferBinder nvals binders
653− r <- bindLocalVariables moduleName (M.toList m1) $ do
654− val' <- TypedValue True <$> check val ret <*> pure ret
656− Nothing -> return (binders, Nothing, val')
658− g' <- check g tyBoolean
659− return (binders, Just g', val')
660− rs <- checkBinders nvals ret bs
664−-- Check that a local variable name is not already used
666−assignVariable :: Ident -> UnifyT Type Check ()
667−assignVariable name = do
668− env <- checkEnv <$> get
669− Just moduleName <- checkCurrentModule <$> get
670− case M.lookup (moduleName, name) (names env) of
671− Just _ -> UnifyT . lift . throwError $ "Variable with name " ++ show name ++ " already exists."
675−-- Check the type of the return values of a statement, returning whether or not the statement returns on
678−checkStatement :: M.Map Ident Type -> Type -> Statement -> UnifyT Type Check (Bool, M.Map Ident Type, Statement)
679−checkStatement mass _ (VariableIntroduction name val) = do
681− val'@(TypedValue _ _ t) <- infer val
682− return (False, M.insert name t mass, VariableIntroduction name val')
683−checkStatement mass _ (Assignment ident val) = do
684− val'@(TypedValue _ _ t) <- infer val
685− case M.lookup ident mass of
686− Nothing -> throwError $ "No local variable with name " ++ show ident
687− Just ty -> do t =?= ty
688− return (False, mass, Assignment ident val')
689−checkStatement mass ret (While val inner) = do
690− val' <- check val tyBoolean
691− (allCodePathsReturn, _, inner') <- checkBlock mass ret inner
692− return (allCodePathsReturn, mass, While val' inner')
693−checkStatement mass ret (If ifst) = do
694− (allCodePathsReturn, ifst') <- checkIfStatement mass ret ifst
695− return (allCodePathsReturn, mass, If ifst')
696−checkStatement mass ret (For ident start end inner) = do
697− Just moduleName <- checkCurrentModule <$> get
698− assignVariable ident
699− start' <- check start tyNumber
700− end' <- check end tyNumber
701− (allCodePathsReturn, _, inner') <- bindLocalVariables moduleName [(ident, tyNumber)] $ checkBlock mass ret inner
702− return (allCodePathsReturn, mass, For ident start' end' inner')
703−checkStatement mass ret (Return val) = do
704− val' <- check val ret
705− return (True, mass, Return (TypedValue True val' ret))
708−-- Check the type of an if-then-else statement
710−checkIfStatement :: M.Map Ident Type -> Type -> IfStatement -> UnifyT Type Check (Bool, IfStatement)
711−checkIfStatement mass ret (IfStatement val thens Nothing) = do
712− val' <- check val tyBoolean
713− (_, _, thens') <- checkBlock mass ret thens
714− return (False, IfStatement val' thens' Nothing)
715−checkIfStatement mass ret (IfStatement val thens (Just elses)) = do
716− val' <- check val tyBoolean
717− (allCodePathsReturn1, _, thens') <- checkBlock mass ret thens
718− (allCodePathsReturn2, elses') <- checkElseStatement mass ret elses
719− return (allCodePathsReturn1 && allCodePathsReturn2, IfStatement val' thens' (Just elses'))
722−-- Check the type of an else statement
724−checkElseStatement :: M.Map Ident Type -> Type -> ElseStatement -> UnifyT Type Check (Bool, ElseStatement)
725−checkElseStatement mass ret (Else elses) = do
726− (allCodePathsReturn, _, elses') <- checkBlock mass ret elses
727− return (allCodePathsReturn, Else elses')
728−checkElseStatement mass ret (ElseIf ifst) = (id *** ElseIf) <$> checkIfStatement mass ret ifst
731−-- Check the type of the return value of a block of statements
733−checkBlock :: M.Map Ident Type -> Type -> [Statement] -> UnifyT Type Check (Bool, M.Map Ident Type, [Statement])
734−checkBlock mass _ [] = return (False, mass, [])
735−checkBlock mass ret (s:ss) = do
736− Just moduleName <- checkCurrentModule <$> get
737− (b1, mass1, s') <- checkStatement mass ret s
738− bindLocalVariables moduleName (M.toList mass1) $ case (b1, ss) of
739− (True, []) -> return (True, mass1, [s'])
740− (True, _) -> throwError "Unreachable code"
742− (b, m, ss'') <- checkBlock mass1 ret ss'
743− return (b, m, s':ss'')
746−-- Generate a new skolem constant
748−newSkolemConstant :: UnifyT Type Check Int
749−newSkolemConstant = runUnknown <$> fresh'
752−-- Generate a new skolem scope
754−newSkolemScope :: UnifyT Type Check SkolemScope
755−newSkolemScope = SkolemScope . runUnknown <$> fresh'
758−-- Skolemize a type variable by replacing its instances with fresh skolem constants
760−skolemize :: String -> Int -> SkolemScope -> Type -> Type
761−skolemize ident sko scope = replaceTypeVars ident (Skolem sko scope)
764−-- Introduce skolem scope at every occurence of a ForAll
766−introduceSkolemScope :: Type -> UnifyT Type Check Type
767−introduceSkolemScope = everywhereM (mkM go)
769− go (ForAll ident ty Nothing) = ForAll ident ty <$> (Just <$> newSkolemScope)
770− go other = return other
773−-- Check the type of a value, rethrowing errors to provide a better error message
775−check :: Value -> Type -> UnifyT Type Check Value
776−check val ty = rethrow errorMessage $ check' val ty
779− "Error checking type of term " ++
780− prettyPrintValue val ++
782− prettyPrintType ty ++
787−-- Check the type of a value
789−check' :: Value -> Type -> UnifyT Type Check Value
790−check' val t@(ForAll ident ty _) = do
791− scope <- newSkolemScope
792− sko <- newSkolemConstant
793− let sk = skolemize ident sko scope ty
794− val' <- check val sk
795− return $ TypedValue True val' (ForAll ident ty (Just scope))
796−check' val t@(ConstrainedType constraints ty) = do
798− Just moduleName <- checkCurrentModule <$> get
799− dictNames <- flip mapM constraints $ \(Qualified _ (ProperName className), _) -> do
800− n <- liftCheck freshDictionaryName
801− return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
802− val' <- withTypeClassDictionaries (zipWith (\name (className, instanceTy) ->
803− TypeClassDictionaryInScope name className instanceTy Nothing TCDRegular) (map (Qualified Nothing) dictNames)
804− (qualifyAllUnqualifiedNames moduleName env constraints)) $
806− return $ TypedValue True (foldr Abs val' dictNames) t
807−check' val t@(SaturatedTypeSynonym name args) = do
808− ty <- introduceSkolemScope <=< expandTypeSynonym name $ args
809− val' <- check val ty
810− return $ TypedValue True val' ty
811−check' val u@(TUnknown _) = do
812− val'@(TypedValue _ _ ty) <- infer val
813− -- Don't unify an unknown with an inferred polytype
814− (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
816− return $ TypedValue True val'' ty'
817−check' v@(NumericLiteral _) t | t == tyNumber =
818− return $ TypedValue True v t
819−check' v@(StringLiteral _) t | t == tyString =
820− return $ TypedValue True v t
821−check' v@(BooleanLiteral _) t | t == tyBoolean =
822− return $ TypedValue True v t
823−check' (ArrayLiteral vals) t@(TypeApp a ty) | a == tyArray = do
824− arr <- ArrayLiteral <$> forM vals (\val -> check val ty)
825− return $ TypedValue True arr t
826−check' (Abs arg ret) ty@(TypeApp (TypeApp t argTy) retTy) | t == tyFunction = do
827− Just moduleName <- checkCurrentModule <$> get
828− ret' <- bindLocalVariables moduleName [(arg, argTy)] $ check ret retTy
829− return $ TypedValue True (Abs arg ret') ty
830−check' (App f arg) ret = do
831− f'@(TypedValue _ _ ft) <- infer f
832− (ret', app) <- checkFunctionApplication f' ft arg
833− subsumes Nothing ret' ret
834− return $ TypedValue True app ret
835−check' v@(Var var) ty = do
836− Just moduleName <- checkCurrentModule <$> get
837− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< lookupVariable moduleName $ var
838− ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty
839− v' <- subsumes (Just v) repl ty'
841− Nothing -> throwError "Unable to check type subsumption"
842− Just v'' -> return $ TypedValue True v'' ty'
843−check' (TypedValue checkType val ty1) ty2 = do
844− Just moduleName <- checkCurrentModule <$> get
845− kind <- liftCheck $ kindOf moduleName ty1
846− guardWith ("Expected type of kind *, was " ++ prettyPrintKind kind) $ kind == Star
847− ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
848− val' <- subsumes (Just val) ty1' ty2
850− Nothing -> throwError "Unable to check type subsumption"
852− val''' <- if checkType then check val'' ty1 else return val''
853− return $ TypedValue checkType (TypedValue True val''' ty1) ty2
854−check' (Case vals binders) ret = do
855− vals' <- mapM infer vals
856− let ts = map (\(TypedValue _ _ t) -> t) vals'
857− binders' <- checkBinders ts ret binders
858− return $ TypedValue True (Case vals' binders') ret
859−check' (IfThenElse cond th el) ty = do
860− cond' <- check cond tyBoolean
863− return $ TypedValue True (IfThenElse cond' th' el') ty
864−check' (ObjectLiteral ps) t@(Object row) = do
865− ensureNoDuplicateProperties ps
866− ps' <- checkProperties ps row False
867− return $ TypedValue True (ObjectLiteral ps') t
868−check' (ObjectUpdate obj ps) t@(Object row) = do
869− ensureNoDuplicateProperties ps
870− us <- zip (map fst ps) <$> replicateM (length ps) fresh
871− let (propsToCheck, rest) = rowToList row
872− propsToRemove = map fst ps
873− remainingProps = filter (\(p, _) -> p `notElem` propsToRemove) propsToCheck
874− obj' <- check obj (Object (rowFromList (us ++ remainingProps, rest)))
875− ps' <- checkProperties ps row True
876− return $ TypedValue True (ObjectUpdate obj' ps') t
877−check' (Accessor prop val) ty = do
879− val' <- check val (Object (RCons prop ty rest))
880− return $ TypedValue True (Accessor prop val') ty
881−check' (Block ss) ret = do
882− (allCodePathsReturn, _, ss') <- checkBlock M.empty ret ss
883− guardWith "Block is missing a return statement" allCodePathsReturn
884− return $ TypedValue True (Block ss') ret
885−check' (Constructor c) ty = do
887− Just moduleName <- checkCurrentModule <$> get
888− case M.lookup (qualify moduleName c) (dataConstructors env) of
889− Nothing -> throwError $ "Constructor " ++ show c ++ " is undefined"
891− repl <- introduceSkolemScope <=< replaceAllTypeSynonyms $ ty1
892− _ <- subsumes Nothing repl ty
893− return $ TypedValue True (Constructor c) ty
894−check' val ty = throwError $ prettyPrintValue val ++ " does not have type " ++ prettyPrintType ty
897−-- Check the type of a collection of named record fields
899−-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
901−checkProperties :: [(String, Value)] -> Type -> Bool -> UnifyT Type Check [(String, Value)]
902−checkProperties ps row lax = let (ts, r') = rowToList row in go ps ts r' where
903− go [] [] REmpty = return []
904− go [] [] u@(TUnknown _) = do u =?= REmpty
906− go [] [] (Skolem _ _) | lax = return []
907− go [] ((p, _): _) _ | lax = return []
908− | otherwise = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have property " ++ p
909− go ((p,_):_) [] REmpty = throwError $ "Property " ++ p ++ " is not present in closed object type " ++ prettyPrintRow row
910− go ((p,v):ps') [] u@(TUnknown _) = do
911− v'@(TypedValue _ _ ty) <- infer v
913− u =?= RCons p ty rest
914− ps'' <- go ps' [] rest
915− return $ (p, v') : ps''
916− go ((p,v):ps') ts r =
919− v'@(TypedValue _ _ ty) <- infer v
921− r =?= RCons p ty rest
922− ps'' <- go ps' ts rest
923− return $ (p, v') : ps''
926− ps'' <- go ps' (delete (p, ty) ts) r
927− return $ (p, v') : ps''
928− go _ _ _ = throwError $ prettyPrintValue (ObjectLiteral ps) ++ " does not have type " ++ prettyPrintType (Object row)
931−-- Check the type of a function application, rethrowing errors to provide a better error message
933−checkFunctionApplication :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
934−checkFunctionApplication fn fnTy arg = rethrow errorMessage $ checkFunctionApplication' fn fnTy arg
936− errorMessage msg = "Error applying function of type "
937− ++ prettyPrintType fnTy
938− ++ " to argument " ++ prettyPrintValue arg
942−-- Check the type of a function application
944−checkFunctionApplication' :: Value -> Type -> Value -> UnifyT Type Check (Type, Value)
945−checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg = do
946− tyFunction' =?= tyFunction
947− arg' <- check arg argTy
948− return (retTy, App fn arg')
949−checkFunctionApplication' fn (ForAll ident ty _) arg = do
950− replaced <- replaceVarWithUnknown ident ty
951− checkFunctionApplication fn replaced arg
952−checkFunctionApplication' fn u@(TUnknown _) arg = do
954− TypedValue _ arg' t <- infer arg
955− (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
956− return $ TypedValue True arg'' t'
957− let ty = (\(TypedValue _ _ t) -> t) arg'
959− u =?= function ty ret
960− return (ret, App fn arg')
961−checkFunctionApplication' fn (SaturatedTypeSynonym name tyArgs) arg = do
962− ty <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
963− checkFunctionApplication fn ty arg
964−checkFunctionApplication' fn (ConstrainedType constraints fnTy) arg = do
966− dicts <- getTypeClassDictionaries
967− Just moduleName <- checkCurrentModule <$> get
968− checkFunctionApplication' (foldl App fn (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))) fnTy arg
969−checkFunctionApplication' _ fnTy arg = throwError $ "Cannot apply a function of type "
970− ++ prettyPrintType fnTy
971− ++ " to argument " ++ prettyPrintValue arg
974−-- Check whether one type subsumes another, rethrowing errors to provide a better error message
976−subsumes :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
977−subsumes val ty1 ty2 = rethrow errorMessage $ subsumes' val ty1 ty2
979− errorMessage msg = "Error checking that type "
980− ++ prettyPrintType ty1
981− ++ " subsumes type "
982− ++ prettyPrintType ty2
986−-- Check whether one type subsumes another
988−subsumes' :: Maybe Value -> Type -> Type -> UnifyT Type Check (Maybe Value)
989−subsumes' val (ForAll ident ty1 _) ty2 = do
990− replaced <- replaceVarWithUnknown ident ty1
991− subsumes val replaced ty2
992−subsumes' val ty1 (ForAll ident ty2 sco) =
995− sko <- newSkolemConstant
996− let sk = skolemize ident sko sco' ty2
998− Nothing -> throwError "Skolem variable scope is unspecified"
999−subsumes' val (TypeApp (TypeApp f1 arg1) ret1) (TypeApp (TypeApp f2 arg2) ret2) | f1 == tyFunction && f2 == tyFunction = do
1000− subsumes Nothing arg2 arg1
1001− subsumes Nothing ret1 ret2
1003−subsumes' val (SaturatedTypeSynonym name tyArgs) ty2 = do
1004− ty1 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1005− subsumes val ty1 ty2
1006−subsumes' val ty1 (SaturatedTypeSynonym name tyArgs) = do
1007− ty2 <- introduceSkolemScope <=< expandTypeSynonym name $ tyArgs
1008− subsumes val ty1 ty2
1009−subsumes' (Just val) (ConstrainedType constraints ty1) ty2 = do
1011− dicts <- getTypeClassDictionaries
1012− Just moduleName <- checkCurrentModule <$> get
1013− _ <- subsumes' Nothing ty1 ty2
1014− return . Just $ foldl App val (map (flip TypeClassDictionary dicts) (qualifyAllUnqualifiedNames moduleName env constraints))
1015−subsumes' val ty1 ty2 = do