5176fdee67a5cd346d2ea7cd5287ab745fdcfc22
[ghc-hetmet.git] / ghc / compiler / typecheck / TcExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[TcExpr]{Typecheck an expression}
5
6 \begin{code}
7 module TcExpr ( tcExpr, tcStmt, tcId ) where
8
9 #include "HsVersions.h"
10
11 import HsSyn            ( HsExpr(..), HsLit(..), ArithSeqInfo(..), 
12                           HsBinds(..), Stmt(..), DoOrListComp(..),
13                           failureFreePat, collectPatBinders
14                         )
15 import RnHsSyn          ( RenamedHsExpr, 
16                           RenamedStmt, RenamedRecordBinds
17                         )
18 import TcHsSyn          ( TcExpr, TcStmt,
19                           TcRecordBinds,
20                           mkHsTyApp
21                         )
22
23 import TcMonad
24 import BasicTypes       ( RecFlag(..) )
25
26 import Inst             ( Inst, InstOrigin(..), OverloadedLit(..),
27                           LIE, emptyLIE, plusLIE, plusLIEs, newOverloadedLit,
28                           newMethod, newMethodWithGivenTy, newDicts )
29 import TcBinds          ( tcBindsAndThen, checkSigTyVars )
30 import TcEnv            ( TcIdOcc(..), tcInstId,
31                           tcLookupLocalValue, tcLookupGlobalValue, tcLookupClassByKey,
32                           tcLookupGlobalValueByKey, newMonoIds,
33                           tcExtendGlobalTyVars, tcLookupGlobalValueMaybe,
34                           tcLookupTyCon
35                         )
36 import TcMatches        ( tcMatchesCase, tcMatchExpected )
37 import TcMonoType       ( tcHsType )
38 import TcPat            ( tcPat )
39 import TcSimplify       ( tcSimplifyAndCheck )
40 import TcType           ( TcType, TcMaybe(..),
41                           tcInstType, tcInstSigTcType, tcInstTyVars,
42                           tcInstSigType, tcInstTcType, tcInstTheta, tcSplitRhoTy,
43                           newTyVarTy, newTyVarTys, zonkTcType )
44 import TcKind           ( TcKind )
45
46 import Class            ( Class )
47 import FieldLabel       ( FieldLabel, fieldLabelName, fieldLabelType )
48 import Id               ( idType, dataConFieldLabels, dataConSig, recordSelectorFieldLabel,
49                           isRecordSelector,
50                           Id, GenId
51                         )
52 import Kind             ( Kind, mkBoxedTypeKind, mkTypeKind, mkArrowKind )
53 import Name             ( Name{-instance Eq-} )
54 import Type             ( mkFunTy, mkAppTy, mkTyVarTy, mkTyVarTys,
55                           splitFunTy_maybe, splitFunTys,
56                           mkTyConApp,
57                           splitForAllTys, splitRhoTy, splitSigmaTy, 
58                           isTauTy, tyVarsOfType, tyVarsOfTypes, 
59                           splitForAllTy_maybe, splitAlgTyConApp, splitAlgTyConApp_maybe
60                         )
61 import TyVar            ( emptyTyVarEnv, zipTyVarEnv,
62                           elementOfTyVarSet, mkTyVarSet, tyVarSetToList
63                         )
64 import TyCon            ( tyConDataCons )
65 import TysPrim          ( intPrimTy, charPrimTy, doublePrimTy,
66                           floatPrimTy, addrPrimTy
67                         )
68 import TysWiredIn       ( boolTy, charTy, stringTy )
69 import PrelInfo         ( ioTyCon_NAME )
70 import Unify            ( unifyTauTy, unifyFunTy, unifyListTy, unifyTupleTy )
71 import Unique           ( Unique, cCallableClassKey, cReturnableClassKey, 
72                           enumFromClassOpKey, enumFromThenClassOpKey,
73                           enumFromToClassOpKey, enumFromThenToClassOpKey,
74                           thenMClassOpKey, zeroClassOpKey, returnMClassOpKey
75                         )
76 import Outputable
77 import PprType          ( GenType, GenTyVar )   -- Instances
78 import Maybes           ( maybeToBool )
79 import ListSetOps       ( minusList )
80 import Util
81 \end{code}
82
83 \begin{code}
84 tcExpr :: RenamedHsExpr                 -- Expession to type check
85        -> TcType s                      -- Expected type (could be a type variable)
86        -> TcM s (TcExpr s, LIE s)
87 \end{code}
88
89 %************************************************************************
90 %*                                                                      *
91 \subsection{The TAUT rules for variables}
92 %*                                                                      *
93 %************************************************************************
94
95 \begin{code}
96 tcExpr (HsVar name) res_ty
97   = tcId name                   `thenNF_Tc` \ (expr', lie, id_ty) ->
98     unifyTauTy res_ty id_ty     `thenTc_`
99
100     -- Check that the result type doesn't have any nested for-alls.
101     -- For example, a "build" on its own is no good; it must be
102     -- applied to something.
103     checkTc (isTauTy id_ty)
104             (lurkingRank2Err name id_ty) `thenTc_`
105
106     returnTc (expr', lie)
107 \end{code}
108
109 %************************************************************************
110 %*                                                                      *
111 \subsection{Literals}
112 %*                                                                      *
113 %************************************************************************
114
115 Overloaded literals.
116
117 \begin{code}
118 tcExpr (HsLit (HsInt i)) res_ty
119   = newOverloadedLit (LiteralOrigin (HsInt i))
120                      (OverloadedIntegral i)
121                      res_ty  `thenNF_Tc` \ stuff ->
122     returnTc stuff
123
124 tcExpr (HsLit (HsFrac f)) res_ty
125   = newOverloadedLit (LiteralOrigin (HsFrac f))
126                      (OverloadedFractional f)
127                      res_ty  `thenNF_Tc` \ stuff ->
128     returnTc stuff
129
130
131 tcExpr (HsLit lit@(HsLitLit s)) res_ty
132   = tcLookupClassByKey cCallableClassKey                `thenNF_Tc` \ cCallableClass ->
133     newDicts (LitLitOrigin (_UNPK_ s))
134              [(cCallableClass, [res_ty])]               `thenNF_Tc` \ (dicts, _) ->
135     returnTc (HsLitOut lit res_ty, dicts)
136 \end{code}
137
138 Primitive literals:
139
140 \begin{code}
141 tcExpr (HsLit lit@(HsCharPrim c)) res_ty
142   = unifyTauTy res_ty charPrimTy                `thenTc_`
143     returnTc (HsLitOut lit charPrimTy, emptyLIE)
144
145 tcExpr (HsLit lit@(HsStringPrim s)) res_ty
146   = unifyTauTy res_ty addrPrimTy                `thenTc_`
147     returnTc (HsLitOut lit addrPrimTy, emptyLIE)
148
149 tcExpr (HsLit lit@(HsIntPrim i)) res_ty
150   = unifyTauTy res_ty intPrimTy         `thenTc_`
151     returnTc (HsLitOut lit intPrimTy, emptyLIE)
152
153 tcExpr (HsLit lit@(HsFloatPrim f)) res_ty
154   = unifyTauTy res_ty floatPrimTy               `thenTc_`
155     returnTc (HsLitOut lit floatPrimTy, emptyLIE)
156
157 tcExpr (HsLit lit@(HsDoublePrim d)) res_ty
158   = unifyTauTy res_ty doublePrimTy              `thenTc_`
159     returnTc (HsLitOut lit doublePrimTy, emptyLIE)
160 \end{code}
161
162 Unoverloaded literals:
163
164 \begin{code}
165 tcExpr (HsLit lit@(HsChar c)) res_ty
166   = unifyTauTy res_ty charTy            `thenTc_`
167     returnTc (HsLitOut lit charTy, emptyLIE)
168
169 tcExpr (HsLit lit@(HsString str)) res_ty
170   = unifyTauTy res_ty stringTy          `thenTc_`
171     returnTc (HsLitOut lit stringTy, emptyLIE)
172 \end{code}
173
174 %************************************************************************
175 %*                                                                      *
176 \subsection{Other expression forms}
177 %*                                                                      *
178 %************************************************************************
179
180 \begin{code}
181 tcExpr (HsPar expr) res_ty -- preserve parens so printing needn't guess where they go
182   = tcExpr expr res_ty
183
184 -- perform the negate *before* overloading the integer, since the case
185 -- of minBound on Ints fails otherwise.  Could be done elsewhere, but
186 -- convenient to do it here.
187
188 tcExpr (NegApp (HsLit (HsInt i)) neg) res_ty
189   = tcExpr (HsLit (HsInt (-i))) res_ty
190
191 tcExpr (NegApp expr neg) res_ty 
192   = tcExpr (HsApp neg expr) res_ty
193
194 tcExpr (HsLam match) res_ty
195   = tcMatchExpected [] res_ty match     `thenTc` \ (match',lie) ->
196     returnTc (HsLam match', lie)
197
198 tcExpr (HsApp e1 e2) res_ty = accum e1 [e2]
199   where
200     accum (HsApp e1 e2) args = accum e1 (e2:args)
201     accum fun args
202       = tcApp fun args res_ty   `thenTc` \ (fun', args', lie) ->
203         returnTc (foldl HsApp fun' args', lie)
204
205 -- equivalent to (op e1) e2:
206 tcExpr (OpApp arg1 op fix arg2) res_ty
207   = tcApp op [arg1,arg2] res_ty `thenTc` \ (op', [arg1', arg2'], lie) ->
208     returnTc (OpApp arg1' op' fix arg2', lie)
209 \end{code}
210
211 Note that the operators in sections are expected to be binary, and
212 a type error will occur if they aren't.
213
214 \begin{code}
215 -- Left sections, equivalent to
216 --      \ x -> e op x,
217 -- or
218 --      \ x -> op e x,
219 -- or just
220 --      op e
221
222 tcExpr in_expr@(SectionL arg op) res_ty
223   = tcApp op [arg] res_ty               `thenTc` \ (op', [arg'], lie) ->
224
225         -- Check that res_ty is a function type
226         -- Without this check we barf in the desugarer on
227         --      f op = (3 `op`)
228         -- because it tries to desugar to
229         --      f op = \r -> 3 op r
230         -- so (3 `op`) had better be a function!
231     tcAddErrCtxt (sectionLAppCtxt in_expr) $
232     unifyFunTy res_ty                   `thenTc_`
233
234     returnTc (SectionL arg' op', lie)
235
236 -- Right sections, equivalent to \ x -> x op expr, or
237 --      \ x -> op x expr
238
239 tcExpr in_expr@(SectionR op expr) res_ty
240   = tcExpr_id op                `thenTc`    \ (op', lie1, op_ty) ->
241     tcAddErrCtxt (sectionRAppCtxt in_expr) $
242     split_fun_ty op_ty 2 {- two args -}                 `thenTc` \ ([arg1_ty, arg2_ty], op_res_ty) ->
243     tcExpr expr arg2_ty                                 `thenTc` \ (expr',lie2) ->
244     unifyTauTy res_ty (mkFunTy arg1_ty op_res_ty)       `thenTc_`
245     returnTc (SectionR op' expr', lie1 `plusLIE` lie2)
246 \end{code}
247
248 The interesting thing about @ccall@ is that it is just a template
249 which we instantiate by filling in details about the types of its
250 argument and result (ie minimal typechecking is performed).  So, the
251 basic story is that we allocate a load of type variables (to hold the
252 arg/result types); unify them with the args/result; and store them for
253 later use.
254
255 \begin{code}
256 tcExpr (CCall lbl args may_gc is_asm ignored_fake_result_ty) res_ty
257   =     -- Get the callable and returnable classes.
258     tcLookupClassByKey cCallableClassKey        `thenNF_Tc` \ cCallableClass ->
259     tcLookupClassByKey cReturnableClassKey      `thenNF_Tc` \ cReturnableClass ->
260     tcLookupTyCon ioTyCon_NAME                  `thenTc` \ (_,_,ioTyCon) ->
261
262     let
263         new_arg_dict (arg, arg_ty)
264           = newDicts (CCallOrigin (_UNPK_ lbl) (Just arg))
265                      [(cCallableClass, [arg_ty])]       `thenNF_Tc` \ (arg_dicts, _) ->
266             returnNF_Tc arg_dicts       -- Actually a singleton bag
267
268         result_origin = CCallOrigin (_UNPK_ lbl) Nothing {- Not an arg -}
269     in
270
271         -- Arguments
272     mapNF_Tc (\ _ -> newTyVarTy mkTypeKind) [1..(length args)] `thenNF_Tc` \ ty_vars ->
273     tcExprs args ty_vars                                       `thenTc`    \ (args', args_lie) ->
274
275         -- The argument types can be unboxed or boxed; the result
276         -- type must, however, be boxed since it's an argument to the IO
277         -- type constructor.
278     newTyVarTy mkBoxedTypeKind                  `thenNF_Tc` \ result_ty ->
279     let
280         io_result_ty = mkTyConApp ioTyCon [result_ty]
281     in
282     case tyConDataCons ioTyCon of { [ioDataCon] ->
283     unifyTauTy res_ty io_result_ty              `thenTc_`
284
285         -- Construct the extra insts, which encode the
286         -- constraints on the argument and result types.
287     mapNF_Tc new_arg_dict (zipEqual "tcExpr:CCall" args ty_vars)    `thenNF_Tc` \ ccarg_dicts_s ->
288     newDicts result_origin [(cReturnableClass, [result_ty])]        `thenNF_Tc` \ (ccres_dict, _) ->
289
290     returnTc (HsApp (HsVar (RealId ioDataCon) `TyApp` [result_ty])
291                     (CCall lbl args' may_gc is_asm io_result_ty),
292                       -- do the wrapping in the newtype constructor here
293               foldr plusLIE ccres_dict ccarg_dicts_s `plusLIE` args_lie)
294     }
295 \end{code}
296
297 \begin{code}
298 tcExpr (HsSCC label expr) res_ty
299   = tcExpr expr res_ty          `thenTc` \ (expr', lie) ->
300     returnTc (HsSCC label expr', lie)
301
302 tcExpr (HsLet binds expr) res_ty
303   = tcBindsAndThen
304         combiner
305         binds                   -- Bindings to check
306         (tc_expr)       `thenTc` \ (expr', lie) ->
307     returnTc (expr', lie)
308   where
309     tc_expr = tcExpr expr res_ty `thenTc` \ (expr', lie) ->
310               returnTc (expr', lie)
311     combiner is_rec bind expr = HsLet (MonoBind bind [] is_rec) expr
312
313 tcExpr in_expr@(HsCase scrut matches src_loc) res_ty
314   = tcAddSrcLoc src_loc                 $
315     tcAddErrCtxt (caseCtxt in_expr)     $
316
317         -- Typecheck the case alternatives first.
318         -- The case patterns tend to give good type info to use
319         -- when typechecking the scrutinee.  For example
320         --      case (map f) of
321         --        (x:xs) -> ...
322         -- will report that map is applied to too few arguments
323
324     tcMatchesCase res_ty matches        `thenTc`    \ (scrut_ty, matches', lie2) ->
325
326     tcAddErrCtxt (caseScrutCtxt scrut)  (
327       tcExpr scrut scrut_ty
328     )                                   `thenTc`    \ (scrut',lie1) ->
329
330     returnTc (HsCase scrut' matches' src_loc, plusLIE lie1 lie2)
331
332 tcExpr (HsIf pred b1 b2 src_loc) res_ty
333   = tcAddSrcLoc src_loc $
334     tcAddErrCtxt (predCtxt pred) (
335     tcExpr pred boolTy  )       `thenTc`    \ (pred',lie1) ->
336
337     tcExpr b1 res_ty            `thenTc`    \ (b1',lie2) ->
338     tcExpr b2 res_ty            `thenTc`    \ (b2',lie3) ->
339     returnTc (HsIf pred' b1' b2' src_loc, plusLIE lie1 (plusLIE lie2 lie3))
340 \end{code}
341
342 \begin{code}
343 tcExpr expr@(HsDo do_or_lc stmts src_loc) res_ty
344   = tcDoStmts do_or_lc stmts src_loc res_ty
345 \end{code}
346
347 \begin{code}
348 tcExpr in_expr@(ExplicitList exprs) res_ty      -- Non-empty list
349   = unifyListTy res_ty                        `thenTc` \ elt_ty ->  
350     mapAndUnzipTc (tc_elt elt_ty) exprs       `thenTc` \ (exprs', lies) ->
351     returnTc (ExplicitListOut elt_ty exprs', plusLIEs lies)
352   where
353     tc_elt elt_ty expr
354       = tcAddErrCtxt (listCtxt expr) $
355         tcExpr expr elt_ty
356
357 tcExpr (ExplicitTuple exprs) res_ty
358   = unifyTupleTy (length exprs) res_ty          `thenTc` \ arg_tys ->
359     mapAndUnzipTc (\ (expr, arg_ty) -> tcExpr expr arg_ty)
360                (exprs `zip` arg_tys) -- we know they're of equal length.
361                                                                  `thenTc` \ (exprs', lies) ->
362     returnTc (ExplicitTuple exprs', plusLIEs lies)
363
364 tcExpr (RecordCon con_name _ rbinds) res_ty
365   = tcLookupGlobalValue con_name        `thenNF_Tc` \ con_id ->
366     tcId con_name                       `thenNF_Tc` \ (con_expr, con_lie, con_tau) ->
367     let
368         (_, record_ty) = splitFunTys con_tau
369     in
370         -- Con is syntactically constrained to be a data constructor
371     ASSERT( maybeToBool (splitAlgTyConApp_maybe record_ty ) )
372     unifyTauTy res_ty record_ty          `thenTc_`
373
374         -- Check that the record bindings match the constructor
375     let
376         bad_fields = badFields rbinds con_id
377     in
378     checkTc (null bad_fields) (badFieldsCon con_id bad_fields)  `thenTc_`
379
380         -- Typecheck the record bindings
381         -- (Do this after checkRecordFields in case there's a field that
382         --  doesn't match the constructor.)
383     tcRecordBinds record_ty rbinds              `thenTc` \ (rbinds', rbinds_lie) ->
384
385     returnTc (RecordCon (RealId con_id) con_expr rbinds', con_lie `plusLIE` rbinds_lie)
386
387
388 -- The main complication with RecordUpd is that we need to explicitly
389 -- handle the *non-updated* fields.  Consider:
390 --
391 --      data T a b = MkT1 { fa :: a, fb :: b }
392 --                 | MkT2 { fa :: a, fc :: Int -> Int }
393 --                 | MkT3 { fd :: a }
394 --      
395 --      upd :: T a b -> c -> T a c
396 --      upd t x = t { fb = x}
397 --
398 -- The type signature on upd is correct (i.e. the result should not be (T a b))
399 -- because upd should be equivalent to:
400 --
401 --      upd t x = case t of 
402 --                      MkT1 p q -> MkT1 p x
403 --                      MkT2 a b -> MkT2 p b
404 --                      MkT3 d   -> error ...
405 --
406 -- So we need to give a completely fresh type to the result record,
407 -- and then constrain it by the fields that are *not* updated ("p" above).
408 --
409 -- Note that because MkT3 doesn't contain all the fields being updated,
410 -- its RHS is simply an error, so it doesn't impose any type constraints
411 --
412 -- All this is done in STEP 4 below.
413
414 tcExpr (RecordUpd record_expr rbinds) res_ty
415   = tcAddErrCtxt recordUpdCtxt                  $
416
417         -- STEP 1
418         -- Figure out the tycon and data cons from the first field name
419     ASSERT( not (null rbinds) )
420     let 
421         ((first_field_name, _, _) : rest) = rbinds
422     in
423     tcLookupGlobalValueMaybe first_field_name   `thenNF_Tc` \ maybe_sel_id ->
424     (case maybe_sel_id of
425         Just sel_id | isRecordSelector sel_id -> returnTc sel_id
426         other                                 -> failWithTc (notSelector first_field_name)
427     )                                           `thenTc` \ sel_id ->
428     let
429         (_, tau)                  = splitForAllTys (idType sel_id)
430         Just (data_ty, _)         = splitFunTy_maybe tau        -- Must succeed since sel_id is a selector
431         (tycon, _, data_cons)     = splitAlgTyConApp data_ty
432         (con_tyvars, theta, _, _, _, _) = dataConSig (head data_cons)
433     in
434     tcInstTyVars con_tyvars                     `thenNF_Tc` \ (_, result_inst_tys, _) ->
435
436         -- STEP 2
437         -- Check for bad fields
438     checkTc (any (null . badFields rbinds) data_cons)
439             (badFieldsUpd rbinds)               `thenTc_`
440         -- STEP 3
441         -- Typecheck the update bindings.
442         -- (Do this after checking for bad fields in case there's a field that
443         --  doesn't match the constructor.)
444     let
445         result_record_ty = mkTyConApp tycon result_inst_tys
446     in
447     unifyTauTy res_ty result_record_ty          `thenTc_`
448     tcRecordBinds result_record_ty rbinds       `thenTc` \ (rbinds', rbinds_lie) ->
449
450         -- STEP 4
451         -- Use the un-updated fields to find a vector of booleans saying
452         -- which type arguments must be the same in updatee and result.
453         --
454         -- WARNING: this code assumes that all data_cons in a common tycon
455         -- have FieldLabels abstracted over the same tyvars.
456     let
457         upd_field_lbls      = [recordSelectorFieldLabel sel_id | (RealId sel_id, _, _) <- rbinds']
458         con_field_lbls_s    = map dataConFieldLabels data_cons
459
460                 -- A constructor is only relevant to this process if
461                 -- it contains all the fields that are being updated
462         relevant_field_lbls_s      = filter is_relevant con_field_lbls_s
463         is_relevant con_field_lbls = all (`elem` con_field_lbls) upd_field_lbls
464
465         non_upd_field_lbls  = concat relevant_field_lbls_s `minusList` upd_field_lbls
466         common_tyvars       = tyVarsOfTypes (map fieldLabelType non_upd_field_lbls)
467
468         mk_inst_ty (tyvar, result_inst_ty) 
469           | tyvar `elementOfTyVarSet` common_tyvars = returnNF_Tc result_inst_ty        -- Same as result type
470           | otherwise                               = newTyVarTy mkBoxedTypeKind        -- Fresh type
471     in
472     mapNF_Tc mk_inst_ty (zip con_tyvars result_inst_tys)        `thenNF_Tc` \ inst_tys ->
473
474         -- STEP 5
475         -- Typecheck the expression to be updated
476     let
477         record_ty = mkTyConApp tycon inst_tys
478     in
479     tcExpr record_expr record_ty                        `thenTc`    \ (record_expr', record_lie) ->
480
481         -- STEP 6
482         -- Figure out the LIE we need.  We have to generate some 
483         -- dictionaries for the data type context, since we are going to
484         -- do some construction.
485         --
486         -- What dictionaries do we need?  For the moment we assume that all
487         -- data constructors have the same context, and grab it from the first
488         -- constructor.  If they have varying contexts then we'd have to 
489         -- union the ones that could participate in the update.
490     let
491         (tyvars, theta, _, _, _, _) = dataConSig (head data_cons)
492         inst_env = zipTyVarEnv tyvars result_inst_tys
493     in
494     tcInstTheta inst_env theta                  `thenNF_Tc` \ theta' ->
495     newDicts RecordUpdOrigin theta'             `thenNF_Tc` \ (con_lie, dicts) ->
496
497         -- Phew!
498     returnTc (RecordUpdOut record_expr' result_record_ty dicts rbinds', 
499               con_lie `plusLIE` record_lie `plusLIE` rbinds_lie)
500
501 tcExpr (ArithSeqIn seq@(From expr)) res_ty
502   = unifyListTy res_ty                        `thenTc` \ elt_ty ->  
503     tcExpr expr elt_ty                        `thenTc` \ (expr', lie1) ->
504
505     tcLookupGlobalValueByKey enumFromClassOpKey `thenNF_Tc` \ sel_id ->
506     newMethod (ArithSeqOrigin seq)
507               (RealId sel_id) [elt_ty]          `thenNF_Tc` \ (lie2, enum_from_id) ->
508
509     returnTc (ArithSeqOut (HsVar enum_from_id) (From expr'),
510               lie1 `plusLIE` lie2)
511
512 tcExpr in_expr@(ArithSeqIn seq@(FromThen expr1 expr2)) res_ty
513   = tcAddErrCtxt (arithSeqCtxt in_expr) $ 
514     unifyListTy  res_ty         `thenTc`    \ elt_ty ->  
515     tcExpr expr1 elt_ty         `thenTc`    \ (expr1',lie1) ->
516     tcExpr expr2 elt_ty         `thenTc`    \ (expr2',lie2) ->
517     tcLookupGlobalValueByKey enumFromThenClassOpKey     `thenNF_Tc` \ sel_id ->
518     newMethod (ArithSeqOrigin seq)
519               (RealId sel_id) [elt_ty]                  `thenNF_Tc` \ (lie3, enum_from_then_id) ->
520
521     returnTc (ArithSeqOut (HsVar enum_from_then_id)
522                            (FromThen expr1' expr2'),
523               lie1 `plusLIE` lie2 `plusLIE` lie3)
524
525 tcExpr in_expr@(ArithSeqIn seq@(FromTo expr1 expr2)) res_ty
526   = tcAddErrCtxt (arithSeqCtxt in_expr) $
527     unifyListTy  res_ty         `thenTc`    \ elt_ty ->  
528     tcExpr expr1 elt_ty         `thenTc`    \ (expr1',lie1) ->
529     tcExpr expr2 elt_ty         `thenTc`    \ (expr2',lie2) ->
530     tcLookupGlobalValueByKey enumFromToClassOpKey       `thenNF_Tc` \ sel_id ->
531     newMethod (ArithSeqOrigin seq)
532               (RealId sel_id) [elt_ty]          `thenNF_Tc` \ (lie3, enum_from_to_id) ->
533
534     returnTc (ArithSeqOut (HsVar enum_from_to_id)
535                           (FromTo expr1' expr2'),
536               lie1 `plusLIE` lie2 `plusLIE` lie3)
537
538 tcExpr in_expr@(ArithSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
539   = tcAddErrCtxt  (arithSeqCtxt in_expr) $
540     unifyListTy  res_ty         `thenTc`    \ elt_ty ->  
541     tcExpr expr1 elt_ty         `thenTc`    \ (expr1',lie1) ->
542     tcExpr expr2 elt_ty         `thenTc`    \ (expr2',lie2) ->
543     tcExpr expr3 elt_ty         `thenTc`    \ (expr3',lie3) ->
544     tcLookupGlobalValueByKey enumFromThenToClassOpKey   `thenNF_Tc` \ sel_id ->
545     newMethod (ArithSeqOrigin seq)
546               (RealId sel_id) [elt_ty]                  `thenNF_Tc` \ (lie4, eft_id) ->
547
548     returnTc (ArithSeqOut (HsVar eft_id)
549                            (FromThenTo expr1' expr2' expr3'),
550               lie1 `plusLIE` lie2 `plusLIE` lie3 `plusLIE` lie4)
551 \end{code}
552
553 %************************************************************************
554 %*                                                                      *
555 \subsection{Expressions type signatures}
556 %*                                                                      *
557 %************************************************************************
558
559 \begin{code}
560 tcExpr in_expr@(ExprWithTySig expr poly_ty) res_ty
561  = tcSetErrCtxt (exprSigCtxt in_expr)   $
562    tcHsType  poly_ty            `thenTc` \ sigma_sig ->
563
564         -- Check the tau-type part
565    tcInstSigType sigma_sig              `thenNF_Tc` \ sigma_sig' ->
566    let
567         (sig_tyvars', sig_theta', sig_tau') = splitSigmaTy sigma_sig'
568    in
569
570         -- Type check the expression, expecting the signature type
571    tcExtendGlobalTyVars sig_tyvars' (
572            tcExpr expr sig_tau'
573    )                                            `thenTc` \ (texpr, lie) ->
574
575         -- Check the type variables of the signature, 
576         -- *after* typechecking the expression
577    checkSigTyVars sig_tyvars' sig_tau'          `thenTc` \ zonked_sig_tyvars ->
578
579         -- Check overloading constraints
580    newDicts SignatureOrigin sig_theta'          `thenNF_Tc` \ (sig_dicts, _) ->
581    tcSimplifyAndCheck
582         (ptext SLIT("the type signature") <+> quotes (ppr sigma_sig))
583         (mkTyVarSet zonked_sig_tyvars)
584         sig_dicts lie                           
585                                                 `thenTc_`
586
587         -- Now match the signature type with res_ty.
588         -- We must not do this earlier, because res_ty might well
589         -- mention variables free in the environment, and we'd get
590         -- bogus complaints about not being able to for-all the
591         -- sig_tyvars
592    unifyTauTy res_ty sig_tau'                   `thenTc_`
593
594         -- If everything is ok, return the stuff unchanged, except for
595         -- the effect of any substutions etc.  We simply discard the
596         -- result of the tcSimplifyAndCheck, except for any default
597         -- resolution it may have done, which is recorded in the
598         -- substitution.
599    returnTc (texpr, lie)
600
601 \end{code}
602
603 Typecheck expression which in most cases will be an Id.
604
605 \begin{code}
606 tcExpr_id :: RenamedHsExpr
607            -> TcM s (TcExpr s,
608                      LIE s,
609                      TcType s)
610 tcExpr_id id_expr
611  = case id_expr of
612         HsVar name -> tcId name                   `thenNF_Tc` \ stuff -> 
613                       returnTc stuff
614         other      -> newTyVarTy mkTypeKind       `thenNF_Tc` \ id_ty ->
615                       tcExpr id_expr id_ty        `thenTc`    \ (id_expr', lie_id) ->
616                       returnTc (id_expr', lie_id, id_ty) 
617 \end{code}
618
619 %************************************************************************
620 %*                                                                      *
621 \subsection{@tcApp@ typchecks an application}
622 %*                                                                      *
623 %************************************************************************
624
625 \begin{code}
626
627 tcApp :: RenamedHsExpr -> [RenamedHsExpr]   -- Function and args
628       -> TcType s                           -- Expected result type of application
629       -> TcM s (TcExpr s, [TcExpr s],       -- Translated fun and args
630                 LIE s)
631
632 tcApp fun args res_ty
633   =     -- First type-check the function
634     tcExpr_id fun                               `thenTc` \ (fun', lie_fun, fun_ty) ->
635
636     tcAddErrCtxt (wrongArgsCtxt "too many" fun args) (
637         split_fun_ty fun_ty (length args)
638     )                                           `thenTc` \ (expected_arg_tys, actual_result_ty) ->
639
640         -- Unify with expected result before type-checking the args
641         -- This is when we might detect a too-few args situation
642     tcAddErrCtxtM (checkArgsCtxt fun args res_ty actual_result_ty) (
643        unifyTauTy res_ty actual_result_ty
644     )                                                   `thenTc_`
645
646         -- Now typecheck the args
647     mapAndUnzipTc (tcArg fun)
648           (zip3 args expected_arg_tys [1..])    `thenTc` \ (args', lie_args_s) ->
649
650     -- Check that the result type doesn't have any nested for-alls.
651     -- For example, a "build" on its own is no good; it must be applied to something.
652     checkTc (isTauTy actual_result_ty)
653             (lurkingRank2Err fun fun_ty)        `thenTc_`
654
655     returnTc (fun', args', lie_fun `plusLIE` plusLIEs lie_args_s)
656
657
658 -- If an error happens we try to figure out whether the
659 -- function has been given too many or too few arguments,
660 -- and say so
661 checkArgsCtxt fun args expected_res_ty actual_res_ty
662   = zonkTcType expected_res_ty    `thenNF_Tc` \ exp_ty' ->
663     zonkTcType actual_res_ty      `thenNF_Tc` \ act_ty' ->
664     let
665       (exp_args, _) = splitFunTys exp_ty'
666       (act_args, _) = splitFunTys act_ty'
667       message | length exp_args < length act_args = wrongArgsCtxt "too few" fun args
668               | length exp_args > length act_args = wrongArgsCtxt "too many" fun args
669               | otherwise                         = appCtxt fun args
670     in
671     returnNF_Tc message
672
673
674 split_fun_ty :: TcType s                -- The type of the function
675              -> Int                     -- Number of arguments
676              -> TcM s ([TcType s],      -- Function argument types
677                        TcType s)        -- Function result types
678
679 split_fun_ty fun_ty 0 
680   = returnTc ([], fun_ty)
681
682 split_fun_ty fun_ty n
683   =     -- Expect the function to have type A->B
684     unifyFunTy fun_ty           `thenTc` \ (arg_ty, res_ty) ->
685     split_fun_ty res_ty (n-1)   `thenTc` \ (arg_tys, final_res_ty) ->
686     returnTc (arg_ty:arg_tys, final_res_ty)
687 \end{code}
688
689 \begin{code}
690 tcArg :: RenamedHsExpr                  -- The function (for error messages)
691       -> (RenamedHsExpr, TcType s, Int) -- Actual argument and expected arg type
692       -> TcM s (TcExpr s, LIE s)        -- Resulting argument and LIE
693
694 tcArg the_fun (arg, expected_arg_ty, arg_no)
695   = tcAddErrCtxt (funAppCtxt the_fun arg arg_no) $
696     tcPolyExpr (ptext SLIT("argument type of") <+> quotes (ppr the_fun))
697                arg expected_arg_ty
698
699
700 -- tcPolyExpr is like tcExpr, except that the expected type
701 -- can be a polymorphic one.
702 tcPolyExpr str arg expected_arg_ty
703   | not (maybeToBool (splitForAllTy_maybe expected_arg_ty))
704   =     -- The ordinary, non-rank-2 polymorphic case
705     tcExpr arg expected_arg_ty
706
707   | otherwise
708   =     -- Ha!  The argument type of the function is a for-all type,
709         -- An example of rank-2 polymorphism.
710
711         -- No need to instantiate the argument type... it's must be the result
712         -- of instantiating a function involving rank-2 polymorphism, so there
713         -- isn't any danger of using the same tyvars twice
714         -- The argument type shouldn't be overloaded type (hence ASSERT)
715
716         -- To ensure that the forall'd type variables don't get unified with each
717         -- other or any other types, we make fresh *signature* type variables
718         -- and unify them with the tyvars.
719     tcInstSigTcType expected_arg_ty     `thenNF_Tc` \ (sig_tyvars, sig_rho) ->
720     let
721         (sig_theta, sig_tau) = splitRhoTy sig_rho
722     in
723         -- Type-check the arg and unify with expected type
724     tcExpr arg sig_tau                          `thenTc` \ (arg', lie_arg) ->
725
726         -- Check that the arg_tyvars havn't been constrained
727         -- The interesting bit here is that we must include the free variables
728         -- of the expected arg ty.  Here's an example:
729         --       runST (newVar True)
730         -- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
731         -- for (newVar True), with s fresh.  Then we unify with the runST's arg type
732         -- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
733         -- So now s' isn't unconstrained because it's linked to a.
734         -- Conclusion: include the free vars of the expected arg type in the
735         -- list of "free vars" for the signature check.
736
737     tcAddErrCtxt (rank2ArgCtxt arg expected_arg_ty) $
738     tcExtendGlobalTyVars (tyVarSetToList (tyVarsOfType expected_arg_ty)) $
739
740     checkSigTyVars sig_tyvars sig_tau           `thenTc` \ zonked_sig_tyvars ->
741     newDicts Rank2Origin sig_theta              `thenNF_Tc` \ (sig_dicts, dict_ids) ->
742         -- ToDo: better origin
743
744     tcSimplifyAndCheck 
745                 str
746                 (mkTyVarSet zonked_sig_tyvars)
747                 sig_dicts lie_arg               `thenTc` \ (free_insts, inst_binds) ->
748
749             -- This HsLet binds any Insts which came out of the simplification.
750             -- It's a bit out of place here, but using AbsBind involves inventing
751             -- a couple of new names which seems worse.
752     returnTc ( TyLam zonked_sig_tyvars $
753                    DictLam dict_ids $
754                    HsLet (MonoBind inst_binds [] Recursive) 
755                    arg' 
756                  , free_insts
757                  )
758 \end{code}
759
760 %************************************************************************
761 %*                                                                      *
762 \subsection{@tcId@ typchecks an identifier occurrence}
763 %*                                                                      *
764 %************************************************************************
765
766 \begin{code}
767 tcId :: Name -> NF_TcM s (TcExpr s, LIE s, TcType s)
768
769 tcId name
770   =     -- Look up the Id and instantiate its type
771     tcLookupLocalValue name     `thenNF_Tc` \ maybe_local ->
772
773     case maybe_local of
774       Just tc_id -> instantiate_it (TcId tc_id) (idType tc_id)
775
776       Nothing ->    tcLookupGlobalValue name             `thenNF_Tc` \ id ->
777                     tcInstType emptyTyVarEnv (idType id) `thenNF_Tc` \ inst_ty ->
778                     let
779                         (tyvars, rho) = splitForAllTys inst_ty 
780                     in
781                     instantiate_it2 (RealId id) tyvars rho
782
783   where
784         -- The instantiate_it loop runs round instantiating the Id.
785         -- It has to be a loop because we are now prepared to entertain
786         -- types like
787         --              f:: forall a. Eq a => forall b. Baz b => tau
788         -- We want to instantiate this to
789         --              f2::tau         {f2 = f1 b (Baz b), f1 = f a (Eq a)}
790     instantiate_it tc_id_occ ty
791       = tcInstTcType ty         `thenNF_Tc` \ (tyvars, rho) ->
792         instantiate_it2 tc_id_occ tyvars rho
793
794     instantiate_it2 tc_id_occ tyvars rho
795       = tcSplitRhoTy rho                                `thenNF_Tc` \ (theta, tau) ->
796         if null theta then      -- Is it overloaded?
797                 returnNF_Tc (mkHsTyApp (HsVar tc_id_occ) arg_tys, emptyLIE, tau)
798         else
799                 -- Yes, it's overloaded
800         newMethodWithGivenTy (OccurrenceOf tc_id_occ)
801                              tc_id_occ arg_tys theta tau `thenNF_Tc` \ (lie1, meth_id) ->
802         instantiate_it meth_id tau                       `thenNF_Tc` \ (expr, lie2, final_tau) ->
803         returnNF_Tc (expr, lie1 `plusLIE` lie2, final_tau)
804
805       where
806         arg_tys       = mkTyVarTys tyvars
807 \end{code}
808
809 %************************************************************************
810 %*                                                                      *
811 \subsection{@tcDoStmts@ typechecks a {\em list} of do statements}
812 %*                                                                      *
813 %************************************************************************
814
815 \begin{code}
816 tcDoStmts do_or_lc stmts src_loc res_ty
817   =     -- get the Monad and MonadZero classes
818         -- create type consisting of a fresh monad tyvar
819     ASSERT( not (null stmts) )
820     tcAddSrcLoc src_loc $
821     newTyVarTy (mkArrowKind mkBoxedTypeKind mkBoxedTypeKind)    `thenNF_Tc` \ m ->
822
823     let
824       tc_stmts []           = returnTc (([], error "tc_stmts"), emptyLIE)
825       tc_stmts (stmt:stmts) = tcStmt tcExpr do_or_lc (mkAppTy m) combine_stmts stmt $
826                               tc_stmts stmts
827
828       combine_stmts stmt@(ReturnStmt _) (Just ty) ([], _) = ([stmt], ty)
829       combine_stmts stmt@(ExprStmt e _) (Just ty) ([], _) = ([stmt], ty)
830       combine_stmts stmt                _         ([], _) = panic "Bad last stmt tcDoStmts"
831       combine_stmts stmt                _     (stmts, ty) = (stmt:stmts, ty)
832     in
833     tc_stmts stmts                      `thenTc`   \ ((stmts', result_ty), final_lie) ->
834     unifyTauTy res_ty result_ty         `thenTc_`
835
836         -- Build the then and zero methods in case we need them
837         -- It's important that "then" and "return" appear just once in the final LIE,
838         -- not only for typechecker efficiency, but also because otherwise during
839         -- simplification we end up with silly stuff like
840         --      then = case d of (t,r) -> t
841         --      then = then
842         -- where the second "then" sees that it already exists in the "available" stuff.
843         --
844     tcLookupGlobalValueByKey returnMClassOpKey  `thenNF_Tc` \ return_sel_id ->
845     tcLookupGlobalValueByKey thenMClassOpKey    `thenNF_Tc` \ then_sel_id ->
846     tcLookupGlobalValueByKey zeroClassOpKey     `thenNF_Tc` \ zero_sel_id ->
847     newMethod DoOrigin
848               (RealId return_sel_id) [m]        `thenNF_Tc` \ (return_lie, return_id) ->
849     newMethod DoOrigin
850               (RealId then_sel_id) [m]          `thenNF_Tc` \ (then_lie, then_id) ->
851     newMethod DoOrigin
852               (RealId zero_sel_id) [m]          `thenNF_Tc` \ (zero_lie, zero_id) ->
853     let
854       monad_lie = then_lie `plusLIE` return_lie `plusLIE` perhaps_zero_lie
855       perhaps_zero_lie | all failure_free stmts' = emptyLIE
856                        | otherwise               = zero_lie
857
858       failure_free (BindStmt pat _ _) = failureFreePat pat
859       failure_free (GuardStmt _ _)    = False
860       failure_free other_stmt         = True
861     in
862     returnTc (HsDoOut do_or_lc stmts' return_id then_id zero_id res_ty src_loc,
863               final_lie `plusLIE` monad_lie)
864
865 \end{code}
866
867 \begin{code}
868 tcStmt :: (RenamedHsExpr -> TcType s -> TcM s (TcExpr s, LIE s))        -- This is tcExpr
869                                 -- The sole, disgusting, reason for this parameter
870                                 -- is to get the effect of polymorphic recursion
871                                 -- ToDo: rm when booting with Haskell 1.3
872        -> DoOrListComp
873        -> (TcType s -> TcType s)                -- Relationship type of pat and rhs in pat <- rhs
874        -> (TcStmt s -> Maybe (TcType s) -> thing -> thing)
875        -> RenamedStmt
876        -> TcM s (thing, LIE s)
877        -> TcM s (thing, LIE s)
878
879 tcStmt tc_expr do_or_lc m combine stmt@(ReturnStmt exp) do_next
880   = ASSERT( case do_or_lc of { DoStmt -> False; ListComp -> True; Guard -> True } )
881     tcSetErrCtxt (stmtCtxt do_or_lc stmt) (
882         newTyVarTy mkTypeKind                `thenNF_Tc` \ exp_ty ->
883         tc_expr exp exp_ty                   `thenTc`    \ (exp', exp_lie) ->
884         returnTc (ReturnStmt exp', exp_lie, m exp_ty)
885     )                                   `thenTc` \ (stmt', stmt_lie, stmt_ty) ->
886     do_next                             `thenTc` \ (thing', thing_lie) ->
887     returnTc (combine stmt' (Just stmt_ty) thing',
888               stmt_lie `plusLIE` thing_lie)
889
890 tcStmt tc_expr do_or_lc m combine stmt@(GuardStmt exp src_loc) do_next
891   = ASSERT( case do_or_lc of { DoStmt -> False; ListComp -> True; Guard -> True } )
892     newTyVarTy mkTypeKind                    `thenNF_Tc` \ exp_ty ->
893     tcAddSrcLoc src_loc                 (
894     tcSetErrCtxt (stmtCtxt do_or_lc stmt) (
895         tc_expr exp boolTy              `thenTc`    \ (exp', exp_lie) ->
896         returnTc (GuardStmt exp' src_loc, exp_lie)
897     ))                                  `thenTc` \ (stmt', stmt_lie) ->
898     do_next                             `thenTc` \ (thing', thing_lie) ->
899     returnTc (combine stmt' Nothing thing',
900               stmt_lie `plusLIE` thing_lie)
901
902 tcStmt tc_expr do_or_lc m combine stmt@(ExprStmt exp src_loc) do_next
903   = ASSERT( case do_or_lc of { DoStmt -> True; ListComp -> False; Guard -> False } )
904     newTyVarTy mkTypeKind                    `thenNF_Tc` \ exp_ty ->
905     tcAddSrcLoc src_loc                 (
906     tcSetErrCtxt (stmtCtxt do_or_lc stmt)       (
907         newTyVarTy mkTypeKind           `thenNF_Tc` \ tau ->
908         let
909             -- exp has type (m tau) for some tau (doesn't matter what)
910             exp_ty = m tau
911         in
912         tc_expr exp exp_ty              `thenTc`    \ (exp', exp_lie) ->
913         returnTc (ExprStmt exp' src_loc, exp_lie, exp_ty)
914     ))                                  `thenTc` \ (stmt',  stmt_lie, stmt_ty) ->
915     do_next                             `thenTc` \ (thing', thing_lie) ->
916     returnTc (combine stmt' (Just stmt_ty) thing',
917               stmt_lie `plusLIE` thing_lie)
918
919 tcStmt tc_expr do_or_lc m combine stmt@(BindStmt pat exp src_loc) do_next
920   = newMonoIds (collectPatBinders pat) mkBoxedTypeKind $ \ _ ->
921     tcAddSrcLoc src_loc         (
922     tcSetErrCtxt (stmtCtxt do_or_lc stmt)       (
923         tcPat pat                       `thenTc`    \ (pat', pat_lie, pat_ty) ->  
924         tc_expr exp (m pat_ty)          `thenTc`    \ (exp', exp_lie) ->
925
926         -- NB: the environment has been extended with the new binders
927         -- which the rhs can't "see", but the renamer should have made
928         -- sure that everything is distinct by now, so there's no problem.
929         -- Putting the tcExpr before the newMonoIds messes up the nesting
930         -- of error contexts, so I didn't  bother
931
932         returnTc (BindStmt pat' exp' src_loc, pat_lie `plusLIE` exp_lie)
933     ))                                  `thenTc` \ (stmt', stmt_lie) ->
934     do_next                             `thenTc` \ (thing', thing_lie) ->
935     returnTc (combine stmt' Nothing thing',
936               stmt_lie `plusLIE` thing_lie)
937
938 tcStmt tc_expr do_or_lc m combine (LetStmt binds) do_next
939      = tcBindsAndThen           -- No error context, but a binding group is
940         combine'                -- rather a large thing for an error context anyway
941         binds
942         do_next
943      where
944         combine' is_rec binds' thing' = combine (LetStmt (MonoBind binds' [] is_rec)) Nothing thing'
945 \end{code}
946
947 %************************************************************************
948 %*                                                                      *
949 \subsection{Record bindings}
950 %*                                                                      *
951 %************************************************************************
952
953 Game plan for record bindings
954 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
955 For each binding 
956         field = value
957 1. look up "field", to find its selector Id, which must have type
958         forall a1..an. T a1 .. an -> tau
959    where tau is the type of the field.  
960
961 2. Instantiate this type
962
963 3. Unify the (T a1 .. an) part with the "expected result type", which
964    is passed in.  This checks that all the field labels come from the
965    same type.
966
967 4. Type check the value using tcArg, passing tau as the expected
968    argument type.
969
970 This extends OK when the field types are universally quantified.
971
972 Actually, to save excessive creation of fresh type variables,
973 we 
974         
975 \begin{code}
976 tcRecordBinds
977         :: TcType s             -- Expected type of whole record
978         -> RenamedRecordBinds
979         -> TcM s (TcRecordBinds s, LIE s)
980
981 tcRecordBinds expected_record_ty rbinds
982   = mapAndUnzipTc do_bind rbinds        `thenTc` \ (rbinds', lies) ->
983     returnTc (rbinds', plusLIEs lies)
984   where
985     do_bind (field_label, rhs, pun_flag)
986       = tcLookupGlobalValue field_label `thenNF_Tc` \ sel_id ->
987         ASSERT( isRecordSelector sel_id )
988                 -- This lookup and assertion will surely succeed, because
989                 -- we check that the fields are indeed record selectors
990                 -- before calling tcRecordBinds
991
992         tcInstId sel_id                 `thenNF_Tc` \ (_, _, tau) ->
993
994                 -- Record selectors all have type
995                 --      forall a1..an.  T a1 .. an -> tau
996         ASSERT( maybeToBool (splitFunTy_maybe tau) )
997         let
998                 -- Selector must have type RecordType -> FieldType
999           Just (record_ty, field_ty) = splitFunTy_maybe tau
1000         in
1001         unifyTauTy expected_record_ty record_ty         `thenTc_`
1002         tcPolyExpr (ptext SLIT("type of field") <+> quotes (ppr field_label))
1003                    rhs field_ty                         `thenTc` \ (rhs', lie) ->
1004         returnTc ((RealId sel_id, rhs', pun_flag), lie)
1005
1006 badFields rbinds data_con
1007   = [field_name | (field_name, _, _) <- rbinds,
1008                   not (field_name `elem` field_names)
1009     ]
1010   where
1011     field_names = map fieldLabelName (dataConFieldLabels data_con)
1012 \end{code}
1013
1014 %************************************************************************
1015 %*                                                                      *
1016 \subsection{@tcExprs@ typechecks a {\em list} of expressions}
1017 %*                                                                      *
1018 %************************************************************************
1019
1020 \begin{code}
1021 tcExprs :: [RenamedHsExpr] -> [TcType s] -> TcM s ([TcExpr s], LIE s)
1022
1023 tcExprs [] [] = returnTc ([], emptyLIE)
1024 tcExprs (expr:exprs) (ty:tys)
1025  = tcExpr  expr  ty             `thenTc` \ (expr',  lie1) ->
1026    tcExprs exprs tys            `thenTc` \ (exprs', lie2) ->
1027    returnTc (expr':exprs', lie1 `plusLIE` lie2)
1028 \end{code}
1029
1030
1031 % =================================================
1032
1033 Errors and contexts
1034 ~~~~~~~~~~~~~~~~~~~
1035
1036 Mini-utils:
1037 \begin{code}
1038 pp_nest_hang :: String -> SDoc -> SDoc
1039 pp_nest_hang label stuff = nest 2 (hang (text label) 4 stuff)
1040 \end{code}
1041
1042 Boring and alphabetical:
1043 \begin{code}
1044 arithSeqCtxt expr
1045   = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
1046
1047 caseCtxt expr
1048   = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
1049
1050 caseScrutCtxt expr
1051   = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1052
1053 exprSigCtxt expr
1054   = hang (ptext SLIT("In an expression with a type signature:"))
1055          4 (ppr expr)
1056
1057 listCtxt expr
1058   = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
1059
1060 predCtxt expr
1061   = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1062
1063 sectionRAppCtxt expr
1064   = hang (ptext SLIT("In the right section:")) 4 (ppr expr)
1065
1066 sectionLAppCtxt expr
1067   = hang (ptext SLIT("In the left section:")) 4 (ppr expr)
1068
1069 funAppCtxt fun arg arg_no
1070   = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"), 
1071                     quotes (ppr fun) <> text ", namely"])
1072          4 (quotes (ppr arg))
1073
1074 stmtCtxt do_or_lc stmt
1075   = hang (ptext SLIT("In a") <+> whatever <> colon)
1076          4 (ppr stmt)
1077   where
1078     whatever = case do_or_lc of
1079                  ListComp -> ptext SLIT("list-comprehension qualifier")
1080                  DoStmt   -> ptext SLIT("do statement")
1081                  Guard    -> ptext SLIT("guard")
1082
1083 wrongArgsCtxt too_many_or_few fun args
1084   = hang (ptext SLIT("Probable cause:") <+> ppr fun
1085                     <+> ptext SLIT("is applied to") <+> text too_many_or_few 
1086                     <+> ptext SLIT("arguments in the call"))
1087          4 (parens (ppr the_app))
1088   where
1089     the_app = foldl HsApp fun args      -- Used in error messages
1090
1091 appCtxt fun args
1092   = ptext SLIT("In the application") <+> (ppr the_app)
1093   where
1094     the_app = foldl HsApp fun args      -- Used in error messages
1095
1096 lurkingRank2Err fun fun_ty
1097   = hang (hsep [ptext SLIT("Illegal use of"), quotes (ppr fun)])
1098          4 (vcat [ptext SLIT("It is applied to too few arguments"),  
1099                   ptext SLIT("so that the result type has for-alls in it")])
1100
1101 rank2ArgCtxt arg expected_arg_ty
1102   = ptext SLIT("In a polymorphic function argument:") <+> ppr arg
1103
1104 badFieldsUpd rbinds
1105   = hang (ptext SLIT("No constructor has all these fields:"))
1106          4 (pprQuotedList fields)
1107   where
1108     fields = [field | (field, _, _) <- rbinds]
1109
1110 recordUpdCtxt = ptext SLIT("In a record update construct")
1111
1112 badFieldsCon con fields
1113   = hsep [ptext SLIT("Constructor"),            ppr con,
1114            ptext SLIT("does not have field(s):"), pprQuotedList fields]
1115
1116 notSelector field
1117   = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1118 \end{code}