2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 TcMatches: Typecheck some @Matches@
9 module TcMatches ( tcMatchesFun, tcGRHSsPat, tcMatchesCase, tcMatchLambda,
11 tcStmts, tcDoStmts, tcBody,
12 tcDoStmt, tcMDoStmt, tcGuardStmt
15 import {-# SOURCE #-} TcExpr( tcSyntaxOp, tcInferRhoNC, tcCheckId,
16 tcMonoExpr, tcMonoExprNC, tcPolyExpr )
32 import Coercion ( mkSymCoI )
38 -- Create chunkified tuple tybes for monad comprehensions
43 #include "HsVersions.h"
46 %************************************************************************
48 \subsection{tcMatchesFun, tcMatchesCase}
50 %************************************************************************
52 @tcMatchesFun@ typechecks a @[Match]@ list which occurs in a
53 @FunMonoBind@. The second argument is the name of the function, which
54 is used in error messages. It checks that all the equations have the
55 same number of arguments before using @tcMatches@ to do the work.
57 Note [Polymorphic expected type for tcMatchesFun]
58 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
59 tcMatchesFun may be given a *sigma* (polymorphic) type
60 so it must be prepared to use tcGen to skolemise it.
61 See Note [sig_tau may be polymorphic] in TcPat.
64 tcMatchesFun :: Name -> Bool
66 -> TcSigmaType -- Expected type of function
67 -> TcM (HsWrapper, MatchGroup TcId) -- Returns type of body
68 tcMatchesFun fun_name inf matches exp_ty
69 = do { -- Check that they all have the same no of arguments
70 -- Location is in the monad, set the caller so that
71 -- any inter-equation error messages get some vaguely
72 -- sensible location. Note: we have to do this odd
73 -- ann-grabbing, because we don't always have annotations in
74 -- hand when we call tcMatchesFun...
75 traceTc "tcMatchesFun" (ppr fun_name $$ ppr exp_ty)
76 ; checkArgs fun_name matches
78 ; (wrap_gen, (wrap_fun, group))
79 <- tcGen (FunSigCtxt fun_name) exp_ty $ \ _ exp_rho ->
80 -- Note [Polymorphic expected type for tcMatchesFun]
81 matchFunTys herald arity exp_rho $ \ pat_tys rhs_ty ->
82 tcMatches match_ctxt pat_tys rhs_ty matches
83 ; return (wrap_gen <.> wrap_fun, group) }
85 arity = matchGroupArity matches
86 herald = ptext (sLit "The equation(s) for")
87 <+> quotes (ppr fun_name) <+> ptext (sLit "have")
88 match_ctxt = MC { mc_what = FunRhs fun_name inf, mc_body = tcBody }
91 @tcMatchesCase@ doesn't do the argument-count check because the
92 parser guarantees that each equation has exactly one argument.
95 tcMatchesCase :: TcMatchCtxt -- Case context
96 -> TcRhoType -- Type of scrutinee
97 -> MatchGroup Name -- The case alternatives
98 -> TcRhoType -- Type of whole case expressions
99 -> TcM (MatchGroup TcId) -- Translated alternatives
101 tcMatchesCase ctxt scrut_ty matches res_ty
102 | isEmptyMatchGroup matches -- Allow empty case expressions
103 = return (MatchGroup [] (mkFunTys [scrut_ty] res_ty))
106 = tcMatches ctxt [scrut_ty] res_ty matches
108 tcMatchLambda :: MatchGroup Name -> TcRhoType -> TcM (HsWrapper, MatchGroup TcId)
109 tcMatchLambda match res_ty
110 = matchFunTys herald n_pats res_ty $ \ pat_tys rhs_ty ->
111 tcMatches match_ctxt pat_tys rhs_ty match
113 n_pats = matchGroupArity match
114 herald = sep [ ptext (sLit "The lambda expression")
115 <+> quotes (pprSetDepth (PartWay 1) $
116 pprMatches (LambdaExpr :: HsMatchContext Name) match),
117 -- The pprSetDepth makes the abstraction print briefly
119 match_ctxt = MC { mc_what = LambdaExpr,
123 @tcGRHSsPat@ typechecks @[GRHSs]@ that occur in a @PatMonoBind@.
126 tcGRHSsPat :: GRHSs Name -> TcRhoType -> TcM (GRHSs TcId)
127 -- Used for pattern bindings
128 tcGRHSsPat grhss res_ty = tcGRHSs match_ctxt grhss res_ty
130 match_ctxt = MC { mc_what = PatBindRhs,
137 :: SDoc -- See Note [Herald for matchExpecteFunTys] in TcUnify
140 -> ([TcSigmaType] -> TcRhoType -> TcM a)
141 -> TcM (HsWrapper, a)
143 -- Written in CPS style for historical reasons;
144 -- could probably be un-CPSd, like matchExpectedTyConApp
146 matchFunTys herald arity res_ty thing_inside
147 = do { (coi, pat_tys, res_ty) <- matchExpectedFunTys herald arity res_ty
148 ; res <- thing_inside pat_tys res_ty
149 ; return (coiToHsWrapper (mkSymCoI coi), res) }
152 %************************************************************************
156 %************************************************************************
159 tcMatches :: TcMatchCtxt
160 -> [TcSigmaType] -- Expected pattern types
161 -> TcRhoType -- Expected result-type of the Match.
163 -> TcM (MatchGroup TcId)
165 data TcMatchCtxt -- c.f. TcStmtCtxt, also in this module
166 = MC { mc_what :: HsMatchContext Name, -- What kind of thing this is
167 mc_body :: LHsExpr Name -- Type checker for a body of
170 -> TcM (LHsExpr TcId) }
172 tcMatches ctxt pat_tys rhs_ty (MatchGroup matches _)
173 = ASSERT( not (null matches) ) -- Ensure that rhs_ty is filled in
174 do { matches' <- mapM (tcMatch ctxt pat_tys rhs_ty) matches
175 ; return (MatchGroup matches' (mkFunTys pat_tys rhs_ty)) }
178 tcMatch :: TcMatchCtxt
179 -> [TcSigmaType] -- Expected pattern types
180 -> TcRhoType -- Expected result-type of the Match.
184 tcMatch ctxt pat_tys rhs_ty match
185 = wrapLocM (tc_match ctxt pat_tys rhs_ty) match
187 tc_match ctxt pat_tys rhs_ty match@(Match pats maybe_rhs_sig grhss)
188 = add_match_ctxt match $
189 do { (pats', grhss') <- tcPats (mc_what ctxt) pats pat_tys $
190 tc_grhss ctxt maybe_rhs_sig grhss rhs_ty
191 ; return (Match pats' Nothing grhss') }
193 tc_grhss ctxt Nothing grhss rhs_ty
194 = tcGRHSs ctxt grhss rhs_ty -- No result signature
196 -- Result type sigs are no longer supported
197 tc_grhss _ (Just {}) _ _
198 = panic "tc_ghrss" -- Rejected by renamer
200 -- For (\x -> e), tcExpr has already said "In the expresssion \x->e"
201 -- so we don't want to add "In the lambda abstraction \x->e"
202 add_match_ctxt match thing_inside
203 = case mc_what ctxt of
204 LambdaExpr -> thing_inside
205 m_ctxt -> addErrCtxt (pprMatchInCtxt m_ctxt match) thing_inside
208 tcGRHSs :: TcMatchCtxt -> GRHSs Name -> TcRhoType
211 -- Notice that we pass in the full res_ty, so that we get
212 -- good inference from simple things like
213 -- f = \(x::forall a.a->a) -> <stuff>
214 -- We used to force it to be a monotype when there was more than one guard
215 -- but we don't need to do that any more
217 tcGRHSs ctxt (GRHSs grhss binds) res_ty
218 = do { (binds', grhss') <- tcLocalBinds binds $
219 mapM (wrapLocM (tcGRHS ctxt res_ty)) grhss
221 ; return (GRHSs grhss' binds') }
224 tcGRHS :: TcMatchCtxt -> TcRhoType -> GRHS Name -> TcM (GRHS TcId)
226 tcGRHS ctxt res_ty (GRHS guards rhs)
227 = do { (guards', rhs') <- tcStmts stmt_ctxt tcGuardStmt guards res_ty $
229 ; return (GRHS guards' rhs') }
231 stmt_ctxt = PatGuard (mc_what ctxt)
235 %************************************************************************
237 \subsection{@tcDoStmts@ typechecks a {\em list} of do statements}
239 %************************************************************************
242 tcDoStmts :: HsStmtContext Name
245 -> SyntaxExpr Name -- 'return' function for monad
248 -> TcM (HsExpr TcId) -- Returns a HsDo
249 tcDoStmts ListComp stmts body _ res_ty
250 = do { (coi, elt_ty) <- matchExpectedListTy res_ty
251 ; (stmts', body') <- tcStmts ListComp (tcLcStmt listTyCon) stmts
254 ; return $ mkHsWrapCoI coi
255 (HsDo ListComp stmts' body' noSyntaxExpr (mkListTy elt_ty)) }
257 tcDoStmts PArrComp stmts body _ res_ty
258 = do { (coi, elt_ty) <- matchExpectedPArrTy res_ty
259 ; (stmts', body') <- tcStmts PArrComp (tcLcStmt parrTyCon) stmts
262 ; return $ mkHsWrapCoI coi
263 (HsDo PArrComp stmts' body' noSyntaxExpr (mkPArrTy elt_ty)) }
265 tcDoStmts DoExpr stmts body _ res_ty
266 = do { (stmts', body') <- tcStmts DoExpr tcDoStmt stmts res_ty $
268 ; return (HsDo DoExpr stmts' body' noSyntaxExpr res_ty) }
270 tcDoStmts MDoExpr stmts body _ res_ty
271 = do { (stmts', body') <- tcStmts MDoExpr tcDoStmt stmts res_ty $
273 ; return (HsDo MDoExpr stmts' body' noSyntaxExpr res_ty) }
275 tcDoStmts MonadComp stmts body return_op res_ty
276 = do { (stmts', (body', return_op')) <- tcStmts MonadComp tcMcStmt stmts res_ty $
277 tcMcBody body return_op
278 ; return $ HsDo MonadComp stmts' body' return_op' res_ty }
280 tcDoStmts ctxt _ _ _ _ = pprPanic "tcDoStmts" (pprStmtContext ctxt)
282 tcBody :: LHsExpr Name -> TcRhoType -> TcM (LHsExpr TcId)
284 = do { traceTc "tcBody" (ppr res_ty)
285 ; body' <- tcMonoExpr body res_ty
291 %************************************************************************
295 %************************************************************************
299 = forall thing. HsStmtContext Name
301 -> TcRhoType -- Result type for comprehension
302 -> (TcRhoType -> TcM thing) -- Checker for what follows the stmt
303 -> TcM (Stmt TcId, thing)
305 tcStmts :: HsStmtContext Name
306 -> TcStmtChecker -- NB: higher-rank type
309 -> (TcRhoType -> TcM thing)
310 -> TcM ([LStmt TcId], thing)
312 -- Note the higher-rank type. stmt_chk is applied at different
313 -- types in the equations for tcStmts
315 tcStmts _ _ [] res_ty thing_inside
316 = do { thing <- thing_inside res_ty
317 ; return ([], thing) }
319 -- LetStmts are handled uniformly, regardless of context
320 tcStmts ctxt stmt_chk (L loc (LetStmt binds) : stmts) res_ty thing_inside
321 = do { (binds', (stmts',thing)) <- tcLocalBinds binds $
322 tcStmts ctxt stmt_chk stmts res_ty thing_inside
323 ; return (L loc (LetStmt binds') : stmts', thing) }
325 -- For the vanilla case, handle the location-setting part
326 tcStmts ctxt stmt_chk (L loc stmt : stmts) res_ty thing_inside
327 = do { (stmt', (stmts', thing)) <-
329 addErrCtxt (pprStmtInCtxt ctxt stmt) $
330 stmt_chk ctxt stmt res_ty $ \ res_ty' ->
332 tcStmts ctxt stmt_chk stmts res_ty' $
334 ; return (L loc stmt' : stmts', thing) }
336 --------------------------------
338 tcGuardStmt :: TcStmtChecker
339 tcGuardStmt _ (ExprStmt guard _ _ _) res_ty thing_inside
340 = do { guard' <- tcMonoExpr guard boolTy
341 ; thing <- thing_inside res_ty
342 ; return (ExprStmt guard' noSyntaxExpr noSyntaxExpr boolTy, thing) }
344 tcGuardStmt ctxt (BindStmt pat rhs _ _) res_ty thing_inside
345 = do { (rhs', rhs_ty) <- tcInferRhoNC rhs -- Stmt has a context already
346 ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat rhs_ty $
348 ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) }
350 tcGuardStmt _ stmt _ _
351 = pprPanic "tcGuardStmt: unexpected Stmt" (ppr stmt)
354 --------------------------------
355 -- List comprehensions and PArrays
357 tcLcStmt :: TyCon -- The list/Parray type constructor ([] or PArray)
360 -- A generator, pat <- rhs
361 tcLcStmt m_tc ctxt (BindStmt pat rhs _ _) res_ty thing_inside
362 = do { pat_ty <- newFlexiTyVarTy liftedTypeKind
363 ; rhs' <- tcMonoExpr rhs (mkTyConApp m_tc [pat_ty])
364 ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $
366 ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) }
369 tcLcStmt _ _ (ExprStmt rhs _ _ _) res_ty thing_inside
370 = do { rhs' <- tcMonoExpr rhs boolTy
371 ; thing <- thing_inside res_ty
372 ; return (ExprStmt rhs' noSyntaxExpr noSyntaxExpr boolTy, thing) }
374 -- A parallel set of 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 bindLocalMethods).
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 <- ...
385 -- | ... ; C y <- ... ]
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.
395 tcLcStmt m_tc ctxt (ParStmt bndr_stmts_s _ _ _) elt_ty thing_inside
396 = do { (pairs', thing) <- loop bndr_stmts_s
397 ; return (ParStmt pairs' noSyntaxExpr noSyntaxExpr noSyntaxExpr, thing) }
399 -- loop :: [([LStmt Name], [Name])] -> TcM ([([LStmt TcId], [TcId])], thing)
400 loop [] = do { thing <- thing_inside elt_ty
401 ; return ([], thing) } -- matching in the branches
403 loop ((stmts, names) : pairs)
404 = do { (stmts', (ids, pairs', thing))
405 <- tcStmts ctxt (tcLcStmt m_tc) stmts elt_ty $ \ _elt_ty' ->
406 do { ids <- tcLookupLocalIds names
407 ; (pairs', thing) <- loop pairs
408 ; return (ids, pairs', thing) }
409 ; return ( (stmts', ids) : pairs', thing ) }
411 tcLcStmt m_tc ctxt (TransformStmt stmts binders usingExpr maybeByExpr _ _) elt_ty thing_inside = do
412 (stmts', (binders', usingExpr', maybeByExpr', thing)) <-
413 tcStmts (TransformStmtCtxt ctxt) (tcLcStmt m_tc) stmts elt_ty $ \elt_ty' -> do
414 let alphaListTy = mkTyConApp m_tc [alphaTy]
416 (usingExpr', maybeByExpr') <-
419 -- We must validate that usingExpr :: forall a. [a] -> [a]
420 let using_ty = mkForAllTy alphaTyVar (alphaListTy `mkFunTy` alphaListTy)
421 usingExpr' <- tcPolyExpr usingExpr using_ty
422 return (usingExpr', Nothing)
424 -- We must infer a type such that e :: t and then check that
425 -- usingExpr :: forall a. (a -> t) -> [a] -> [a]
426 (byExpr', tTy) <- tcInferRhoNC byExpr
427 let using_ty = mkForAllTy alphaTyVar $
428 (alphaTy `mkFunTy` tTy)
429 `mkFunTy` alphaListTy `mkFunTy` alphaListTy
430 usingExpr' <- tcPolyExpr usingExpr using_ty
431 return (usingExpr', Just byExpr')
433 binders' <- tcLookupLocalIds binders
434 thing <- thing_inside elt_ty'
436 return (binders', usingExpr', maybeByExpr', thing)
438 return (TransformStmt stmts' binders' usingExpr' maybeByExpr' noSyntaxExpr noSyntaxExpr, thing)
440 tcLcStmt m_tc ctxt (GroupStmt stmts bindersMap by using _ _ _) elt_ty thing_inside
441 = do { let (bndr_names, list_bndr_names) = unzip bindersMap
443 ; (stmts', (bndr_ids, by', using_ty, elt_ty')) <-
444 tcStmts (TransformStmtCtxt ctxt) (tcLcStmt m_tc) stmts elt_ty $ \elt_ty' -> do
447 Nothing -> -- check that using :: forall a. [a] -> [[a]]
448 return (Nothing, mkForAllTy alphaTyVar $
449 alphaListTy `mkFunTy` alphaListListTy)
451 Just by_e -> -- check that using :: forall a. (a -> t) -> [a] -> [[a]]
453 do { (by_e', t_ty) <- tcInferRhoNC by_e
454 ; return (Just by_e', mkForAllTy alphaTyVar $
455 (alphaTy `mkFunTy` t_ty)
456 `mkFunTy` alphaListTy
457 `mkFunTy` alphaListListTy) }
458 -- Find the Ids (and hence types) of all old binders
459 bndr_ids <- tcLookupLocalIds bndr_names
461 return (bndr_ids, by', using_ty, elt_ty')
463 -- Ensure that every old binder of type b is linked up with
464 -- its new binder which should have type [b]
465 ; let list_bndr_ids = zipWith mk_list_bndr list_bndr_names bndr_ids
466 bindersMap' = bndr_ids `zip` list_bndr_ids
467 -- See Note [GroupStmt binder map] in HsExpr
469 ; using' <- case using of
470 Left e -> do { e' <- tcPolyExpr e using_ty; return (Left e') }
471 Right e -> do { e' <- tcPolyExpr (noLoc e) using_ty; return (Right (unLoc e')) }
473 -- Type check the thing in the environment with
474 -- these new binders and return the result
475 ; thing <- tcExtendIdEnv list_bndr_ids (thing_inside elt_ty')
476 ; return (GroupStmt stmts' bindersMap' by' using' noSyntaxExpr noSyntaxExpr noSyntaxExpr, thing) }
478 alphaListTy = mkTyConApp m_tc [alphaTy]
479 alphaListListTy = mkTyConApp m_tc [alphaListTy]
481 mk_list_bndr :: Name -> TcId -> TcId
482 mk_list_bndr list_bndr_name bndr_id
483 = mkLocalId list_bndr_name (mkTyConApp m_tc [idType bndr_id])
485 tcLcStmt _ _ stmt _ _
486 = pprPanic "tcLcStmt: unexpected Stmt" (ppr stmt)
489 --------------------------------
490 -- Monad comprehensions
492 tcMcStmt :: TcStmtChecker
494 -- Generators for monad comprehensions ( pat <- rhs )
496 -- [ body | q <- gen ] -> gen :: m a
499 tcMcStmt ctxt (BindStmt pat rhs bind_op fail_op) res_ty thing_inside
500 = do { rhs_ty <- newFlexiTyVarTy liftedTypeKind
501 ; pat_ty <- newFlexiTyVarTy liftedTypeKind
502 ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
503 ; bind_op' <- tcSyntaxOp MCompOrigin bind_op
504 (mkFunTys [rhs_ty, mkFunTy pat_ty new_res_ty] res_ty)
506 -- If (but only if) the pattern can fail,
507 -- typecheck the 'fail' operator
508 ; fail_op' <- if isIrrefutableHsPat pat
509 then return noSyntaxExpr
510 else tcSyntaxOp MCompOrigin fail_op (mkFunTy stringTy new_res_ty)
512 ; rhs' <- tcMonoExprNC rhs rhs_ty
513 ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $
514 thing_inside new_res_ty
516 ; return (BindStmt pat' rhs' bind_op' fail_op', thing) }
518 -- Boolean expressions.
520 -- [ body | stmts, expr ] -> expr :: m Bool
522 tcMcStmt _ (ExprStmt rhs then_op guard_op _) res_ty thing_inside
523 = do { -- Deal with rebindable syntax:
524 -- guard_op :: test_ty -> rhs_ty
525 -- then_op :: rhs_ty -> new_res_ty -> res_ty
526 -- Where test_ty is, for example, Bool
527 test_ty <- newFlexiTyVarTy liftedTypeKind
528 ; rhs_ty <- newFlexiTyVarTy liftedTypeKind
529 ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
530 ; rhs' <- tcMonoExpr rhs test_ty
531 ; guard_op' <- tcSyntaxOp MCompOrigin guard_op
532 (mkFunTy test_ty rhs_ty)
533 ; then_op' <- tcSyntaxOp MCompOrigin then_op
534 (mkFunTys [rhs_ty, new_res_ty] res_ty)
535 ; thing <- thing_inside new_res_ty
536 ; return (ExprStmt rhs' then_op' guard_op' rhs_ty, thing) }
538 -- Transform statements.
540 -- [ body | stmts, then f ] -> f :: forall a. m a -> m a
541 -- [ body | stmts, then f by e ] -> f :: forall a. (a -> t) -> m a -> m a
543 tcMcStmt ctxt (TransformStmt stmts binders usingExpr maybeByExpr return_op bind_op) elt_ty thing_inside
545 -- We don't know the types of binders yet, so we use this dummy and
546 -- later unify this type with the `m_bndr_ty`
547 ty_dummy <- newFlexiTyVarTy liftedTypeKind
549 ; (stmts', (binders', usingExpr', maybeByExpr', return_op', bind_op', thing)) <-
550 tcStmts (TransformStmtCtxt ctxt) tcMcStmt stmts ty_dummy $ \elt_ty' -> do
551 { (_, (m_ty, _)) <- matchExpectedAppTy elt_ty'
552 ; (usingExpr', maybeByExpr') <-
555 -- We must validate that usingExpr :: forall a. m a -> m a
556 let using_ty = mkForAllTy alphaTyVar $
557 (m_ty `mkAppTy` alphaTy)
559 (m_ty `mkAppTy` alphaTy)
560 usingExpr' <- tcPolyExpr usingExpr using_ty
561 return (usingExpr', Nothing)
563 -- We must infer a type such that e :: t and then check that
564 -- usingExpr :: forall a. (a -> t) -> m a -> m a
565 (byExpr', tTy) <- tcInferRhoNC byExpr
566 let using_ty = mkForAllTy alphaTyVar $
567 (alphaTy `mkFunTy` tTy)
569 (m_ty `mkAppTy` alphaTy)
571 (m_ty `mkAppTy` alphaTy)
572 usingExpr' <- tcPolyExpr usingExpr using_ty
573 return (usingExpr', Just byExpr')
575 ; bndr_ids <- tcLookupLocalIds binders
577 -- `return` and `>>=` are used to pass around/modify our
578 -- binders, so we know their types:
580 -- return :: (a,b,c,..) -> m (a,b,c,..)
581 -- (>>=) :: m (a,b,c,..)
582 -- -> ( (a,b,c,..) -> m (a,b,c,..) )
585 ; let bndr_ty = mkChunkified mkBoxedTupleTy $ map idType bndr_ids
586 m_bndr_ty = m_ty `mkAppTy` bndr_ty
588 ; return_op' <- tcSyntaxOp MCompOrigin return_op
589 (bndr_ty `mkFunTy` m_bndr_ty)
591 ; bind_op' <- tcSyntaxOp MCompOrigin bind_op $
592 m_bndr_ty `mkFunTy` (bndr_ty `mkFunTy` elt_ty)
595 -- Unify types of the inner comprehension and the binders type
596 ; _ <- unifyType elt_ty' m_bndr_ty
598 -- Typecheck the `thing` with out old type (which is the type
599 -- of the final result of our comprehension)
600 ; thing <- thing_inside elt_ty
602 ; return (bndr_ids, usingExpr', maybeByExpr', return_op', bind_op', thing) }
604 ; return (TransformStmt stmts' binders' usingExpr' maybeByExpr' return_op' bind_op', thing) }
606 -- Grouping statements
608 -- [ body | stmts, then group by e ]
610 -- [ body | stmts, then group by e using f ]
612 -- f :: forall a. (a -> t) -> m a -> m (m a)
613 -- [ body | stmts, then group using f ]
614 -- -> f :: forall a. m a -> m (m a)
616 tcMcStmt ctxt (GroupStmt stmts bindersMap by using return_op bind_op liftM_op) elt_ty thing_inside
617 = do { let (bndr_names, m_bndr_names) = unzip bindersMap
619 ; (_,(m_ty,_)) <- matchExpectedAppTy elt_ty
620 ; let alphaMTy = m_ty `mkAppTy` alphaTy
621 alphaMMTy = m_ty `mkAppTy` alphaMTy
623 -- We don't know the type of the bindings yet. It's not elt_ty!
624 ; bndr_ty_dummy <- newFlexiTyVarTy liftedTypeKind
626 ; (stmts', (bndr_ids, by', using_ty, return_op', bind_op')) <-
627 tcStmts (TransformStmtCtxt ctxt) tcMcStmt stmts bndr_ty_dummy $ \elt_ty' -> do
630 Nothing -> -- check that using :: forall a. m a -> m (m a)
631 return (Nothing, mkForAllTy alphaTyVar $
632 alphaMTy `mkFunTy` alphaMMTy)
634 Just by_e -> -- check that using :: forall a. (a -> t) -> m a -> m (m a)
636 do { (by_e', t_ty) <- tcInferRhoNC by_e
637 ; return (Just by_e', mkForAllTy alphaTyVar $
638 (alphaTy `mkFunTy` t_ty)
640 `mkFunTy` alphaMMTy) }
643 -- Find the Ids (and hence types) of all old binders
644 ; bndr_ids <- tcLookupLocalIds bndr_names
646 -- 'return' is only used for the binders, so we know its type.
648 -- return :: (a,b,c,..) -> m (a,b,c,..)
650 ; let bndr_ty = mkChunkified mkBoxedTupleTy $ map idType bndr_ids
651 m_bndr_ty = m_ty `mkAppTy` bndr_ty
652 ; return_op' <- tcSyntaxOp MCompOrigin return_op $ bndr_ty `mkFunTy` m_bndr_ty
654 -- '>>=' is used to pass the grouped binders to the rest of the
657 -- (>>=) :: m (m a, m b, m c, ..)
658 -- -> ( (m a, m b, m c, ..) -> new_elt_ty )
661 ; let bndr_m_ty = mkChunkified mkBoxedTupleTy $ map (mkAppTy m_ty . idType) bndr_ids
662 m_bndr_m_ty = m_ty `mkAppTy` bndr_m_ty
663 ; new_elt_ty <- newFlexiTyVarTy liftedTypeKind
664 ; bind_op' <- tcSyntaxOp MCompOrigin bind_op $
665 m_bndr_m_ty `mkFunTy` (bndr_m_ty `mkFunTy` new_elt_ty)
668 -- Finally make sure the type of the inner comprehension
669 -- represents the types of our binders
670 ; _ <- unifyType elt_ty' m_bndr_ty
672 ; return (bndr_ids, by', using_ty, return_op', bind_op') }
674 ; let mk_m_bndr :: Name -> TcId -> TcId
675 mk_m_bndr m_bndr_name bndr_id =
676 mkLocalId m_bndr_name (m_ty `mkAppTy` idType bndr_id)
678 -- Ensure that every old binder of type `b` is linked up with its
679 -- new binder which should have type `m b`
680 m_bndr_ids = zipWith mk_m_bndr m_bndr_names bndr_ids
681 bindersMap' = bndr_ids `zip` m_bndr_ids
683 -- See Note [GroupStmt binder map] in HsExpr
685 ; using' <- case using of
686 Left e -> do { e' <- tcPolyExpr e using_ty; return (Left e') }
687 Right e -> do { e' <- tcPolyExpr (noLoc e) using_ty; return (Right (unLoc e')) }
689 -- Type check 'liftM' with 'forall a b. (a -> b) -> m_ty a -> m_ty b'
690 ; liftM_op' <- fmap unLoc . tcPolyExpr (noLoc liftM_op) $
691 mkForAllTy alphaTyVar $ mkForAllTy betaTyVar $
692 (alphaTy `mkFunTy` betaTy)
694 (m_ty `mkAppTy` alphaTy)
696 (m_ty `mkAppTy` betaTy)
698 -- Type check the thing in the environment with these new binders and
700 ; thing <- tcExtendIdEnv m_bndr_ids (thing_inside elt_ty)
702 ; return (GroupStmt stmts' bindersMap' by' using' return_op' bind_op' liftM_op', thing) }
704 -- Typecheck `ParStmt`. See `tcLcStmt` for more informations about typechecking
707 -- Note: The `mzip` function will get typechecked via:
709 -- ParStmt [st1::t1, st2::t2, st3::t3]
712 -- -> (m st2 -> m st3 -> m (st2, st3)) -- recursive call
713 -- -> m (st1, (st2, st3))
715 tcMcStmt ctxt (ParStmt bndr_stmts_s mzip_op bind_op return_op) elt_ty thing_inside
716 = do { (_,(m_ty,_)) <- matchExpectedAppTy elt_ty
717 ; (pairs', thing) <- loop m_ty bndr_stmts_s
719 ; let mzip_ty = mkForAllTys [alphaTyVar, betaTyVar] $
720 (m_ty `mkAppTy` alphaTy)
722 (m_ty `mkAppTy` betaTy)
724 (m_ty `mkAppTy` mkBoxedTupleTy [alphaTy, betaTy])
725 ; mzip_op' <- unLoc `fmap` tcPolyExpr (noLoc mzip_op) mzip_ty
728 ; let tys = map (mkChunkified mkBoxedTupleTy . map idType . snd) pairs'
729 tuple_ty = mk_tuple_ty tys
731 ; bind_op' <- tcSyntaxOp MCompOrigin bind_op $
732 (m_ty `mkAppTy` tuple_ty)
734 (tuple_ty `mkFunTy` elt_ty)
738 ; return_op' <- fmap unLoc . tcPolyExpr (noLoc return_op) $
739 mkForAllTy alphaTyVar $
740 alphaTy `mkFunTy` (m_ty `mkAppTy` alphaTy)
741 ; return (ParStmt pairs' mzip_op' bind_op' return_op', thing) }
743 where mk_tuple_ty tys = foldr (\tn tm -> mkBoxedTupleTy [tn, tm]) (last tys) (init tys)
745 -- loop :: Type -- m_ty
746 -- -> [([LStmt Name], [Name])]
747 -- -> TcM ([([LStmt TcId], [TcId])], thing)
748 loop _ [] = do { thing <- thing_inside elt_ty
749 ; return ([], thing) } -- matching in the branches
751 loop m_ty ((stmts, names) : pairs)
752 = do { -- type dummy since we don't know all binder types yet
753 ty_dummy <- newFlexiTyVarTy liftedTypeKind
754 ; (stmts', (ids, pairs', thing))
755 <- tcStmts ctxt tcMcStmt stmts ty_dummy $ \elt_ty' ->
756 do { ids <- tcLookupLocalIds names
757 ; _ <- unifyType elt_ty' (m_ty `mkAppTy` (mkChunkified mkBoxedTupleTy) (map idType ids))
758 ; (pairs', thing) <- loop m_ty pairs
759 ; return (ids, pairs', thing) }
760 ; return ( (stmts', ids) : pairs', thing ) }
763 = pprPanic "tcMcStmt: unexpected Stmt" (ppr stmt)
765 -- Typecheck 'body' with type 'a' instead of 'm a' like the rest of the
766 -- statements, ignore the second type argument coming from the tcStmts loop
767 tcMcBody :: LHsExpr Name
770 -> TcM (LHsExpr TcId, SyntaxExpr TcId)
771 tcMcBody body return_op res_ty
772 = do { (_, (_, a_ty)) <- matchExpectedAppTy res_ty
773 ; body' <- tcMonoExpr body a_ty
774 ; return_op' <- tcSyntaxOp MCompOrigin return_op
775 (a_ty `mkFunTy` res_ty)
776 ; return (body', return_op')
780 --------------------------------
782 -- The main excitement here is dealing with rebindable syntax
784 tcDoStmt :: TcStmtChecker
786 tcDoStmt ctxt (BindStmt pat rhs bind_op fail_op) res_ty thing_inside
787 = do { -- Deal with rebindable syntax:
788 -- (>>=) :: rhs_ty -> (pat_ty -> new_res_ty) -> res_ty
789 -- This level of generality is needed for using do-notation
790 -- in full generality; see Trac #1537
792 -- I'd like to put this *after* the tcSyntaxOp
793 -- (see Note [Treat rebindable syntax first], but that breaks
794 -- the rigidity info for GADTs. When we move to the new story
795 -- for GADTs, we can move this after tcSyntaxOp
796 rhs_ty <- newFlexiTyVarTy liftedTypeKind
797 ; pat_ty <- newFlexiTyVarTy liftedTypeKind
798 ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
799 ; bind_op' <- tcSyntaxOp DoOrigin bind_op
800 (mkFunTys [rhs_ty, mkFunTy pat_ty new_res_ty] res_ty)
802 -- If (but only if) the pattern can fail,
803 -- typecheck the 'fail' operator
804 ; fail_op' <- if isIrrefutableHsPat pat
805 then return noSyntaxExpr
806 else tcSyntaxOp DoOrigin fail_op (mkFunTy stringTy new_res_ty)
808 ; rhs' <- tcMonoExprNC rhs rhs_ty
809 ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $
810 thing_inside new_res_ty
812 ; return (BindStmt pat' rhs' bind_op' fail_op', thing) }
815 tcDoStmt _ (ExprStmt rhs then_op _ _) res_ty thing_inside
816 = do { -- Deal with rebindable syntax;
817 -- (>>) :: rhs_ty -> new_res_ty -> res_ty
818 -- See also Note [Treat rebindable syntax first]
819 rhs_ty <- newFlexiTyVarTy liftedTypeKind
820 ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
821 ; then_op' <- tcSyntaxOp DoOrigin then_op
822 (mkFunTys [rhs_ty, new_res_ty] res_ty)
824 ; rhs' <- tcMonoExprNC rhs rhs_ty
825 ; thing <- thing_inside new_res_ty
826 ; return (ExprStmt rhs' then_op' noSyntaxExpr rhs_ty, thing) }
828 tcDoStmt ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = later_names
829 , recS_rec_ids = rec_names, recS_ret_fn = ret_op
830 , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op })
832 = do { let tup_names = rec_names ++ filterOut (`elem` rec_names) later_names
833 ; tup_elt_tys <- newFlexiTyVarTys (length tup_names) liftedTypeKind
834 ; let tup_ids = zipWith mkLocalId tup_names tup_elt_tys
835 tup_ty = mkBoxedTupleTy tup_elt_tys
837 ; tcExtendIdEnv tup_ids $ do
838 { stmts_ty <- newFlexiTyVarTy liftedTypeKind
839 ; (stmts', (ret_op', tup_rets))
840 <- tcStmts ctxt tcDoStmt stmts stmts_ty $ \ inner_res_ty ->
841 do { tup_rets <- zipWithM tcCheckId tup_names tup_elt_tys
842 -- Unify the types of the "final" Ids (which may
843 -- be polymorphic) with those of "knot-tied" Ids
844 ; ret_op' <- tcSyntaxOp DoOrigin ret_op (mkFunTy tup_ty inner_res_ty)
845 ; return (ret_op', tup_rets) }
847 ; mfix_res_ty <- newFlexiTyVarTy liftedTypeKind
848 ; mfix_op' <- tcSyntaxOp DoOrigin mfix_op
849 (mkFunTy (mkFunTy tup_ty stmts_ty) mfix_res_ty)
851 ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
852 ; bind_op' <- tcSyntaxOp DoOrigin bind_op
853 (mkFunTys [mfix_res_ty, mkFunTy tup_ty new_res_ty] res_ty)
855 ; thing <- thing_inside new_res_ty
856 -- ; lie_binds <- bindLocalMethods lie tup_ids
858 ; let rec_ids = takeList rec_names tup_ids
859 ; later_ids <- tcLookupLocalIds later_names
860 ; traceTc "tcdo" $ vcat [ppr rec_ids <+> ppr (map idType rec_ids),
861 ppr later_ids <+> ppr (map idType later_ids)]
862 ; return (RecStmt { recS_stmts = stmts', recS_later_ids = later_ids
863 , recS_rec_ids = rec_ids, recS_ret_fn = ret_op'
864 , recS_mfix_fn = mfix_op', recS_bind_fn = bind_op'
865 , recS_rec_rets = tup_rets }, thing)
869 = pprPanic "tcDoStmt: unexpected Stmt" (ppr stmt)
872 Note [Treat rebindable syntax first]
873 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
875 do { bar; ... } :: IO ()
876 we want to typecheck 'bar' in the knowledge that it should be an IO thing,
877 pushing info from the context into the RHS. To do this, we check the
878 rebindable syntax first, and push that information into (tcMonoExprNC rhs).
879 Otherwise the error shows up when cheking the rebindable syntax, and
880 the expected/inferred stuff is back to front (see Trac #3613).
883 --------------------------------
885 -- The distinctive features here are
887 -- (b) no rebindable syntax
889 tcMDoStmt :: (LHsExpr Name -> TcM (LHsExpr TcId, TcType)) -- RHS inference
891 tcMDoStmt tc_rhs ctxt (BindStmt pat rhs _ _) res_ty thing_inside
892 = do { (rhs', pat_ty) <- tc_rhs rhs
893 ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $
895 ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) }
897 tcMDoStmt tc_rhs _ (ExprStmt rhs _ _ _) res_ty thing_inside
898 = do { (rhs', elt_ty) <- tc_rhs rhs
899 ; thing <- thing_inside res_ty
900 ; return (ExprStmt rhs' noSyntaxExpr noSyntaxExpr elt_ty, thing) }
902 tcMDoStmt tc_rhs ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = laterNames
903 , recS_rec_ids = recNames }) res_ty thing_inside
904 = do { rec_tys <- newFlexiTyVarTys (length recNames) liftedTypeKind
905 ; let rec_ids = zipWith mkLocalId recNames rec_tys
906 ; tcExtendIdEnv rec_ids $ do
907 { (stmts', (later_ids, rec_rets))
908 <- tcStmts ctxt (tcMDoStmt tc_rhs) stmts res_ty $ \ _res_ty' ->
909 -- ToDo: res_ty not really right
910 do { rec_rets <- zipWithM tcCheckId recNames rec_tys
911 ; later_ids <- tcLookupLocalIds laterNames
912 ; return (later_ids, rec_rets) }
914 ; thing <- tcExtendIdEnv later_ids (thing_inside res_ty)
915 -- NB: The rec_ids for the recursive things
916 -- already scope over this part. This binding may shadow
917 -- some of them with polymorphic things with the same Name
918 -- (see note [RecStmt] in HsExpr)
920 ; return (RecStmt stmts' later_ids rec_ids noSyntaxExpr noSyntaxExpr noSyntaxExpr rec_rets, thing)
923 tcMDoStmt _ _ stmt _ _
924 = pprPanic "tcMDoStmt: unexpected Stmt" (ppr stmt)
929 %************************************************************************
931 \subsection{Errors and contexts}
933 %************************************************************************
935 @sameNoOfArgs@ takes a @[RenamedMatch]@ and decides whether the same
936 number of args are used in each equation.
939 checkArgs :: Name -> MatchGroup Name -> TcM ()
940 checkArgs fun (MatchGroup (match1:matches) _)
941 | null bad_matches = return ()
943 = failWithTc (vcat [ptext (sLit "Equations for") <+> quotes (ppr fun) <+>
944 ptext (sLit "have different numbers of arguments"),
945 nest 2 (ppr (getLoc match1)),
946 nest 2 (ppr (getLoc (head bad_matches)))])
948 n_args1 = args_in_match match1
949 bad_matches = [m | m <- matches, args_in_match m /= n_args1]
951 args_in_match :: LMatch Name -> Int
952 args_in_match (L _ (Match pats _ _)) = length pats
953 checkArgs fun _ = pprPanic "TcPat.checkArgs" (ppr fun) -- Matches always non-empty