Fix origin for addDataConStupidTheta
[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, idName )
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, instCall,
33                           newMethodWithGivenTy, instStupidTheta )
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, addDataConStupidTheta, 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?  The tyConStupidTheta tells us.
493     let
494         theta' = substTheta inst_env (tyConStupidTheta tycon)
495     in
496     instStupidTheta RecordUpdOrigin theta'      `thenM_`
497
498         -- Phew!
499     returnM (mkHsCoerce co_fn (RecordUpd record_expr' rbinds' record_ty result_record_ty))
500 \end{code}
501
502
503 %************************************************************************
504 %*                                                                      *
505         Arithmetic sequences                    e.g. [a,b..]
506         and their parallel-array counterparts   e.g. [: a,b.. :]
507                 
508 %*                                                                      *
509 %************************************************************************
510
511 \begin{code}
512 tcExpr (ArithSeq _ seq@(From expr)) res_ty
513   = do  { elt_ty <- boxySplitListTy res_ty
514         ; expr' <- tcPolyExpr expr elt_ty
515         ; enum_from <- newMethodFromName (ArithSeqOrigin seq) 
516                               elt_ty enumFromName
517         ; return (ArithSeq (HsVar enum_from) (From expr')) }
518
519 tcExpr in_expr@(ArithSeq _ seq@(FromThen 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_then <- newMethodFromName (ArithSeqOrigin seq) 
524                               elt_ty enumFromThenName
525         ; return (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
526
527
528 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
529   = do  { elt_ty <- boxySplitListTy res_ty
530         ; expr1' <- tcPolyExpr expr1 elt_ty
531         ; expr2' <- tcPolyExpr expr2 elt_ty
532         ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq) 
533                               elt_ty enumFromToName
534         ; return (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
535
536 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
537   = do  { elt_ty <- boxySplitListTy res_ty
538         ; expr1' <- tcPolyExpr expr1 elt_ty
539         ; expr2' <- tcPolyExpr expr2 elt_ty
540         ; expr3' <- tcPolyExpr expr3 elt_ty
541         ; eft <- newMethodFromName (ArithSeqOrigin seq) 
542                       elt_ty enumFromThenToName
543         ; return (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
544
545 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
546   = do  { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
547         ; expr1' <- tcPolyExpr expr1 elt_ty
548         ; expr2' <- tcPolyExpr expr2 elt_ty
549         ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq) 
550                                       elt_ty enumFromToPName
551         ; return (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
552
553 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
554   = do  { [elt_ty] <- boxySplitTyConApp parrTyCon res_ty
555         ; expr1' <- tcPolyExpr expr1 elt_ty
556         ; expr2' <- tcPolyExpr expr2 elt_ty
557         ; expr3' <- tcPolyExpr expr3 elt_ty
558         ; eft <- newMethodFromName (PArrSeqOrigin seq)
559                       elt_ty enumFromThenToPName
560         ; return (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
561
562 tcExpr (PArrSeq _ _) _ 
563   = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
564     -- the parser shouldn't have generated it and the renamer shouldn't have
565     -- let it through
566 \end{code}
567
568
569 %************************************************************************
570 %*                                                                      *
571                 Template Haskell
572 %*                                                                      *
573 %************************************************************************
574
575 \begin{code}
576 #ifdef GHCI     /* Only if bootstrapped */
577         -- Rename excludes these cases otherwise
578 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
579 tcExpr (HsBracket brack)  res_ty = do   { e <- tcBracket brack res_ty
580                                         ; return (unLoc e) }
581 #endif /* GHCI */
582 \end{code}
583
584
585 %************************************************************************
586 %*                                                                      *
587                 Catch-all
588 %*                                                                      *
589 %************************************************************************
590
591 \begin{code}
592 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
593 \end{code}
594
595
596 %************************************************************************
597 %*                                                                      *
598                 Applications
599 %*                                                                      *
600 %************************************************************************
601
602 \begin{code}
603 ---------------------------
604 tcApp :: HsExpr Name                            -- Function
605       -> Arity                                  -- Number of args reqd
606       -> ([BoxySigmaType] -> TcM arg_results)   -- Argument type-checker
607       -> BoxyRhoType                            -- Result type
608       -> TcM (HsExpr TcId, arg_results)         
609
610 -- (tcFun fun n_args arg_checker res_ty)
611 -- The argument type checker, arg_checker, will be passed exactly n_args types
612
613 tcApp (HsVar fun_name) n_args arg_checker res_ty
614   = tcIdApp fun_name n_args arg_checker res_ty
615
616 tcApp fun n_args arg_checker res_ty     -- The vanilla case (rula APP)
617   = do  { arg_boxes <- newBoxyTyVars (replicate n_args argTypeKind)
618         ; fun'      <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
619         ; arg_tys'  <- mapM readFilledBox arg_boxes
620         ; args'     <- arg_checker arg_tys'
621         ; return (fun', args') }
622
623 ---------------------------
624 tcIdApp :: Name                                 -- Function
625         -> Arity                                -- Number of args reqd
626         -> ([BoxySigmaType] -> TcM arg_results) -- Argument type-checker
627                 -- The arg-checker guarantees to fill all boxes in the arg types
628         -> BoxyRhoType                          -- Result type
629         -> TcM (HsExpr TcId, arg_results)               
630
631 -- Call         (f e1 ... en) :: res_ty
632 -- Type         f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
633 --                      (where k <= n; fres has the rest)
634 -- NB:  if k < n then the function doesn't have enough args, and
635 --      presumably fres is a type variable that we are going to 
636 --      instantiate with a function type
637 --
638 -- Then         fres <= bx_(k+1) -> ... -> bx_n -> res_ty
639
640 tcIdApp fun_name n_args arg_checker res_ty
641   = do  { let orig = OccurrenceOf fun_name
642         ; (fun, fun_ty) <- lookupFun orig fun_name
643
644         -- Split up the function type
645         ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy fun_ty
646               (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
647
648               qtvs = concatMap fst tv_theta_prs         -- Quantified tyvars
649               arg_qtvs = exactTyVarsOfTypes fun_arg_tys
650               res_qtvs = exactTyVarsOfType fun_res_ty
651                 -- NB: exactTyVarsOfType.  See Note [Silly type synonyms in smart-app]
652               tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
653               k              = length fun_arg_tys       -- k <= n_args
654               n_missing_args = n_args - k               -- Always >= 0
655
656         -- Match the result type of the function with the
657         -- result type of the context, to get an inital substitution
658         ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
659         ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
660               res_ty'        = mkFunTys extra_arg_tys' res_ty
661         ; qtys' <- preSubType qtvs tau_qtvs fun_res_ty res_ty'
662         ; let arg_subst    = zipOpenTvSubst qtvs qtys'
663               fun_arg_tys' = substTys arg_subst fun_arg_tys
664
665         -- Typecheck the arguments!
666         -- Doing so will fill arg_qtvs and extra_arg_tys'
667         ; args' <- arg_checker (fun_arg_tys' ++ extra_arg_tys')
668
669         -- Strip boxes from the qtvs that have been filled in by the arg checking
670         -- AND any variables that are mentioned in neither arg nor result
671         -- the latter are mentioned only in constraints; stripBoxyType will 
672         -- fill them with a monotype
673         ; let strip qtv qty' | qtv `elemVarSet` arg_qtvs = stripBoxyType qty'
674                              | otherwise                 = return qty'
675         ; qtys'' <- zipWithM strip qtvs qtys'
676         ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
677
678         -- Result subsumption
679         ; let res_subst = zipOpenTvSubst qtvs qtys''
680               fun_res_ty'' = substTy res_subst fun_res_ty
681               res_ty'' = mkFunTys extra_arg_tys'' res_ty
682         ; co_fn <- tcFunResTy fun_name fun_res_ty'' res_ty''
683                             
684         -- And pack up the results
685         -- By applying the coercion just to the *function* we can make
686         -- tcFun work nicely for OpApp and Sections too
687         ; fun' <- instFun orig fun res_subst tv_theta_prs
688         ; co_fn' <- wrapFunResCoercion fun_arg_tys' co_fn
689         ; return (mkHsCoerce co_fn' fun', args') }
690 \end{code}
691
692 Note [Silly type synonyms in smart-app]
693 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
694 When we call sripBoxyType, all of the boxes should be filled
695 in.  But we need to be careful about type synonyms:
696         type T a = Int
697         f :: T a -> Int
698         ...(f x)...
699 In the call (f x) we'll typecheck x, expecting it to have type
700 (T box).  Usually that would fill in the box, but in this case not;
701 because 'a' is discarded by the silly type synonym T.  So we must
702 use exactTyVarsOfType to figure out which type variables are free 
703 in the argument type.
704
705 \begin{code}
706 -- tcId is a specialisation of tcIdApp when there are no arguments
707 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
708 --                ; return res }
709
710 tcId :: InstOrigin
711      -> Name                                    -- Function
712      -> BoxyRhoType                             -- Result type
713      -> TcM (HsExpr TcId)
714 tcId orig fun_name res_ty
715   = do  { traceTc (text "tcId" <+> ppr fun_name <+> ppr res_ty)
716         ; (fun, fun_ty) <- lookupFun orig fun_name
717
718         -- Split up the function type
719         ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy fun_ty
720               qtvs = concatMap fst tv_theta_prs -- Quantified tyvars
721               tau_qtvs = exactTyVarsOfType fun_tau      -- Mentioned in the tau part
722         ; qtv_tys <- preSubType qtvs tau_qtvs fun_tau res_ty
723
724         -- Do the subsumption check wrt the result type
725         ; let res_subst = zipTopTvSubst qtvs qtv_tys
726               fun_tau'  = substTy res_subst fun_tau
727
728         ; co_fn <- tcFunResTy fun_name fun_tau' res_ty
729
730         -- And pack up the results
731         ; fun' <- instFun orig fun res_subst tv_theta_prs 
732         ; return (mkHsCoerce co_fn fun') }
733
734 --      Note [Push result type in]
735 --
736 -- Unify with expected result before (was: after) type-checking the args
737 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
738 -- This is when we might detect a too-few args situation.
739 -- (One can think of cases when the opposite order would give
740 -- a better error message.)
741 -- [March 2003: I'm experimenting with putting this first.  Here's an 
742 --              example where it actually makes a real difference
743 --    class C t a b | t a -> b
744 --    instance C Char a Bool
745 --
746 --    data P t a = forall b. (C t a b) => MkP b
747 --    data Q t   = MkQ (forall a. P t a)
748
749 --    f1, f2 :: Q Char;
750 --    f1 = MkQ (MkP True)
751 --    f2 = MkQ (MkP True :: forall a. P Char a)
752 --
753 -- With the change, f1 will type-check, because the 'Char' info from
754 -- the signature is propagated into MkQ's argument. With the check
755 -- in the other order, the extra signature in f2 is reqd.]
756
757 ---------------------------
758 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
759 -- Typecheck a syntax operator, checking that it has the specified type
760 -- The operator is always a variable at this stage (i.e. renamer output)
761 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
762 tcSyntaxOp orig other      ty = pprPanic "tcSyntaxOp" (ppr other)
763
764 ---------------------------
765 instFun :: InstOrigin
766         -> HsExpr TcId
767         -> TvSubst                -- The instantiating substitution
768         -> [([TyVar], ThetaType)] -- Stuff to instantiate
769         -> TcM (HsExpr TcId)    
770
771 instFun orig fun subst []
772   = return fun          -- Common short cut
773
774 instFun orig fun subst tv_theta_prs
775   = do  { let ty_theta_prs' = map subst_pr tv_theta_prs
776
777                 -- Make two ad-hoc checks 
778         ; doStupidChecks fun ty_theta_prs'
779
780                 -- Now do normal instantiation
781         ; go True fun ty_theta_prs' }
782   where
783     subst_pr (tvs, theta) 
784         = (map (substTyVar subst) tvs, substTheta subst theta)
785
786     go _ fun [] = return fun
787
788     go True (HsVar fun_id) ((tys,theta) : prs)
789         | want_method_inst theta
790         = do { meth_id <- newMethodWithGivenTy orig fun_id tys
791              ; go False (HsVar meth_id) prs }
792                 -- Go round with 'False' to prevent further use
793                 -- of newMethod: see Note [Multiple instantiation]
794
795     go _ fun ((tys, theta) : prs)
796         = do { co_fn <- instCall orig tys theta
797              ; go False (HsCoerce co_fn fun) prs }
798
799         --      Hack Alert (want_method_inst)!
800         -- See Note [No method sharing]
801         -- If   f :: (%x :: T) => Int -> Int
802         -- Then if we have two separate calls, (f 3, f 4), we cannot
803         -- make a method constraint that then gets shared, thus:
804         --      let m = f %x in (m 3, m 4)
805         -- because that loses the linearity of the constraint.
806         -- The simplest thing to do is never to construct a method constraint
807         -- in the first place that has a linear implicit parameter in it.
808     want_method_inst theta =  not (null theta)                  -- Overloaded
809                            && not (any isLinearPred theta)      -- Not linear
810                            && not opt_NoMethodSharing
811                 -- See Note [No method sharing] below
812 \end{code}
813
814 Note [Multiple instantiation]
815 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
816 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
817 For example, consider
818         f :: forall a. Eq a => forall b. Ord b => a -> b
819 At a call to f, at say [Int, Bool], it's tempting to translate the call to 
820
821         f_m1
822   where
823         f_m1 :: forall b. Ord b => Int -> b
824         f_m1 = f Int dEqInt
825
826         f_m2 :: Int -> Bool
827         f_m2 = f_m1 Bool dOrdBool
828
829 But notice that f_m2 has f_m1 as its meth_id.  Now the danger is that if we do
830 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
831         f_m1 = f_mx
832 But it's entirely possible that f_m2 will continue to float out, because it
833 mentions no type variables.  Result, f_m1 isn't in scope.
834
835 Here's a concrete example that does this (test tc200):
836
837     class C a where
838       f :: Eq b => b -> a -> Int
839       baz :: Eq a => Int -> a -> Int
840
841     instance C Int where
842       baz = f
843
844 Current solution: only do the "method sharing" thing for the first type/dict
845 application, not for the iterated ones.  A horribly subtle point.
846
847 Note [No method sharing]
848 ~~~~~~~~~~~~~~~~~~~~~~~~
849 The -fno-method-sharing flag controls what happens so far as the LIE
850 is concerned.  The default case is that for an overloaded function we 
851 generate a "method" Id, and add the Method Inst to the LIE.  So you get
852 something like
853         f :: Num a => a -> a
854         f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
855 If you specify -fno-method-sharing, the dictionary application 
856 isn't shared, so we get
857         f :: Num a => a -> a
858         f = /\a (d:Num a) (x:a) -> (+) a d x x
859 This gets a bit less sharing, but
860         a) it's better for RULEs involving overloaded functions
861         b) perhaps fewer separated lambdas
862
863 \begin{code}
864 tcArgs :: LHsExpr Name                          -- The function (for error messages)
865        -> [LHsExpr Name] -> [TcSigmaType]       -- Actual arguments and expected arg types
866        -> TcM [LHsExpr TcId]                    -- Resulting args
867
868 tcArgs fun args expected_arg_tys
869   = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
870
871 tcArg :: LHsExpr Name                           -- The function (for error messages)
872        -> (LHsExpr Name, BoxySigmaType, Int)    -- Actual argument and expected arg type
873        -> TcM (LHsExpr TcId)                    -- Resulting argument
874 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no) $
875                               tcPolyExprNC arg 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@ typchecks 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 (mkHsCoerce 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 rbinds
1060   = do  { mb_binds <- mappM do_bind rbinds
1061         ; return (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") <+> quotes (ppr tycon)
1142                 <+> ptext SLIT("is not (yet) supported"),
1143           ptext SLIT("Use pattern-matching instead")]
1144 badFieldsUpd rbinds
1145   = hang (ptext SLIT("No constructor has all these fields:"))
1146          4 (pprQuotedList (recBindFields rbinds))
1147
1148 naughtyRecordSel sel_id
1149   = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+> 
1150     ptext SLIT("as a function due to escaped type variables") $$ 
1151     ptext SLIT("Probably fix: use pattern-matching syntax instead")
1152
1153 notSelector field
1154   = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1155
1156 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1157 missingStrictFields con fields
1158   = header <> rest
1159   where
1160     rest | null fields = empty  -- Happens for non-record constructors 
1161                                 -- with strict fields
1162          | otherwise   = colon <+> pprWithCommas ppr fields
1163
1164     header = ptext SLIT("Constructor") <+> quotes (ppr con) <+> 
1165              ptext SLIT("does not have the required strict field(s)") 
1166           
1167 missingFields :: DataCon -> [FieldLabel] -> SDoc
1168 missingFields con fields
1169   = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:") 
1170         <+> pprWithCommas ppr fields
1171
1172 callCtxt fun args
1173   = 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}