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