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