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