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