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