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