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