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