@@ -14,6 +14,7 @@
1414-----------------------------------------------------------------------------
1515
1616{-# LANGUAGE FlexibleContexts #-}
17+{-# LANGUAGE ScopedTypeVariables #-}
1718{-# LANGUAGE MultiParamTypeClasses #-}
1819{-# LANGUAGE OverloadedStrings #-}
1920{-# LANGUAGE CPP #-}
@@ -47,10 +48,9 @@ import qualified Data.Map as M
4748import Control.Applicative
4849#endif
4950import Control.Monad
50−import Control.Monad.State
51−import Control.Monad.Unify
51+import Control.Monad.State.Class (MonadState(..), gets)
5252import Control.Monad.Error.Class (MonadError(..))
53−import Control.Monad.Writer.Class (tell)
53+import Control.Monad.Writer.Class (MonadWriter(..))
5454
5555import Language.PureScript.Crash
5656import Language.PureScript.AST
@@ -70,11 +70,13 @@ import Language.PureScript.TypeChecker.Unify
7070import Language.PureScript.TypeClassDictionaries
7171import Language.PureScript.Types
7272
73−-- |
74−-- Infer the types of multiple mutually-recursive values, and return elaborated values including
73+-- | Infer the types of multiple mutually-recursive values, and return elaborated values including
7574-- type class dictionaries and type annotations.
76−--
77−typesOf :: ModuleName -> [(Ident, Expr)] -> Check [(Ident, (Expr, Type))]
75+typesOf ::
76+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
77+ ModuleName ->
78+ [(Ident, Expr)] ->
79+ m [(Ident, (Expr, Type))]
7880typesOf moduleName vals = do
7981 tys <- fmap tidyUp . liftUnifyWarnings replace $ do
8082 (untyped, typed, dict, untypedDict) <- typeDictionaryForBindingGroup moduleName vals
@@ -92,17 +94,21 @@ typesOf moduleName vals = do
9294 return (ident, (val', varIfUnknown ty))
9395 where
9496 -- Apply the substitution that was returned from runUnify to both types and (type-annotated) values
95− tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (sub $?) val, sub $? ty))) ts
97+ tidyUp (ts, sub) = map (\(i, (val, ty)) -> (i, (overTypes (substituteType sub) val, substituteType sub ty))) ts
9698 -- Replace all the wildcards types with their inferred types
97− replace sub (ErrorMessage hints (WildcardInferredType ty)) = ErrorMessage hints $ WildcardInferredType (sub $? ty)
98− replace sub (ErrorMessage hints (MissingTypeDeclaration name ty)) = ErrorMessage hints $ MissingTypeDeclaration name (varIfUnknown (sub $? ty))
99+ replace sub (ErrorMessage hints (WildcardInferredType ty)) = ErrorMessage hints . WildcardInferredType $ substituteType sub ty
100+ replace sub (ErrorMessage hints (MissingTypeDeclaration name ty)) = ErrorMessage hints $ MissingTypeDeclaration name (varIfUnknown (substituteType sub ty))
99101 replace _ em = em
100102
101103type TypeData = M.Map (ModuleName, Ident) (Type, NameKind, NameVisibility)
102104
103105type UntypedData = [(Ident, Type)]
104106
105−typeDictionaryForBindingGroup :: ModuleName -> [(Ident, Expr)] -> UnifyT Type Check ([(Ident, Expr)], [(Ident, (Expr, Type, Bool))], TypeData, UntypedData)
107+typeDictionaryForBindingGroup ::
108+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
109+ ModuleName ->
110+ [(Ident, Expr)] ->
111+ m ([(Ident, Expr)], [(Ident, (Expr, Type, Bool))], TypeData, UntypedData)
106112typeDictionaryForBindingGroup moduleName vals = do
107113 let
108114 -- Map each declaration to a name/value pair, with an optional type, if the declaration is typed
@@ -114,7 +120,7 @@ typeDictionaryForBindingGroup moduleName vals = do
114120 typedDict = map (\(ident, (_, ty, _)) -> (ident, ty)) typed
115121
116122 -- Create fresh unification variables for the types of untyped declarations
117− untypedNames <- replicateM (length untyped) fresh
123+ untypedNames <- replicateM (length untyped) freshType
118124
119125 let
120126 -- Make a map of names to the unification variables of untyped declarations
@@ -123,12 +129,17 @@ typeDictionaryForBindingGroup moduleName vals = do
123129 dict = M.fromList (map (\(ident, ty) -> ((moduleName, ident), (ty, Private, Undefined))) $ typedDict ++ untypedDict)
124130 return (untyped, typed, dict, untypedDict)
125131
126−checkTypedBindingGroupElement :: ModuleName -> (Ident, (Expr, Type, Bool)) -> TypeData -> UnifyT Type Check (Ident, (Expr, Type))
132+checkTypedBindingGroupElement ::
133+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
134+ ModuleName ->
135+ (Ident, (Expr, Type, Bool)) ->
136+ TypeData ->
137+ m (Ident, (Expr, Type))
127138checkTypedBindingGroupElement mn (ident, (val', ty, checkType)) dict = do
128139 -- Replace type wildcards
129140 ty' <- replaceTypeWildcards ty
130141 -- Kind check
131− (kind, args) <- liftCheck $ kindOfWithScopedVars ty
142+ (kind, args) <- kindOfWithScopedVars ty
132143 checkTypeKind ty kind
133144 -- Check the type with the new names in scope
134145 ty'' <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty'
@@ -137,17 +148,21 @@ checkTypedBindingGroupElement mn (ident, (val', ty, checkType)) dict = do
137148 else return (TypedValue False val' ty'')
138149 return (ident, (val'', ty''))
139150
140−typeForBindingGroupElement :: Bool -> (Ident, Expr) -> TypeData -> UntypedData -> UnifyT Type Check (Ident, (Expr, Type))
151+typeForBindingGroupElement ::
152+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
153+ Bool ->
154+ (Ident, Expr) ->
155+ TypeData ->
156+ UntypedData ->
157+ m (Ident, (Expr, Type))
141158typeForBindingGroupElement warn (ident, val) dict untypedDict = do
142159 -- Infer the type with the new names in scope
143160 TypedValue _ val' ty <- bindNames dict $ infer val
144− ty =?= fromMaybe (internalError "name not found in dictionary") (lookup ident untypedDict)
161+ unifyTypes ty $ fromMaybe (internalError "name not found in dictionary") (lookup ident untypedDict)
145162 when warn . tell . errorMessage $ MissingTypeDeclaration ident ty
146163 return (ident, (TypedValue True val' ty, ty))
147164
148−-- |
149−-- Check if a value contains a type annotation
150−--
165+-- | Check if a value contains a type annotation
151166isTyped :: (Ident, Expr) -> Either (Ident, Expr) (Ident, (Expr, Type, Bool))
152167isTyped (name, TypedValue checkType value ty) = Right (name, (value, ty, checkType))
153168isTyped (name, value) = Left (name, value)
@@ -163,10 +178,12 @@ overTypes f = let (_, f', _) = everywhereOnValues id g id in f'
163178 g (TypeClassDictionary (nm, tys) sco) = TypeClassDictionary (nm, map f tys) sco
164179 g other = other
165180
166−-- |
167−-- Replace type class dictionary placeholders with inferred type class dictionaries
168−--
169−replaceTypeClassDictionaries :: ModuleName -> Expr -> Check Expr
181+-- | Replace type class dictionary placeholders with inferred type class dictionaries
182+replaceTypeClassDictionaries ::
183+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
184+ ModuleName ->
185+ Expr ->
186+ m Expr
170187replaceTypeClassDictionaries mn =
171188 let (_, f, _) = everywhereOnValuesTopDownM return go return
172189 in f
@@ -174,20 +191,24 @@ replaceTypeClassDictionaries mn =
174191 go (TypeClassDictionary constraint dicts) = entails mn dicts constraint
175192 go other = return other
176193
177−-- |
178−-- Check the kind of a type, failing if it is not of kind *.
179−--
180−checkTypeKind :: Type -> Kind -> UnifyT t Check ()
194+-- | Check the kind of a type, failing if it is not of kind *.
195+checkTypeKind ::
196+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m) =>
197+ Type ->
198+ Kind ->
199+ m ()
181200checkTypeKind ty kind = guardWith (errorMessage (ExpectedType ty kind)) $ kind == Star
182201
183−-- |
184−-- Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
202+-- | Remove any ForAlls and ConstrainedType constructors in a type by introducing new unknowns
185203-- or TypeClassDictionary values.
186204--
187205-- This is necessary during type checking to avoid unifying a polymorphic type with a
188206-- unification variable.
189−--
190−instantiatePolyTypeWithUnknowns :: Expr -> Type -> UnifyT Type Check (Expr, Type)
207+instantiatePolyTypeWithUnknowns ::
208+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m) =>
209+ Expr ->
210+ Type ->
211+ m (Expr, Type)
191212instantiatePolyTypeWithUnknowns val (ForAll ident ty _) = do
192213 ty' <- replaceVarWithUnknown ident ty
193214 instantiatePolyTypeWithUnknowns val ty'
@@ -197,16 +218,18 @@ instantiatePolyTypeWithUnknowns val (ConstrainedType constraints ty) = do
197218 return (foldl App val (map (flip TypeClassDictionary dicts) constraints), ty')
198219instantiatePolyTypeWithUnknowns val ty = return (val, ty)
199220
200−-- |
201−-- Infer a type for a value, rethrowing any error to provide a more useful error message
202−--
203−infer :: Expr -> UnifyT Type Check Expr
221+-- | Infer a type for a value, rethrowing any error to provide a more useful error message
222+infer ::
223+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
224+ Expr ->
225+ m Expr
204226infer val = rethrow (addHint (ErrorInferringType val)) $ infer' val
205227
206−-- |
207−-- Infer a type for a value
208−--
209−infer' :: Expr -> UnifyT Type Check Expr
228+-- | Infer a type for a value
229+infer' ::
230+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
231+ Expr ->
232+ m Expr
210233infer' v@(NumericLiteral (Left _)) = return $ TypedValue True v tyInt
211234infer' v@(NumericLiteral (Right _)) = return $ TypedValue True v tyNumber
212235infer' v@(StringLiteral _) = return $ TypedValue True v tyString
@@ -214,8 +237,8 @@ infer' v@(CharLiteral _) = return $ TypedValue True v tyChar
214237infer' v@(BooleanLiteral _) = return $ TypedValue True v tyBoolean
215238infer' (ArrayLiteral vals) = do
216239 ts <- mapM infer vals
217− els <- fresh
218− forM_ ts $ \(TypedValue _ _ t) -> els =?= t
240+ els <- freshType
241+ forM_ ts $ \(TypedValue _ _ t) -> unifyTypes els t
219242 return $ TypedValue True (ArrayLiteral ts) (TypeApp tyArray els)
220243infer' (ObjectLiteral ps) = do
221244 ensureNoDuplicateProperties ps
@@ -225,20 +248,20 @@ infer' (ObjectLiteral ps) = do
225248 return $ TypedValue True (ObjectLiteral (zip (map fst ps) ts)) ty
226249infer' (ObjectUpdate o ps) = do
227250 ensureNoDuplicateProperties ps
228− row <- fresh
251+ row <- freshType
229252 newVals <- zipWith (\(name, _) t -> (name, t)) ps <$> mapM (infer . snd) ps
230253 let newTys = map (\(name, TypedValue _ _ ty) -> (name, ty)) newVals
231− oldTys <- zip (map fst ps) <$> replicateM (length ps) fresh
254+ oldTys <- zip (map fst ps) <$> replicateM (length ps) freshType
232255 let oldTy = TypeApp tyObject $ rowFromList (oldTys, row)
233256 o' <- TypedValue True <$> check o oldTy <*> pure oldTy
234257 return $ TypedValue True (ObjectUpdate o' newVals) $ TypeApp tyObject $ rowFromList (newTys, row)
235258infer' (Accessor prop val) = rethrow (addHint (ErrorCheckingAccessor val prop)) $ do
236− field <- fresh
237− rest <- fresh
259+ field <- freshType
260+ rest <- freshType
238261 typed <- check val (TypeApp tyObject (RCons prop field rest))
239262 return $ TypedValue True (Accessor prop typed) field
240263infer' (Abs (Left arg) ret) = do
241− ty <- fresh
264+ ty <- freshType
242265 Just moduleName <- checkCurrentModule <$> get
243266 withBindingGroupVisible $ bindLocalVariables moduleName [(arg, ty, Defined)] $ do
244267 body@(TypedValue _ _ bodyTy) <- infer' ret
@@ -265,7 +288,7 @@ infer' v@(Constructor c) = do
265288 return $ TypedValue True v' ty'
266289infer' (Case vals binders) = do
267290 (vals', ts) <- instantiateForBinders vals binders
268− ret <- fresh
291+ ret <- freshType
269292 binders' <- checkBinders ts ret binders
270293 return $ TypedValue True (Case vals' binders') ret
271294infer' (IfThenElse cond th el) = do
@@ -282,7 +305,7 @@ infer' (SuperClassDictionary className tys) = do
282305 return $ TypeClassDictionary (className, tys) dicts
283306infer' (TypedValue checkType val ty) = do
284307 Just moduleName <- checkCurrentModule <$> get
285− (kind, args) <- liftCheck $ kindOfWithScopedVars ty
308+ (kind, args) <- kindOfWithScopedVars ty
286309 checkTypeKind ty kind
287310 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty
288311 val' <- if checkType then withScopedTypeVars moduleName args (check val ty') else return val
@@ -290,22 +313,28 @@ infer' (TypedValue checkType val ty) = do
290313infer' (PositionedValue pos _ val) = warnAndRethrowWithPosition pos $ infer' val
291314infer' _ = internalError "Invalid argument to infer"
292315
293−inferLetBinding :: [Declaration] -> [Declaration] -> Expr -> (Expr -> UnifyT Type Check Expr) -> UnifyT Type Check ([Declaration], Expr)
316+inferLetBinding ::
317+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
318+ [Declaration] ->
319+ [Declaration] ->
320+ Expr ->
321+ (Expr -> m Expr) ->
322+ m ([Declaration], Expr)
294323inferLetBinding seen [] ret j = (,) seen <$> withBindingGroupVisible (j ret)
295324inferLetBinding seen (ValueDeclaration ident nameKind [] (Right (tv@(TypedValue checkType val ty))) : rest) ret j = do
296325 Just moduleName <- checkCurrentModule <$> get
297− (kind, args) <- liftCheck $ kindOfWithScopedVars ty
326+ (kind, args) <- kindOfWithScopedVars ty
298327 checkTypeKind ty kind
299328 let dict = M.singleton (moduleName, ident) (ty, nameKind, Undefined)
300329 ty' <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty
301330 TypedValue _ val' ty'' <- if checkType then withScopedTypeVars moduleName args (bindNames dict (check val ty')) else return tv
302331 bindNames (M.singleton (moduleName, ident) (ty'', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] (Right (TypedValue checkType val' ty''))]) rest ret j
303332inferLetBinding seen (ValueDeclaration ident nameKind [] (Right val) : rest) ret j = do
304− valTy <- fresh
333+ valTy <- freshType
305334 Just moduleName <- checkCurrentModule <$> get
306335 let dict = M.singleton (moduleName, ident) (valTy, nameKind, Undefined)
307336 TypedValue _ val' valTy' <- bindNames dict $ infer val
308− valTy =?= valTy'
337+ unifyTypes valTy valTy'
309338 bindNames (M.singleton (moduleName, ident) (valTy', nameKind, Defined)) $ inferLetBinding (seen ++ [ValueDeclaration ident nameKind [] (Right val')]) rest ret j
310339inferLetBinding seen (BindingGroupDeclaration ds : rest) ret j = do
311340 Just moduleName <- checkCurrentModule <$> get
@@ -321,16 +350,18 @@ inferLetBinding seen (PositionedDeclaration pos com d : ds) ret j = warnAndRethr
321350 return (PositionedDeclaration pos com d' : ds', val')
322351inferLetBinding _ _ _ _ = internalError "Invalid argument to inferLetBinding"
323352
324−-- |
325−-- Infer the types of variables brought into scope by a binder
326−--
327−inferBinder :: Type -> Binder -> UnifyT Type Check (M.Map Ident Type)
353+-- | Infer the types of variables brought into scope by a binder
354+inferBinder :: forall m.
355+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
356+ Type ->
357+ Binder ->
358+ m (M.Map Ident Type)
328359inferBinder _ NullBinder = return M.empty
329−inferBinder val (StringBinder _) = val =?= tyString >> return M.empty
330−inferBinder val (CharBinder _) = val =?= tyChar >> return M.empty
331−inferBinder val (NumberBinder (Left _)) = val =?= tyInt >> return M.empty
332−inferBinder val (NumberBinder (Right _)) = val =?= tyNumber >> return M.empty
333−inferBinder val (BooleanBinder _) = val =?= tyBoolean >> return M.empty
360+inferBinder val (StringBinder _) = unifyTypes val tyString >> return M.empty
361+inferBinder val (CharBinder _) = unifyTypes val tyChar >> return M.empty
362+inferBinder val (NumberBinder (Left _)) = unifyTypes val tyInt >> return M.empty
363+inferBinder val (NumberBinder (Right _)) = unifyTypes val tyNumber >> return M.empty
364+inferBinder val (BooleanBinder _) = unifyTypes val tyBoolean >> return M.empty
334365inferBinder val (VarBinder name) = return $ M.singleton name val
335366inferBinder val (ConstructorBinder ctor binders) = do
336367 env <- getEnv
@@ -340,7 +371,7 @@ inferBinder val (ConstructorBinder ctor binders) = do
340371 fn' <- introduceSkolemScope <=< replaceAllTypeSynonyms $ fn
341372 let (args, ret) = peelArgs fn'
342373 unless (length args == length binders) . throwError . errorMessage $ IncorrectConstructorArity ctor
343− ret =?= val
374+ unifyTypes ret val
344375 M.unions <$> zipWithM inferBinder (reverse args) binders
345376 _ -> throwError . errorMessage $ UnknownDataConstructor ctor Nothing
346377 where
@@ -350,23 +381,23 @@ inferBinder val (ConstructorBinder ctor binders) = do
350381 go args (TypeApp (TypeApp fn arg) ret) | fn == tyFunction = go (arg : args) ret
351382 go args ret = (args, ret)
352383inferBinder val (ObjectBinder props) = do
353− row <- fresh
354− rest <- fresh
384+ row <- freshType
385+ rest <- freshType
355386 m1 <- inferRowProperties row rest props
356− val =?= TypeApp tyObject row
387+ unifyTypes val (TypeApp tyObject row)
357388 return m1
358389 where
359− inferRowProperties :: Type -> Type -> [(String, Binder)] -> UnifyT Type Check (M.Map Ident Type)
360− inferRowProperties nrow row [] = nrow =?= row >> return M.empty
390+ inferRowProperties :: Type -> Type -> [(String, Binder)] -> m (M.Map Ident Type)
391+ inferRowProperties nrow row [] = unifyTypes nrow row >> return M.empty
361392 inferRowProperties nrow row ((name, binder):binders) = do
362− propTy <- fresh
393+ propTy <- freshType
363394 m1 <- inferBinder propTy binder
364395 m2 <- inferRowProperties nrow (RCons name propTy row) binders
365396 return $ m1 `M.union` m2
366397inferBinder val (ArrayBinder binders) = do
367− el <- fresh
398+ el <- freshType
368399 m1 <- M.unions <$> mapM (inferBinder el) binders
369− val =?= TypeApp tyArray el
400+ unifyTypes val (TypeApp tyArray el)
370401 return m1
371402inferBinder val (NamedBinder name binder) = do
372403 m <- inferBinder val binder
@@ -378,9 +409,9 @@ inferBinder val (PositionedBinder pos _ binder) =
378409-- and use `kindOfWithScopedVars`.
379410inferBinder val (TypedBinder ty binder) = do
380411 ty1 <- replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty
381− kind <- liftCheck $ kindOf ty1
412+ kind <- kindOf ty1
382413 checkTypeKind ty1 kind
383− val =?= ty1
414+ unifyTypes val ty1
384415 inferBinder val binder
385416
386417-- | Returns true if a binder requires its argument type to be a monotype.
@@ -393,7 +424,11 @@ binderRequiresMonotype (PositionedBinder _ _ b) = binderRequiresMonotype b
393424binderRequiresMonotype _ = True
394425
395426-- | Instantiate polytypes only when necessitated by a binder.
396−instantiateForBinders :: [Expr] -> [CaseAlternative] -> UnifyT Type Check ([Expr], [Type])
427+instantiateForBinders ::
428+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
429+ [Expr] ->
430+ [CaseAlternative] ->
431+ m ([Expr], [Type])
397432instantiateForBinders vals cas = unzip <$> zipWithM (\val inst -> do
398433 TypedValue _ val' ty <- infer val
399434 if inst
@@ -406,7 +441,12 @@ instantiateForBinders vals cas = unzip <$> zipWithM (\val inst -> do
406441-- |
407442-- Check the types of the return values in a set of binders in a case statement
408443--
409−checkBinders :: [Type] -> Type -> [CaseAlternative] -> UnifyT Type Check [CaseAlternative]
444+checkBinders ::
445+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
446+ [Type] ->
447+ Type ->
448+ [CaseAlternative] ->
449+ m [CaseAlternative]
410450checkBinders _ _ [] = return []
411451checkBinders nvals ret (CaseAlternative binders result : bs) = do
412452 guardWith (errorMessage $ OverlappingArgNames Nothing) $
@@ -431,13 +471,21 @@ checkBinders nvals ret (CaseAlternative binders result : bs) = do
431471-- |
432472-- Check the type of a value, rethrowing errors to provide a better error message
433473--
434−check :: Expr -> Type -> UnifyT Type Check Expr
474+check ::
475+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
476+ Expr ->
477+ Type ->
478+ m Expr
435479check val ty = rethrow (addHint (ErrorCheckingType val ty)) $ check' val ty
436480
437481-- |
438482-- Check the type of a value
439483--
440−check' :: Expr -> Type -> UnifyT Type Check Expr
484+check' :: forall m.
485+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
486+ Expr ->
487+ Type ->
488+ m Expr
441489check' val (ForAll ident ty _) = do
442490 scope <- newSkolemScope
443491 sko <- newSkolemConstant
@@ -447,15 +495,15 @@ check' val (ForAll ident ty _) = do
447495 return $ TypedValue True val' (ForAll ident ty (Just scope))
448496check' val t@(ConstrainedType constraints ty) = do
449497 dictNames <- forM constraints $ \(Qualified _ (ProperName className), _) -> do
450− n <- liftCheck freshDictionaryName
498+ n <- freshDictionaryName
451499 return $ Ident $ "__dict_" ++ className ++ "_" ++ show n
452− dicts <- join <$> liftCheck (zipWithM (newDictionaries []) (map (Qualified Nothing) dictNames) constraints)
500+ dicts <- join <$> zipWithM (newDictionaries []) (map (Qualified Nothing) dictNames) constraints
453501 val' <- withBindingGroupVisible $ withTypeClassDictionaries dicts $ check val ty
454502 return $ TypedValue True (foldr (Abs . Left) val' dictNames) t
455503 where
456504 -- | Add a dictionary for the constraint to the scope, and dictionaries
457− -- for all implies superclass instances.
458− newDictionaries :: [(Qualified ProperName, Integer)] -> Qualified Ident -> (Qualified ProperName, [Type]) -> Check [TypeClassDictionaryInScope]
505+ -- for all implied superclass instances.
506+ newDictionaries :: [(Qualified ProperName, Integer)] -> Qualified Ident -> (Qualified ProperName, [Type]) -> m [TypeClassDictionaryInScope]
459507 newDictionaries path name (className, instanceTy) = do
460508 tcs <- gets (typeClasses . checkEnv)
461509 let (args, _, superclasses) = fromMaybe (internalError "newDictionaries: type class lookup failed") $ M.lookup className tcs
@@ -472,7 +520,7 @@ check' val u@(TUnknown _) = do
472520 val'@(TypedValue _ _ ty) <- infer val
473521 -- Don't unify an unknown with an inferred polytype
474522 (val'', ty') <- instantiatePolyTypeWithUnknowns val' ty
475− ty' =?= u
523+ unifyTypes ty' u
476524 return $ TypedValue True val'' ty'
477525check' v@(NumericLiteral (Left _)) t | t == tyInt =
478526 return $ TypedValue True v t
@@ -485,11 +533,11 @@ check' v@(CharLiteral _) t | t == tyChar =
485533check' v@(BooleanLiteral _) t | t == tyBoolean =
486534 return $ TypedValue True v t
487535check' (ArrayLiteral vals) t@(TypeApp a ty) = do
488− a =?= tyArray
536+ unifyTypes a tyArray
489537 array <- ArrayLiteral <$> forM vals (`check` ty)
490538 return $ TypedValue True array t
491539check' (Abs (Left arg) ret) ty@(TypeApp (TypeApp t argTy) retTy) = do
492− t =?= tyFunction
540+ unifyTypes t tyFunction
493541 Just moduleName <- checkCurrentModule <$> get
494542 ret' <- withBindingGroupVisible $ bindLocalVariables moduleName [(arg, argTy, Defined)] $ check ret retTy
495543 return $ TypedValue True (Abs (Left arg) ret') ty
@@ -518,7 +566,7 @@ check' (SuperClassDictionary className tys) _ = do
518566 return $ TypeClassDictionary (className, tys) dicts
519567check' (TypedValue checkType val ty1) ty2 = do
520568 Just moduleName <- checkCurrentModule <$> get
521− (kind, args) <- liftCheck $ kindOfWithScopedVars ty1
569+ (kind, args) <- kindOfWithScopedVars ty1
522570 checkTypeKind ty1 kind
523571 ty1' <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty1
524572 ty2' <- introduceSkolemScope <=< replaceAllTypeSynonyms <=< replaceTypeWildcards $ ty2
@@ -550,12 +598,12 @@ check' e@(ObjectUpdate obj ps) t@(TypeApp o row) | o == tyObject = do
550598 -- We check _obj_ against the type _t_ with the types in _ps_ replaced with unknowns.
551599 let (propsToCheck, rest) = rowToList row
552600 (removedProps, remainingProps) = partition (\(p, _) -> p `elem` map fst ps) propsToCheck
553− us <- zip (map fst removedProps) <$> replicateM (length ps) fresh
601+ us <- zip (map fst removedProps) <$> replicateM (length ps) freshType
554602 obj' <- check obj (TypeApp tyObject (rowFromList (us ++ remainingProps, rest)))
555603 ps' <- checkProperties e ps row True
556604 return $ TypedValue True (ObjectUpdate obj' ps') t
557605check' (Accessor prop val) ty = rethrow (addHint (ErrorCheckingAccessor val prop)) $ do
558− rest <- fresh
606+ rest <- freshType
559607 val' <- check val (TypeApp tyObject (RCons prop ty rest))
560608 return $ TypedValue True (Accessor prop val') ty
561609check' v@(Constructor c) ty = do
@@ -589,12 +637,18 @@ check' val ty = do
589637--
590638-- The @lax@ parameter controls whether or not every record member has to be provided. For object updates, this is not the case.
591639--
592−checkProperties :: Expr -> [(String, Expr)] -> Type -> Bool -> UnifyT Type Check [(String, Expr)]
640+checkProperties ::
641+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
642+ Expr ->
643+ [(String, Expr)] ->
644+ Type ->
645+ Bool ->
646+ m [(String, Expr)]
593647checkProperties expr ps row lax = let (ts, r') = rowToList row in go ps ts r' where
594648 go [] [] REmpty = return []
595649 go [] [] u@(TUnknown _)
596650 | lax = return []
597− | otherwise = do u =?= REmpty
651+ | otherwise = do unifyTypes u REmpty
598652 return []
599653 go [] [] Skolem{} | lax = return []
600654 go [] ((p, _): _) _ | lax = return []
@@ -604,8 +658,8 @@ checkProperties expr ps row lax = let (ts, r') = rowToList row in go ps ts r' wh
604658 case lookup p ts of
605659 Nothing -> do
606660 v'@(TypedValue _ _ ty) <- infer v
607− rest <- fresh
608− r =?= RCons p ty rest
661+ rest <- freshType
662+ unifyTypes r (RCons p ty rest)
609663 ps'' <- go ps' ts rest
610664 return $ (p, v') : ps''
611665 Just ty -> do
@@ -614,20 +668,28 @@ checkProperties expr ps row lax = let (ts, r') = rowToList row in go ps ts r' wh
614668 return $ (p, v') : ps''
615669 go _ _ _ = throwError . errorMessage $ ExprDoesNotHaveType expr (TypeApp tyObject row)
616670
617−-- |
618−-- Check the type of a function application, rethrowing errors to provide a better error message
619−--
620−checkFunctionApplication :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
671+-- | Check the type of a function application, rethrowing errors to provide a better error message
672+checkFunctionApplication ::
673+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
674+ Expr ->
675+ Type ->
676+ Expr ->
677+ Maybe Type ->
678+ m (Type, Expr)
621679checkFunctionApplication fn fnTy arg ret = rethrow (addHint (ErrorInApplication fn fnTy arg)) $ do
622− subst <- unifyCurrentSubstitution <$> UnifyT get
623− checkFunctionApplication' fn (subst $? fnTy) arg (($?) subst <$> ret)
624−
625−-- |
626−-- Check the type of a function application
627−--
628−checkFunctionApplication' :: Expr -> Type -> Expr -> Maybe Type -> UnifyT Type Check (Type, Expr)
680+ subst <- gets checkSubstitution
681+ checkFunctionApplication' fn (substituteType subst fnTy) arg (substituteType subst <$> ret)
682+
683+-- | Check the type of a function application
684+checkFunctionApplication' ::
685+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) =>
686+ Expr ->
687+ Type ->
688+ Expr ->
689+ Maybe Type ->
690+ m (Type, Expr)
629691checkFunctionApplication' fn (TypeApp (TypeApp tyFunction' argTy) retTy) arg ret = do
630− tyFunction' =?= tyFunction
692+ unifyTypes tyFunction' tyFunction
631693 arg' <- check arg argTy
632694 case ret of
633695 Nothing -> return (retTy, App fn arg')
@@ -643,8 +705,8 @@ checkFunctionApplication' fn u@(TUnknown _) arg ret = do
643705 (arg'', t') <- instantiatePolyTypeWithUnknowns arg' t
644706 return $ TypedValue True arg'' t'
645707 let ty = (\(TypedValue _ _ t) -> t) arg'
646− ret' <- maybe fresh return ret
647− u =?= function ty ret'
708+ ret' <- maybe freshType return ret
709+ unifyTypes u (function ty ret')
648710 return (ret', App fn arg')
649711checkFunctionApplication' fn (KindedType ty _) arg ret =
650712 checkFunctionApplication fn ty arg ret
@@ -655,11 +717,15 @@ checkFunctionApplication' fn fnTy dict@TypeClassDictionary{} _ =
655717 return (fnTy, App fn dict)
656718checkFunctionApplication' _ fnTy arg _ = throwError . errorMessage $ CannotApplyFunction fnTy arg
657719
658−-- |
659−-- Compute the meet of two types, i.e. the most general type which both types subsume.
660−-- TODO: handle constrained types
661−--
662−meet :: Expr -> Expr -> Type -> Type -> UnifyT Type Check (Expr, Expr, Type)
720+-- | Compute the meet of two types, i.e. the most general type which both types subsume.
721+-- TODO: is this really needed?
722+meet ::
723+ (Functor m, Applicative m, MonadState CheckState m, MonadError MultipleErrors m) =>
724+ Expr ->
725+ Expr ->
726+ Type ->
727+ Type ->
728+ m (Expr, Expr, Type)
663729meet e1 e2 (ForAll ident t1 _) t2 = do
664730 t1' <- replaceVarWithUnknown ident t1
665731 meet e1 e2 t1' t2
@@ -667,7 +733,7 @@ meet e1 e2 t1 (ForAll ident t2 _) = do
667733 t2' <- replaceVarWithUnknown ident t2
668734 meet e1 e2 t1 t2'
669735meet e1 e2 t1 t2 = do
670− t1 =?= t2
736+ unifyTypes t1 t2
671737 return (e1, e2, t1)
672738
673739-- |