Kinding wibble in TH brackets
[ghc-hetmet.git] / ghc / compiler / typecheck / TcExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcExpr]{Typecheck an expression}
5
6 \begin{code}
7 module TcExpr ( tcPolyExpr, tcPolyExprNC, 
8                 tcMonoExpr, tcInferRho, tcSyntaxOp ) where
9
10 #include "HsVersions.h"
11
12 #ifdef GHCI     /* Only if bootstrapped */
13 import {-# SOURCE #-}   TcSplice( tcSpliceExpr, tcBracket )
14 import HsSyn            ( nlHsVar )
15 import Id               ( Id )
16 import Name             ( isExternalName )
17 import TcType           ( isTauTy )
18 import TcEnv            ( checkWellStaged )
19 import HsSyn            ( nlHsApp )
20 import qualified DsMeta
21 #endif
22
23 import HsSyn            ( HsExpr(..), LHsExpr, ArithSeqInfo(..), recBindFields,
24                           HsMatchContext(..), HsRecordBinds, 
25                           mkHsCoerce, mkHsApp, mkHsDictApp, mkHsTyApp )
26 import TcHsSyn          ( hsLitType )
27 import TcRnMonad
28 import TcUnify          ( tcInfer, tcSubExp, tcGen, boxyUnify, subFunTys, zapToMonotype, stripBoxyType,
29                           boxySplitListTy, boxySplitTyConApp, wrapFunResCoercion, boxySubMatchType, 
30                           unBox )
31 import BasicTypes       ( Arity, isMarkedStrict )
32 import Inst             ( newMethodFromName, newIPDict, instToId,
33                           newDicts, newMethodWithGivenTy, tcInstStupidTheta )
34 import TcBinds          ( tcLocalBinds )
35 import TcEnv            ( tcLookup, tcLookupId,
36                           tcLookupDataCon, tcLookupGlobalId
37                         )
38 import TcArrows         ( tcProc )
39 import TcMatches        ( tcMatchesCase, tcMatchLambda, tcDoStmts, TcMatchCtxt(..) )
40 import TcHsType         ( tcHsSigType, UserTypeCtxt(..) )
41 import TcPat            ( tcOverloadedLit, badFieldCon )
42 import TcMType          ( tcInstTyVars, newFlexiTyVarTy, newBoxyTyVars, readFilledBox, 
43                           tcInstBoxyTyVar, tcInstTyVar, zonkTcType )
44 import TcType           ( TcType, TcSigmaType, TcRhoType, 
45                           BoxySigmaType, BoxyRhoType, ThetaType,
46                           tcSplitFunTys, mkTyVarTys, mkFunTys, 
47                           tcMultiSplitSigmaTy, tcSplitFunTysN, 
48                           isSigmaTy, mkFunTy, mkTyConApp, isLinearPred,
49                           exactTyVarsOfType, exactTyVarsOfTypes, mkTyVarTy, 
50                           tidyOpenType,
51                           zipTopTvSubst, zipOpenTvSubst, substTys, substTyVar, lookupTyVar
52                         )
53 import Kind             ( argTypeKind )
54
55 import Id               ( idType, idName, recordSelectorFieldLabel, isRecordSelector, 
56                           isNaughtyRecordSelector, isDataConId_maybe )
57 import DataCon          ( DataCon, dataConFieldLabels, dataConStrictMarks, dataConSourceArity,
58                           dataConWrapId, isVanillaDataCon, dataConTyVars, dataConOrigArgTys )
59 import Name             ( Name )
60 import TyCon            ( FieldLabel, tyConStupidTheta, tyConDataCons )
61 import Type             ( substTheta, substTy )
62 import Var              ( TyVar, tyVarKind )
63 import VarSet           ( emptyVarSet, elemVarSet, unionVarSet )
64 import TysWiredIn       ( boolTy, parrTyCon, tupleTyCon )
65 import PrelNames        ( enumFromName, enumFromThenName, 
66                           enumFromToName, enumFromThenToName,
67                           enumFromToPName, enumFromThenToPName, negateName
68                         )
69 import DynFlags
70 import StaticFlags      ( opt_NoMethodSharing )
71 import HscTypes         ( TyThing(..) )
72 import SrcLoc           ( Located(..), unLoc, noLoc, getLoc )
73 import Util
74 import ListSetOps       ( assocMaybe )
75 import Maybes           ( catMaybes )
76 import Outputable
77 import FastString
78
79 #ifdef DEBUG
80 import TyCon            ( tyConArity )
81 #endif
82 \end{code}
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection{Main wrappers}
87 %*                                                                      *
88 %************************************************************************
89
90 \begin{code}
91 tcPolyExpr, tcPolyExprNC
92          :: LHsExpr Name                -- Expession to type check
93          -> BoxySigmaType               -- Expected type (could be a polytpye)
94          -> TcM (LHsExpr TcId)  -- Generalised expr with expected type
95
96 -- tcPolyExpr is a convenient place (frequent but not too frequent) place
97 -- to add context information.
98 -- The NC version does not do so, usually because the caller wants
99 -- to do so himself.
100
101 tcPolyExpr expr res_ty  
102   = addErrCtxt (exprCtxt (unLoc expr)) $
103     tcPolyExprNC expr res_ty
104
105 tcPolyExprNC expr res_ty 
106   | isSigmaTy res_ty
107   = do  { (gen_fn, expr') <- tcGen res_ty emptyVarSet (tcPolyExprNC expr)
108                 -- Note the recursive call to tcPolyExpr, because the
109                 -- type may have multiple layers of for-alls
110         ; return (L (getLoc expr') (mkHsCoerce gen_fn (unLoc expr'))) }
111
112   | otherwise
113   = tcMonoExpr expr res_ty
114
115 ---------------
116 tcPolyExprs :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
117 tcPolyExprs [] [] = returnM []
118 tcPolyExprs (expr:exprs) (ty:tys)
119  = do   { expr'  <- tcPolyExpr  expr  ty
120         ; exprs' <- tcPolyExprs exprs tys
121         ; returnM (expr':exprs') }
122 tcPolyExprs exprs tys = pprPanic "tcPolyExprs" (ppr exprs $$ ppr tys)
123
124 ---------------
125 tcMonoExpr :: LHsExpr Name      -- Expression to type check
126            -> BoxyRhoType       -- Expected type (could be a type variable)
127                                 -- Definitely no foralls at the top
128                                 -- Can contain boxes, which will be filled in
129            -> TcM (LHsExpr TcId)
130
131 tcMonoExpr (L loc expr) res_ty
132   = ASSERT( not (isSigmaTy res_ty) )
133     setSrcSpan loc $
134     do  { expr' <- tcExpr expr res_ty
135         ; return (L loc expr') }
136
137 ---------------
138 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
139 tcInferRho expr = tcInfer (tcMonoExpr expr)
140 \end{code}
141
142
143
144 %************************************************************************
145 %*                                                                      *
146         tcExpr: the main expression typechecker
147 %*                                                                      *
148 %************************************************************************
149
150 \begin{code}
151 tcExpr :: HsExpr Name -> BoxyRhoType -> TcM (HsExpr TcId)
152 tcExpr (HsVar name)     res_ty = tcId (OccurrenceOf name) name res_ty
153
154 tcExpr (HsLit lit)      res_ty = do { boxyUnify (hsLitType lit) res_ty
155                                     ; return (HsLit lit) }
156
157 tcExpr (HsPar expr)     res_ty = do { expr' <- tcMonoExpr expr res_ty
158                                     ; return (HsPar expr') }
159
160 tcExpr (HsSCC lbl expr) res_ty = do { expr' <- tcMonoExpr expr res_ty
161                                     ; returnM (HsSCC lbl expr') }
162
163 tcExpr (HsCoreAnn lbl expr) res_ty       -- hdaume: core annotation
164   = do  { expr' <- tcMonoExpr expr res_ty
165         ; return (HsCoreAnn lbl expr') }
166
167 tcExpr (HsOverLit lit) res_ty  
168   = do  { lit' <- tcOverloadedLit (LiteralOrigin lit) lit res_ty
169         ; return (HsOverLit lit') }
170
171 tcExpr (NegApp expr neg_expr) res_ty
172   = do  { neg_expr' <- tcSyntaxOp (OccurrenceOf negateName) neg_expr
173                                   (mkFunTy res_ty res_ty)
174         ; expr' <- tcMonoExpr expr res_ty
175         ; return (NegApp expr' neg_expr') }
176
177 tcExpr (HsIPVar ip) res_ty
178   = do  {       -- Implicit parameters must have a *tau-type* not a 
179                 -- type scheme.  We enforce this by creating a fresh
180                 -- type variable as its type.  (Because res_ty may not
181                 -- be a tau-type.)
182           ip_ty <- newFlexiTyVarTy argTypeKind  -- argTypeKind: it can't be an unboxed tuple
183         ; co_fn <- tcSubExp ip_ty res_ty
184         ; (ip', inst) <- newIPDict (IPOccOrigin ip) ip ip_ty
185         ; extendLIE inst
186         ; return (mkHsCoerce co_fn (HsIPVar ip')) }
187
188 tcExpr (HsApp e1 e2) res_ty 
189   = go e1 [e2]
190   where
191     go :: LHsExpr Name -> [LHsExpr Name] -> TcM (HsExpr TcId)
192     go (L _ (HsApp e1 e2)) args = go e1 (e2:args)
193     go lfun@(L loc fun) args
194         = do { (fun', args') <- addErrCtxt (callCtxt lfun args) $
195                                 tcApp fun (length args) (tcArgs lfun args) res_ty
196              ; return (unLoc (foldl mkHsApp (L loc fun') args')) }
197
198 tcExpr (HsLam match) res_ty
199   = do  { (co_fn, match') <- tcMatchLambda match res_ty
200         ; return (mkHsCoerce co_fn (HsLam match')) }
201
202 tcExpr in_expr@(ExprWithTySig expr sig_ty) res_ty
203  = do   { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
204         ; expr' <- tcPolyExpr expr sig_tc_ty
205         ; co_fn <- tcSubExp sig_tc_ty res_ty
206         ; return (mkHsCoerce co_fn (ExprWithTySigOut expr' sig_ty)) }
207
208 tcExpr (HsType ty) res_ty
209   = failWithTc (text "Can't handle type argument:" <+> ppr ty)
210         -- This is the syntax for type applications that I was planning
211         -- but there are difficulties (e.g. what order for type args)
212         -- so it's not enabled yet.
213         -- Can't eliminate it altogether from the parser, because the
214         -- same parser parses *patterns*.
215 \end{code}
216
217
218 %************************************************************************
219 %*                                                                      *
220                 Infix operators and sections
221 %*                                                                      *
222 %************************************************************************
223
224 \begin{code}
225 tcExpr in_expr@(OpApp arg1 lop@(L loc op) fix arg2) res_ty
226   = do  { (op', [arg1', arg2']) <- tcApp op 2 (tcArgs lop [arg1,arg2]) res_ty
227         ; return (OpApp arg1' (L loc op') fix arg2') }
228
229 -- Left sections, equivalent to
230 --      \ x -> e op x,
231 -- or
232 --      \ x -> op e x,
233 -- or just
234 --      op e
235 --
236 -- We treat it as similar to the latter, so we don't
237 -- actually require the function to take two arguments
238 -- at all.  For example, (x `not`) means (not x);
239 -- you get postfix operators!  Not really Haskell 98
240 -- I suppose, but it's less work and kind of useful.
241
242 tcExpr in_expr@(SectionL arg1 lop@(L loc op)) res_ty
243   = do  { (op', [arg1']) <- tcApp op 1 (tcArgs lop [arg1]) res_ty
244         ; return (SectionL arg1' (L loc op')) }
245
246 -- Right sections, equivalent to \ x -> x `op` expr, or
247 --      \ x -> op x expr
248  
249 tcExpr in_expr@(SectionR lop@(L loc op) arg2) res_ty
250   = do  { (co_fn, (op', arg2')) <- subFunTys doc 1 res_ty $ \ [arg1_ty'] res_ty' ->
251                                    tcApp op 2 (tc_args arg1_ty') res_ty'
252         ; return (mkHsCoerce co_fn (SectionR (L loc op') arg2')) }
253   where
254     doc = ptext SLIT("The section") <+> quotes (ppr in_expr)
255                 <+> ptext SLIT("takes one argument")
256     tc_args arg1_ty' [arg1_ty, arg2_ty] 
257         = do { boxyUnify arg1_ty' arg1_ty
258              ; tcArg lop (arg2, arg2_ty, 2) }
259 \end{code}
260
261 \begin{code}
262 tcExpr (HsLet binds expr) res_ty
263   = do  { (binds', expr') <- tcLocalBinds binds $
264                              tcMonoExpr expr res_ty   
265         ; return (HsLet binds' expr') }
266
267 tcExpr (HsCase scrut matches) exp_ty
268   = do  {  -- We used to typecheck the case alternatives first.
269            -- The case patterns tend to give good type info to use
270            -- when typechecking the scrutinee.  For example
271            --   case (map f) of
272            --     (x:xs) -> ...
273            -- will report that map is applied to too few arguments
274            --
275            -- But now, in the GADT world, we need to typecheck the scrutinee
276            -- first, to get type info that may be refined in the case alternatives
277           (scrut', scrut_ty) <- addErrCtxt (caseScrutCtxt scrut)
278                                            (tcInferRho scrut)
279
280         ; traceTc (text "HsCase" <+> ppr scrut_ty)
281         ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
282         ; return (HsCase scrut' matches') }
283  where
284     match_ctxt = MC { mc_what = CaseAlt,
285                       mc_body = tcPolyExpr }
286
287 tcExpr (HsIf pred b1 b2) res_ty
288   = do  { pred' <- addErrCtxt (predCtxt pred) $
289                    tcMonoExpr pred boolTy
290         ; b1' <- tcMonoExpr b1 res_ty
291         ; b2' <- tcMonoExpr b2 res_ty
292         ; return (HsIf pred' b1' b2') }
293
294 tcExpr (HsDo do_or_lc stmts body _) res_ty
295   = tcDoStmts do_or_lc stmts body res_ty
296
297 tcExpr in_expr@(ExplicitList _ exprs) res_ty    -- Non-empty list
298   = do  { elt_ty <- boxySplitListTy res_ty
299         ; exprs' <- mappM (tc_elt elt_ty) exprs
300         ; return (ExplicitList elt_ty exprs') }
301   where
302     tc_elt elt_ty expr = tcPolyExpr expr elt_ty
303
304 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty    -- maybe empty
305   = do  { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
306         ; exprs' <- mappM (tc_elt elt_ty) exprs 
307         ; ifM (null exprs) (zapToMonotype elt_ty)
308                 -- If there are no expressions in the comprehension
309                 -- we must still fill in the box
310                 -- (Not needed for [] and () becuase they happen
311                 --  to parse as data constructors.)
312         ; return (ExplicitPArr elt_ty exprs') }
313   where
314     tc_elt elt_ty expr = tcPolyExpr expr elt_ty
315
316 tcExpr (ExplicitTuple exprs boxity) res_ty
317   = do  { arg_tys <- boxySplitTyConApp (tupleTyCon boxity (length exprs)) res_ty
318         ; exprs' <-  tcPolyExprs exprs arg_tys
319         ; return (ExplicitTuple exprs' boxity) }
320
321 tcExpr (HsProc pat cmd) res_ty
322   = do  { (pat', cmd') <- tcProc pat cmd res_ty
323         ; return (HsProc pat' cmd') }
324
325 tcExpr e@(HsArrApp _ _ _ _ _) _
326   = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e), 
327                       ptext SLIT("was found where an expression was expected")])
328
329 tcExpr e@(HsArrForm _ _ _) _
330   = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e), 
331                       ptext SLIT("was found where an expression was expected")])
332 \end{code}
333
334 %************************************************************************
335 %*                                                                      *
336                 Record construction and update
337 %*                                                                      *
338 %************************************************************************
339
340 \begin{code}
341 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
342   = do  { data_con <- tcLookupDataCon con_name
343
344         -- Check for missing fields
345         ; checkMissingFields data_con rbinds
346
347         ; let arity = dataConSourceArity data_con
348               check_fields arg_tys 
349                   = do  { rbinds' <- tcRecordBinds data_con arg_tys rbinds
350                         ; mapM unBox arg_tys 
351                         ; return rbinds' }
352                 -- The unBox ensures that all the boxes in arg_tys are indeed
353                 -- filled, which is the invariant expected by tcIdApp
354
355         ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
356
357         ; returnM (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
358
359 -- The main complication with RecordUpd is that we need to explicitly
360 -- handle the *non-updated* fields.  Consider:
361 --
362 --      data T a b = MkT1 { fa :: a, fb :: b }
363 --                 | MkT2 { fa :: a, fc :: Int -> Int }
364 --                 | MkT3 { fd :: a }
365 --      
366 --      upd :: T a b -> c -> T a c
367 --      upd t x = t { fb = x}
368 --
369 -- The type signature on upd is correct (i.e. the result should not be (T a b))
370 -- because upd should be equivalent to:
371 --
372 --      upd t x = case t of 
373 --                      MkT1 p q -> MkT1 p x
374 --                      MkT2 a b -> MkT2 p b
375 --                      MkT3 d   -> error ...
376 --
377 -- So we need to give a completely fresh type to the result record,
378 -- and then constrain it by the fields that are *not* updated ("p" above).
379 --
380 -- Note that because MkT3 doesn't contain all the fields being updated,
381 -- its RHS is simply an error, so it doesn't impose any type constraints
382 --
383 -- All this is done in STEP 4 below.
384 --
385 -- Note about GADTs
386 -- ~~~~~~~~~~~~~~~~
387 -- For record update we require that every constructor involved in the
388 -- update (i.e. that has all the specified fields) is "vanilla".  I
389 -- don't know how to do the update otherwise.
390
391
392 tcExpr expr@(RecordUpd record_expr rbinds _ _) res_ty
393   =     -- STEP 0
394         -- Check that the field names are really field names
395     ASSERT( notNull rbinds )
396     let 
397         field_names = map fst rbinds
398     in
399     mappM (tcLookupGlobalId.unLoc) field_names  `thenM` \ sel_ids ->
400         -- The renamer has already checked that they
401         -- are all in scope
402     let
403         bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name) 
404                    | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
405                      not (isRecordSelector sel_id)      -- Excludes class ops
406                    ]
407     in
408     checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM)  `thenM_`
409     
410         -- STEP 1
411         -- Figure out the tycon and data cons from the first field name
412     let
413                 -- It's OK to use the non-tc splitters here (for a selector)
414         upd_field_lbls  = recBindFields rbinds
415         sel_id : _      = sel_ids
416         (tycon, _)      = recordSelectorFieldLabel sel_id       -- We've failed already if
417         data_cons       = tyConDataCons tycon           -- it's not a field label
418         relevant_cons   = filter is_relevant data_cons
419         is_relevant con = all (`elem` dataConFieldLabels con) upd_field_lbls
420     in
421
422         -- STEP 2
423         -- Check that at least one constructor has all the named fields
424         -- i.e. has an empty set of bad fields returned by badFields
425     checkTc (not (null relevant_cons))
426             (badFieldsUpd rbinds)       `thenM_`
427
428         -- Check that all relevant data cons are vanilla.  Doing record updates on 
429         -- GADTs and/or existentials is more than my tiny brain can cope with today
430     checkTc (all isVanillaDataCon relevant_cons)
431             (nonVanillaUpd tycon)       `thenM_`
432
433         -- STEP 4
434         -- Use the un-updated fields to find a vector of booleans saying
435         -- which type arguments must be the same in updatee and result.
436         --
437         -- WARNING: this code assumes that all data_cons in a common tycon
438         -- have FieldLabels abstracted over the same tyvars.
439     let
440                 -- A constructor is only relevant to this process if
441                 -- it contains *all* the fields that are being updated
442         con1            = head relevant_cons    -- A representative constructor
443         con1_tyvars     = dataConTyVars con1
444         con1_flds       = dataConFieldLabels con1
445         con1_arg_tys    = dataConOrigArgTys con1
446         common_tyvars   = exactTyVarsOfTypes [ty | (fld,ty) <- con1_flds `zip` con1_arg_tys
447                                                  , not (fld `elem` upd_field_lbls) ]
448
449         is_common_tv tv = tv `elemVarSet` common_tyvars
450
451         mk_inst_ty tv result_inst_ty 
452           | is_common_tv tv = returnM result_inst_ty            -- Same as result type
453           | otherwise       = newFlexiTyVarTy (tyVarKind tv)    -- Fresh type, of correct kind
454     in
455     tcInstTyVars con1_tyvars                            `thenM` \ (_, result_inst_tys, inst_env) ->
456     zipWithM mk_inst_ty con1_tyvars result_inst_tys     `thenM` \ inst_tys ->
457
458         -- STEP 3
459         -- Typecheck the update bindings.
460         -- (Do this after checking for bad fields in case there's a field that
461         --  doesn't match the constructor.)
462     let
463         result_record_ty = mkTyConApp tycon result_inst_tys
464         con1_arg_tys'    = map (substTy inst_env) con1_arg_tys
465     in
466     tcSubExp result_record_ty res_ty            `thenM` \ co_fn ->
467     tcRecordBinds con1 con1_arg_tys' rbinds     `thenM` \ rbinds' ->
468
469         -- STEP 5
470         -- Typecheck the expression to be updated
471     let
472         record_ty = ASSERT( length inst_tys == tyConArity tycon )
473                     mkTyConApp tycon inst_tys
474         -- This is one place where the isVanilla check is important
475         -- So that inst_tys matches the tycon
476     in
477     tcMonoExpr record_expr record_ty            `thenM` \ record_expr' ->
478
479         -- STEP 6
480         -- Figure out the LIE we need.  We have to generate some 
481         -- dictionaries for the data type context, since we are going to
482         -- do pattern matching over the data cons.
483         --
484         -- What dictionaries do we need?  
485         -- We just take the context of the first data constructor
486         -- This isn't right, but I just can't bear to union up all the relevant ones
487     let
488         theta' = substTheta inst_env (tyConStupidTheta tycon)
489     in
490     newDicts RecordUpdOrigin theta'     `thenM` \ dicts ->
491     extendLIEs dicts                    `thenM_`
492
493         -- Phew!
494     returnM (mkHsCoerce co_fn (RecordUpd record_expr' rbinds' record_ty result_record_ty))
495 \end{code}
496
497
498 %************************************************************************
499 %*                                                                      *
500         Arithmetic sequences                    e.g. [a,b..]
501         and their parallel-array counterparts   e.g. [: a,b.. :]
502                 
503 %*                                                                      *
504 %************************************************************************
505
506 \begin{code}
507 tcExpr (ArithSeq _ seq@(From expr)) res_ty
508   = do  { elt_ty <- boxySplitListTy res_ty
509         ; expr' <- tcPolyExpr expr elt_ty
510         ; enum_from <- newMethodFromName (ArithSeqOrigin seq) 
511                               elt_ty enumFromName
512         ; return (ArithSeq (HsVar enum_from) (From expr')) }
513
514 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
515   = do  { elt_ty <- boxySplitListTy res_ty
516         ; expr1' <- tcPolyExpr expr1 elt_ty
517         ; expr2' <- tcPolyExpr expr2 elt_ty
518         ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq) 
519                               elt_ty enumFromThenName
520         ; return (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
521
522
523 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
524   = do  { elt_ty <- boxySplitListTy res_ty
525         ; expr1' <- tcPolyExpr expr1 elt_ty
526         ; expr2' <- tcPolyExpr expr2 elt_ty
527         ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq) 
528                               elt_ty enumFromToName
529         ; return (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
530
531 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
532   = do  { elt_ty <- boxySplitListTy res_ty
533         ; expr1' <- tcPolyExpr expr1 elt_ty
534         ; expr2' <- tcPolyExpr expr2 elt_ty
535         ; expr3' <- tcPolyExpr expr3 elt_ty
536         ; eft <- newMethodFromName (ArithSeqOrigin seq) 
537                       elt_ty enumFromThenToName
538         ; return (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
539
540 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
541   = do  { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
542         ; expr1' <- tcPolyExpr expr1 elt_ty
543         ; expr2' <- tcPolyExpr expr2 elt_ty
544         ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq) 
545                                       elt_ty enumFromToPName
546         ; return (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
547
548 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
549   = do  { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
550         ; expr1' <- tcPolyExpr expr1 elt_ty
551         ; expr2' <- tcPolyExpr expr2 elt_ty
552         ; expr3' <- tcPolyExpr expr3 elt_ty
553         ; eft <- newMethodFromName (PArrSeqOrigin seq)
554                       elt_ty enumFromThenToPName
555         ; return (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
556
557 tcExpr (PArrSeq _ _) _ 
558   = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
559     -- the parser shouldn't have generated it and the renamer shouldn't have
560     -- let it through
561 \end{code}
562
563
564 %************************************************************************
565 %*                                                                      *
566                 Template Haskell
567 %*                                                                      *
568 %************************************************************************
569
570 \begin{code}
571 #ifdef GHCI     /* Only if bootstrapped */
572         -- Rename excludes these cases otherwise
573 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
574 tcExpr (HsBracket brack)  res_ty = do   { e <- tcBracket brack res_ty
575                                         ; return (unLoc e) }
576 #endif /* GHCI */
577 \end{code}
578
579
580 %************************************************************************
581 %*                                                                      *
582                 Catch-all
583 %*                                                                      *
584 %************************************************************************
585
586 \begin{code}
587 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
588 \end{code}
589
590
591 %************************************************************************
592 %*                                                                      *
593                 Applications
594 %*                                                                      *
595 %************************************************************************
596
597 \begin{code}
598 ---------------------------
599 tcApp :: HsExpr Name                            -- Function
600       -> Arity                                  -- Number of args reqd
601       -> ([BoxySigmaType] -> TcM arg_results)   -- Argument type-checker
602       -> BoxyRhoType                            -- Result type
603       -> TcM (HsExpr TcId, arg_results)         
604
605 -- (tcFun fun n_args arg_checker res_ty)
606 -- The argument type checker, arg_checker, will be passed exactly n_args types
607
608 tcApp (HsVar fun_name) n_args arg_checker res_ty
609   = tcIdApp fun_name n_args arg_checker res_ty
610
611 tcApp fun n_args arg_checker res_ty     -- The vanilla case (rula APP)
612   = do  { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
613         ; fun'      <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
614         ; arg_tys'  <- mapM readFilledBox arg_boxes
615         ; args'     <- arg_checker arg_tys'
616         ; return (fun', args') }
617
618 ---------------------------
619 tcIdApp :: Name                                 -- Function
620         -> Arity                                -- Number of args reqd
621         -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
622                 -- The arg-checker guarantees to fill all boxes in the arg types
623         -> BoxyRhoType                          -- Result type
624         -> TcM (HsExpr TcId, arg_results)               
625
626 -- Call         (f e1 ... en) :: res_ty
627 -- Type         f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
628 --                      (where k <= n; fres has the rest)
629 -- NB:  if k < n then the function doesn't have enough args, and
630 --      presumably fres is a type variable that we are going to 
631 --      instantiate with a function type
632 --
633 -- Then         fres <= bx_(k+1) -> ... -> bx_n -> res_ty
634
635 tcIdApp fun_name n_args arg_checker res_ty
636   = do  { fun_id <- lookupFun (OccurrenceOf fun_name) fun_name
637
638         -- Split up the function type
639         ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy (idType fun_id)
640               (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
641
642               qtvs = concatMap fst tv_theta_prs         -- Quantified tyvars
643               arg_qtvs = exactTyVarsOfTypes fun_arg_tys
644               res_qtvs = exactTyVarsOfType fun_res_ty
645                 -- NB: exactTyVarsOfType.  See Note [Silly type synonyms in smart-app]
646               tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
647               k              = length fun_arg_tys       -- k <= n_args
648               n_missing_args = n_args - k               -- Always >= 0
649
650         -- Match the result type of the function with the
651         -- result type of the context, to get an inital substitution
652         ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
653         ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
654               res_ty'        = mkFunTys extra_arg_tys' res_ty
655               subst          = boxySubMatchType arg_qtvs fun_res_ty res_ty'
656                                 -- Only bind arg_qtvs, since only they will be
657                                 -- *definitely* be filled in by arg_checker
658                                 -- E.g.  error :: forall a. String -> a
659                                 --       (error "foo") :: bx5
660                                 --  Don't make subst [a |-> bx5]
661                                 --  because then the result subsumption becomes
662                                 --              bx5 ~ bx5
663                                 --  and the unifer doesn't expect the 
664                                 --  same box on both sides
665               inst_qtv tv | Just boxy_ty <- lookupTyVar subst tv = return boxy_ty
666                           | tv `elemVarSet` tau_qtvs = do { tv' <- tcInstBoxyTyVar tv
667                                                           ; return (mkTyVarTy tv') }
668                           | otherwise                = do { tv' <- tcInstTyVar tv
669                                                           ; return (mkTyVarTy tv') }
670                         -- The 'otherwise' case handles type variables that are
671                         -- mentioned only in the constraints, not in argument or 
672                         -- result types.  We'll make them tau-types
673
674         ; qtys' <- mapM inst_qtv qtvs
675         ; let arg_subst    = zipOpenTvSubst qtvs qtys'
676               fun_arg_tys' = substTys arg_subst fun_arg_tys
677
678         -- Typecheck the arguments!
679         -- Doing so will fill arg_qtvs and extra_arg_tys'
680         ; args' <- arg_checker (fun_arg_tys' ++ extra_arg_tys')
681
682         ; let strip qtv qty' | qtv `elemVarSet` arg_qtvs = stripBoxyType qty'
683                              | otherwise                 = return qty'
684         ; qtys'' <- zipWithM strip qtvs qtys'
685         ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
686
687         -- Result subsumption
688         ; let res_subst = zipOpenTvSubst qtvs qtys''
689               fun_res_ty'' = substTy res_subst fun_res_ty
690               res_ty'' = mkFunTys extra_arg_tys'' res_ty
691         ; co_fn <- addErrCtxtM (checkFunResCtxt fun_name res_ty fun_res_ty'') $
692                    tcSubExp fun_res_ty'' res_ty''
693                             
694         -- And pack up the results
695         -- By applying the coercion just to the *function* we can make
696         -- tcFun work nicely for OpApp and Sections too
697         ; fun' <- instFun fun_id qtvs qtys'' tv_theta_prs
698         ; co_fn' <- wrapFunResCoercion fun_arg_tys' co_fn
699         ; return (mkHsCoerce co_fn' fun', args') }
700 \end{code}
701
702 Note [Silly type synonyms in smart-app]
703 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
704 When we call sripBoxyType, all of the boxes should be filled
705 in.  But we need to be careful about type synonyms:
706         type T a = Int
707         f :: T a -> Int
708         ...(f x)...
709 In the call (f x) we'll typecheck x, expecting it to have type
710 (T box).  Usually that would fill in the box, but in this case not;
711 because 'a' is discarded by the silly type synonym T.  So we must
712 use exactTyVarsOfType to figure out which type variables are free 
713 in the argument type.
714
715 \begin{code}
716 -- tcId is a specialisation of tcIdApp when there are no arguments
717 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
718 --                ; return res }
719
720 tcId :: InstOrigin
721      -> Name                                    -- Function
722      -> BoxyRhoType                             -- Result type
723      -> TcM (HsExpr TcId)
724 tcId orig fun_name res_ty
725   = do  { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
726         ; fun_id <- lookupFun orig fun_name
727
728         -- Split up the function type
729         ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy (idType fun_id)
730               qtvs     = concatMap fst tv_theta_prs     -- Quantified tyvars
731               tau_qtvs = exactTyVarsOfType fun_tau      -- Mentiond in the tau part
732               inst_qtv tv | tv `elemVarSet` tau_qtvs = do { tv' <- tcInstBoxyTyVar tv
733                                                           ; return (mkTyVarTy tv') }
734                           | otherwise                = do { tv' <- tcInstTyVar tv
735                                                           ; return (mkTyVarTy tv') }
736
737         -- Do the subsumption check wrt the result type
738         ; qtv_tys <- mapM inst_qtv qtvs
739         ; let res_subst   = zipTopTvSubst qtvs qtv_tys
740               fun_tau' = substTy res_subst fun_tau
741
742         ; co_fn <- addErrCtxtM (checkFunResCtxt fun_name res_ty fun_tau') $
743                    tcSubExp fun_tau' res_ty
744
745         -- And pack up the results
746         ; fun' <- instFun fun_id qtvs qtv_tys tv_theta_prs 
747         ; return (mkHsCoerce co_fn fun') }
748
749 --      Note [Push result type in]
750 --
751 -- Unify with expected result before (was: after) type-checking the args
752 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
753 -- This is when we might detect a too-few args situation.
754 -- (One can think of cases when the opposite order would give
755 -- a better error message.)
756 -- [March 2003: I'm experimenting with putting this first.  Here's an 
757 --              example where it actually makes a real difference
758 --    class C t a b | t a -> b
759 --    instance C Char a Bool
760 --
761 --    data P t a = forall b. (C t a b) => MkP b
762 --    data Q t   = MkQ (forall a. P t a)
763
764 --    f1, f2 :: Q Char;
765 --    f1 = MkQ (MkP True)
766 --    f2 = MkQ (MkP True :: forall a. P Char a)
767 --
768 -- With the change, f1 will type-check, because the 'Char' info from
769 -- the signature is propagated into MkQ's argument. With the check
770 -- in the other order, the extra signature in f2 is reqd.]
771
772 ---------------------------
773 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
774 -- Typecheck a syntax operator, checking that it has the specified type
775 -- The operator is always a variable at this stage (i.e. renamer output)
776 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
777 tcSyntaxOp orig other      ty = pprPanic "tcSyntaxOp" (ppr other)
778
779 ---------------------------
780 instFun :: TcId
781         -> [TyVar] -> [TcType]  -- Quantified type variables and 
782                                 -- their instantiating types
783         -> [([TyVar], ThetaType)]       -- Stuff to instantiate
784         -> TcM (HsExpr TcId)    
785 instFun fun_id qtvs qtv_tys []
786   = return (HsVar fun_id)       -- Common short cut
787
788 instFun fun_id qtvs qtv_tys tv_theta_prs
789   = do  { let subst = zipOpenTvSubst qtvs qtv_tys
790               ty_theta_prs' = map subst_pr tv_theta_prs
791               subst_pr (tvs, theta) = (map (substTyVar subst) tvs, 
792                                        substTheta subst theta)
793
794                 -- The ty_theta_prs' is always non-empty
795               ((tys1',theta1') : further_prs') = ty_theta_prs'
796                 
797                 -- First, chuck in the constraints from 
798                 -- the "stupid theta" of a data constructor (sigh)
799         ; case isDataConId_maybe fun_id of
800                 Just con -> tcInstStupidTheta con tys1'
801                 Nothing  -> return ()
802
803         ; if want_method_inst theta1'
804           then do { meth_id <- newMethodWithGivenTy orig fun_id tys1'
805                         -- See Note [Multiple instantiation]
806                   ; go (HsVar meth_id) further_prs' }
807           else go (HsVar fun_id) ty_theta_prs'
808         }
809   where
810     orig = OccurrenceOf (idName fun_id)
811
812     go fun [] = return fun
813
814     go fun ((tys, theta) : prs)
815         = do { dicts <- newDicts orig theta
816              ; extendLIEs dicts
817              ; let the_app = unLoc $ mkHsDictApp (mkHsTyApp (noLoc fun) tys)
818                                                  (map instToId dicts)
819              ; go the_app prs }
820
821         --      Hack Alert (want_method_inst)!
822         -- See Note [No method sharing]
823         -- If   f :: (%x :: T) => Int -> Int
824         -- Then if we have two separate calls, (f 3, f 4), we cannot
825         -- make a method constraint that then gets shared, thus:
826         --      let m = f %x in (m 3, m 4)
827         -- because that loses the linearity of the constraint.
828         -- The simplest thing to do is never to construct a method constraint
829         -- in the first place that has a linear implicit parameter in it.
830     want_method_inst theta =  not (null theta)                  -- Overloaded
831                            && not (any isLinearPred theta)      -- Not linear
832                            && not opt_NoMethodSharing
833                 -- See Note [No method sharing] below
834 \end{code}
835
836 Note [Multiple instantiation]
837 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
838 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
839 For example, consider
840         f :: forall a. Eq a => forall b. Ord b => a -> b
841 At a call to f, at say [Int, Bool], it's tempting to translate the call to 
842
843         f_m1
844   where
845         f_m1 :: forall b. Ord b => Int -> b
846         f_m1 = f Int dEqInt
847
848         f_m2 :: Int -> Bool
849         f_m2 = f_m1 Bool dOrdBool
850
851 But notice that f_m2 has f_m1 as its meth_id.  Now the danger is that if we do
852 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
853         f_m1 = f_mx
854 But it's entirely possible that f_m2 will continue to float out, because it
855 mentions no type variables.  Result, f_m1 isn't in scope.
856
857 Here's a concrete example that does this (test tc200):
858
859     class C a where
860       f :: Eq b => b -> a -> Int
861       baz :: Eq a => Int -> a -> Int
862
863     instance C Int where
864       baz = f
865
866 Current solution: only do the "method sharing" thing for the first type/dict
867 application, not for the iterated ones.  A horribly subtle point.
868
869 Note [No method sharing]
870 ~~~~~~~~~~~~~~~~~~~~~~~~
871 The -fno-method-sharing flag controls what happens so far as the LIE
872 is concerned.  The default case is that for an overloaded function we 
873 generate a "method" Id, and add the Method Inst to the LIE.  So you get
874 something like
875         f :: Num a => a -> a
876         f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
877 If you specify -fno-method-sharing, the dictionary application 
878 isn't shared, so we get
879         f :: Num a => a -> a
880         f = /\a (d:Num a) (x:a) -> (+) a d x x
881 This gets a bit less sharing, but
882         a) it's better for RULEs involving overloaded functions
883         b) perhaps fewer separated lambdas
884
885 \begin{code}
886 tcArgs :: LHsExpr Name                          -- The function (for error messages)
887        -> [LHsExpr Name] -> [TcSigmaType]       -- Actual arguments and expected arg types
888        -> TcM [LHsExpr TcId]                    -- Resulting args
889
890 tcArgs fun args expected_arg_tys
891   = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
892
893 tcArg :: LHsExpr Name                           -- The function (for error messages)
894        -> (LHsExpr Name, BoxySigmaType, Int)    -- Actual argument and expected arg type
895        -> TcM (LHsExpr TcId)                    -- Resulting argument
896 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no) $
897                               tcPolyExprNC arg ty
898
899
900 ----------------
901 -- If an error happens we try to figure out whether the
902 -- function has been given too many or too few arguments,
903 -- and say so.
904 checkFunResCtxt fun expected_res_ty actual_res_ty tidy_env
905   = zonkTcType expected_res_ty    `thenM` \ exp_ty' ->
906     zonkTcType actual_res_ty      `thenM` \ act_ty' ->
907     let
908       (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
909       (env2, act_ty'') = tidyOpenType env1     act_ty'
910       (exp_args, _)    = tcSplitFunTys exp_ty''
911       (act_args, _)    = tcSplitFunTys act_ty''
912
913       len_act_args     = length act_args
914       len_exp_args     = length exp_args
915
916       message | len_exp_args < len_act_args = wrongArgsCtxt "too few"  fun
917               | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun
918               | otherwise                   = empty
919     in
920     returnM (env2, message)
921 \end{code}
922
923
924 %************************************************************************
925 %*                                                                      *
926 \subsection{@tcId@ typchecks an identifier occurrence}
927 %*                                                                      *
928 %************************************************************************
929
930 \begin{code}
931 lookupFun :: InstOrigin -> Name -> TcM TcId
932 lookupFun orig id_name
933   = do  { thing <- tcLookup id_name
934         ; case thing of
935             AGlobal (ADataCon con) -> return (dataConWrapId con)
936
937             AGlobal (AnId id) 
938                 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
939                 | otherwise                  -> return id
940                 -- A global cannot possibly be ill-staged
941                 -- nor does it need the 'lifting' treatment
942
943 #ifndef GHCI
944             ATcId id th_level _ -> return id                    -- Non-TH case
945 #else
946             ATcId id th_level _ -> do { use_stage <- getStage   -- TH case
947                                       ; thLocalId orig id_name id th_level use_stage }
948 #endif
949
950             other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
951     }
952
953 #ifdef GHCI  /* GHCI and TH is on */
954 --------------------------------------
955 -- thLocalId : Check for cross-stage lifting
956 thLocalId orig id_name id th_bind_lvl (Brack use_lvl ps_var lie_var)
957   | use_lvl > th_bind_lvl
958   = thBrackId orig id_name id ps_var lie_var
959 thLocalId orig id_name id th_bind_lvl use_stage
960   = do  { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
961         ; return id }
962
963 --------------------------------------
964 thBrackId orig id_name id ps_var lie_var
965   | isExternalName id_name
966   =     -- Top-level identifiers in this module,
967         -- (which have External Names)
968         -- are just like the imported case:
969         -- no need for the 'lifting' treatment
970         -- E.g.  this is fine:
971         --   f x = x
972         --   g y = [| f 3 |]
973         -- But we do need to put f into the keep-alive
974         -- set, because after desugaring the code will
975         -- only mention f's *name*, not f itself.
976     do  { keepAliveTc id_name; return id }
977
978   | otherwise
979   =     -- Nested identifiers, such as 'x' in
980         -- E.g. \x -> [| h x |]
981         -- We must behave as if the reference to x was
982         --      h $(lift x)     
983         -- We use 'x' itself as the splice proxy, used by 
984         -- the desugarer to stitch it all back together.
985         -- If 'x' occurs many times we may get many identical
986         -- bindings of the same splice proxy, but that doesn't
987         -- matter, although it's a mite untidy.
988     do  { let id_ty = idType id
989         ; checkTc (isTauTy id_ty) (polySpliceErr id)
990                -- If x is polymorphic, its occurrence sites might
991                -- have different instantiations, so we can't use plain
992                -- 'x' as the splice proxy name.  I don't know how to 
993                -- solve this, and it's probably unimportant, so I'm
994                -- just going to flag an error for now
995    
996         ; id_ty' <- zapToMonotype id_ty
997                 -- The id_ty might have an OpenTypeKind, but we
998                 -- can't instantiate the Lift class at that kind,
999                 -- so we zap it to a LiftedTypeKind monotype
1000                 -- C.f. the call in TcPat.newLitInst
1001
1002         ; setLIEVar lie_var     $ do
1003         { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1004                    -- Put the 'lift' constraint into the right LIE
1005            
1006                    -- Update the pending splices
1007         ; ps <- readMutVar ps_var
1008         ; writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1009
1010         ; return id } }
1011 #endif /* GHCI */
1012 \end{code}
1013
1014 Note [Multiple instantiation]
1015 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1016 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
1017 For example, consider
1018         f :: forall a. Eq a => forall b. Ord b => a -> b
1019 At a call to f, at say [Int, Bool], it's tempting to translate the call to 
1020
1021         f_m1
1022   where
1023         f_m1 :: forall b. Ord b => Int -> b
1024         f_m1 = f Int dEqInt
1025
1026         f_m2 :: Int -> Bool
1027         f_m2 = f_m1 Bool dOrdBool
1028
1029 But notice that f_m2 has f_m1 as its meth_id.  Now the danger is that if we do
1030 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
1031         f_m1 = f_mx
1032 But it's entirely possible that f_m2 will continue to float out, because it
1033 mentions no type variables.  Result, f_m1 isn't in scope.
1034
1035 Here's a concrete example that does this (test tc200):
1036
1037     class C a where
1038       f :: Eq b => b -> a -> Int
1039       baz :: Eq a => Int -> a -> Int
1040
1041     instance C Int where
1042       baz = f
1043
1044 Current solution: only do the "method sharing" thing for the first type/dict
1045 application, not for the iterated ones.  A horribly subtle point.
1046
1047
1048 %************************************************************************
1049 %*                                                                      *
1050 \subsection{Record bindings}
1051 %*                                                                      *
1052 %************************************************************************
1053
1054 Game plan for record bindings
1055 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1056 1. Find the TyCon for the bindings, from the first field label.
1057
1058 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1059
1060 For each binding field = value
1061
1062 3. Instantiate the field type (from the field label) using the type
1063    envt from step 2.
1064
1065 4  Type check the value using tcArg, passing the field type as 
1066    the expected argument type.
1067
1068 This extends OK when the field types are universally quantified.
1069
1070         
1071 \begin{code}
1072 tcRecordBinds
1073         :: DataCon
1074         -> [TcType]     -- Expected type for each field
1075         -> HsRecordBinds Name
1076         -> TcM (HsRecordBinds TcId)
1077
1078 tcRecordBinds data_con arg_tys rbinds
1079   = do  { mb_binds <- mappM do_bind rbinds
1080         ; return (catMaybes mb_binds) }
1081   where
1082     flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1083     do_bind (L loc field_lbl, rhs)
1084       | Just field_ty <- assocMaybe flds_w_tys field_lbl
1085       = addErrCtxt (fieldCtxt field_lbl)        $
1086         do { rhs'   <- tcPolyExprNC rhs field_ty
1087            ; sel_id <- tcLookupId field_lbl
1088            ; ASSERT( isRecordSelector sel_id )
1089              return (Just (L loc sel_id, rhs')) }
1090       | otherwise
1091       = do { addErrTc (badFieldCon data_con field_lbl)
1092            ; return Nothing }
1093
1094 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1095 checkMissingFields data_con rbinds
1096   | null field_labels   -- Not declared as a record;
1097                         -- But C{} is still valid if no strict fields
1098   = if any isMarkedStrict field_strs then
1099         -- Illegal if any arg is strict
1100         addErrTc (missingStrictFields data_con [])
1101     else
1102         returnM ()
1103                         
1104   | otherwise           -- A record
1105   = checkM (null missing_s_fields)
1106            (addErrTc (missingStrictFields data_con missing_s_fields))   `thenM_`
1107
1108     doptM Opt_WarnMissingFields         `thenM` \ warn ->
1109     checkM (not (warn && notNull missing_ns_fields))
1110            (warnTc True (missingFields data_con missing_ns_fields))
1111
1112   where
1113     missing_s_fields
1114         = [ fl | (fl, str) <- field_info,
1115                  isMarkedStrict str,
1116                  not (fl `elem` field_names_used)
1117           ]
1118     missing_ns_fields
1119         = [ fl | (fl, str) <- field_info,
1120                  not (isMarkedStrict str),
1121                  not (fl `elem` field_names_used)
1122           ]
1123
1124     field_names_used = recBindFields rbinds
1125     field_labels     = dataConFieldLabels data_con
1126
1127     field_info = zipEqual "missingFields"
1128                           field_labels
1129                           field_strs
1130
1131     field_strs = dataConStrictMarks data_con
1132 \end{code}
1133
1134 %************************************************************************
1135 %*                                                                      *
1136 \subsection{Errors and contexts}
1137 %*                                                                      *
1138 %************************************************************************
1139
1140 Boring and alphabetical:
1141 \begin{code}
1142 caseScrutCtxt expr
1143   = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1144
1145 exprCtxt expr
1146   = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1147
1148 fieldCtxt field_name
1149   = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1150
1151 funAppCtxt fun arg arg_no
1152   = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"), 
1153                     quotes (ppr fun) <> text ", namely"])
1154          4 (quotes (ppr arg))
1155
1156 predCtxt expr
1157   = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1158
1159 nonVanillaUpd tycon
1160   = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") <+> quotes (ppr tycon)
1161                 <+> ptext SLIT("is not (yet) supported"),
1162           ptext SLIT("Use pattern-matching instead")]
1163 badFieldsUpd rbinds
1164   = hang (ptext SLIT("No constructor has all these fields:"))
1165          4 (pprQuotedList (recBindFields rbinds))
1166
1167 naughtyRecordSel sel_id
1168   = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+> 
1169     ptext SLIT("as a function due to escaped type variables") $$ 
1170     ptext SLIT("Probably fix: use pattern-matching syntax instead")
1171
1172 notSelector field
1173   = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1174
1175 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1176 missingStrictFields con fields
1177   = header <> rest
1178   where
1179     rest | null fields = empty  -- Happens for non-record constructors 
1180                                 -- with strict fields
1181          | otherwise   = colon <+> pprWithCommas ppr fields
1182
1183     header = ptext SLIT("Constructor") <+> quotes (ppr con) <+> 
1184              ptext SLIT("does not have the required strict field(s)") 
1185           
1186 missingFields :: DataCon -> [FieldLabel] -> SDoc
1187 missingFields con fields
1188   = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:") 
1189         <+> pprWithCommas ppr fields
1190
1191 callCtxt fun args
1192   = ptext SLIT("In the call") <+> parens (ppr (foldl mkHsApp fun args))
1193
1194 wrongArgsCtxt too_many_or_few fun
1195   = ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1196         <+> ptext SLIT("is applied to") <+> text too_many_or_few 
1197         <+> ptext SLIT("arguments")
1198
1199 #ifdef GHCI
1200 polySpliceErr :: Id -> SDoc
1201 polySpliceErr id
1202   = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)
1203 #endif
1204 \end{code}