579e5d486ecd3049611b6c65221278f30f283a97
[ghc-hetmet.git] / compiler / typecheck / TcMatches.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 TcMatches: Typecheck some @Matches@
7
8 \begin{code}
9 module TcMatches ( tcMatchesFun, tcGRHSsPat, tcMatchesCase, tcMatchLambda,
10                    TcMatchCtxt(..), 
11                    tcStmts, tcStmtsAndThen, tcDoStmts, tcBody,
12                    tcDoStmt, tcMDoStmt, tcGuardStmt
13        ) where
14
15 import {-# SOURCE #-}   TcExpr( tcSyntaxOp, tcInferRhoNC, tcInferRho, tcCheckId,
16                                 tcMonoExpr, tcMonoExprNC, tcPolyExpr )
17
18 import HsSyn
19 import BasicTypes
20 import TcRnMonad
21 import TcEnv
22 import TcPat
23 import TcMType
24 import TcType
25 import TcBinds
26 import TcUnify
27 import Name
28 import TysWiredIn
29 import Id
30 import TyCon
31 import TysPrim
32 import Coercion         ( mkSymCoI )
33 import Outputable
34 import Util
35 import SrcLoc
36 import FastString
37
38 -- Create chunkified tuple tybes for monad comprehensions
39 import MkCore
40
41 import Control.Monad
42
43 #include "HsVersions.h"
44 \end{code}
45
46 %************************************************************************
47 %*                                                                      *
48 \subsection{tcMatchesFun, tcMatchesCase}
49 %*                                                                      *
50 %************************************************************************
51
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.
56
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.
62
63 \begin{code}
64 tcMatchesFun :: Name -> Bool
65              -> MatchGroup Name
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
77
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) }
84   where
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 }
89 \end{code}
90
91 @tcMatchesCase@ doesn't do the argument-count check because the
92 parser guarantees that each equation has exactly one argument.
93
94 \begin{code}
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
100
101 tcMatchesCase ctxt scrut_ty matches res_ty
102   | isEmptyMatchGroup matches   -- Allow empty case expressions
103   = return (MatchGroup [] (mkFunTys [scrut_ty] res_ty)) 
104
105   | otherwise
106   = tcMatches ctxt [scrut_ty] res_ty matches
107
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
112   where
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
118                 ptext (sLit "has")]
119     match_ctxt = MC { mc_what = LambdaExpr,
120                       mc_body = tcBody }
121 \end{code}
122
123 @tcGRHSsPat@ typechecks @[GRHSs]@ that occur in a @PatMonoBind@.
124
125 \begin{code}
126 tcGRHSsPat :: GRHSs Name -> TcRhoType -> TcM (GRHSs TcId)
127 -- Used for pattern bindings
128 tcGRHSsPat grhss res_ty = tcGRHSs match_ctxt grhss res_ty
129   where
130     match_ctxt = MC { mc_what = PatBindRhs,
131                       mc_body = tcBody }
132 \end{code}
133
134
135 \begin{code}
136 matchFunTys
137   :: SDoc       -- See Note [Herald for matchExpecteFunTys] in TcUnify
138   -> Arity
139   -> TcRhoType
140   -> ([TcSigmaType] -> TcRhoType -> TcM a)
141   -> TcM (HsWrapper, a)
142
143 -- Written in CPS style for historical reasons; 
144 -- could probably be un-CPSd, like matchExpectedTyConApp
145
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) }
150 \end{code}
151
152 %************************************************************************
153 %*                                                                      *
154 \subsection{tcMatch}
155 %*                                                                      *
156 %************************************************************************
157
158 \begin{code}
159 tcMatches :: TcMatchCtxt
160           -> [TcSigmaType]      -- Expected pattern types
161           -> TcRhoType          -- Expected result-type of the Match.
162           -> MatchGroup Name
163           -> TcM (MatchGroup TcId)
164
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
168                                                 -- an alternative
169                  -> TcRhoType
170                  -> TcM (LHsExpr TcId) }        
171
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)) }
176
177 -------------
178 tcMatch :: TcMatchCtxt
179         -> [TcSigmaType]        -- Expected pattern types
180         -> TcRhoType            -- Expected result-type of the Match.
181         -> LMatch Name
182         -> TcM (LMatch TcId)
183
184 tcMatch ctxt pat_tys rhs_ty match 
185   = wrapLocM (tc_match ctxt pat_tys rhs_ty) match
186   where
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') }
192
193     tc_grhss ctxt Nothing grhss rhs_ty 
194       = tcGRHSs ctxt grhss rhs_ty       -- No result signature
195
196         -- Result type sigs are no longer supported
197     tc_grhss _ (Just {}) _ _
198       = panic "tc_ghrss"        -- Rejected by renamer
199
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
206
207 -------------
208 tcGRHSs :: TcMatchCtxt -> GRHSs Name -> TcRhoType
209         -> TcM (GRHSs TcId)
210
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
216
217 tcGRHSs ctxt (GRHSs grhss binds) res_ty
218   = do  { (binds', grhss') <- tcLocalBinds binds $
219                               mapM (wrapLocM (tcGRHS ctxt res_ty)) grhss
220
221         ; return (GRHSs grhss' binds') }
222
223 -------------
224 tcGRHS :: TcMatchCtxt -> TcRhoType -> GRHS Name -> TcM (GRHS TcId)
225
226 tcGRHS ctxt res_ty (GRHS guards rhs)
227   = do  { (guards', rhs') <- tcStmtsAndThen stmt_ctxt tcGuardStmt guards res_ty $
228                              mc_body ctxt rhs
229         ; return (GRHS guards' rhs') }
230   where
231     stmt_ctxt  = PatGuard (mc_what ctxt)
232 \end{code}
233
234
235 %************************************************************************
236 %*                                                                      *
237 \subsection{@tcDoStmts@ typechecks a {\em list} of do statements}
238 %*                                                                      *
239 %************************************************************************
240
241 \begin{code}
242 tcDoStmts :: HsStmtContext Name 
243           -> [LStmt Name]
244           -> TcRhoType
245           -> TcM (HsExpr TcId)          -- Returns a HsDo
246 tcDoStmts ListComp stmts res_ty
247   = do  { (coi, elt_ty) <- matchExpectedListTy res_ty
248         ; stmts' <- tcStmts ListComp (tcLcStmt listTyCon) stmts elt_ty
249         ; return $ mkHsWrapCoI coi 
250                      (HsDo ListComp stmts' (mkListTy elt_ty)) }
251
252 tcDoStmts PArrComp stmts res_ty
253   = do  { (coi, elt_ty) <- matchExpectedPArrTy res_ty
254         ; stmts' <- tcStmts PArrComp (tcLcStmt parrTyCon) stmts elt_ty
255         ; return $ mkHsWrapCoI coi 
256                      (HsDo PArrComp stmts' (mkPArrTy elt_ty)) }
257
258 tcDoStmts DoExpr stmts res_ty
259   = do  { stmts' <- tcStmts DoExpr tcDoStmt stmts res_ty
260         ; return (HsDo DoExpr stmts' res_ty) }
261
262 tcDoStmts MDoExpr stmts res_ty
263   = do  { stmts' <- tcStmts MDoExpr tcDoStmt stmts res_ty
264         ; return (HsDo MDoExpr stmts' res_ty) }
265
266 tcDoStmts MonadComp stmts res_ty
267   = do  { stmts' <- tcStmts MonadComp tcMcStmt stmts res_ty 
268         ; return (HsDo MonadComp stmts' res_ty) }
269
270 tcDoStmts ctxt _ _ = pprPanic "tcDoStmts" (pprStmtContext ctxt)
271
272 tcBody :: LHsExpr Name -> TcRhoType -> TcM (LHsExpr TcId)
273 tcBody body res_ty
274   = do  { traceTc "tcBody" (ppr res_ty)
275         ; body' <- tcMonoExpr body res_ty
276         ; return body' 
277         } 
278 \end{code}
279
280
281 %************************************************************************
282 %*                                                                      *
283 \subsection{tcStmts}
284 %*                                                                      *
285 %************************************************************************
286
287 \begin{code}
288 type TcStmtChecker
289   =  forall thing. HsStmtContext Name
290                 -> Stmt Name
291                 -> TcRhoType                    -- Result type for comprehension
292                 -> (TcRhoType -> TcM thing)     -- Checker for what follows the stmt
293                 -> TcM (Stmt TcId, thing)
294
295 tcStmts :: HsStmtContext Name
296         -> TcStmtChecker        -- NB: higher-rank type
297         -> [LStmt Name]
298         -> TcRhoType
299         -> TcM [LStmt TcId]
300 tcStmts ctxt stmt_chk stmts res_ty
301   = do { (stmts', _) <- tcStmtsAndThen ctxt stmt_chk stmts res_ty $
302                         const (return ())
303        ; return stmts' }
304
305 tcStmtsAndThen :: HsStmtContext Name
306                -> TcStmtChecker -- NB: higher-rank type
307                -> [LStmt Name]
308                -> TcRhoType
309                -> (TcRhoType -> TcM thing)
310                -> TcM ([LStmt TcId], thing)
311
312 -- Note the higher-rank type.  stmt_chk is applied at different
313 -- types in the equations for tcStmts
314
315 tcStmtsAndThen _ _ [] res_ty thing_inside
316   = do  { thing <- thing_inside res_ty
317         ; return ([], thing) }
318
319 -- LetStmts are handled uniformly, regardless of context
320 tcStmtsAndThen ctxt stmt_chk (L loc (LetStmt binds) : stmts) res_ty thing_inside
321   = do  { (binds', (stmts',thing)) <- tcLocalBinds binds $
322                                       tcStmtsAndThen ctxt stmt_chk stmts res_ty thing_inside
323         ; return (L loc (LetStmt binds') : stmts', thing) }
324
325 -- For the vanilla case, handle the location-setting part
326 tcStmtsAndThen ctxt stmt_chk (L loc stmt : stmts) res_ty thing_inside
327   = do  { (stmt', (stmts', thing)) <- 
328                 setSrcSpan loc                              $
329                 addErrCtxt (pprStmtInCtxt ctxt stmt)        $
330                 stmt_chk ctxt stmt res_ty                   $ \ res_ty' ->
331                 popErrCtxt                                  $
332                 tcStmtsAndThen ctxt stmt_chk stmts res_ty'  $
333                 thing_inside
334         ; return (L loc stmt' : stmts', thing) }
335
336 --------------------------------
337 --      Pattern guards
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) }
343
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 $
347                             thing_inside res_ty
348         ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) }
349
350 tcGuardStmt _ stmt _ _
351   = pprPanic "tcGuardStmt: unexpected Stmt" (ppr stmt)
352
353
354 --------------------------------
355 --      List comprehensions and PArrays
356
357 tcLcStmt :: TyCon       -- The list/Parray type constructor ([] or PArray)
358          -> TcStmtChecker
359
360 tcLcStmt _ _ (LastStmt body _) elt_ty thing_inside
361   = do { body' <- tcMonoExprNC body elt_ty
362        ; thing <- thing_inside (panic "tcLcStmt: thing_inside")
363        ; return (LastStmt body' noSyntaxExpr, thing) }
364
365 -- A generator, pat <- rhs
366 tcLcStmt m_tc ctxt (BindStmt pat rhs _ _) elt_ty thing_inside
367  = do   { pat_ty <- newFlexiTyVarTy liftedTypeKind
368         ; rhs'   <- tcMonoExpr rhs (mkTyConApp m_tc [pat_ty])
369         ; (pat', thing)  <- tcPat (StmtCtxt ctxt) pat pat_ty $
370                             thing_inside elt_ty
371         ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) }
372
373 -- A boolean guard
374 tcLcStmt _ _ (ExprStmt rhs _ _ _) elt_ty thing_inside
375   = do  { rhs'  <- tcMonoExpr rhs boolTy
376         ; thing <- thing_inside elt_ty
377         ; return (ExprStmt rhs' noSyntaxExpr noSyntaxExpr boolTy, thing) }
378
379 -- A parallel set of comprehensions
380 --      [ (g x, h x) | ... ; let g v = ...
381 --                   | ... ; let h v = ... ]
382 --
383 -- It's possible that g,h are overloaded, so we need to feed the LIE from the
384 -- (g x, h x) up through both lots of bindings (so we get the bindLocalMethods).
385 -- Similarly if we had an existential pattern match:
386 --
387 --      data T = forall a. Show a => C a
388 --
389 --      [ (show x, show y) | ... ; C x <- ...
390 --                         | ... ; C y <- ... ]
391 --
392 -- Then we need the LIE from (show x, show y) to be simplified against
393 -- the bindings for x and y.  
394 -- 
395 -- It's difficult to do this in parallel, so we rely on the renamer to 
396 -- ensure that g,h and x,y don't duplicate, and simply grow the environment.
397 -- So the binders of the first parallel group will be in scope in the second
398 -- group.  But that's fine; there's no shadowing to worry about.
399
400 tcLcStmt m_tc ctxt (ParStmt bndr_stmts_s _ _ _) elt_ty thing_inside
401   = do  { (pairs', thing) <- loop bndr_stmts_s
402         ; return (ParStmt pairs' noSyntaxExpr noSyntaxExpr noSyntaxExpr, thing) }
403   where
404     -- loop :: [([LStmt Name], [Name])] -> TcM ([([LStmt TcId], [TcId])], thing)
405     loop [] = do { thing <- thing_inside elt_ty
406                  ; return ([], thing) }         -- matching in the branches
407
408     loop ((stmts, names) : pairs)
409       = do { (stmts', (ids, pairs', thing))
410                 <- tcStmtsAndThen ctxt (tcLcStmt m_tc) stmts elt_ty $ \ _elt_ty' ->
411                    do { ids <- tcLookupLocalIds names
412                       ; (pairs', thing) <- loop pairs
413                       ; return (ids, pairs', thing) }
414            ; return ( (stmts', ids) : pairs', thing ) }
415
416 tcLcStmt m_tc ctxt (TransStmt { trS_form = form, trS_stmts = stmts
417                               , trS_bndrs =  bindersMap
418                               , trS_by = by, trS_using = using }) elt_ty thing_inside
419   = do { let (bndr_names, n_bndr_names) = unzip bindersMap
420              unused_ty = pprPanic "tcLcStmt: inner ty" (ppr bindersMap)
421              -- The inner 'stmts' lack a LastStmt, so the element type
422              --  passed in to tcStmtsAndThen is never looked at
423        ; (stmts', (bndr_ids, by'))
424             <- tcStmtsAndThen (TransformStmtCtxt ctxt) (tcLcStmt m_tc) stmts unused_ty $ \_ -> do
425                { by' <- case by of
426                            Nothing -> return Nothing
427                            Just e  -> do { e_ty <- tcInferRho e; return (Just e_ty) }
428                ; bndr_ids <- tcLookupLocalIds bndr_names
429                ; return (bndr_ids, by') }
430
431        ; let m_app ty = mkTyConApp m_tc [ty]
432
433        --------------- Typecheck the 'using' function -------------
434        -- using :: ((a,b,c)->t) -> m (a,b,c) -> m (a,b,c)m      (ThenForm)
435        --       :: ((a,b,c)->t) -> m (a,b,c) -> m (m (a,b,c)))  (GroupForm)
436
437          -- n_app :: Type -> Type   -- Wraps a 'ty' into '[ty]' for GroupForm
438        ; let n_app = case form of
439                        ThenForm -> (\ty -> ty)
440                        _        -> m_app
441
442              by_arrow :: Type -> Type     -- Wraps 'ty' to '(a->t) -> ty' if the By is present
443              by_arrow = case by' of
444                           Nothing       -> \ty -> ty
445                           Just (_,e_ty) -> \ty -> e_ty `mkFunTy` ty
446
447              tup_ty        = mkBigCoreVarTupTy bndr_ids
448              poly_arg_ty   = m_app alphaTy
449              poly_res_ty   = m_app (n_app alphaTy)
450              using_poly_ty = mkForAllTy alphaTyVar $ by_arrow $ 
451                              poly_arg_ty `mkFunTy` poly_res_ty
452
453        ; using' <- tcPolyExpr using using_poly_ty
454        ; let final_using = fmap (HsWrap (WpTyApp tup_ty)) using' 
455
456              -- 'stmts' returns a result of type (m1_ty tuple_ty),
457              -- typically something like [(Int,Bool,Int)]
458              -- We don't know what tuple_ty is yet, so we use a variable
459        ; let mk_n_bndr :: Name -> TcId -> TcId
460              mk_n_bndr n_bndr_name bndr_id = mkLocalId n_bndr_name (n_app (idType bndr_id))
461
462              -- Ensure that every old binder of type `b` is linked up with its
463              -- new binder which should have type `n b`
464              -- See Note [GroupStmt binder map] in HsExpr
465              n_bndr_ids  = zipWith mk_n_bndr n_bndr_names bndr_ids
466              bindersMap' = bndr_ids `zip` n_bndr_ids
467
468        -- Type check the thing in the environment with 
469        -- these new binders and return the result
470        ; thing <- tcExtendIdEnv n_bndr_ids (thing_inside elt_ty)
471
472        ; return (emptyTransStmt { trS_stmts = stmts', trS_bndrs = bindersMap' 
473                                 , trS_by = fmap fst by', trS_using = final_using 
474                                 , trS_form = form }, thing) }
475     
476 tcLcStmt _ _ stmt _ _
477   = pprPanic "tcLcStmt: unexpected Stmt" (ppr stmt)
478         
479
480 --------------------------------
481 --      Monad comprehensions
482
483 tcMcStmt :: TcStmtChecker
484
485 tcMcStmt _ (LastStmt body return_op) res_ty thing_inside
486   = do  { a_ty       <- newFlexiTyVarTy liftedTypeKind
487         ; return_op' <- tcSyntaxOp MCompOrigin return_op
488                                    (a_ty `mkFunTy` res_ty)
489         ; body'      <- tcMonoExprNC body a_ty
490         ; thing      <- thing_inside (panic "tcMcStmt: thing_inside")
491         ; return (LastStmt body' return_op', thing) } 
492
493 -- Generators for monad comprehensions ( pat <- rhs )
494 --
495 --   [ body | q <- gen ]  ->  gen :: m a
496 --                            q   ::   a
497 --
498
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
504            -- (>>=) :: rhs_ty -> (pat_ty -> new_res_ty) -> res_ty
505         ; bind_op'   <- tcSyntaxOp MCompOrigin bind_op 
506                              (mkFunTys [rhs_ty, mkFunTy pat_ty new_res_ty] res_ty)
507
508            -- If (but only if) the pattern can fail, typecheck the 'fail' operator
509         ; fail_op' <- if isIrrefutableHsPat pat 
510                       then return noSyntaxExpr
511                       else tcSyntaxOp MCompOrigin fail_op (mkFunTy stringTy new_res_ty)
512
513         ; rhs' <- tcMonoExprNC rhs rhs_ty
514         ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $
515                            thing_inside new_res_ty
516
517         ; return (BindStmt pat' rhs' bind_op' fail_op', thing) }
518
519 -- Boolean expressions.
520 --
521 --   [ body | stmts, expr ]  ->  expr :: m Bool
522 --
523 tcMcStmt _ (ExprStmt rhs then_op guard_op _) res_ty thing_inside
524   = do  { -- Deal with rebindable syntax:
525           --    guard_op :: test_ty -> rhs_ty
526           --    then_op  :: rhs_ty -> new_res_ty -> res_ty
527           -- Where test_ty is, for example, Bool
528           test_ty    <- newFlexiTyVarTy liftedTypeKind
529         ; rhs_ty     <- newFlexiTyVarTy liftedTypeKind
530         ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
531         ; rhs'       <- tcMonoExpr rhs test_ty
532         ; guard_op'  <- tcSyntaxOp MCompOrigin guard_op
533                                    (mkFunTy test_ty rhs_ty)
534         ; then_op'   <- tcSyntaxOp MCompOrigin then_op
535                                    (mkFunTys [rhs_ty, new_res_ty] res_ty)
536         ; thing      <- thing_inside new_res_ty
537         ; return (ExprStmt rhs' then_op' guard_op' rhs_ty, thing) }
538
539 -- Grouping statements
540 --
541 --   [ body | stmts, then group by e ]
542 --     ->  e :: t
543 --   [ body | stmts, then group by e using f ]
544 --     ->  e :: t
545 --         f :: forall a. (a -> t) -> m a -> m (m a)
546 --   [ body | stmts, then group using f ]
547 --     ->  f :: forall a. m a -> m (m a)
548
549 -- We type [ body | (stmts, group by e using f), ... ]
550 --     f <optional by> [ (a,b,c) | stmts ] >>= \(a,b,c) -> ...body....
551 --
552 -- We type the functions as follows:
553 --     f <optional by> :: m1 (a,b,c) -> m2 (a,b,c)              (ThenForm)
554 --                     :: m1 (a,b,c) -> m2 (n (a,b,c))          (GroupForm)
555 --     (>>=) :: m2 (a,b,c)     -> ((a,b,c)   -> res) -> res     (ThenForm)
556 --           :: m2 (n (a,b,c)) -> (n (a,b,c) -> res) -> res     (GroupForm)
557 -- 
558 tcMcStmt ctxt (TransStmt { trS_stmts = stmts, trS_bndrs = bindersMap
559                          , trS_by = by, trS_using = using, trS_form = form
560                          , trS_ret = return_op, trS_bind = bind_op 
561                          , trS_fmap = fmap_op }) res_ty thing_inside
562   = do { let star_star_kind = liftedTypeKind `mkArrowKind` liftedTypeKind
563        ; m1_ty   <- newFlexiTyVarTy star_star_kind
564        ; m2_ty   <- newFlexiTyVarTy star_star_kind
565        ; tup_ty  <- newFlexiTyVarTy liftedTypeKind
566        ; by_e_ty <- newFlexiTyVarTy liftedTypeKind      -- The type of the 'by' expression (if any)
567
568        --------------- Typecheck the 'using' function -------------
569        -- using :: ((a,b,c)->t) -> m1 (a,b,c) -> m2 (n (a,b,c))
570
571          -- n_app :: Type -> Type   -- Wraps a 'ty' into '(n ty)' for GroupForm
572        ; n_app <- case form of
573                     ThenForm -> return (\ty -> ty)
574                     _        -> do { n_ty <- newFlexiTyVarTy star_star_kind
575                                    ; return (n_ty `mkAppTy`) }
576        ; let by_arrow :: Type -> Type     -- Wraps 'ty' to '(a->t) -> ty' if the By is present
577              by_arrow = case by of
578                           Nothing -> \ty -> ty
579                           Just {} -> \ty -> by_e_ty `mkFunTy` ty
580
581              poly_arg_ty  = m1_ty `mkAppTy` alphaTy
582              using_arg_ty = m1_ty `mkAppTy` tup_ty
583              poly_res_ty  = m2_ty `mkAppTy` n_app alphaTy
584              using_res_ty = m2_ty `mkAppTy` n_app tup_ty
585              using_poly_ty = mkForAllTy alphaTyVar $ by_arrow $ 
586                              poly_arg_ty `mkFunTy` poly_res_ty
587
588        ; using' <- tcPolyExpr using using_poly_ty
589        ; let final_using = fmap (HsWrap (WpTyApp tup_ty)) using' 
590
591        --------------- Typecheck the 'bind' function -------------
592        -- (>>=) :: m2 (n (a,b,c)) -> ( n (a,b,c) -> new_res_ty ) -> res_ty
593        ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
594        ; let n_tup_ty = n_app tup_ty    -- n (a,b,c)
595        ; bind_op' <- tcSyntaxOp MCompOrigin bind_op $
596                                 using_res_ty `mkFunTy` (n_tup_ty `mkFunTy` new_res_ty)
597                                              `mkFunTy` res_ty
598
599        --------------- Typecheck the 'fmap' function -------------
600        ; fmap_op' <- case form of
601                        ThenForm -> return noSyntaxExpr
602                        _ -> fmap unLoc . tcPolyExpr (noLoc fmap_op) $
603                             mkForAllTy alphaTyVar $ mkForAllTy betaTyVar $
604                             (alphaTy `mkFunTy` betaTy)
605                             `mkFunTy` (n_app alphaTy)
606                             `mkFunTy` (n_app betaTy)
607
608              -- 'stmts' returns a result of type (m1_ty tuple_ty),
609              -- typically something like [(Int,Bool,Int)]
610              -- We don't know what tuple_ty is yet, so we use a variable
611        ; let (bndr_names, n_bndr_names) = unzip bindersMap
612        ; (stmts', (bndr_ids, by', return_op')) <-
613             tcStmtsAndThen (TransformStmtCtxt ctxt) tcMcStmt stmts using_arg_ty $ \res_ty' -> do
614                 { by' <- case by of
615                            Nothing -> return Nothing
616                            Just e  -> do { e' <- tcMonoExpr e by_e_ty; return (Just e') }
617
618                 -- Find the Ids (and hence types) of all old binders
619                 ; bndr_ids <- tcLookupLocalIds bndr_names
620
621                 -- 'return' is only used for the binders, so we know its type.
622                 --   return :: (a,b,c,..) -> m (a,b,c,..)
623                 ; return_op' <- tcSyntaxOp MCompOrigin return_op $ 
624                                 (mkBigCoreVarTupTy bndr_ids) `mkFunTy` res_ty'
625
626                 ; return (bndr_ids, by', return_op') }
627
628        ; let mk_n_bndr :: Name -> TcId -> TcId
629              mk_n_bndr n_bndr_name bndr_id = mkLocalId n_bndr_name (n_app (idType bndr_id))
630
631              -- Ensure that every old binder of type `b` is linked up with its
632              -- new binder which should have type `n b`
633              -- See Note [GroupStmt binder map] in HsExpr
634              n_bndr_ids = zipWith mk_n_bndr n_bndr_names bndr_ids
635              bindersMap' = bndr_ids `zip` n_bndr_ids
636
637        -- Type check the thing in the environment with 
638        -- these new binders and return the result
639        ; thing <- tcExtendIdEnv n_bndr_ids (thing_inside res_ty)
640
641        ; return (TransStmt { trS_stmts = stmts', trS_bndrs = bindersMap' 
642                            , trS_by = by', trS_using = final_using 
643                            , trS_ret = return_op', trS_bind = bind_op'
644                            , trS_fmap = fmap_op', trS_form = form }, thing) }
645
646 -- Typecheck `ParStmt`. See `tcLcStmt` for more informations about typechecking
647 -- of `ParStmt`s.
648 --
649 -- Note: The `mzip` function will get typechecked via:
650 --
651 --   ParStmt [st1::t1, st2::t2, st3::t3]
652 --   
653 --   mzip :: m st1
654 --        -> (m st2 -> m st3 -> m (st2, st3))   -- recursive call
655 --        -> m (st1, (st2, st3))
656 --
657 tcMcStmt ctxt (ParStmt bndr_stmts_s mzip_op bind_op return_op) res_ty thing_inside
658   = do  { (_,(m_ty,_)) <- matchExpectedAppTy res_ty
659         -- ToDo: what if the coercion isn't the identity?
660
661         ; (pairs', thing) <- loop m_ty bndr_stmts_s
662
663         ; let mzip_ty  = mkForAllTys [alphaTyVar, betaTyVar] $
664                          (m_ty `mkAppTy` alphaTy)
665                          `mkFunTy`
666                          (m_ty `mkAppTy` betaTy)
667                          `mkFunTy`
668                          (m_ty `mkAppTy` mkBoxedTupleTy [alphaTy, betaTy])
669         ; mzip_op' <- unLoc `fmap` tcPolyExpr (noLoc mzip_op) mzip_ty
670
671         -- Typecheck bind:
672         ; let tys      = map (mkBigCoreVarTupTy . snd) pairs'
673               tuple_ty = mk_tuple_ty tys
674
675         ; bind_op' <- tcSyntaxOp MCompOrigin bind_op $
676                          (m_ty `mkAppTy` tuple_ty)
677                          `mkFunTy`
678                          (tuple_ty `mkFunTy` res_ty)
679                          `mkFunTy`
680                          res_ty
681
682         ; return_op' <- fmap unLoc . tcPolyExpr (noLoc return_op) $
683                             mkForAllTy alphaTyVar $
684                             alphaTy `mkFunTy` (m_ty `mkAppTy` alphaTy)
685
686         ; return (ParStmt pairs' mzip_op' bind_op' return_op', thing) }
687
688  where mk_tuple_ty tys = foldr1 (\tn tm -> mkBoxedTupleTy [tn, tm]) tys
689
690        -- loop :: Type                                  -- m_ty
691        --      -> [([LStmt Name], [Name])]
692        --      -> TcM ([([LStmt TcId], [TcId])], thing)
693        loop _ [] = do { thing <- thing_inside res_ty
694                       ; return ([], thing) }           -- matching in the branches
695
696        loop m_ty ((stmts, names) : pairs)
697          = do { -- type dummy since we don't know all binder types yet
698                 ty_dummy <- newFlexiTyVarTy liftedTypeKind
699               ; (stmts', (ids, pairs', thing))
700                    <- tcStmtsAndThen ctxt tcMcStmt stmts ty_dummy $ \res_ty' ->
701                       do { ids <- tcLookupLocalIds names
702                          ; _ <- unifyType res_ty' (m_ty `mkAppTy` mkBigCoreVarTupTy ids)
703                          ; (pairs', thing) <- loop m_ty pairs
704                          ; return (ids, pairs', thing) }
705               ; return ( (stmts', ids) : pairs', thing ) }
706
707 tcMcStmt _ stmt _ _
708   = pprPanic "tcMcStmt: unexpected Stmt" (ppr stmt)
709
710 --------------------------------
711 --      Do-notation
712 -- The main excitement here is dealing with rebindable syntax
713
714 tcDoStmt :: TcStmtChecker
715
716 tcDoStmt _ (LastStmt body _) res_ty thing_inside
717   = do { body' <- tcMonoExprNC body res_ty
718        ; thing <- thing_inside (panic "tcDoStmt: thing_inside")
719        ; return (LastStmt body' noSyntaxExpr, thing) }
720
721 tcDoStmt ctxt (BindStmt pat rhs bind_op fail_op) res_ty thing_inside
722   = do  {       -- Deal with rebindable syntax:
723                 --       (>>=) :: rhs_ty -> (pat_ty -> new_res_ty) -> res_ty
724                 -- This level of generality is needed for using do-notation
725                 -- in full generality; see Trac #1537
726
727                 -- I'd like to put this *after* the tcSyntaxOp 
728                 -- (see Note [Treat rebindable syntax first], but that breaks 
729                 -- the rigidity info for GADTs.  When we move to the new story
730                 -- for GADTs, we can move this after tcSyntaxOp
731           rhs_ty     <- newFlexiTyVarTy liftedTypeKind
732         ; pat_ty     <- newFlexiTyVarTy liftedTypeKind
733         ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
734         ; bind_op'   <- tcSyntaxOp DoOrigin bind_op 
735                              (mkFunTys [rhs_ty, mkFunTy pat_ty new_res_ty] res_ty)
736
737                 -- If (but only if) the pattern can fail, 
738                 -- typecheck the 'fail' operator
739         ; fail_op' <- if isIrrefutableHsPat pat 
740                       then return noSyntaxExpr
741                       else tcSyntaxOp DoOrigin fail_op (mkFunTy stringTy new_res_ty)
742
743         ; rhs' <- tcMonoExprNC rhs rhs_ty
744         ; (pat', thing) <- tcPat (StmtCtxt ctxt) pat pat_ty $
745                            thing_inside new_res_ty
746
747         ; return (BindStmt pat' rhs' bind_op' fail_op', thing) }
748
749
750 tcDoStmt _ (ExprStmt rhs then_op _ _) res_ty thing_inside
751   = do  {       -- Deal with rebindable syntax; 
752                 --   (>>) :: rhs_ty -> new_res_ty -> res_ty
753                 -- See also Note [Treat rebindable syntax first]
754           rhs_ty     <- newFlexiTyVarTy liftedTypeKind
755         ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
756         ; then_op' <- tcSyntaxOp DoOrigin then_op 
757                            (mkFunTys [rhs_ty, new_res_ty] res_ty)
758
759         ; rhs' <- tcMonoExprNC rhs rhs_ty
760         ; thing <- thing_inside new_res_ty
761         ; return (ExprStmt rhs' then_op' noSyntaxExpr rhs_ty, thing) }
762
763 tcDoStmt ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = later_names
764                        , recS_rec_ids = rec_names, recS_ret_fn = ret_op
765                        , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op }) 
766          res_ty thing_inside
767   = do  { let tup_names = rec_names ++ filterOut (`elem` rec_names) later_names
768         ; tup_elt_tys <- newFlexiTyVarTys (length tup_names) liftedTypeKind
769         ; let tup_ids = zipWith mkLocalId tup_names tup_elt_tys
770               tup_ty  = mkBoxedTupleTy tup_elt_tys
771
772         ; tcExtendIdEnv tup_ids $ do
773         { stmts_ty <- newFlexiTyVarTy liftedTypeKind
774         ; (stmts', (ret_op', tup_rets))
775                 <- tcStmtsAndThen ctxt tcDoStmt stmts stmts_ty   $ \ inner_res_ty ->
776                    do { tup_rets <- zipWithM tcCheckId tup_names tup_elt_tys
777                              -- Unify the types of the "final" Ids (which may 
778                              -- be polymorphic) with those of "knot-tied" Ids
779                       ; ret_op' <- tcSyntaxOp DoOrigin ret_op (mkFunTy tup_ty inner_res_ty)
780                       ; return (ret_op', tup_rets) }
781
782         ; mfix_res_ty <- newFlexiTyVarTy liftedTypeKind
783         ; mfix_op' <- tcSyntaxOp DoOrigin mfix_op
784                                  (mkFunTy (mkFunTy tup_ty stmts_ty) mfix_res_ty)
785
786         ; new_res_ty <- newFlexiTyVarTy liftedTypeKind
787         ; bind_op' <- tcSyntaxOp DoOrigin bind_op 
788                                  (mkFunTys [mfix_res_ty, mkFunTy tup_ty new_res_ty] res_ty)
789
790         ; thing <- thing_inside new_res_ty
791 --         ; lie_binds <- bindLocalMethods lie tup_ids
792   
793         ; let rec_ids = takeList rec_names tup_ids
794         ; later_ids <- tcLookupLocalIds later_names
795         ; traceTc "tcdo" $ vcat [ppr rec_ids <+> ppr (map idType rec_ids),
796                                  ppr later_ids <+> ppr (map idType later_ids)]
797         ; return (RecStmt { recS_stmts = stmts', recS_later_ids = later_ids
798                           , recS_rec_ids = rec_ids, recS_ret_fn = ret_op' 
799                           , recS_mfix_fn = mfix_op', recS_bind_fn = bind_op'
800                           , recS_rec_rets = tup_rets, recS_ret_ty = stmts_ty }, thing)
801         }}
802
803 tcDoStmt _ stmt _ _
804   = pprPanic "tcDoStmt: unexpected Stmt" (ppr stmt)
805 \end{code}
806
807 Note [Treat rebindable syntax first]
808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
809 When typechecking
810         do { bar; ... } :: IO ()
811 we want to typecheck 'bar' in the knowledge that it should be an IO thing,
812 pushing info from the context into the RHS.  To do this, we check the
813 rebindable syntax first, and push that information into (tcMonoExprNC rhs).
814 Otherwise the error shows up when cheking the rebindable syntax, and
815 the expected/inferred stuff is back to front (see Trac #3613).
816
817 \begin{code}
818 --------------------------------
819 --      Mdo-notation
820 -- The distinctive features here are
821 --      (a) RecStmts, and
822 --      (b) no rebindable syntax
823
824 tcMDoStmt :: (LHsExpr Name -> TcM (LHsExpr TcId, TcType))       -- RHS inference
825           -> TcStmtChecker
826 -- Used only by TcArrows... should be gotten rid of
827 tcMDoStmt tc_rhs ctxt (BindStmt pat rhs _ _) res_ty thing_inside
828   = do  { (rhs', pat_ty) <- tc_rhs rhs
829         ; (pat', thing)  <- tcPat (StmtCtxt ctxt) pat pat_ty $
830                             thing_inside res_ty
831         ; return (BindStmt pat' rhs' noSyntaxExpr noSyntaxExpr, thing) }
832
833 tcMDoStmt tc_rhs _ (ExprStmt rhs _ _ _) res_ty thing_inside
834   = do  { (rhs', elt_ty) <- tc_rhs rhs
835         ; thing          <- thing_inside res_ty
836         ; return (ExprStmt rhs' noSyntaxExpr noSyntaxExpr elt_ty, thing) }
837
838 tcMDoStmt tc_rhs ctxt (RecStmt { recS_stmts = stmts, recS_later_ids = laterNames
839                                , recS_rec_ids = recNames }) res_ty thing_inside
840   = do  { rec_tys <- newFlexiTyVarTys (length recNames) liftedTypeKind
841         ; let rec_ids = zipWith mkLocalId recNames rec_tys
842         ; tcExtendIdEnv rec_ids $ do
843         { (stmts', (later_ids, rec_rets))
844                 <- tcStmtsAndThen ctxt (tcMDoStmt tc_rhs) stmts res_ty  $ \ _res_ty' ->
845                         -- ToDo: res_ty not really right
846                    do { rec_rets <- zipWithM tcCheckId recNames rec_tys
847                       ; later_ids <- tcLookupLocalIds laterNames
848                       ; return (later_ids, rec_rets) }
849
850         ; thing <- tcExtendIdEnv later_ids (thing_inside res_ty)
851                 -- NB:  The rec_ids for the recursive things 
852                 --      already scope over this part. This binding may shadow
853                 --      some of them with polymorphic things with the same Name
854                 --      (see note [RecStmt] in HsExpr)
855
856         ; return (emptyRecStmt { recS_stmts = stmts', recS_later_ids = later_ids
857                                , recS_rec_ids = rec_ids, recS_rec_rets = rec_rets
858                                , recS_ret_ty = res_ty }, thing)
859         }}
860
861 tcMDoStmt _ _ stmt _ _
862   = pprPanic "tcMDoStmt: unexpected Stmt" (ppr stmt)
863 \end{code}
864
865
866 %************************************************************************
867 %*                                                                      *
868 \subsection{Errors and contexts}
869 %*                                                                      *
870 %************************************************************************
871
872 @sameNoOfArgs@ takes a @[RenamedMatch]@ and decides whether the same
873 number of args are used in each equation.
874
875 \begin{code}
876 checkArgs :: Name -> MatchGroup Name -> TcM ()
877 checkArgs fun (MatchGroup (match1:matches) _)
878     | null bad_matches = return ()
879     | otherwise
880     = failWithTc (vcat [ptext (sLit "Equations for") <+> quotes (ppr fun) <+> 
881                           ptext (sLit "have different numbers of arguments"),
882                         nest 2 (ppr (getLoc match1)),
883                         nest 2 (ppr (getLoc (head bad_matches)))])
884   where
885     n_args1 = args_in_match match1
886     bad_matches = [m | m <- matches, args_in_match m /= n_args1]
887
888     args_in_match :: LMatch Name -> Int
889     args_in_match (L _ (Match pats _ _)) = length pats
890 checkArgs fun _ = pprPanic "TcPat.checkArgs" (ppr fun) -- Matches always non-empty
891 \end{code}
892