Monadify typecheck/TcExpr: use do, return and standard monad functions
[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                  = WpCo $ 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         ; result <- go True fun ty_theta_prs' 
789         ; traceTc (text "instFun result" <+> ppr result)
790         ; return result
791         }
792   where
793     subst_pr (tvs, theta) 
794         = (substTyVars subst tvs, substTheta subst theta)
795
796     go _ fun [] = do {traceTc (text "go _ fun [] returns" <+> ppr fun) ; return fun }
797
798     go True (HsVar fun_id) ((tys,theta) : prs)
799         | want_method_inst theta
800         = do { traceTc (text "go (HsVar fun_id) ((tys,theta) : prs) | want_method_inst theta")
801              ; meth_id <- newMethodWithGivenTy orig fun_id tys
802              ; go False (HsVar meth_id) prs }
803                 -- Go round with 'False' to prevent further use
804                 -- of newMethod: see Note [Multiple instantiation]
805
806     go _ fun ((tys, theta) : prs)
807         = do { co_fn <- instCall orig tys theta
808              ; traceTc (text "go yields co_fn" <+> ppr co_fn)
809              ; go False (HsWrap co_fn fun) prs }
810
811         -- See Note [No method sharing]
812     want_method_inst theta =  not (null theta)  -- Overloaded
813                            && not opt_NoMethodSharing
814 \end{code}
815
816 Note [Multiple instantiation]
817 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
818 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
819 For example, consider
820         f :: forall a. Eq a => forall b. Ord b => a -> b
821 At a call to f, at say [Int, Bool], it's tempting to translate the call to 
822
823         f_m1
824   where
825         f_m1 :: forall b. Ord b => Int -> b
826         f_m1 = f Int dEqInt
827
828         f_m2 :: Int -> Bool
829         f_m2 = f_m1 Bool dOrdBool
830
831 But notice that f_m2 has f_m1 as its meth_id.  Now the danger is that if we do
832 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
833         f_m1 = f_mx
834 But it's entirely possible that f_m2 will continue to float out, because it
835 mentions no type variables.  Result, f_m1 isn't in scope.
836
837 Here's a concrete example that does this (test tc200):
838
839     class C a where
840       f :: Eq b => b -> a -> Int
841       baz :: Eq a => Int -> a -> Int
842
843     instance C Int where
844       baz = f
845
846 Current solution: only do the "method sharing" thing for the first type/dict
847 application, not for the iterated ones.  A horribly subtle point.
848
849 Note [No method sharing]
850 ~~~~~~~~~~~~~~~~~~~~~~~~
851 The -fno-method-sharing flag controls what happens so far as the LIE
852 is concerned.  The default case is that for an overloaded function we 
853 generate a "method" Id, and add the Method Inst to the LIE.  So you get
854 something like
855         f :: Num a => a -> a
856         f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
857 If you specify -fno-method-sharing, the dictionary application 
858 isn't shared, so we get
859         f :: Num a => a -> a
860         f = /\a (d:Num a) (x:a) -> (+) a d x x
861 This gets a bit less sharing, but
862         a) it's better for RULEs involving overloaded functions
863         b) perhaps fewer separated lambdas
864
865 Note [Left to right]
866 ~~~~~~~~~~~~~~~~~~~~
867 tcArgs implements a left-to-right order, which goes beyond what is described in the
868 impredicative type inference paper.  In particular, it allows
869         runST $ foo
870 where runST :: (forall s. ST s a) -> a
871 When typechecking the application of ($)::(a->b) -> a -> b, we first check that
872 runST has type (a->b), thereby filling in a=forall s. ST s a.  Then we un-box this type
873 before checking foo.  The left-to-right order really helps here.
874
875 \begin{code}
876 tcArgs :: LHsExpr Name                          -- The function (for error messages)
877        -> [LHsExpr Name]                        -- Actual args
878        -> ArgChecker [LHsExpr TcId]
879
880 type ArgChecker results
881    = [TyVar] -> [TcSigmaType]           -- Current instantiation
882    -> [TcSigmaType]                     -- Expected arg types (**before** applying the instantiation)
883    -> TcM ([TcSigmaType], results)      -- Resulting instaniation and args
884
885 tcArgs fun args qtvs qtys arg_tys
886   = go 1 qtys args arg_tys
887   where
888     go n qtys [] [] = return (qtys, [])
889     go n qtys (arg:args) (arg_ty:arg_tys)
890         = do { arg' <- tcArg fun n arg qtvs qtys arg_ty
891              ; qtys' <- mapM refineBox qtys     -- Exploit new info
892              ; (qtys'', args') <- go (n+1) qtys' args arg_tys
893              ; return (qtys'', arg':args') }
894     go n qtys args arg_tys = panic "tcArgs"
895
896 tcArg :: LHsExpr Name                           -- The function
897       -> Int                                    --   and arg number (for error messages)
898       -> LHsExpr Name
899       -> [TyVar] -> [TcSigmaType]               -- Instantiate the arg type like this
900       -> BoxySigmaType
901       -> TcM (LHsExpr TcId)                     -- Resulting argument
902 tcArg fun arg_no arg qtvs qtys ty
903   = addErrCtxt (funAppCtxt fun arg arg_no) $
904     tcPolyExprNC arg (substTyWith qtvs qtys ty)
905 \end{code}
906
907
908 Note [tagToEnum#]
909 ~~~~~~~~~~~~~~~~~
910 Nasty check to ensure that tagToEnum# is applied to a type that is an
911 enumeration TyCon.  Unification may refine the type later, but this
912 check won't see that, alas.  It's crude but it works.
913
914 Here's are two cases that should fail
915         f :: forall a. a
916         f = tagToEnum# 0        -- Can't do tagToEnum# at a type variable
917
918         g :: Int
919         g = tagToEnum# 0        -- Int is not an enumeration
920
921
922 \begin{code}
923 doStupidChecks :: HsExpr TcId
924                -> [([TcType], ThetaType)]
925                -> TcM ()
926 -- Check two tiresome and ad-hoc cases
927 -- (a) the "stupid theta" for a data con; add the constraints
928 --     from the "stupid theta" of a data constructor (sigh)
929 -- (b) deal with the tagToEnum# problem: see Note [tagToEnum#]
930
931 doStupidChecks (HsVar fun_id) ((tys,_):_)
932   | Just con <- isDataConId_maybe fun_id   -- (a)
933   = addDataConStupidTheta con tys
934
935   | fun_id `hasKey` tagToEnumKey           -- (b)
936   = do  { tys' <- zonkTcTypes tys
937         ; checkTc (ok tys') (tagToEnumError tys')
938         }
939   where
940     ok []       = False
941     ok (ty:tys) = case tcSplitTyConApp_maybe ty of
942                         Just (tc,_) -> isEnumerationTyCon tc
943                         Nothing     -> False
944
945 doStupidChecks fun tv_theta_prs
946   = return () -- The common case
947                                       
948
949 tagToEnumError tys
950   = hang (ptext SLIT("Bad call to tagToEnum#") <+> at_type)
951          2 (vcat [ptext SLIT("Specify the type by giving a type signature"),
952                   ptext SLIT("e.g. (tagToEnum# x) :: Bool")])
953   where
954     at_type | null tys = empty  -- Probably never happens
955             | otherwise = ptext SLIT("at type") <+> ppr (head tys)
956 \end{code}
957
958 %************************************************************************
959 %*                                                                      *
960 \subsection{@tcId@ typechecks an identifier occurrence}
961 %*                                                                      *
962 %************************************************************************
963
964 \begin{code}
965 lookupFun :: InstOrigin -> Name -> TcM (HsExpr TcId, TcType)
966 lookupFun orig id_name
967   = do  { thing <- tcLookup id_name
968         ; case thing of
969             AGlobal (ADataCon con) -> return (HsVar wrap_id, idType wrap_id)
970                                    where
971                                       wrap_id = dataConWrapId con
972
973             AGlobal (AnId id) 
974                 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
975                 | otherwise                  -> return (HsVar id, idType id)
976                 -- A global cannot possibly be ill-staged
977                 -- nor does it need the 'lifting' treatment
978
979             ATcId { tct_id = id, tct_type = ty, tct_co = mb_co, tct_level = lvl }
980                 -> do { thLocalId orig id ty lvl
981                       ; case mb_co of
982                           Unrefineable    -> return (HsVar id, ty)
983                           Rigid co        -> return (mkHsWrap co (HsVar id), ty)        
984                           Wobbly          -> traceTc (text "lookupFun" <+> ppr id) >> return (HsVar id, ty)     -- Wobbly, or no free vars
985                           WobblyInvisible -> failWithTc (ppr id_name <+> ptext SLIT(" not in scope because it has a wobbly type (solution: add a type annotation)"))
986                       }
987
988             other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
989     }
990
991 #ifndef GHCI  /* GHCI and TH is off */
992 --------------------------------------
993 -- thLocalId : Check for cross-stage lifting
994 thLocalId orig id id_ty th_bind_lvl
995   = return ()
996
997 #else         /* GHCI and TH is on */
998 thLocalId orig id id_ty th_bind_lvl 
999   = do  { use_stage <- getStage -- TH case
1000         ; case use_stage of
1001             Brack use_lvl ps_var lie_var | use_lvl > th_bind_lvl
1002                   -> thBrackId orig id ps_var lie_var
1003             other -> do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
1004                         ; return id }
1005         }
1006
1007 --------------------------------------
1008 thBrackId orig id ps_var lie_var
1009   | thTopLevelId id
1010   =     -- Top-level identifiers in this module,
1011         -- (which have External Names)
1012         -- are just like the imported case:
1013         -- no need for the 'lifting' treatment
1014         -- E.g.  this is fine:
1015         --   f x = x
1016         --   g y = [| f 3 |]
1017         -- But we do need to put f into the keep-alive
1018         -- set, because after desugaring the code will
1019         -- only mention f's *name*, not f itself.
1020     do  { keepAliveTc id; return id }
1021
1022   | otherwise
1023   =     -- Nested identifiers, such as 'x' in
1024         -- E.g. \x -> [| h x |]
1025         -- We must behave as if the reference to x was
1026         --      h $(lift x)     
1027         -- We use 'x' itself as the splice proxy, used by 
1028         -- the desugarer to stitch it all back together.
1029         -- If 'x' occurs many times we may get many identical
1030         -- bindings of the same splice proxy, but that doesn't
1031         -- matter, although it's a mite untidy.
1032     do  { let id_ty = idType id
1033         ; checkTc (isTauTy id_ty) (polySpliceErr id)
1034                -- If x is polymorphic, its occurrence sites might
1035                -- have different instantiations, so we can't use plain
1036                -- 'x' as the splice proxy name.  I don't know how to 
1037                -- solve this, and it's probably unimportant, so I'm
1038                -- just going to flag an error for now
1039    
1040         ; id_ty' <- zapToMonotype id_ty
1041                 -- The id_ty might have an OpenTypeKind, but we
1042                 -- can't instantiate the Lift class at that kind,
1043                 -- so we zap it to a LiftedTypeKind monotype
1044                 -- C.f. the call in TcPat.newLitInst
1045
1046         ; setLIEVar lie_var     $ do
1047         { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1048                    -- Put the 'lift' constraint into the right LIE
1049            
1050                    -- Update the pending splices
1051         ; ps <- readMutVar ps_var
1052         ; writeMutVar ps_var ((idName id, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1053
1054         ; return id } }
1055 #endif /* GHCI */
1056 \end{code}
1057
1058
1059 %************************************************************************
1060 %*                                                                      *
1061 \subsection{Record bindings}
1062 %*                                                                      *
1063 %************************************************************************
1064
1065 Game plan for record bindings
1066 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1067 1. Find the TyCon for the bindings, from the first field label.
1068
1069 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1070
1071 For each binding field = value
1072
1073 3. Instantiate the field type (from the field label) using the type
1074    envt from step 2.
1075
1076 4  Type check the value using tcArg, passing the field type as 
1077    the expected argument type.
1078
1079 This extends OK when the field types are universally quantified.
1080
1081         
1082 \begin{code}
1083 tcRecordBinds
1084         :: DataCon
1085         -> [TcType]     -- Expected type for each field
1086         -> HsRecordBinds Name
1087         -> TcM (HsRecordBinds TcId)
1088
1089 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1090   = do  { mb_binds <- mapM do_bind rbinds
1091         ; return (HsRecFields (catMaybes mb_binds) dd) }
1092   where
1093     flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1094     do_bind fld@(HsRecField { hsRecFieldId = L loc field_lbl, hsRecFieldArg = rhs })
1095       | Just field_ty <- assocMaybe flds_w_tys field_lbl
1096       = addErrCtxt (fieldCtxt field_lbl)        $
1097         do { rhs'   <- tcPolyExprNC rhs field_ty
1098            ; sel_id <- tcLookupField field_lbl
1099            ; ASSERT( isRecordSelector sel_id )
1100              return (Just (fld { hsRecFieldId = L loc sel_id, hsRecFieldArg = rhs' })) }
1101       | otherwise
1102       = do { addErrTc (badFieldCon data_con field_lbl)
1103            ; return Nothing }
1104
1105 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1106 checkMissingFields data_con rbinds
1107   | null field_labels   -- Not declared as a record;
1108                         -- But C{} is still valid if no strict fields
1109   = if any isMarkedStrict field_strs then
1110         -- Illegal if any arg is strict
1111         addErrTc (missingStrictFields data_con [])
1112     else
1113         return ()
1114                         
1115   | otherwise = do              -- A record
1116     unless (null missing_s_fields)
1117            (addErrTc (missingStrictFields data_con missing_s_fields))
1118
1119     warn <- doptM Opt_WarnMissingFields
1120     unless (not (warn && notNull missing_ns_fields))
1121            (warnTc True (missingFields data_con missing_ns_fields))
1122
1123   where
1124     missing_s_fields
1125         = [ fl | (fl, str) <- field_info,
1126                  isMarkedStrict str,
1127                  not (fl `elem` field_names_used)
1128           ]
1129     missing_ns_fields
1130         = [ fl | (fl, str) <- field_info,
1131                  not (isMarkedStrict str),
1132                  not (fl `elem` field_names_used)
1133           ]
1134
1135     field_names_used = hsRecFields rbinds
1136     field_labels     = dataConFieldLabels data_con
1137
1138     field_info = zipEqual "missingFields"
1139                           field_labels
1140                           field_strs
1141
1142     field_strs = dataConStrictMarks data_con
1143 \end{code}
1144
1145 %************************************************************************
1146 %*                                                                      *
1147 \subsection{Errors and contexts}
1148 %*                                                                      *
1149 %************************************************************************
1150
1151 Boring and alphabetical:
1152 \begin{code}
1153 caseScrutCtxt expr
1154   = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1155
1156 exprCtxt expr
1157   = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1158
1159 fieldCtxt field_name
1160   = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1161
1162 funAppCtxt fun arg arg_no
1163   = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"), 
1164                     quotes (ppr fun) <> text ", namely"])
1165          4 (quotes (ppr arg))
1166
1167 predCtxt expr
1168   = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1169
1170 nonVanillaUpd tycon
1171   = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") 
1172                 <+> quotes (pprSourceTyCon tycon)
1173                 <+> ptext SLIT("is not (yet) supported"),
1174           ptext SLIT("Use pattern-matching instead")]
1175 badFieldsUpd rbinds
1176   = hang (ptext SLIT("No constructor has all these fields:"))
1177          4 (pprQuotedList (hsRecFields rbinds))
1178
1179 naughtyRecordSel sel_id
1180   = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+> 
1181     ptext SLIT("as a function due to escaped type variables") $$ 
1182     ptext SLIT("Probably fix: use pattern-matching syntax instead")
1183
1184 notSelector field
1185   = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1186
1187 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1188 missingStrictFields con fields
1189   = header <> rest
1190   where
1191     rest | null fields = empty  -- Happens for non-record constructors 
1192                                 -- with strict fields
1193          | otherwise   = colon <+> pprWithCommas ppr fields
1194
1195     header = ptext SLIT("Constructor") <+> quotes (ppr con) <+> 
1196              ptext SLIT("does not have the required strict field(s)") 
1197           
1198 missingFields :: DataCon -> [FieldLabel] -> SDoc
1199 missingFields con fields
1200   = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:") 
1201         <+> pprWithCommas ppr fields
1202
1203 -- callCtxt fun args = ptext SLIT("In the call") <+> parens (ppr (foldl mkHsApp fun args))
1204
1205 #ifdef GHCI
1206 polySpliceErr :: Id -> SDoc
1207 polySpliceErr id
1208   = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)
1209 #endif
1210 \end{code}