[project @ 2005-10-14 11:22:41 by simonpj]
[ghc-hetmet.git] / ghc / 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 ( tcCheckSigma, tcCheckRho, tcInferRho, 
8                 tcMonoExpr, tcExpr, tcSyntaxOp
9    ) where
10
11 #include "HsVersions.h"
12
13 #ifdef GHCI     /* Only if bootstrapped */
14 import {-# SOURCE #-}   TcSplice( tcSpliceExpr, tcBracket )
15 import HsSyn            ( nlHsVar )
16 import Id               ( Id )
17 import Name             ( isExternalName )
18 import TcType           ( isTauTy )
19 import TcEnv            ( checkWellStaged )
20 import HsSyn            ( nlHsApp )
21 import qualified DsMeta
22 #endif
23
24 import HsSyn            ( HsExpr(..), LHsExpr, HsLit(..), ArithSeqInfo(..), recBindFields,
25                           HsMatchContext(..), HsRecordBinds, mkHsApp )
26 import TcHsSyn          ( hsLitType, (<$>) )
27 import TcRnMonad
28 import TcUnify          ( Expected(..), tcInfer, zapExpectedType, zapExpectedTo, 
29                           tcSubExp, tcGen, tcSub,
30                           unifyFunTys, zapToListTy, zapToTyConApp )
31 import BasicTypes       ( isMarkedStrict )
32 import Inst             ( tcOverloadedLit, newMethodFromName, newIPDict,
33                           newDicts, newMethodWithGivenTy, tcInstStupidTheta, tcInstCall )
34 import TcBinds          ( tcLocalBinds )
35 import TcEnv            ( tcLookup, tcLookupId,
36                           tcLookupDataCon, tcLookupGlobalId
37                         )
38 import TcArrows         ( tcProc )
39 import TcMatches        ( tcMatchesCase, tcMatchLambda, tcDoStmts, tcThingWithSig, TcMatchCtxt(..) )
40 import TcHsType         ( tcHsSigType, UserTypeCtxt(..) )
41 import TcPat            ( badFieldCon, refineTyVars )
42 import TcMType          ( tcInstTyVars, tcInstType, newTyFlexiVarTy, zonkTcType )
43 import TcType           ( TcTyVar, TcType, TcSigmaType, TcRhoType, 
44                           tcSplitFunTys, mkTyVarTys,
45                           isSigmaTy, mkFunTy, mkTyConApp, tyVarsOfTypes, isLinearPred,
46                           tcSplitSigmaTy, tidyOpenType
47                         )
48 import Kind             ( openTypeKind, liftedTypeKind, argTypeKind )
49
50 import Id               ( idType, recordSelectorFieldLabel, isRecordSelector, isNaughtyRecordSelector )
51 import DataCon          ( DataCon, dataConFieldLabels, dataConStrictMarks, 
52                           dataConWrapId, isVanillaDataCon, dataConTyVars, dataConOrigArgTys )
53 import Name             ( Name )
54 import TyCon            ( TyCon, FieldLabel, tyConStupidTheta, tyConArity, tyConDataCons )
55 import Type             ( substTheta, substTy )
56 import Var              ( tyVarKind )
57 import VarSet           ( emptyVarSet, elemVarSet )
58 import TysWiredIn       ( boolTy, parrTyCon, tupleTyCon )
59 import PrelNames        ( enumFromName, enumFromThenName, 
60                           enumFromToName, enumFromThenToName,
61                           enumFromToPName, enumFromThenToPName, negateName
62                         )
63 import DynFlags
64 import StaticFlags      ( opt_NoMethodSharing )
65 import HscTypes         ( TyThing(..) )
66 import SrcLoc           ( Located(..), unLoc, getLoc )
67 import Util
68 import ListSetOps       ( assocMaybe )
69 import Maybes           ( catMaybes )
70 import Outputable
71 import FastString
72 \end{code}
73
74 %************************************************************************
75 %*                                                                      *
76 \subsection{Main wrappers}
77 %*                                                                      *
78 %************************************************************************
79
80 \begin{code}
81 -- tcCheckSigma does type *checking*; it's passed the expected type of the result
82 tcCheckSigma :: LHsExpr Name            -- Expession to type check
83              -> TcSigmaType             -- Expected type (could be a polytpye)
84              -> TcM (LHsExpr TcId)      -- Generalised expr with expected type
85
86 tcCheckSigma expr expected_ty 
87   = -- traceTc (text "tcExpr" <+> (ppr expected_ty $$ ppr expr)) `thenM_`
88     tc_expr' expr expected_ty
89
90 tc_expr' expr sigma_ty
91   | isSigmaTy sigma_ty
92   = tcGen sigma_ty emptyVarSet (
93         \ rho_ty -> tcCheckRho expr rho_ty
94     )                           `thenM` \ (gen_fn, expr') ->
95     returnM (L (getLoc expr') (gen_fn <$> unLoc expr'))
96
97 tc_expr' expr rho_ty    -- Monomorphic case
98   = tcCheckRho expr rho_ty
99 \end{code}
100
101 Typecheck expression which in most cases will be an Id.
102 The expression can return a higher-ranked type, such as
103         (forall a. a->a) -> Int
104 so we must create a hole to pass in as the expected tyvar.
105
106 \begin{code}
107 tcCheckRho :: LHsExpr Name -> TcRhoType -> TcM (LHsExpr TcId)
108 tcCheckRho expr rho_ty = tcMonoExpr expr (Check rho_ty)
109
110 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
111 tcInferRho (L loc (HsVar name)) = setSrcSpan loc $ do 
112                                   { (e,_,ty) <- tcId (OccurrenceOf name) name
113                                   ; return (L loc e, ty) }
114 tcInferRho expr                 = tcInfer (tcMonoExpr expr)
115
116 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
117 -- Typecheck a syntax operator, checking that it has the specified type
118 -- The operator is always a variable at this stage (i.e. renamer output)
119 tcSyntaxOp orig (HsVar op) ty = do { (expr', _, id_ty) <- tcId orig op
120                                    ; co_fn <- tcSub ty id_ty
121                                    ; returnM (co_fn <$> expr') }
122 tcSyntaxOp orig other      ty = pprPanic "tcSyntaxOp" (ppr other)
123 \end{code}
124
125
126
127 %************************************************************************
128 %*                                                                      *
129 \subsection{The TAUT rules for variables}TcExpr
130 %*                                                                      *
131 %************************************************************************
132
133 \begin{code}
134 tcMonoExpr :: LHsExpr Name              -- Expession to type check
135            -> Expected TcRhoType        -- Expected type (could be a type variable)
136                                         -- Definitely no foralls at the top
137                                         -- Can be a 'hole'.
138            -> TcM (LHsExpr TcId)
139
140 tcMonoExpr (L loc expr) res_ty
141   = setSrcSpan loc (do { expr' <- tcExpr expr res_ty
142                        ; return (L loc expr') })
143
144 tcExpr :: HsExpr Name -> Expected TcRhoType -> TcM (HsExpr TcId)
145 tcExpr (HsVar name) res_ty
146   = do  { (expr', _, id_ty) <- tcId (OccurrenceOf name) name
147         ; co_fn <- tcSubExp res_ty id_ty
148         ; returnM (co_fn <$> expr') }
149
150 tcExpr (HsIPVar ip) res_ty
151   =     -- Implicit parameters must have a *tau-type* not a 
152         -- type scheme.  We enforce this by creating a fresh
153         -- type variable as its type.  (Because res_ty may not
154         -- be a tau-type.)
155     newTyFlexiVarTy argTypeKind         `thenM` \ ip_ty ->
156         -- argTypeKind: it can't be an unboxed tuple
157     newIPDict (IPOccOrigin ip) ip ip_ty `thenM` \ (ip', inst) ->
158     extendLIE inst                      `thenM_`
159     tcSubExp res_ty ip_ty               `thenM` \ co_fn ->
160     returnM (co_fn <$> HsIPVar ip')
161 \end{code}
162
163
164 %************************************************************************
165 %*                                                                      *
166 \subsection{Expressions type signatures}
167 %*                                                                      *
168 %************************************************************************
169
170 \begin{code}
171 tcExpr in_expr@(ExprWithTySig expr poly_ty) res_ty
172  = addErrCtxt (exprCtxt in_expr)                        $
173    tcHsSigType ExprSigCtxt poly_ty                      `thenM` \ sig_tc_ty ->
174    tcThingWithSig sig_tc_ty (tcCheckRho expr) res_ty    `thenM` \ (co_fn, expr') ->
175    returnM (co_fn <$> ExprWithTySigOut expr' poly_ty)
176
177 tcExpr (HsType ty) res_ty
178   = failWithTc (text "Can't handle type argument:" <+> ppr ty)
179         -- This is the syntax for type applications that I was planning
180         -- but there are difficulties (e.g. what order for type args)
181         -- so it's not enabled yet.
182         -- Can't eliminate it altogether from the parser, because the
183         -- same parser parses *patterns*.
184 \end{code}
185
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection{Other expression forms}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 tcExpr (HsPar expr)    res_ty  = tcMonoExpr expr res_ty `thenM` \ expr' -> 
195                                   returnM (HsPar expr')
196 tcExpr (HsSCC lbl expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' ->
197                                   returnM (HsSCC lbl expr')
198 tcExpr (HsCoreAnn lbl expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' ->  -- hdaume: core annotation
199                                          returnM (HsCoreAnn lbl expr')
200
201 tcExpr (HsLit lit) res_ty  = tcLit lit res_ty
202
203 tcExpr (HsOverLit lit) res_ty  
204   = zapExpectedType res_ty liftedTypeKind               `thenM` \ res_ty' ->
205         -- Overloaded literals must have liftedTypeKind, because
206         -- we're instantiating an overloaded function here,
207         -- whereas res_ty might be openTypeKind. This was a bug in 6.2.2
208     tcOverloadedLit (LiteralOrigin lit) lit res_ty'     `thenM` \ lit' ->
209     returnM (HsOverLit lit')
210
211 tcExpr (NegApp expr neg_expr) res_ty
212   = do  { res_ty' <- zapExpectedType res_ty liftedTypeKind
213         ; neg_expr' <- tcSyntaxOp (OccurrenceOf negateName) neg_expr
214                                   (mkFunTy res_ty' res_ty')
215         ; expr' <- tcCheckRho expr res_ty'
216         ; return (NegApp expr' neg_expr') }
217
218 tcExpr (HsLam match) res_ty
219   = tcMatchLambda match res_ty          `thenM` \ match' ->
220     returnM (HsLam match')
221
222 tcExpr (HsApp e1 e2) res_ty 
223   = tcApp e1 [e2] res_ty
224 \end{code}
225
226 Note that the operators in sections are expected to be binary, and
227 a type error will occur if they aren't.
228
229 \begin{code}
230 -- Left sections, equivalent to
231 --      \ x -> e op x,
232 -- or
233 --      \ x -> op e x,
234 -- or just
235 --      op e
236
237 tcExpr in_expr@(SectionL arg1 op) res_ty
238   = tcInferRho op                               `thenM` \ (op', op_ty) ->
239     unifyInfixTy op in_expr op_ty               `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
240     tcArg op (arg1, arg1_ty, 1)                 `thenM` \ arg1' ->
241     addErrCtxt (exprCtxt in_expr)               $
242     tcSubExp res_ty (mkFunTy arg2_ty op_res_ty) `thenM` \ co_fn ->
243     returnM (co_fn <$> SectionL arg1' op')
244
245 -- Right sections, equivalent to \ x -> x op expr, or
246 --      \ x -> op x expr
247
248 tcExpr in_expr@(SectionR op arg2) res_ty
249   = tcInferRho op                               `thenM` \ (op', op_ty) ->
250     unifyInfixTy op in_expr op_ty               `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
251     tcArg op (arg2, arg2_ty, 2)                 `thenM` \ arg2' ->
252     addErrCtxt (exprCtxt in_expr)               $
253     tcSubExp res_ty (mkFunTy arg1_ty op_res_ty) `thenM` \ co_fn ->
254     returnM (co_fn <$> SectionR op' arg2')
255
256 -- equivalent to (op e1) e2:
257
258 tcExpr in_expr@(OpApp arg1 op fix arg2) res_ty
259   = tcInferRho op                               `thenM` \ (op', op_ty) ->
260     unifyInfixTy op in_expr op_ty               `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
261     tcArg op (arg1, arg1_ty, 1)                 `thenM` \ arg1' ->
262     tcArg op (arg2, arg2_ty, 2)                 `thenM` \ arg2' ->
263     addErrCtxt (exprCtxt in_expr)               $
264     tcSubExp res_ty op_res_ty                   `thenM` \ co_fn ->
265     returnM (co_fn <$> OpApp arg1' op' fix arg2')
266 \end{code}
267
268 \begin{code}
269 tcExpr (HsLet binds expr) res_ty
270   = do  { (binds', expr') <- tcLocalBinds binds $
271                              tcMonoExpr expr res_ty   
272         ; return (HsLet binds' expr') }
273
274 tcExpr in_expr@(HsCase scrut matches) exp_ty
275   =     -- We used to typecheck the case alternatives first.
276         -- The case patterns tend to give good type info to use
277         -- when typechecking the scrutinee.  For example
278         --      case (map f) of
279         --        (x:xs) -> ...
280         -- will report that map is applied to too few arguments
281         --
282         -- But now, in the GADT world, we need to typecheck the scrutinee
283         -- first, to get type info that may be refined in the case alternatives
284     addErrCtxt (caseScrutCtxt scrut)
285                (tcInferRho scrut)       `thenM`    \ (scrut', scrut_ty) ->
286
287     addErrCtxt (caseCtxt in_expr)                       $
288     tcMatchesCase match_ctxt scrut_ty matches exp_ty    `thenM` \ matches' ->
289     returnM (HsCase scrut' matches') 
290  where
291     match_ctxt = MC { mc_what = CaseAlt,
292                       mc_body = tcMonoExpr }
293
294 tcExpr (HsIf pred b1 b2) res_ty
295   = addErrCtxt (predCtxt pred)
296         (tcCheckRho pred boolTy)        `thenM`    \ pred' ->
297
298     zapExpectedType res_ty openTypeKind `thenM`    \ res_ty' ->
299         -- C.f. the call to zapToType in TcMatches.tcMatches
300
301     tcCheckRho b1 res_ty'               `thenM`    \ b1' ->
302     tcCheckRho b2 res_ty'               `thenM`    \ b2' ->
303     returnM (HsIf pred' b1' b2')
304
305 tcExpr (HsDo do_or_lc stmts body _) res_ty
306   = tcDoStmts do_or_lc stmts body res_ty
307
308 tcExpr in_expr@(ExplicitList _ exprs) res_ty    -- Non-empty list
309   = zapToListTy res_ty                `thenM` \ elt_ty ->  
310     mappM (tc_elt elt_ty) exprs       `thenM` \ exprs' ->
311     returnM (ExplicitList elt_ty exprs')
312   where
313     tc_elt elt_ty expr
314       = addErrCtxt (listCtxt expr) $
315         tcCheckRho expr elt_ty
316
317 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty    -- maybe empty
318   = do  { [elt_ty] <- zapToTyConApp parrTyCon res_ty
319         ; exprs' <- mappM (tc_elt elt_ty) exprs 
320         ; return (ExplicitPArr elt_ty exprs') }
321   where
322     tc_elt elt_ty expr
323       = addErrCtxt (parrCtxt expr) (tcCheckRho expr elt_ty)
324
325 tcExpr (ExplicitTuple exprs boxity) res_ty
326   = do  { arg_tys <- zapToTyConApp (tupleTyCon boxity (length exprs)) res_ty
327         ; exprs' <-  tcCheckRhos exprs arg_tys
328         ; return (ExplicitTuple exprs' boxity) }
329
330 tcExpr (HsProc pat cmd) res_ty
331   = tcProc pat cmd res_ty                       `thenM` \ (pat', cmd') ->
332     returnM (HsProc pat' cmd')
333
334 tcExpr e@(HsArrApp _ _ _ _ _) _
335   = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e), 
336                       ptext SLIT("was found where an expression was expected")])
337
338 tcExpr e@(HsArrForm _ _ _) _
339   = failWithTc (vcat [ptext SLIT("The arrow command"), nest 2 (ppr e), 
340                       ptext SLIT("was found where an expression was expected")])
341 \end{code}
342
343 %************************************************************************
344 %*                                                                      *
345                 Record construction and update
346 %*                                                                      *
347 %************************************************************************
348
349 \begin{code}
350 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
351   = addErrCtxt (recordConCtxt expr) $
352     do  { (con_expr, _, con_tau) <- setSrcSpan loc $ 
353                                     tcId (OccurrenceOf con_name) con_name
354         ; data_con <- tcLookupDataCon con_name
355
356         ; let (arg_tys, record_ty) = tcSplitFunTys con_tau
357               flds_w_tys = zipEqual "tcExpr RecordCon" (dataConFieldLabels data_con) arg_tys
358
359         -- Make the result type line up
360         ; zapExpectedTo res_ty record_ty
361
362         -- Typecheck the record bindings
363         ; rbinds' <- tcRecordBinds data_con flds_w_tys rbinds
364     
365         -- Check for missing fields
366         ; checkMissingFields data_con rbinds
367
368         ; returnM (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
369
370 -- The main complication with RecordUpd is that we need to explicitly
371 -- handle the *non-updated* fields.  Consider:
372 --
373 --      data T a b = MkT1 { fa :: a, fb :: b }
374 --                 | MkT2 { fa :: a, fc :: Int -> Int }
375 --                 | MkT3 { fd :: a }
376 --      
377 --      upd :: T a b -> c -> T a c
378 --      upd t x = t { fb = x}
379 --
380 -- The type signature on upd is correct (i.e. the result should not be (T a b))
381 -- because upd should be equivalent to:
382 --
383 --      upd t x = case t of 
384 --                      MkT1 p q -> MkT1 p x
385 --                      MkT2 a b -> MkT2 p b
386 --                      MkT3 d   -> error ...
387 --
388 -- So we need to give a completely fresh type to the result record,
389 -- and then constrain it by the fields that are *not* updated ("p" above).
390 --
391 -- Note that because MkT3 doesn't contain all the fields being updated,
392 -- its RHS is simply an error, so it doesn't impose any type constraints
393 --
394 -- All this is done in STEP 4 below.
395
396 tcExpr expr@(RecordUpd record_expr rbinds _ _) res_ty
397   = addErrCtxt (recordUpdCtxt   expr)           $
398
399         -- STEP 0
400         -- Check that the field names are really field names
401     ASSERT( notNull rbinds )
402     let 
403         field_names = map fst rbinds
404     in
405     mappM (tcLookupGlobalId.unLoc) field_names  `thenM` \ sel_ids ->
406         -- The renamer has already checked that they
407         -- are all in scope
408     let
409         bad_guys = [ setSrcSpan loc $ addErrTc (notSelector field_name) 
410                    | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
411                      not (isRecordSelector sel_id)      -- Excludes class ops
412                    ]
413     in
414     checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM)  `thenM_`
415     
416         -- STEP 1
417         -- Figure out the tycon and data cons from the first field name
418     let
419                 -- It's OK to use the non-tc splitters here (for a selector)
420         sel_id : _   = sel_ids
421         (tycon, _)   = recordSelectorFieldLabel sel_id  -- We've failed already if
422         data_cons    = tyConDataCons tycon              -- it's not a field label
423     in
424
425         -- Check that all data cons are vanilla.  Doing record updates on GADTs
426         -- and/or existentials is more than my tiny brain can cope with today
427         -- [I think we might be able to manage if none of the selectors is naughty,
428         --  but that's for another day.]
429     checkTc (all isVanillaDataCon data_cons)
430             (nonVanillaUpd tycon)       `thenM_`
431
432         -- STEP 2
433         -- Check that at least one constructor has all the named fields
434         -- i.e. has an empty set of bad fields returned by badFields
435     checkTc (any (null . badFields rbinds) data_cons)
436             (badFieldsUpd rbinds)       `thenM_`
437
438         -- STEP 4
439         -- Use the un-updated fields to find a vector of booleans saying
440         -- which type arguments must be the same in updatee and result.
441         --
442         -- WARNING: this code assumes that all data_cons in a common tycon
443         -- have FieldLabels abstracted over the same tyvars.
444     let
445         upd_field_lbls      = recBindFields rbinds
446
447                 -- A constructor is only relevant to this process if
448                 -- it contains *all* the fields that are being updated
449         relevant_cons   = filter is_relevant data_cons
450         is_relevant con = all (`elem` dataConFieldLabels con) upd_field_lbls
451         con1            = head relevant_cons    -- A representative constructor
452         con1_tyvars     = dataConTyVars con1
453         con1_fld_tys    = dataConFieldLabels con1 `zip` dataConOrigArgTys con1
454         common_tyvars   = tyVarsOfTypes [ty | (fld,ty) <- con1_fld_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       = newTyFlexiVarTy (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         inst_fld_tys     = [(fld, substTy inst_env ty) | (fld, ty) <- con1_fld_tys]
473     in
474     zapExpectedTo res_ty result_record_ty       `thenM_`
475     tcRecordBinds con1 inst_fld_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     tcCheckRho 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 (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   = zapToListTy res_ty                          `thenM` \ elt_ty ->  
517     tcCheckRho expr elt_ty                      `thenM` \ expr' ->
518
519     newMethodFromName (ArithSeqOrigin seq) 
520                       elt_ty enumFromName       `thenM` \ enum_from ->
521
522     returnM (ArithSeq (HsVar enum_from) (From expr'))
523
524 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
525   = addErrCtxt (arithSeqCtxt in_expr) $ 
526     zapToListTy  res_ty                                 `thenM`    \ elt_ty ->  
527     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
528     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
529     newMethodFromName (ArithSeqOrigin seq) 
530                       elt_ty enumFromThenName           `thenM` \ enum_from_then ->
531
532     returnM (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2'))
533
534
535 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
536   = addErrCtxt (arithSeqCtxt in_expr) $
537     zapToListTy  res_ty                                 `thenM`    \ elt_ty ->  
538     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
539     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
540     newMethodFromName (ArithSeqOrigin seq) 
541                       elt_ty enumFromToName             `thenM` \ enum_from_to ->
542
543     returnM (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2'))
544
545 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
546   = addErrCtxt  (arithSeqCtxt in_expr) $
547     zapToListTy  res_ty                                 `thenM`    \ elt_ty ->  
548     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
549     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
550     tcCheckRho expr3 elt_ty                             `thenM`    \ expr3' ->
551     newMethodFromName (ArithSeqOrigin seq) 
552                       elt_ty enumFromThenToName         `thenM` \ eft ->
553
554     returnM (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3'))
555
556 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
557   = addErrCtxt (parrSeqCtxt in_expr) $
558     zapToTyConApp parrTyCon res_ty                      `thenM`    \ [elt_ty] ->  
559     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
560     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
561     newMethodFromName (PArrSeqOrigin seq) 
562                       elt_ty enumFromToPName            `thenM` \ enum_from_to ->
563
564     returnM (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2'))
565
566 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
567   = addErrCtxt  (parrSeqCtxt in_expr) $
568     zapToTyConApp parrTyCon res_ty                      `thenM`    \ [elt_ty] ->  
569     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
570     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
571     tcCheckRho expr3 elt_ty                             `thenM`    \ expr3' ->
572     newMethodFromName (PArrSeqOrigin seq)
573                       elt_ty enumFromThenToPName        `thenM` \ eft ->
574
575     returnM (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3'))
576
577 tcExpr (PArrSeq _ _) _ 
578   = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
579     -- the parser shouldn't have generated it and the renamer shouldn't have
580     -- let it through
581 \end{code}
582
583
584 %************************************************************************
585 %*                                                                      *
586                 Template Haskell
587 %*                                                                      *
588 %************************************************************************
589
590 \begin{code}
591 #ifdef GHCI     /* Only if bootstrapped */
592         -- Rename excludes these cases otherwise
593 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
594 tcExpr (HsBracket brack)  res_ty = do   { e <- tcBracket brack res_ty
595                                         ; return (unLoc e) }
596 #endif /* GHCI */
597 \end{code}
598
599
600 %************************************************************************
601 %*                                                                      *
602                 Catch-all
603 %*                                                                      *
604 %************************************************************************
605
606 \begin{code}
607 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
608 \end{code}
609
610
611 %************************************************************************
612 %*                                                                      *
613 \subsection{@tcApp@ typchecks an application}
614 %*                                                                      *
615 %************************************************************************
616
617 \begin{code}
618
619 tcApp :: LHsExpr Name -> [LHsExpr Name]         -- Function and args
620       -> Expected TcRhoType                     -- Expected result type of application
621       -> TcM (HsExpr TcId)                      -- Translated fun and args
622
623 tcApp (L _ (HsApp e1 e2)) args res_ty 
624   = tcApp e1 (e2:args) res_ty           -- Accumulate the arguments
625
626 tcApp fun args res_ty
627   = do  { let n_args = length args
628         ; (fun', fun_tvs, fun_tau) <- tcFun fun         -- Type-check the function
629
630         -- Extract its argument types
631         ; (expected_arg_tys, actual_res_ty)
632               <- do { traceTc (text "tcApp" <+> (ppr fun $$ ppr fun_tau))
633                     ; let msg = sep [ptext SLIT("The function") <+> quotes (ppr fun),
634                                      ptext SLIT("is applied to") 
635                                      <+> speakN n_args <+> ptext SLIT("arguments")]
636                     ; unifyFunTys msg n_args fun_tau }
637
638         ; case res_ty of
639             Check _ -> do       -- Connect to result type first
640                                 -- See Note [Push result type in]
641                 { co_fn    <- tcResult fun args res_ty actual_res_ty
642                 ; the_app' <- tcArgs fun fun' args expected_arg_tys
643                 ; traceTc (text "tcApp: check" <+> vcat [ppr fun <+> ppr args,
644                                                          ppr the_app', ppr actual_res_ty])
645                 ; returnM (co_fn <$> the_app') }
646
647             Infer _ -> do       -- Type check args first, then
648                                 -- refine result type, then do tcResult
649                 { the_app'       <- tcArgs fun fun' args expected_arg_tys
650                 ; subst          <- refineTyVars fun_tvs
651                 ; let actual_res_ty' = substTy subst actual_res_ty
652                 ; co_fn          <- tcResult fun args res_ty actual_res_ty'
653                 ; traceTc (text "tcApp: infer" <+> vcat [ppr fun <+> ppr args, ppr the_app',
654                                                          ppr actual_res_ty, ppr actual_res_ty'])
655                 ; returnM (co_fn <$> the_app') }
656         }
657
658 --      Note [Push result type in]
659 --
660 -- Unify with expected result before (was: after) type-checking the args
661 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
662 -- This is when we might detect a too-few args situation.
663 -- (One can think of cases when the opposite order would give
664 -- a better error message.)
665 -- [March 2003: I'm experimenting with putting this first.  Here's an 
666 --              example where it actually makes a real difference
667 --    class C t a b | t a -> b
668 --    instance C Char a Bool
669 --
670 --    data P t a = forall b. (C t a b) => MkP b
671 --    data Q t   = MkQ (forall a. P t a)
672
673 --    f1, f2 :: Q Char;
674 --    f1 = MkQ (MkP True)
675 --    f2 = MkQ (MkP True :: forall a. P Char a)
676 --
677 -- With the change, f1 will type-check, because the 'Char' info from
678 -- the signature is propagated into MkQ's argument. With the check
679 -- in the other order, the extra signature in f2 is reqd.]
680
681 ----------------
682 tcFun :: LHsExpr Name -> TcM (LHsExpr TcId, [TcTyVar], TcRhoType)
683 -- Instantiate the function, returning the type variables used
684 -- If the function isn't simple, infer its type, and return no 
685 -- type variables
686 tcFun (L loc (HsVar f)) = setSrcSpan loc $ do
687                           { (fun', tvs, fun_tau) <- tcId (OccurrenceOf f) f
688                           ; return (L loc fun', tvs, fun_tau) }
689 tcFun fun = do { (fun', fun_tau) <- tcInfer (tcMonoExpr fun)
690                ; return (fun', [], fun_tau) }
691
692 ----------------
693 tcArgs :: LHsExpr Name                          -- The function (for error messages)
694        -> LHsExpr TcId                          -- The function (to build into result)
695        -> [LHsExpr Name] -> [TcSigmaType]       -- Actual arguments and expected arg types
696        -> TcM (HsExpr TcId)                     -- Resulting application
697
698 tcArgs fun fun' args expected_arg_tys
699   = do  { args' <- mappM (tcArg fun) (zip3 args expected_arg_tys [1..])
700         ; return (unLoc (foldl mkHsApp fun' args')) }
701
702 tcArg :: LHsExpr Name                           -- The function (for error messages)
703        -> (LHsExpr Name, TcSigmaType, Int)      -- Actual argument and expected arg type
704        -> TcM (LHsExpr TcId)                    -- Resulting argument
705 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no)
706                                          (tcCheckSigma arg ty)
707
708 ----------------
709 tcResult fun args res_ty actual_res_ty
710   = addErrCtxtM (checkArgsCtxt fun args res_ty actual_res_ty)
711                 (tcSubExp res_ty actual_res_ty)
712
713 ----------------
714 -- If an error happens we try to figure out whether the
715 -- function has been given too many or too few arguments,
716 -- and say so.
717 -- The ~(Check...) is because in the Infer case the tcSubExp 
718 -- definitely won't fail, so we can be certain we're in the Check branch
719 checkArgsCtxt fun args (Infer _) actual_res_ty tidy_env
720   = return (tidy_env, ptext SLIT("Urk infer"))
721
722 checkArgsCtxt fun args (Check expected_res_ty) actual_res_ty tidy_env
723   = zonkTcType expected_res_ty    `thenM` \ exp_ty' ->
724     zonkTcType actual_res_ty      `thenM` \ act_ty' ->
725     let
726       (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
727       (env2, act_ty'') = tidyOpenType env1     act_ty'
728       (exp_args, _)    = tcSplitFunTys exp_ty''
729       (act_args, _)    = tcSplitFunTys act_ty''
730
731       len_act_args     = length act_args
732       len_exp_args     = length exp_args
733
734       message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun args
735               | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun args
736               | otherwise                   = appCtxt fun args
737     in
738     returnM (env2, message)
739
740 ----------------
741 unifyInfixTy :: LHsExpr Name -> HsExpr Name -> TcType
742              -> TcM ([TcType], TcType)
743 -- This wrapper just prepares the error message for unifyFunTys
744 unifyInfixTy op expr op_ty
745   = unifyFunTys msg 2 op_ty
746   where
747     msg = sep [herald <+> quotes (ppr expr),
748                ptext SLIT("requires") <+> quotes (ppr op)
749                  <+> ptext SLIT("to take two arguments")]
750     herald = case expr of
751                 OpApp _ _ _ _ -> ptext SLIT("The infix expression")
752                 other         -> ptext SLIT("The operator section")
753 \end{code}
754
755
756 %************************************************************************
757 %*                                                                      *
758 \subsection{@tcId@ typchecks an identifier occurrence}
759 %*                                                                      *
760 %************************************************************************
761
762 tcId instantiates an occurrence of an Id.
763 The instantiate_it loop runs round instantiating the Id.
764 It has to be a loop because we are now prepared to entertain
765 types like
766         f:: forall a. Eq a => forall b. Baz b => tau
767 We want to instantiate this to
768         f2::tau         {f2 = f1 b (Baz b), f1 = f a (Eq a)}
769
770 The -fno-method-sharing flag controls what happens so far as the LIE
771 is concerned.  The default case is that for an overloaded function we 
772 generate a "method" Id, and add the Method Inst to the LIE.  So you get
773 something like
774         f :: Num a => a -> a
775         f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
776 If you specify -fno-method-sharing, the dictionary application 
777 isn't shared, so we get
778         f :: Num a => a -> a
779         f = /\a (d:Num a) (x:a) -> (+) a d x x
780 This gets a bit less sharing, but
781         a) it's better for RULEs involving overloaded functions
782         b) perhaps fewer separated lambdas
783
784 \begin{code}
785 tcId :: InstOrigin -> Name -> TcM (HsExpr TcId, [TcTyVar], TcRhoType)
786         -- Return the type variables at which the function
787         -- is instantiated, as well as the translated variable and its type
788
789 tcId orig id_name       -- Look up the Id and instantiate its type
790   = tcLookup id_name    `thenM` \ thing ->
791     case thing of {
792         AGlobal (ADataCon con)  -- Similar, but instantiate the stupid theta too
793           -> do { (expr, tvs, tau) <- instantiate (dataConWrapId con)
794                 ; tcInstStupidTheta con (mkTyVarTys tvs)
795                 -- Remember to chuck in the constraints from the "silly context"
796                 ; return (expr, tvs, tau) }
797
798     ;   AGlobal (AnId id) | isNaughtyRecordSelector id 
799                           -> failWithTc (naughtyRecordSel id)
800     ;   AGlobal (AnId id) -> instantiate id
801                 -- A global cannot possibly be ill-staged
802                 -- nor does it need the 'lifting' treatment
803
804     ;   ATcId id th_level -> tc_local_id id th_level
805
806     ;   other -> failWithTc (ppr other <+> ptext SLIT("used where a value identifer was expected"))
807     }
808   where
809
810 #ifndef GHCI
811     tc_local_id id th_bind_lvl                  -- Non-TH case
812         = instantiate id
813
814 #else /* GHCI and TH is on */
815     tc_local_id id th_bind_lvl                  -- TH case
816         =       -- Check for cross-stage lifting
817           getStage                              `thenM` \ use_stage -> 
818           case use_stage of
819               Brack use_lvl ps_var lie_var
820                 | use_lvl > th_bind_lvl 
821                 -> if isExternalName id_name then       
822                         -- Top-level identifiers in this module,
823                         -- (which have External Names)
824                         -- are just like the imported case:
825                         -- no need for the 'lifting' treatment
826                         -- E.g.  this is fine:
827                         --   f x = x
828                         --   g y = [| f 3 |]
829                         -- But we do need to put f into the keep-alive
830                         -- set, because after desugaring the code will
831                         -- only mention f's *name*, not f itself.
832                         keepAliveTc id_name     `thenM_` 
833                         instantiate id
834
835                    else -- Nested identifiers, such as 'x' in
836                         -- E.g. \x -> [| h x |]
837                         -- We must behave as if the reference to x was
838                         --      h $(lift x)     
839                         -- We use 'x' itself as the splice proxy, used by 
840                         -- the desugarer to stitch it all back together.
841                         -- If 'x' occurs many times we may get many identical
842                         -- bindings of the same splice proxy, but that doesn't
843                         -- matter, although it's a mite untidy.
844                    let
845                        id_ty = idType id
846                    in
847                    checkTc (isTauTy id_ty)      (polySpliceErr id)      `thenM_` 
848                        -- If x is polymorphic, its occurrence sites might
849                        -- have different instantiations, so we can't use plain
850                        -- 'x' as the splice proxy name.  I don't know how to 
851                        -- solve this, and it's probably unimportant, so I'm
852                        -- just going to flag an error for now
853    
854                    setLIEVar lie_var    (
855                    newMethodFromName orig id_ty DsMeta.liftName `thenM` \ lift ->
856                            -- Put the 'lift' constraint into the right LIE
857            
858                    -- Update the pending splices
859                    readMutVar ps_var                    `thenM` \ ps ->
860                    writeMutVar ps_var ((id_name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)     `thenM_`
861            
862                    returnM (HsVar id, [], id_ty))
863
864               other -> 
865                 checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage `thenM_`
866                 instantiate id
867 #endif /* GHCI */
868
869     instantiate :: TcId -> TcM (HsExpr TcId, [TcTyVar], TcRhoType)
870     instantiate fun_id = loop (HsVar fun_id) [] (idType fun_id)
871
872     loop (HsVar fun_id) tvs fun_ty
873         | want_method_inst fun_ty
874         = tcInstType fun_ty             `thenM` \ (tyvars, theta, tau) ->
875           newMethodWithGivenTy orig fun_id 
876                 (mkTyVarTys tyvars) theta tau   `thenM` \ meth_id ->
877           loop (HsVar meth_id) (tvs ++ tyvars) tau
878
879     loop fun tvs fun_ty 
880         | isSigmaTy fun_ty
881         = tcInstCall orig fun_ty        `thenM` \ (inst_fn, new_tvs, tau) ->
882           loop (inst_fn <$> fun) (tvs ++ new_tvs) tau
883
884         | otherwise
885         = returnM (fun, tvs, fun_ty)
886
887         --      Hack Alert (want_method_inst)!
888         -- If   f :: (%x :: T) => Int -> Int
889         -- Then if we have two separate calls, (f 3, f 4), we cannot
890         -- make a method constraint that then gets shared, thus:
891         --      let m = f %x in (m 3, m 4)
892         -- because that loses the linearity of the constraint.
893         -- The simplest thing to do is never to construct a method constraint
894         -- in the first place that has a linear implicit parameter in it.
895     want_method_inst fun_ty 
896         | opt_NoMethodSharing = False   
897         | otherwise           = case tcSplitSigmaTy fun_ty of
898                                   (_,[],_)    -> False  -- Not overloaded
899                                   (_,theta,_) -> not (any isLinearPred theta)
900 \end{code}
901
902 %************************************************************************
903 %*                                                                      *
904 \subsection{Record bindings}
905 %*                                                                      *
906 %************************************************************************
907
908 Game plan for record bindings
909 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
910 1. Find the TyCon for the bindings, from the first field label.
911
912 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
913
914 For each binding field = value
915
916 3. Instantiate the field type (from the field label) using the type
917    envt from step 2.
918
919 4  Type check the value using tcArg, passing the field type as 
920    the expected argument type.
921
922 This extends OK when the field types are universally quantified.
923
924         
925 \begin{code}
926 tcRecordBinds
927         :: DataCon
928         -> [(FieldLabel,TcType)]        -- Expected type for each field
929         -> HsRecordBinds Name
930         -> TcM (HsRecordBinds TcId)
931
932 tcRecordBinds data_con flds_w_tys rbinds
933   = do  { mb_binds <- mappM do_bind rbinds
934         ; return (catMaybes mb_binds) }
935   where
936     do_bind (L loc field_lbl, rhs)
937       | Just field_ty <- assocMaybe flds_w_tys field_lbl
938       = addErrCtxt (fieldCtxt field_lbl)        $
939         do { rhs'   <- tcCheckSigma rhs field_ty
940            ; sel_id <- tcLookupId field_lbl
941            ; ASSERT( isRecordSelector sel_id )
942              return (Just (L loc sel_id, rhs')) }
943       | otherwise
944       = do { addErrTc (badFieldCon data_con field_lbl)
945            ; return Nothing }
946
947 badFields rbinds data_con
948   = filter (not . (`elem` field_names)) (recBindFields rbinds)
949   where
950     field_names = dataConFieldLabels data_con
951
952 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
953 checkMissingFields data_con rbinds
954   | null field_labels   -- Not declared as a record;
955                         -- But C{} is still valid if no strict fields
956   = if any isMarkedStrict field_strs then
957         -- Illegal if any arg is strict
958         addErrTc (missingStrictFields data_con [])
959     else
960         returnM ()
961                         
962   | otherwise           -- A record
963   = checkM (null missing_s_fields)
964            (addErrTc (missingStrictFields data_con missing_s_fields))   `thenM_`
965
966     doptM Opt_WarnMissingFields         `thenM` \ warn ->
967     checkM (not (warn && notNull missing_ns_fields))
968            (warnTc True (missingFields data_con missing_ns_fields))
969
970   where
971     missing_s_fields
972         = [ fl | (fl, str) <- field_info,
973                  isMarkedStrict str,
974                  not (fl `elem` field_names_used)
975           ]
976     missing_ns_fields
977         = [ fl | (fl, str) <- field_info,
978                  not (isMarkedStrict str),
979                  not (fl `elem` field_names_used)
980           ]
981
982     field_names_used = recBindFields rbinds
983     field_labels     = dataConFieldLabels data_con
984
985     field_info = zipEqual "missingFields"
986                           field_labels
987                           field_strs
988
989     field_strs = dataConStrictMarks data_con
990 \end{code}
991
992 %************************************************************************
993 %*                                                                      *
994 \subsection{@tcCheckRhos@ typechecks a {\em list} of expressions}
995 %*                                                                      *
996 %************************************************************************
997
998 \begin{code}
999 tcCheckRhos :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
1000
1001 tcCheckRhos [] [] = returnM []
1002 tcCheckRhos (expr:exprs) (ty:tys)
1003  = tcCheckRho  expr  ty         `thenM` \ expr' ->
1004    tcCheckRhos exprs tys        `thenM` \ exprs' ->
1005    returnM (expr':exprs')
1006 tcCheckRhos exprs tys = pprPanic "tcCheckRhos" (ppr exprs $$ ppr tys)
1007 \end{code}
1008
1009
1010 %************************************************************************
1011 %*                                                                      *
1012 \subsection{Literals}
1013 %*                                                                      *
1014 %************************************************************************
1015
1016 Overloaded literals.
1017
1018 \begin{code}
1019 tcLit :: HsLit -> Expected TcRhoType -> TcM (HsExpr TcId)
1020 tcLit lit res_ty 
1021   = zapExpectedTo res_ty (hsLitType lit)                `thenM_`
1022     returnM (HsLit lit)
1023 \end{code}
1024
1025
1026 %************************************************************************
1027 %*                                                                      *
1028 \subsection{Errors and contexts}
1029 %*                                                                      *
1030 %************************************************************************
1031
1032 Boring and alphabetical:
1033 \begin{code}
1034 arithSeqCtxt expr
1035   = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
1036
1037 parrSeqCtxt expr
1038   = hang (ptext SLIT("In a parallel array sequence:")) 4 (ppr expr)
1039
1040 caseCtxt expr
1041   = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
1042
1043 caseScrutCtxt expr
1044   = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1045
1046 exprCtxt expr
1047   = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1048
1049 fieldCtxt field_name
1050   = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1051
1052 funAppCtxt fun arg arg_no
1053   = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"), 
1054                     quotes (ppr fun) <> text ", namely"])
1055          4 (quotes (ppr arg))
1056
1057 listCtxt expr
1058   = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
1059
1060 parrCtxt expr
1061   = hang (ptext SLIT("In the parallel array element:")) 4 (ppr expr)
1062
1063 predCtxt expr
1064   = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1065
1066 appCtxt fun args
1067   = ptext SLIT("In the application") <+> quotes (ppr the_app)
1068   where
1069     the_app = foldl mkHsApp fun args    -- Used in error messages
1070
1071 nonVanillaUpd tycon
1072   = vcat [ptext SLIT("Record update for the non-Haskell-98 data type") <+> quotes (ppr tycon)
1073                 <+> ptext SLIT("is not (yet) supported"),
1074           ptext SLIT("Use pattern-matching instead")]
1075 badFieldsUpd rbinds
1076   = hang (ptext SLIT("No constructor has all these fields:"))
1077          4 (pprQuotedList (recBindFields rbinds))
1078
1079 recordUpdCtxt expr = ptext SLIT("In the record update:") <+> ppr expr
1080 recordConCtxt expr = ptext SLIT("In the record construction:") <+> ppr expr
1081
1082 naughtyRecordSel sel_id
1083   = ptext SLIT("Cannot use record selector") <+> quotes (ppr sel_id) <+> 
1084     ptext SLIT("as a function due to escaped type variables") $$ 
1085     ptext SLIT("Probably fix: use pattern-matching syntax instead")
1086
1087 notSelector field
1088   = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1089
1090 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1091 missingStrictFields con fields
1092   = header <> rest
1093   where
1094     rest | null fields = empty  -- Happens for non-record constructors 
1095                                 -- with strict fields
1096          | otherwise   = colon <+> pprWithCommas ppr fields
1097
1098     header = ptext SLIT("Constructor") <+> quotes (ppr con) <+> 
1099              ptext SLIT("does not have the required strict field(s)") 
1100           
1101 missingFields :: DataCon -> [FieldLabel] -> SDoc
1102 missingFields con fields
1103   = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:") 
1104         <+> pprWithCommas ppr fields
1105
1106 wrongArgsCtxt too_many_or_few fun args
1107   = hang (ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1108                     <+> ptext SLIT("is applied to") <+> text too_many_or_few 
1109                     <+> ptext SLIT("arguments in the call"))
1110          4 (parens (ppr the_app))
1111   where
1112     the_app = foldl mkHsApp fun args    -- Used in error messages
1113
1114 #ifdef GHCI
1115 polySpliceErr :: Id -> SDoc
1116 polySpliceErr id
1117   = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)
1118 #endif
1119 \end{code}