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