2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcMatches]{Typecheck some @Matches@}
7 module TcMatches ( tcMatchesFun, tcMatchesCase, tcMatchLambda,
8 tcDoStmts, tcStmtsAndThen, tcGRHSs
11 #include "HsVersions.h"
13 import {-# SOURCE #-} TcExpr( tcMonoExpr )
15 import HsSyn ( HsExpr(..), HsBinds(..), Match(..), GRHSs(..), GRHS(..),
16 MonoBinds(..), Stmt(..), HsMatchContext(..), HsStmtContext(..),
17 pprMatch, getMatchLoc, pprMatchContext, pprStmtCtxt, isDoExpr,
18 mkMonoBind, nullMonoBinds, collectSigTysFromPats, andMonoBindList
20 import RnHsSyn ( RenamedMatch, RenamedGRHSs, RenamedStmt,
21 RenamedPat, RenamedMatchContext )
22 import TcHsSyn ( TcMatch, TcGRHSs, TcStmt, TcDictBinds,
23 TcMonoBinds, TcPat, TcStmt )
26 import TcMonoType ( tcAddScopedTyVars, tcHsSigType, UserTypeCtxt(..) )
27 import Inst ( tcSyntaxName )
28 import TcEnv ( TcId, tcLookupLocalIds, tcExtendLocalValEnv, tcExtendLocalValEnv2 )
29 import TcPat ( tcPat, tcMonoPatBndr )
30 import TcMType ( newTyVarTy, newTyVarTys, zonkTcType, zapToType )
31 import TcType ( TcType, TcTyVar, tyVarsOfType, tidyOpenTypes, tidyOpenType,
32 mkFunTy, isOverloadedTy, liftedTypeKind, openTypeKind,
33 mkArrowKind, mkAppTy )
34 import TcBinds ( tcBindsAndThen )
35 import TcUnify ( unifyPArrTy,subFunTy, unifyListTy, unifyTauTy,
36 checkSigTyVarsWrt, tcSubExp, isIdCoercion, (<$>), unifyTauTyLists )
37 import TcSimplify ( tcSimplifyCheck, bindInstsOfLocalFuns )
39 import PrelNames ( monadNames, mfixName )
40 import TysWiredIn ( boolTy, mkListTy, mkPArrTy )
41 import Id ( idType, mkSysLocal, mkLocalId )
42 import CoreFVs ( idFreeTyVars )
43 import BasicTypes ( RecFlag(..) )
47 import Util ( isSingleton, lengthExceeds, notNull, zipEqual )
53 %************************************************************************
55 \subsection{tcMatchesFun, tcMatchesCase}
57 %************************************************************************
59 @tcMatchesFun@ typechecks a @[Match]@ list which occurs in a
60 @FunMonoBind@. The second argument is the name of the function, which
61 is used in error messages. It checks that all the equations have the
62 same number of arguments before using @tcMatches@ to do the work.
65 tcMatchesFun :: [(Name,Id)] -- Bindings for the variables bound in this group
67 -> TcType -- Expected type
71 tcMatchesFun xve fun_name expected_ty matches@(first_match:_)
72 = -- Check that they all have the same no of arguments
73 -- Set the location to that of the first equation, so that
74 -- any inter-equation error messages get some vaguely
75 -- sensible location. Note: we have to do this odd
76 -- ann-grabbing, because we don't always have annotations in
77 -- hand when we call tcMatchesFun...
78 addSrcLoc (getMatchLoc first_match) (
79 checkTc (sameNoOfArgs matches)
80 (varyingArgsErr fun_name matches)
83 -- ToDo: Don't use "expected" stuff if there ain't a type signature
84 -- because inconsistency between branches
85 -- may show up as something wrong with the (non-existent) type signature
87 -- No need to zonk expected_ty, because subFunTy does that on the fly
88 tcMatches xve (FunRhs fun_name) matches expected_ty
91 @tcMatchesCase@ doesn't do the argument-count check because the
92 parser guarantees that each equation has exactly one argument.
95 tcMatchesCase :: [RenamedMatch] -- The case alternatives
96 -> TcType -- Type of whole case expressions
97 -> TcM (TcType, -- Inferred type of the scrutinee
98 [TcMatch]) -- Translated alternatives
100 tcMatchesCase matches expr_ty
101 = newTyVarTy openTypeKind `thenM` \ scrut_ty ->
102 tcMatches [] CaseAlt matches (mkFunTy scrut_ty expr_ty) `thenM` \ matches' ->
103 returnM (scrut_ty, matches')
105 tcMatchLambda :: RenamedMatch -> TcType -> TcM TcMatch
106 tcMatchLambda match res_ty = tcMatch [] LambdaExpr match res_ty
111 tcMatches :: [(Name,Id)]
112 -> RenamedMatchContext
117 tcMatches xve ctxt matches expected_ty
118 = -- If there is more than one branch, and expected_ty is a 'hole',
119 -- all branches must be types, not type schemes, otherwise the
120 -- in which we check them would affect the result.
121 (if lengthExceeds matches 1 then
122 zapToType expected_ty
124 returnM expected_ty) `thenM` \ expected_ty' ->
126 mappM (tc_match expected_ty') matches
128 tc_match expected_ty match = tcMatch xve ctxt match expected_ty
132 %************************************************************************
136 %************************************************************************
139 tcMatch :: [(Name,Id)]
140 -> RenamedMatchContext
142 -> TcType -- Expected result-type of the Match.
143 -- Early unification with this guy gives better error messages
144 -- We regard the Match as having type
145 -- (ty1 -> ... -> tyn -> result_ty)
146 -- where there are n patterns.
149 tcMatch xve1 ctxt match@(Match pats maybe_rhs_sig grhss) expected_ty
150 = addSrcLoc (getMatchLoc match) $ -- At one stage I removed this;
151 addErrCtxt (matchCtxt ctxt match) $ -- I'm not sure why, so I put it back
152 tcMatchPats pats expected_ty tc_grhss `thenM` \ (pats', grhss', ex_binds) ->
153 returnM (Match pats' Nothing (glue_on Recursive ex_binds grhss'))
157 = tcExtendLocalValEnv2 xve1 $
159 -- Deal with the result signature
160 case maybe_rhs_sig of
161 Nothing -> tcGRHSs ctxt grhss rhs_ty
163 Just sig -> tcAddScopedTyVars [sig] $
164 -- Bring into scope the type variables in the signature
165 tcHsSigType ResSigCtxt sig `thenM` \ sig_ty ->
166 tcGRHSs ctxt grhss sig_ty `thenM` \ grhss' ->
167 tcSubExp rhs_ty sig_ty `thenM` \ co_fn ->
168 returnM (lift_grhss co_fn rhs_ty grhss')
170 -- lift_grhss pushes the coercion down to the right hand sides,
171 -- because there is no convenient place to hang it otherwise.
172 lift_grhss co_fn rhs_ty grhss
173 | isIdCoercion co_fn = grhss
174 lift_grhss co_fn rhs_ty (GRHSs grhss binds ty)
175 = GRHSs (map lift_grhs grhss) binds rhs_ty -- Change the type, since we
177 lift_grhs (GRHS stmts loc) = GRHS (map lift_stmt stmts) loc
179 lift_stmt (ResultStmt e l) = ResultStmt (co_fn <$> e) l
180 lift_stmt stmt = stmt
182 -- glue_on just avoids stupid dross
183 glue_on _ EmptyMonoBinds grhss = grhss -- The common case
184 glue_on is_rec mbinds (GRHSs grhss binds ty)
185 = GRHSs grhss (mkMonoBind mbinds [] is_rec `ThenBinds` binds) ty
188 tcGRHSs :: RenamedMatchContext -> RenamedGRHSs
192 tcGRHSs ctxt (GRHSs grhss binds _) expected_ty
193 = tcBindsAndThen glue_on binds (tc_grhss grhss)
196 = mappM tc_grhs grhss `thenM` \ grhss' ->
197 returnM (GRHSs grhss' EmptyBinds expected_ty)
199 tc_grhs (GRHS guarded locn)
201 tcStmts PatGuard (\ty -> ty, expected_ty) guarded `thenM` \ guarded' ->
202 returnM (GRHS guarded' locn)
206 %************************************************************************
208 \subsection{tcMatchPats}
210 %************************************************************************
214 :: [RenamedPat] -> TcType
216 -> TcM ([TcPat], a, TcDictBinds)
217 -- Typecheck the patterns, extend the environment to bind the variables,
218 -- do the thing inside, use any existentially-bound dictionaries to
219 -- discharge parts of the returning LIE, and deal with pattern type
222 tcMatchPats pats expected_ty thing_inside
223 = -- STEP 1: Bring pattern-signature type variables into scope
224 tcAddScopedTyVars (collectSigTysFromPats pats) (
226 -- STEP 2: Typecheck the patterns themselves, gathering all the stuff
227 -- then do the thing inside
228 getLIE (tc_match_pats pats expected_ty thing_inside)
230 ) `thenM` \ ((pats', ex_tvs, ex_ids, ex_lie, result), lie_req) ->
232 -- STEP 4: Check for existentially bound type variables
233 -- Do this *outside* the scope of the tcAddScopedTyVars, else checkSigTyVars
234 -- complains that 'a' is captured by the inscope 'a'! (Test (d) in checkSigTyVars.)
236 -- I'm a bit concerned that lie_req1 from an 'inner' pattern in the list
237 -- might need (via lie_req2) something made available from an 'outer'
238 -- pattern. But it's inconvenient to deal with, and I can't find an example
239 tcCheckExistentialPat ex_tvs ex_ids ex_lie lie_req expected_ty `thenM` \ ex_binds ->
240 -- NB: we *must* pass "expected_ty" not "result_ty" to tcCheckExistentialPat
241 -- For example, we must reject this program:
242 -- data C = forall a. C (a -> Int)
244 -- Here, result_ty will be simply Int, but expected_ty is (a -> Int).
246 returnM (pats', result, ex_binds)
248 tc_match_pats [] expected_ty thing_inside
249 = thing_inside expected_ty `thenM` \ answer ->
250 returnM ([], emptyBag, [], [], answer)
252 tc_match_pats (pat:pats) expected_ty thing_inside
253 = subFunTy expected_ty $ \ arg_ty rest_ty ->
254 -- This is the unique place we call subFunTy
255 -- The point is that if expected_y is a "hole", we want
256 -- to make arg_ty and rest_ty as "holes" too.
257 tcPat tcMonoPatBndr pat arg_ty `thenM` \ (pat', ex_tvs, pat_bndrs, ex_lie) ->
259 xve = bagToList pat_bndrs
260 ex_ids = [id | (_, id) <- xve]
261 -- ex_ids is all the pattern-bound Ids, a superset
262 -- of the existential Ids used in checkExistentialPat
264 tcExtendLocalValEnv2 xve $
265 tc_match_pats pats rest_ty thing_inside `thenM` \ (pats', exs_tvs, exs_ids, exs_lie, answer) ->
266 returnM ( pat':pats',
267 ex_tvs `unionBags` exs_tvs,
274 tcCheckExistentialPat :: Bag TcTyVar -- Existentially quantified tyvars bound by pattern
275 -> [TcId] -- Ids bound by this pattern; used
276 -- (a) by bindsInstsOfLocalFuns
277 -- (b) to generate helpful error messages
278 -> [Inst] -- and context
279 -> [Inst] -- Required context
280 -> TcType -- and type of the Match; vars in here must not escape
281 -> TcM TcDictBinds -- LIE to float out and dict bindings
282 tcCheckExistentialPat ex_tvs ex_ids ex_lie lie_req match_ty
283 | isEmptyBag ex_tvs && all not_overloaded ex_ids
284 -- Short cut for case when there are no existentials
285 -- and no polymorphic overloaded variables
286 -- e.g. f :: (forall a. Ord a => a -> a) -> Int -> Int
288 -- Here we must discharge op Methods
289 = ASSERT( null ex_lie )
290 extendLIEs lie_req `thenM_`
291 returnM EmptyMonoBinds
294 = addErrCtxtM (sigPatCtxt tv_list ex_ids match_ty) $
296 -- In case there are any polymorpic, overloaded binders in the pattern
297 -- (which can happen in the case of rank-2 type signatures, or data constructors
298 -- with polymorphic arguments), we must do a bindInstsOfLocalFns here
299 getLIE (bindInstsOfLocalFuns lie_req ex_ids) `thenM` \ (inst_binds, lie) ->
301 -- Deal with overloaded functions bound by the pattern
302 tcSimplifyCheck doc tv_list ex_lie lie `thenM` \ dict_binds ->
303 checkSigTyVarsWrt (tyVarsOfType match_ty) tv_list `thenM_`
305 returnM (dict_binds `AndMonoBinds` inst_binds)
307 doc = text ("existential context of a data constructor")
308 tv_list = bagToList ex_tvs
309 not_overloaded id = not (isOverloadedTy (idType id))
313 %************************************************************************
315 \subsection{@tcDoStmts@ typechecks a {\em list} of do statements}
317 %************************************************************************
320 tcDoStmts :: HsStmtContext -> [RenamedStmt] -> [Name] -> TcType
321 -> TcM (TcMonoBinds, [TcStmt], [Id])
322 tcDoStmts PArrComp stmts method_names res_ty
323 = unifyPArrTy res_ty `thenM` \elt_ty ->
324 tcStmts PArrComp (mkPArrTy, elt_ty) stmts `thenM` \ stmts' ->
325 returnM (EmptyMonoBinds, stmts', [{- unused -}])
327 tcDoStmts ListComp stmts method_names res_ty
328 = unifyListTy res_ty `thenM` \ elt_ty ->
329 tcStmts ListComp (mkListTy, elt_ty) stmts `thenM` \ stmts' ->
330 returnM (EmptyMonoBinds, stmts', [{- unused -}])
332 tcDoStmts do_or_mdo_expr stmts method_names res_ty
333 = newTyVarTy (mkArrowKind liftedTypeKind liftedTypeKind) `thenM` \ m_ty ->
334 newTyVarTy liftedTypeKind `thenM` \ elt_ty ->
335 unifyTauTy res_ty (mkAppTy m_ty elt_ty) `thenM_`
337 tcStmts do_or_mdo_expr (mkAppTy m_ty, elt_ty) stmts `thenM` \ stmts' ->
339 -- Build the then and zero methods in case we need them
340 -- It's important that "then" and "return" appear just once in the final LIE,
341 -- not only for typechecker efficiency, but also because otherwise during
342 -- simplification we end up with silly stuff like
343 -- then = case d of (t,r) -> t
345 -- where the second "then" sees that it already exists in the "available" stuff.
347 mapAndUnzipM (tc_syn_name m_ty)
348 (zipEqual "tcDoStmts" currentMonadNames method_names) `thenM` \ (binds, ids) ->
349 returnM (andMonoBindList binds, stmts', ids)
351 currentMonadNames = case do_or_mdo_expr of
353 MDoExpr -> monadNames ++ [mfixName]
354 tc_syn_name :: TcType -> (Name,Name) -> TcM (TcMonoBinds, Id)
355 tc_syn_name m_ty (std_nm, usr_nm)
356 = tcSyntaxName DoOrigin m_ty std_nm usr_nm `thenM` \ (expr, expr_ty) ->
358 HsVar v -> returnM (EmptyMonoBinds, v)
359 other -> newUnique `thenM` \ uniq ->
361 id = mkSysLocal FSLIT("syn") uniq expr_ty
363 returnM (VarMonoBind id expr, id)
367 %************************************************************************
371 %************************************************************************
373 Typechecking statements is rendered a bit tricky by parallel list comprehensions:
375 [ (g x, h x) | ... ; let g v = ...
376 | ... ; let h v = ... ]
378 It's possible that g,h are overloaded, so we need to feed the LIE from the
379 (g x, h x) up through both lots of bindings (so we get the bindInstsOfLocalFuns).
380 Similarly if we had an existential pattern match:
382 data T = forall a. Show a => C a
384 [ (show x, show y) | ... ; C x <- ...
387 Then we need the LIE from (show x, show y) to be simplified against
388 the bindings for x and y.
390 It's difficult to do this in parallel, so we rely on the renamer to
391 ensure that g,h and x,y don't duplicate, and simply grow the environment.
392 So the binders of the first parallel group will be in scope in the second
393 group. But that's fine; there's no shadowing to worry about.
396 tcStmts do_or_lc m_ty stmts
397 = ASSERT( notNull stmts )
398 tcStmtsAndThen (:) do_or_lc m_ty stmts (returnM [])
401 :: (TcStmt -> thing -> thing) -- Combiner
403 -> (TcType -> TcType, TcType) -- m, the relationship type of pat and rhs in pat <- rhs
404 -- elt_ty, where type of the comprehension is (m elt_ty)
410 tcStmtsAndThen combine do_or_lc m_ty [] do_next
413 tcStmtsAndThen combine do_or_lc m_ty (stmt:stmts) do_next
414 = tcStmtAndThen combine do_or_lc m_ty stmt
415 (tcStmtsAndThen combine do_or_lc m_ty stmts do_next)
418 tcStmtAndThen combine do_or_lc m_ty (LetStmt binds) thing_inside
419 = tcBindsAndThen -- No error context, but a binding group is
420 (glue_binds combine) -- rather a large thing for an error context anyway
424 tcStmtAndThen combine do_or_lc m_ty@(m,elt_ty) stmt@(BindStmt pat exp src_loc) thing_inside
425 = addSrcLoc src_loc $
426 addErrCtxt (stmtCtxt do_or_lc stmt) $
427 newTyVarTy liftedTypeKind `thenM` \ pat_ty ->
428 tcMonoExpr exp (m pat_ty) `thenM` \ exp' ->
429 tcMatchPats [pat] (mkFunTy pat_ty (m elt_ty)) (\ _ ->
430 popErrCtxt thing_inside
431 ) `thenM` \ ([pat'], thing, dict_binds) ->
432 returnM (combine (BindStmt pat' exp' src_loc)
433 (glue_binds combine Recursive dict_binds thing))
436 tcStmtAndThen combine do_or_lc m_ty (ParStmtOut bndr_stmts_s) thing_inside
437 = loop bndr_stmts_s `thenM` \ (pairs', thing) ->
438 returnM (combine (ParStmtOut pairs') thing)
441 = thing_inside `thenM` \ thing ->
444 loop ((bndrs,stmts) : pairs)
446 combine_par ListComp m_ty stmts
447 -- Notice we pass on m_ty; the result type is used only
448 -- to get escaping type variables for checkExistentialPat
449 (tcLookupLocalIds bndrs `thenM` \ bndrs' ->
450 loop pairs `thenM` \ (pairs', thing) ->
451 returnM ([], (bndrs', pairs', thing))) `thenM` \ (stmts', (bndrs', pairs', thing)) ->
453 returnM ((bndrs',stmts') : pairs', thing)
455 combine_par stmt (stmts, thing) = (stmt:stmts, thing)
458 tcStmtAndThen combine do_or_lc m_ty (RecStmt recNames stmts) thing_inside
459 = newTyVarTys (length recNames) liftedTypeKind `thenM` \ recTys ->
460 tcExtendLocalValEnv (zipWith mkLocalId recNames recTys) $
461 tcStmtsAndThen combine_rec do_or_lc m_ty stmts (
462 tcLookupLocalIds recNames `thenM` \ rn ->
464 ) `thenM` \ (stmts', recNames') ->
466 -- Unify the types of the "final" Ids with those of "knot-tied" Ids
467 unifyTauTyLists recTys (map idType recNames') `thenM_`
469 thing_inside `thenM` \ thing ->
471 returnM (combine (RecStmt recNames' stmts') thing)
473 combine_rec stmt (stmts, thing) = (stmt:stmts, thing)
476 tcStmtAndThen combine do_or_lc m_ty@(m, res_elt_ty) stmt@(ExprStmt exp _ locn) thing_inside
477 = setErrCtxt (stmtCtxt do_or_lc stmt) (
478 if isDoExpr do_or_lc then
479 newTyVarTy openTypeKind `thenM` \ any_ty ->
480 tcMonoExpr exp (m any_ty) `thenM` \ exp' ->
481 returnM (ExprStmt exp' any_ty locn)
483 tcMonoExpr exp boolTy `thenM` \ exp' ->
484 returnM (ExprStmt exp' boolTy locn)
487 thing_inside `thenM` \ thing ->
488 returnM (combine stmt' thing)
492 tcStmtAndThen combine do_or_lc m_ty@(m, res_elt_ty) stmt@(ResultStmt exp locn) thing_inside
493 = setErrCtxt (stmtCtxt do_or_lc stmt) (
494 if isDoExpr do_or_lc then
495 tcMonoExpr exp (m res_elt_ty)
497 tcMonoExpr exp res_elt_ty
500 thing_inside `thenM` \ thing ->
502 returnM (combine (ResultStmt exp' locn) thing)
505 ------------------------------
506 glue_binds combine is_rec binds thing
507 | nullMonoBinds binds = thing
508 | otherwise = combine (LetStmt (mkMonoBind binds [] is_rec)) thing
512 %************************************************************************
514 \subsection{Errors and contexts}
516 %************************************************************************
518 @sameNoOfArgs@ takes a @[RenamedMatch]@ and decides whether the same
519 number of args are used in each equation.
522 sameNoOfArgs :: [RenamedMatch] -> Bool
523 sameNoOfArgs matches = isSingleton (nub (map args_in_match matches))
525 args_in_match :: RenamedMatch -> Int
526 args_in_match (Match pats _ _) = length pats
530 varyingArgsErr name matches
531 = sep [ptext SLIT("Varying number of arguments for function"), quotes (ppr name)]
533 matchCtxt ctxt match = hang (pprMatchContext ctxt <> colon) 4 (pprMatch ctxt match)
534 stmtCtxt do_or_lc stmt = hang (pprStmtCtxt do_or_lc <> colon) 4 (ppr stmt)
536 sigPatCtxt bound_tvs bound_ids match_ty tidy_env
537 = zonkTcType match_ty `thenM` \ match_ty' ->
539 (env1, tidy_tys) = tidyOpenTypes tidy_env (map idType show_ids)
540 (env2, tidy_mty) = tidyOpenType env1 match_ty'
543 sep [ptext SLIT("When checking an existential match that binds"),
544 nest 4 (vcat (zipWith ppr_id show_ids tidy_tys)),
545 ptext SLIT("and whose type is") <+> ppr tidy_mty])
547 show_ids = filter is_interesting bound_ids
548 is_interesting id = any (`elemVarSet` idFreeTyVars id) bound_tvs
550 ppr_id id ty = ppr id <+> dcolon <+> ppr ty
551 -- Don't zonk the types so we get the separate, un-unified versions