[project @ 2002-10-22 10:31:21 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcExpr]{Typecheck an expression}
5
6 \begin{code}
7 module TcExpr ( tcExpr, tcExpr_id, tcMonoExpr ) where
8
9 #include "HsVersions.h"
10
11 #ifdef GHCI     /* Only if bootstrapped */
12 import {-# SOURCE #-}   TcSplice( tcSpliceExpr, tcBracket )
13 import HsSyn            ( HsReify(..), ReifyFlavour(..) )
14 import TcEnv            ( bracketOK, tcMetaTy, tcLookupGlobal,
15                           wellStaged, metaLevel )
16 import TcSimplify       ( tcSimplifyBracket )
17 import Name             ( isExternalName )
18 import qualified DsMeta
19 #endif
20
21 import HsSyn            ( HsExpr(..), HsLit(..), ArithSeqInfo(..),
22                           mkMonoBind, recBindFields
23                         )
24 import RnHsSyn          ( RenamedHsExpr, RenamedRecordBinds )
25 import TcHsSyn          ( TcExpr, TcRecordBinds, hsLitType, mkHsDictApp, mkHsTyApp, mkHsLet )
26 import TcRnMonad
27 import TcUnify          ( tcSubExp, tcGen, (<$>),
28                           unifyTauTy, unifyFunTy, unifyListTy, unifyPArrTy,
29                           unifyTupleTy )
30 import BasicTypes       ( RecFlag(..),  isMarkedStrict )
31 import Inst             ( InstOrigin(..), 
32                           newOverloadedLit, newMethodFromName, newIPDict,
33                           newDicts, newMethodWithGivenTy, 
34                           instToId, tcInstCall, tcInstDataCon
35                         )
36 import TcBinds          ( tcBindsAndThen )
37 import TcEnv            ( tcLookupClass, tcLookupGlobal_maybe, tcLookupIdLvl,
38                           tcLookupTyCon, tcLookupDataCon, tcLookupId
39                         )
40 import TcMatches        ( tcMatchesCase, tcMatchLambda, tcDoStmts )
41 import TcMonoType       ( tcHsSigType, UserTypeCtxt(..) )
42 import TcPat            ( badFieldCon )
43 import TcSimplify       ( tcSimplifyIPs )
44 import TcMType          ( tcInstTyVars, tcInstType, newHoleTyVarTy, zapToType,
45                           newTyVarTy, newTyVarTys, zonkTcType, readHoleResult )
46 import TcType           ( TcType, TcSigmaType, TcRhoType, TyVarDetails(VanillaTv),
47                           tcSplitFunTys, tcSplitTyConApp, mkTyVarTys,
48                           isSigmaTy, mkFunTy, mkFunTys,
49                           mkTyConApp, mkClassPred, tcFunArgTy,
50                           tyVarsOfTypes, isLinearPred,
51                           liftedTypeKind, openTypeKind, 
52                           tcSplitSigmaTy, tcTyConAppTyCon,
53                           tidyOpenType
54                         )
55 import FieldLabel       ( FieldLabel, fieldLabelName, fieldLabelType, fieldLabelTyCon )
56 import Id               ( Id, idType, recordSelectorFieldLabel, isRecordSelector, isDataConWrapId_maybe )
57 import DataCon          ( DataCon, dataConFieldLabels, dataConSig, dataConStrictMarks )
58 import Name             ( Name )
59 import TyCon            ( TyCon, tyConTyVars, tyConTheta, isAlgTyCon, tyConDataCons )
60 import Subst            ( mkTopTyVarSubst, substTheta, substTy )
61 import VarSet           ( emptyVarSet, elemVarSet )
62 import TysWiredIn       ( boolTy )
63 import PrelNames        ( cCallableClassName, cReturnableClassName, 
64                           enumFromName, enumFromThenName, 
65                           enumFromToName, enumFromThenToName,
66                           enumFromToPName, enumFromThenToPName,
67                           ioTyConName
68                         )
69 import ListSetOps       ( minusList )
70 import CmdLineOpts
71 import HscTypes         ( TyThing(..) )
72
73 import Util
74 import Outputable
75 import FastString
76 \end{code}
77
78 %************************************************************************
79 %*                                                                      *
80 \subsection{Main wrappers}
81 %*                                                                      *
82 %************************************************************************
83
84 \begin{code}
85 tcExpr :: RenamedHsExpr         -- Expession to type check
86         -> TcSigmaType          -- Expected type (could be a polytpye)
87         -> TcM TcExpr           -- Generalised expr with expected type
88
89 tcExpr expr expected_ty 
90   = traceTc (text "tcExpr" <+> (ppr expected_ty $$ ppr expr)) `thenM_`
91     tc_expr' expr expected_ty
92
93 tc_expr' expr expected_ty
94   | not (isSigmaTy expected_ty)  -- Monomorphic case
95   = tcMonoExpr expr expected_ty
96
97   | otherwise
98   = tcGen expected_ty emptyVarSet (
99         tcMonoExpr expr
100     )                           `thenM` \ (gen_fn, expr') ->
101     returnM (gen_fn <$> expr')
102 \end{code}
103
104
105 %************************************************************************
106 %*                                                                      *
107 \subsection{The TAUT rules for variables}
108 %*                                                                      *
109 %************************************************************************
110
111 \begin{code}
112 tcMonoExpr :: RenamedHsExpr             -- Expession to type check
113            -> TcRhoType                 -- Expected type (could be a type variable)
114                                         -- Definitely no foralls at the top
115                                         -- Can be a 'hole'.
116            -> TcM TcExpr
117
118 tcMonoExpr (HsVar name) res_ty
119   = tcId name                   `thenM` \ (expr', id_ty) ->
120     tcSubExp res_ty id_ty       `thenM` \ co_fn ->
121     returnM (co_fn <$> expr')
122
123 tcMonoExpr (HsIPVar ip) res_ty
124   =     -- Implicit parameters must have a *tau-type* not a 
125         -- type scheme.  We enforce this by creating a fresh
126         -- type variable as its type.  (Because res_ty may not
127         -- be a tau-type.)
128     newTyVarTy openTypeKind             `thenM` \ ip_ty ->
129     newIPDict (IPOcc ip) ip ip_ty       `thenM` \ (ip', inst) ->
130     extendLIE inst                      `thenM_`
131     tcSubExp res_ty ip_ty               `thenM` \ co_fn ->
132     returnM (co_fn <$> HsIPVar ip')
133 \end{code}
134
135
136 %************************************************************************
137 %*                                                                      *
138 \subsection{Expressions type signatures}
139 %*                                                                      *
140 %************************************************************************
141
142 \begin{code}
143 tcMonoExpr in_expr@(ExprWithTySig expr poly_ty) res_ty
144  = addErrCtxt (exprSigCtxt in_expr)     $
145    tcHsSigType ExprSigCtxt poly_ty      `thenM` \ sig_tc_ty ->
146    tcExpr expr sig_tc_ty                `thenM` \ expr' ->
147
148         -- Must instantiate the outer for-alls of sig_tc_ty
149         -- else we risk instantiating a ? res_ty to a forall-type
150         -- which breaks the invariant that tcMonoExpr only returns phi-types
151    tcInstCall SignatureOrigin sig_tc_ty `thenM` \ (inst_fn, inst_sig_ty) ->
152    tcSubExp res_ty inst_sig_ty          `thenM` \ co_fn ->
153
154    returnM (co_fn <$> inst_fn expr')
155
156 tcMonoExpr (HsType ty) res_ty
157   = failWithTc (text "Can't handle type argument:" <+> ppr ty)
158         -- This is the syntax for type applications that I was planning
159         -- but there are difficulties (e.g. what order for type args)
160         -- so it's not enabled yet.
161         -- Can't eliminate it altogether from the parser, because the
162         -- same parser parses *patterns*.
163 \end{code}
164
165
166 %************************************************************************
167 %*                                                                      *
168 \subsection{Other expression forms}
169 %*                                                                      *
170 %************************************************************************
171
172 \begin{code}
173 tcMonoExpr (HsLit lit)     res_ty  = tcLit lit res_ty
174 tcMonoExpr (HsOverLit lit) res_ty  = newOverloadedLit (LiteralOrigin lit) lit res_ty
175 tcMonoExpr (HsPar expr)    res_ty  = tcMonoExpr expr res_ty     `thenM` \ expr' -> 
176                                      returnM (HsPar expr')
177 tcMonoExpr (HsSCC lbl expr) res_ty = tcMonoExpr expr res_ty     `thenM` \ expr' ->
178                                      returnM (HsSCC lbl expr')
179
180
181 tcMonoExpr (NegApp expr neg_name) res_ty
182   = tcMonoExpr (HsApp (HsVar neg_name) expr) res_ty
183         -- ToDo: use tcSyntaxName
184
185 tcMonoExpr (HsLam match) res_ty
186   = tcMatchLambda match res_ty          `thenM` \ match' ->
187     returnM (HsLam match')
188
189 tcMonoExpr (HsApp e1 e2) res_ty 
190   = tcApp e1 [e2] res_ty
191 \end{code}
192
193 Note that the operators in sections are expected to be binary, and
194 a type error will occur if they aren't.
195
196 \begin{code}
197 -- Left sections, equivalent to
198 --      \ x -> e op x,
199 -- or
200 --      \ x -> op e x,
201 -- or just
202 --      op e
203
204 tcMonoExpr in_expr@(SectionL arg1 op) res_ty
205   = tcExpr_id op                                `thenM` \ (op', op_ty) ->
206     split_fun_ty op_ty 2 {- two args -}         `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
207     tcArg op (arg1, arg1_ty, 1)                 `thenM` \ arg1' ->
208     addErrCtxt (exprCtxt in_expr)               $
209     tcSubExp res_ty (mkFunTy arg2_ty op_res_ty) `thenM` \ co_fn ->
210     returnM (co_fn <$> SectionL arg1' op')
211
212 -- Right sections, equivalent to \ x -> x op expr, or
213 --      \ x -> op x expr
214
215 tcMonoExpr in_expr@(SectionR op arg2) res_ty
216   = tcExpr_id op                                `thenM` \ (op', op_ty) ->
217     split_fun_ty op_ty 2 {- two args -}         `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
218     tcArg op (arg2, arg2_ty, 2)                 `thenM` \ arg2' ->
219     addErrCtxt (exprCtxt in_expr)               $
220     tcSubExp res_ty (mkFunTy arg1_ty op_res_ty) `thenM` \ co_fn ->
221     returnM (co_fn <$> SectionR op' arg2')
222
223 -- equivalent to (op e1) e2:
224
225 tcMonoExpr in_expr@(OpApp arg1 op fix arg2) res_ty
226   = tcExpr_id op                                `thenM` \ (op', op_ty) ->
227     split_fun_ty op_ty 2 {- two args -}         `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
228     tcArg op (arg1, arg1_ty, 1)                 `thenM` \ arg1' ->
229     tcArg op (arg2, arg2_ty, 2)                 `thenM` \ arg2' ->
230     addErrCtxt (exprCtxt in_expr)               $
231     tcSubExp res_ty op_res_ty                   `thenM` \ co_fn ->
232     returnM (OpApp arg1' op' fix arg2')
233 \end{code}
234
235 \begin{code}
236 tcMonoExpr (HsLet binds expr) res_ty
237   = tcBindsAndThen
238         combiner
239         binds                   -- Bindings to check
240         (tcMonoExpr expr res_ty)
241   where
242     combiner is_rec bind expr = HsLet (mkMonoBind bind [] is_rec) expr
243
244 tcMonoExpr in_expr@(HsCase scrut matches src_loc) res_ty
245   = addSrcLoc src_loc                   $
246     addErrCtxt (caseCtxt in_expr)       $
247
248         -- Typecheck the case alternatives first.
249         -- The case patterns tend to give good type info to use
250         -- when typechecking the scrutinee.  For example
251         --      case (map f) of
252         --        (x:xs) -> ...
253         -- will report that map is applied to too few arguments
254         --
255         -- Not only that, but it's better to check the matches on their
256         -- own, so that we get the expected results for scoped type variables.
257         --      f x = case x of
258         --              (p::a, q::b) -> (q,p)
259         -- The above should work: the match (p,q) -> (q,p) is polymorphic as
260         -- claimed by the pattern signatures.  But if we typechecked the
261         -- match with x in scope and x's type as the expected type, we'd be hosed.
262
263     tcMatchesCase matches res_ty        `thenM`    \ (scrut_ty, matches') ->
264
265     addErrCtxt (caseScrutCtxt scrut)    (
266       tcMonoExpr scrut scrut_ty
267     )                                   `thenM`    \ scrut' ->
268
269     returnM (HsCase scrut' matches' src_loc)
270
271 tcMonoExpr (HsIf pred b1 b2 src_loc) res_ty
272   = addSrcLoc src_loc   $
273     addErrCtxt (predCtxt pred) (
274     tcMonoExpr pred boolTy      )       `thenM`    \ pred' ->
275
276     zapToType res_ty                    `thenM`    \ res_ty' ->
277         -- C.f. the call to zapToType in TcMatches.tcMatches
278
279     tcMonoExpr b1 res_ty'               `thenM`    \ b1' ->
280     tcMonoExpr b2 res_ty'               `thenM`    \ b2' ->
281     returnM (HsIf pred' b1' b2' src_loc)
282
283 tcMonoExpr (HsDo do_or_lc stmts method_names _ src_loc) res_ty
284   = addSrcLoc src_loc           $
285     tcDoStmts do_or_lc stmts method_names res_ty        `thenM` \ (binds, stmts', methods') ->
286     returnM (mkHsLet binds (HsDo do_or_lc stmts' methods' res_ty src_loc))
287
288 tcMonoExpr in_expr@(ExplicitList _ exprs) res_ty        -- Non-empty list
289   = unifyListTy res_ty                `thenM` \ elt_ty ->  
290     mappM (tc_elt elt_ty) exprs       `thenM` \ exprs' ->
291     returnM (ExplicitList elt_ty exprs')
292   where
293     tc_elt elt_ty expr
294       = addErrCtxt (listCtxt expr) $
295         tcMonoExpr expr elt_ty
296
297 tcMonoExpr in_expr@(ExplicitPArr _ exprs) res_ty        -- maybe empty
298   = unifyPArrTy res_ty                `thenM` \ elt_ty ->  
299     mappM (tc_elt elt_ty) exprs       `thenM` \ exprs' ->
300     returnM (ExplicitPArr elt_ty exprs')
301   where
302     tc_elt elt_ty expr
303       = addErrCtxt (parrCtxt expr) $
304         tcMonoExpr expr elt_ty
305
306 tcMonoExpr (ExplicitTuple exprs boxity) res_ty
307   = unifyTupleTy boxity (length exprs) res_ty   `thenM` \ arg_tys ->
308     tcMonoExprs exprs arg_tys                   `thenM` \ exprs' ->
309     returnM (ExplicitTuple exprs' boxity)
310 \end{code}
311
312
313 %************************************************************************
314 %*                                                                      *
315                 Foreign calls
316 %*                                                                      *
317 %************************************************************************
318
319 The interesting thing about @ccall@ is that it is just a template
320 which we instantiate by filling in details about the types of its
321 argument and result (ie minimal typechecking is performed).  So, the
322 basic story is that we allocate a load of type variables (to hold the
323 arg/result types); unify them with the args/result; and store them for
324 later use.
325
326 \begin{code}
327 tcMonoExpr e0@(HsCCall lbl args may_gc is_casm ignored_fake_result_ty) res_ty
328
329   = getDOpts                            `thenM` \ dflags ->
330
331     checkTc (not (is_casm && dopt_HscLang dflags /= HscC)) 
332         (vcat [text "_casm_ is only supported when compiling via C (-fvia-C).",
333                text "Either compile with -fvia-C, or, better, rewrite your code",
334                text "to use the foreign function interface.  _casm_s are deprecated",
335                text "and support for them may one day disappear."])
336                                         `thenM_`
337
338     -- Get the callable and returnable classes.
339     tcLookupClass cCallableClassName    `thenM` \ cCallableClass ->
340     tcLookupClass cReturnableClassName  `thenM` \ cReturnableClass ->
341     tcLookupTyCon ioTyConName           `thenM` \ ioTyCon ->
342     let
343         new_arg_dict (arg, arg_ty)
344           = newDicts (CCallOrigin (unpackFS lbl) (Just arg))
345                      [mkClassPred cCallableClass [arg_ty]]      `thenM` \ arg_dicts ->
346             returnM arg_dicts   -- Actually a singleton bag
347
348         result_origin = CCallOrigin (unpackFS lbl) Nothing {- Not an arg -}
349     in
350
351         -- Arguments
352     let tv_idxs | null args  = []
353                 | otherwise  = [1..length args]
354     in
355     newTyVarTys (length tv_idxs) openTypeKind           `thenM` \ arg_tys ->
356     tcMonoExprs args arg_tys                            `thenM` \ args' ->
357
358         -- The argument types can be unlifted or lifted; the result
359         -- type must, however, be lifted since it's an argument to the IO
360         -- type constructor.
361     newTyVarTy liftedTypeKind           `thenM` \ result_ty ->
362     let
363         io_result_ty = mkTyConApp ioTyCon [result_ty]
364     in
365     unifyTauTy res_ty io_result_ty              `thenM_`
366
367         -- Construct the extra insts, which encode the
368         -- constraints on the argument and result types.
369     mappM new_arg_dict (zipEqual "tcMonoExpr:CCall" args arg_tys)       `thenM` \ ccarg_dicts_s ->
370     newDicts result_origin [mkClassPred cReturnableClass [result_ty]]   `thenM` \ ccres_dict ->
371     extendLIEs (ccres_dict ++ concat ccarg_dicts_s)                     `thenM_`
372     returnM (HsCCall lbl args' may_gc is_casm io_result_ty)
373 \end{code}
374
375
376 %************************************************************************
377 %*                                                                      *
378                 Record construction and update
379 %*                                                                      *
380 %************************************************************************
381
382 \begin{code}
383 tcMonoExpr expr@(RecordCon con_name rbinds) res_ty
384   = addErrCtxt (recordConCtxt expr)             $
385     tcId con_name                       `thenM` \ (con_expr, con_tau) ->
386     let
387         (_, record_ty)   = tcSplitFunTys con_tau
388         (tycon, ty_args) = tcSplitTyConApp record_ty
389     in
390     ASSERT( isAlgTyCon tycon )
391     unifyTauTy res_ty record_ty          `thenM_`
392
393         -- Check that the record bindings match the constructor
394         -- con_name is syntactically constrained to be a data constructor
395     tcLookupDataCon con_name    `thenM` \ data_con ->
396     let
397         bad_fields = badFields rbinds data_con
398     in
399     if notNull bad_fields then
400         mappM (addErrTc . badFieldCon data_con) bad_fields      `thenM_`
401         failM   -- Fail now, because tcRecordBinds will crash on a bad field
402     else
403
404         -- Typecheck the record bindings
405     tcRecordBinds tycon ty_args rbinds          `thenM` \ rbinds' ->
406     
407         -- Check for missing fields
408     checkMissingFields data_con rbinds          `thenM_` 
409
410     returnM (RecordConOut data_con con_expr rbinds')
411
412 -- The main complication with RecordUpd is that we need to explicitly
413 -- handle the *non-updated* fields.  Consider:
414 --
415 --      data T a b = MkT1 { fa :: a, fb :: b }
416 --                 | MkT2 { fa :: a, fc :: Int -> Int }
417 --                 | MkT3 { fd :: a }
418 --      
419 --      upd :: T a b -> c -> T a c
420 --      upd t x = t { fb = x}
421 --
422 -- The type signature on upd is correct (i.e. the result should not be (T a b))
423 -- because upd should be equivalent to:
424 --
425 --      upd t x = case t of 
426 --                      MkT1 p q -> MkT1 p x
427 --                      MkT2 a b -> MkT2 p b
428 --                      MkT3 d   -> error ...
429 --
430 -- So we need to give a completely fresh type to the result record,
431 -- and then constrain it by the fields that are *not* updated ("p" above).
432 --
433 -- Note that because MkT3 doesn't contain all the fields being updated,
434 -- its RHS is simply an error, so it doesn't impose any type constraints
435 --
436 -- All this is done in STEP 4 below.
437
438 tcMonoExpr expr@(RecordUpd record_expr rbinds) res_ty
439   = addErrCtxt (recordUpdCtxt   expr)           $
440
441         -- STEP 0
442         -- Check that the field names are really field names
443     ASSERT( notNull rbinds )
444     let 
445         field_names = recBindFields rbinds
446     in
447     mappM tcLookupGlobal_maybe field_names              `thenM` \ maybe_sel_ids ->
448     let
449         bad_guys = [ addErrTc (notSelector field_name) 
450                    | (field_name, maybe_sel_id) <- field_names `zip` maybe_sel_ids,
451                       case maybe_sel_id of
452                         Just (AnId sel_id) -> not (isRecordSelector sel_id)
453                         other              -> True
454                    ]
455     in
456     checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM)  `thenM_`
457     
458         -- STEP 1
459         -- Figure out the tycon and data cons from the first field name
460     let
461                 -- It's OK to use the non-tc splitters here (for a selector)
462         (Just (AnId sel_id) : _) = maybe_sel_ids
463
464         (_, _, tau)  = tcSplitSigmaTy (idType sel_id)   -- Selectors can be overloaded
465                                                         -- when the data type has a context
466         data_ty      = tcFunArgTy tau                   -- Must succeed since sel_id is a selector
467         tycon        = tcTyConAppTyCon data_ty
468         data_cons    = tyConDataCons tycon
469         tycon_tyvars = tyConTyVars tycon                -- The data cons use the same type vars
470     in
471     tcInstTyVars VanillaTv tycon_tyvars         `thenM` \ (_, result_inst_tys, inst_env) ->
472
473         -- STEP 2
474         -- Check that at least one constructor has all the named fields
475         -- i.e. has an empty set of bad fields returned by badFields
476     checkTc (any (null . badFields rbinds) data_cons)
477             (badFieldsUpd rbinds)               `thenM_`
478
479         -- STEP 3
480         -- Typecheck the update bindings.
481         -- (Do this after checking for bad fields in case there's a field that
482         --  doesn't match the constructor.)
483     let
484         result_record_ty = mkTyConApp tycon result_inst_tys
485     in
486     unifyTauTy res_ty result_record_ty          `thenM_`
487     tcRecordBinds tycon result_inst_tys rbinds  `thenM` \ rbinds' ->
488
489         -- STEP 4
490         -- Use the un-updated fields to find a vector of booleans saying
491         -- which type arguments must be the same in updatee and result.
492         --
493         -- WARNING: this code assumes that all data_cons in a common tycon
494         -- have FieldLabels abstracted over the same tyvars.
495     let
496         upd_field_lbls      = map recordSelectorFieldLabel (recBindFields rbinds')
497         con_field_lbls_s    = map dataConFieldLabels data_cons
498
499                 -- A constructor is only relevant to this process if
500                 -- it contains all the fields that are being updated
501         relevant_field_lbls_s      = filter is_relevant con_field_lbls_s
502         is_relevant con_field_lbls = all (`elem` con_field_lbls) upd_field_lbls
503
504         non_upd_field_lbls  = concat relevant_field_lbls_s `minusList` upd_field_lbls
505         common_tyvars       = tyVarsOfTypes (map fieldLabelType non_upd_field_lbls)
506
507         mk_inst_ty (tyvar, result_inst_ty) 
508           | tyvar `elemVarSet` common_tyvars = returnM result_inst_ty   -- Same as result type
509           | otherwise                        = newTyVarTy liftedTypeKind        -- Fresh type
510     in
511     mappM mk_inst_ty (zip tycon_tyvars result_inst_tys) `thenM` \ inst_tys ->
512
513         -- STEP 5
514         -- Typecheck the expression to be updated
515     let
516         record_ty = mkTyConApp tycon inst_tys
517     in
518     tcMonoExpr record_expr record_ty            `thenM` \ record_expr' ->
519
520         -- STEP 6
521         -- Figure out the LIE we need.  We have to generate some 
522         -- dictionaries for the data type context, since we are going to
523         -- do pattern matching over the data cons.
524         --
525         -- What dictionaries do we need?  
526         -- We just take the context of the type constructor
527     let
528         theta' = substTheta inst_env (tyConTheta tycon)
529     in
530     newDicts RecordUpdOrigin theta'     `thenM` \ dicts ->
531     extendLIEs dicts                    `thenM_`
532
533         -- Phew!
534     returnM (RecordUpdOut record_expr' record_ty result_record_ty rbinds') 
535 \end{code}
536
537
538 %************************************************************************
539 %*                                                                      *
540         Arithmetic sequences                    e.g. [a,b..]
541         and their parallel-array counterparts   e.g. [: a,b.. :]
542                 
543 %*                                                                      *
544 %************************************************************************
545
546 \begin{code}
547 tcMonoExpr (ArithSeqIn seq@(From expr)) res_ty
548   = unifyListTy res_ty                          `thenM` \ elt_ty ->  
549     tcMonoExpr expr elt_ty                      `thenM` \ expr' ->
550
551     newMethodFromName (ArithSeqOrigin seq) 
552                       elt_ty enumFromName       `thenM` \ enum_from ->
553
554     returnM (ArithSeqOut (HsVar enum_from) (From expr'))
555
556 tcMonoExpr in_expr@(ArithSeqIn seq@(FromThen expr1 expr2)) res_ty
557   = addErrCtxt (arithSeqCtxt in_expr) $ 
558     unifyListTy  res_ty                                 `thenM`    \ elt_ty ->  
559     tcMonoExpr expr1 elt_ty                             `thenM`    \ expr1' ->
560     tcMonoExpr expr2 elt_ty                             `thenM`    \ expr2' ->
561     newMethodFromName (ArithSeqOrigin seq) 
562                       elt_ty enumFromThenName           `thenM` \ enum_from_then ->
563
564     returnM (ArithSeqOut (HsVar enum_from_then) (FromThen expr1' expr2'))
565
566
567 tcMonoExpr in_expr@(ArithSeqIn seq@(FromTo expr1 expr2)) res_ty
568   = addErrCtxt (arithSeqCtxt in_expr) $
569     unifyListTy  res_ty                                 `thenM`    \ elt_ty ->  
570     tcMonoExpr expr1 elt_ty                             `thenM`    \ expr1' ->
571     tcMonoExpr expr2 elt_ty                             `thenM`    \ expr2' ->
572     newMethodFromName (ArithSeqOrigin seq) 
573                       elt_ty enumFromToName             `thenM` \ enum_from_to ->
574
575     returnM (ArithSeqOut (HsVar enum_from_to) (FromTo expr1' expr2'))
576
577 tcMonoExpr in_expr@(ArithSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
578   = addErrCtxt  (arithSeqCtxt in_expr) $
579     unifyListTy  res_ty                                 `thenM`    \ elt_ty ->  
580     tcMonoExpr expr1 elt_ty                             `thenM`    \ expr1' ->
581     tcMonoExpr expr2 elt_ty                             `thenM`    \ expr2' ->
582     tcMonoExpr expr3 elt_ty                             `thenM`    \ expr3' ->
583     newMethodFromName (ArithSeqOrigin seq) 
584                       elt_ty enumFromThenToName         `thenM` \ eft ->
585
586     returnM (ArithSeqOut (HsVar eft) (FromThenTo expr1' expr2' expr3'))
587
588 tcMonoExpr in_expr@(PArrSeqIn seq@(FromTo expr1 expr2)) res_ty
589   = addErrCtxt (parrSeqCtxt in_expr) $
590     unifyPArrTy  res_ty                                 `thenM`    \ elt_ty ->  
591     tcMonoExpr expr1 elt_ty                             `thenM`    \ expr1' ->
592     tcMonoExpr expr2 elt_ty                             `thenM`    \ expr2' ->
593     newMethodFromName (PArrSeqOrigin seq) 
594                       elt_ty enumFromToPName            `thenM` \ enum_from_to ->
595
596     returnM (PArrSeqOut (HsVar enum_from_to) (FromTo expr1' expr2'))
597
598 tcMonoExpr in_expr@(PArrSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
599   = addErrCtxt  (parrSeqCtxt in_expr) $
600     unifyPArrTy  res_ty                                 `thenM`    \ elt_ty ->  
601     tcMonoExpr expr1 elt_ty                             `thenM`    \ expr1' ->
602     tcMonoExpr expr2 elt_ty                             `thenM`    \ expr2' ->
603     tcMonoExpr expr3 elt_ty                             `thenM`    \ expr3' ->
604     newMethodFromName (PArrSeqOrigin seq)
605                       elt_ty enumFromThenToPName        `thenM` \ eft ->
606
607     returnM (PArrSeqOut (HsVar eft) (FromThenTo expr1' expr2' expr3'))
608
609 tcMonoExpr (PArrSeqIn _) _ 
610   = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
611     -- the parser shouldn't have generated it and the renamer shouldn't have
612     -- let it through
613 \end{code}
614
615
616 %************************************************************************
617 %*                                                                      *
618                 Template Haskell
619 %*                                                                      *
620 %************************************************************************
621
622 \begin{code}
623 #ifdef GHCI     /* Only if bootstrapped */
624         -- Rename excludes these cases otherwise
625
626 tcMonoExpr (HsSplice n expr loc) res_ty = addSrcLoc loc (tcSpliceExpr n expr res_ty)
627   
628 tcMonoExpr (HsBracket brack loc) res_ty
629   = addSrcLoc loc                       $
630     getStage                            `thenM` \ level ->
631     case bracketOK level of {
632         Nothing         -> failWithTc (illegalBracket level) ;
633         Just next_level ->
634
635         -- Typecheck expr to make sure it is valid,
636         -- but throw away the results.  We'll type check
637         -- it again when we actually use it.
638     newMutVar []                        `thenM` \ pending_splices ->
639     getLIEVar                           `thenM` \ lie_var ->
640
641     setStage (Brack next_level pending_splices lie_var) (
642         getLIE (tcBracket brack)
643     )                                   `thenM` \ (meta_ty, lie) ->
644     tcSimplifyBracket lie               `thenM_`  
645
646     unifyTauTy res_ty meta_ty           `thenM_`
647
648         -- Return the original expression, not the type-decorated one
649     readMutVar pending_splices          `thenM` \ pendings ->
650     returnM (HsBracketOut brack pendings)
651     }
652
653 tcMonoExpr (HsReify (Reify flavour name)) res_ty
654   = addErrCtxt (ptext SLIT("At the reification of") <+> ppr name)       $
655     tcMetaTy  tycon_name        `thenM` \ reify_ty ->
656     unifyTauTy res_ty reify_ty  `thenM_`
657     returnM (HsReify (ReifyOut flavour name))
658   where
659     tycon_name = case flavour of
660                    ReifyDecl -> DsMeta.decTyConName
661                    ReifyType -> DsMeta.typTyConName
662                    ReifyFixity -> pprPanic "tcMonoExpr: cant do reifyFixity yet" (ppr name)
663 #endif GHCI
664 \end{code}
665
666 %************************************************************************
667 %*                                                                      *
668 \subsection{Implicit Parameter bindings}
669 %*                                                                      *
670 %************************************************************************
671
672 \begin{code}
673 tcMonoExpr (HsWith expr binds is_with) res_ty
674   = getLIE (tcMonoExpr expr res_ty)     `thenM` \ (expr', expr_lie) ->
675     mapAndUnzipM tc_ip_bind binds       `thenM` \ (avail_ips, binds') ->
676
677         -- If the binding binds ?x = E, we  must now 
678         -- discharge any ?x constraints in expr_lie
679     tcSimplifyIPs avail_ips expr_lie    `thenM` \ dict_binds ->
680     let
681         expr'' = HsLet (mkMonoBind dict_binds [] Recursive) expr'
682     in
683     returnM (HsWith expr'' binds' is_with)
684   where
685     tc_ip_bind (ip, expr)
686       = newTyVarTy openTypeKind         `thenM` \ ty ->
687         getSrcLocM                      `thenM` \ loc ->
688         newIPDict (IPBind ip) ip ty     `thenM` \ (ip', ip_inst) ->
689         tcMonoExpr expr ty              `thenM` \ expr' ->
690         returnM (ip_inst, (ip', expr'))
691 \end{code}
692
693
694 %************************************************************************
695 %*                                                                      *
696                 Catch-all
697 %*                                                                      *
698 %************************************************************************
699
700 \begin{code}
701 tcMonoExpr other _ = pprPanic "tcMonoExpr" (ppr other)
702 \end{code}
703
704
705 %************************************************************************
706 %*                                                                      *
707 \subsection{@tcApp@ typchecks an application}
708 %*                                                                      *
709 %************************************************************************
710
711 \begin{code}
712
713 tcApp :: RenamedHsExpr -> [RenamedHsExpr]       -- Function and args
714       -> TcType                                 -- Expected result type of application
715       -> TcM TcExpr                             -- Translated fun and args
716
717 tcApp (HsApp e1 e2) args res_ty 
718   = tcApp e1 (e2:args) res_ty           -- Accumulate the arguments
719
720 tcApp fun args res_ty
721   =     -- First type-check the function
722     tcExpr_id fun                               `thenM` \ (fun', fun_ty) ->
723
724     addErrCtxt (wrongArgsCtxt "too many" fun args) (
725         traceTc (text "tcApp" <+> (ppr fun $$ ppr fun_ty))      `thenM_`
726         split_fun_ty fun_ty (length args)
727     )                                           `thenM` \ (expected_arg_tys, actual_result_ty) ->
728
729         -- Now typecheck the args
730     mappM (tcArg fun)
731           (zip3 args expected_arg_tys [1..])    `thenM` \ args' ->
732
733         -- Unify with expected result after type-checking the args
734         -- so that the info from args percolates to actual_result_ty.
735         -- This is when we might detect a too-few args situation.
736         -- (One can think of cases when the opposite order would give
737         -- a better error message.)
738     addErrCtxtM (checkArgsCtxt fun args res_ty actual_result_ty)
739                   (tcSubExp res_ty actual_result_ty)    `thenM` \ co_fn ->
740
741     returnM (co_fn <$> foldl HsApp fun' args') 
742
743
744 -- If an error happens we try to figure out whether the
745 -- function has been given too many or too few arguments,
746 -- and say so
747 checkArgsCtxt fun args expected_res_ty actual_res_ty tidy_env
748   = zonkTcType expected_res_ty    `thenM` \ exp_ty' ->
749     zonkTcType actual_res_ty      `thenM` \ act_ty' ->
750     let
751       (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
752       (env2, act_ty'') = tidyOpenType env1     act_ty'
753       (exp_args, _)    = tcSplitFunTys exp_ty''
754       (act_args, _)    = tcSplitFunTys act_ty''
755
756       len_act_args     = length act_args
757       len_exp_args     = length exp_args
758
759       message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun args
760               | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun args
761               | otherwise                   = appCtxt fun args
762     in
763     returnM (env2, message)
764
765
766 split_fun_ty :: TcType          -- The type of the function
767              -> Int             -- Number of arguments
768              -> TcM ([TcType],  -- Function argument types
769                      TcType)    -- Function result types
770
771 split_fun_ty fun_ty 0 
772   = returnM ([], fun_ty)
773
774 split_fun_ty fun_ty n
775   =     -- Expect the function to have type A->B
776     unifyFunTy fun_ty           `thenM` \ (arg_ty, res_ty) ->
777     split_fun_ty res_ty (n-1)   `thenM` \ (arg_tys, final_res_ty) ->
778     returnM (arg_ty:arg_tys, final_res_ty)
779 \end{code}
780
781 \begin{code}
782 tcArg :: RenamedHsExpr                          -- The function (for error messages)
783       -> (RenamedHsExpr, TcSigmaType, Int)      -- Actual argument and expected arg type
784       -> TcM TcExpr                             -- Resulting argument and LIE
785
786 tcArg the_fun (arg, expected_arg_ty, arg_no)
787   = addErrCtxt (funAppCtxt the_fun arg arg_no) $
788     tcExpr arg expected_arg_ty
789 \end{code}
790
791
792 %************************************************************************
793 %*                                                                      *
794 \subsection{@tcId@ typchecks an identifier occurrence}
795 %*                                                                      *
796 %************************************************************************
797
798 tcId instantiates an occurrence of an Id.
799 The instantiate_it loop runs round instantiating the Id.
800 It has to be a loop because we are now prepared to entertain
801 types like
802         f:: forall a. Eq a => forall b. Baz b => tau
803 We want to instantiate this to
804         f2::tau         {f2 = f1 b (Baz b), f1 = f a (Eq a)}
805
806 The -fno-method-sharing flag controls what happens so far as the LIE
807 is concerned.  The default case is that for an overloaded function we 
808 generate a "method" Id, and add the Method Inst to the LIE.  So you get
809 something like
810         f :: Num a => a -> a
811         f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
812 If you specify -fno-method-sharing, the dictionary application 
813 isn't shared, so we get
814         f :: Num a => a -> a
815         f = /\a (d:Num a) (x:a) -> (+) a d x x
816 This gets a bit less sharing, but
817         a) it's better for RULEs involving overloaded functions
818         b) perhaps fewer separated lambdas
819
820 \begin{code}
821 tcId :: Name -> TcM (TcExpr, TcType)
822 tcId name       -- Look up the Id and instantiate its type
823   = tcLookupIdLvl name                  `thenM` \ (id, bind_lvl) ->
824
825         -- Check for cross-stage lifting
826 #ifdef GHCI
827     getStage                            `thenM` \ use_stage -> 
828     case use_stage of
829       Brack use_lvl ps_var lie_var
830         | use_lvl > bind_lvl && not (isExternalName name)
831         ->      -- E.g. \x -> [| h x |]
832                         -- We must behave as if the reference to x was
833                         --      h $(lift x)     
834                         -- We use 'x' itself as the splice proxy, used by 
835                         -- the desugarer to stitch it all back together
836                         -- NB: isExernalName is true of top level things, 
837                         -- and false of nested bindings
838         
839         let
840             id_ty = idType id
841         in
842         checkTc (isTauTy id_ty) (polySpliceErr id)      `thenM_` 
843                     -- If x is polymorphic, its occurrence sites might
844                     -- have different instantiations, so we can't use plain
845                     -- 'x' as the splice proxy name.  I don't know how to 
846                     -- solve this, and it's probably unimportant, so I'm
847                     -- just going to flag an error for now
848
849         setLIEVar lie_var       (
850         newMethodFromName orig id_ty DsMeta.liftName    `thenM` \ lift ->
851                 -- Put the 'lift' constraint into the right LIE
852         
853         -- Update the pending splices
854         readMutVar ps_var                       `thenM` \ ps ->
855         writeMutVar ps_var ((name, HsApp (HsVar lift) (HsVar id)) : ps) `thenM_`
856
857         returnM (HsVar id, id_ty))
858
859       other -> 
860         let
861            use_lvl = metaLevel use_stage
862         in
863         checkTc (wellStaged bind_lvl use_lvl)
864                 (badStageErr id bind_lvl use_lvl)       `thenM_`
865 #endif
866         -- This is the bit that handles the no-Template-Haskell case
867         case isDataConWrapId_maybe id of
868                 Nothing       -> loop (HsVar id) (idType id)
869                 Just data_con -> inst_data_con id data_con
870
871   where
872     orig = OccurrenceOf name
873
874     loop (HsVar fun_id) fun_ty
875         | want_method_inst fun_ty
876         = tcInstType VanillaTv fun_ty           `thenM` \ (tyvars, theta, tau) ->
877           newMethodWithGivenTy orig fun_id 
878                 (mkTyVarTys tyvars) theta tau   `thenM` \ meth_id ->
879           loop (HsVar meth_id) tau
880
881     loop fun fun_ty 
882         | isSigmaTy fun_ty
883         = tcInstCall orig fun_ty        `thenM` \ (inst_fn, tau) ->
884           loop (inst_fn fun) tau
885
886         | otherwise
887         = returnM (fun, fun_ty)
888
889     want_method_inst fun_ty 
890         | opt_NoMethodSharing = False   
891         | otherwise           = case tcSplitSigmaTy fun_ty of
892                                   (_,[],_)    -> False  -- Not overloaded
893                                   (_,theta,_) -> not (any isLinearPred theta)
894         -- This is a slight hack.
895         -- If   f :: (%x :: T) => Int -> Int
896         -- Then if we have two separate calls, (f 3, f 4), we cannot
897         -- make a method constraint that then gets shared, thus:
898         --      let m = f %x in (m 3, m 4)
899         -- because that loses the linearity of the constraint.
900         -- The simplest thing to do is never to construct a method constraint
901         -- in the first place that has a linear implicit parameter in it.
902
903         -- We treat data constructors differently, because we have to generate
904         -- constraints for their silly theta, which no longer appears in
905         -- the type of dataConWrapId.  It's dual to TcPat.tcConstructor
906     inst_data_con id data_con
907       = tcInstDataCon orig data_con     `thenM` \ (ty_args, ex_dicts, arg_tys, result_ty, _) ->
908         extendLIEs ex_dicts             `thenM_`
909         returnM (mkHsDictApp (mkHsTyApp (HsVar id) ty_args) (map instToId ex_dicts), 
910                  mkFunTys arg_tys result_ty)
911 \end{code}
912
913 Typecheck expression which in most cases will be an Id.
914 The expression can return a higher-ranked type, such as
915         (forall a. a->a) -> Int
916 so we must create a HoleTyVarTy to pass in as the expected tyvar.
917
918 \begin{code}
919 tcExpr_id :: RenamedHsExpr -> TcM (TcExpr, TcType)
920 tcExpr_id (HsVar name) = tcId name
921 tcExpr_id expr         = newHoleTyVarTy                 `thenM` \ id_ty ->
922                          tcMonoExpr expr id_ty          `thenM` \ expr' ->
923                          readHoleResult id_ty           `thenM` \ id_ty' ->
924                          returnM (expr', id_ty') 
925 \end{code}
926
927
928 %************************************************************************
929 %*                                                                      *
930 \subsection{Record bindings}
931 %*                                                                      *
932 %************************************************************************
933
934 Game plan for record bindings
935 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
936 1. Find the TyCon for the bindings, from the first field label.
937
938 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
939
940 For each binding field = value
941
942 3. Instantiate the field type (from the field label) using the type
943    envt from step 2.
944
945 4  Type check the value using tcArg, passing the field type as 
946    the expected argument type.
947
948 This extends OK when the field types are universally quantified.
949
950         
951 \begin{code}
952 tcRecordBinds
953         :: TyCon                -- Type constructor for the record
954         -> [TcType]             -- Args of this type constructor
955         -> RenamedRecordBinds
956         -> TcM TcRecordBinds
957
958 tcRecordBinds tycon ty_args rbinds
959   = mappM do_bind rbinds
960   where
961     tenv = mkTopTyVarSubst (tyConTyVars tycon) ty_args
962
963     do_bind (field_lbl_name, rhs)
964       = addErrCtxt (fieldCtxt field_lbl_name)   $
965            tcLookupId field_lbl_name            `thenM` \ sel_id ->
966         let
967             field_lbl = recordSelectorFieldLabel sel_id
968             field_ty  = substTy tenv (fieldLabelType field_lbl)
969         in
970         ASSERT( isRecordSelector sel_id )
971                 -- This lookup and assertion will surely succeed, because
972                 -- we check that the fields are indeed record selectors
973                 -- before calling tcRecordBinds
974         ASSERT2( fieldLabelTyCon field_lbl == tycon, ppr field_lbl )
975                 -- The caller of tcRecordBinds has already checked
976                 -- that all the fields come from the same type
977
978         tcExpr rhs field_ty                     `thenM` \ rhs' ->
979
980         returnM (sel_id, rhs')
981
982 badFields rbinds data_con
983   = filter (not . (`elem` field_names)) (recBindFields rbinds)
984   where
985     field_names = map fieldLabelName (dataConFieldLabels data_con)
986
987 checkMissingFields :: DataCon -> RenamedRecordBinds -> TcM ()
988 checkMissingFields data_con rbinds
989   | null field_labels   -- Not declared as a record;
990                         -- But C{} is still valid if no strict fields
991   = if any isMarkedStrict field_strs then
992         -- Illegal if any arg is strict
993         addErrTc (missingStrictFields data_con [])
994     else
995         returnM ()
996                         
997   | otherwise           -- A record
998   = checkM (null missing_s_fields)
999            (addErrTc (missingStrictFields data_con missing_s_fields))   `thenM_`
1000
1001     doptM Opt_WarnMissingFields         `thenM` \ warn ->
1002     checkM (not (warn && notNull missing_ns_fields))
1003            (warnTc True (missingFields data_con missing_ns_fields))
1004
1005   where
1006     missing_s_fields
1007         = [ fl | (fl, str) <- field_info,
1008                  isMarkedStrict str,
1009                  not (fieldLabelName fl `elem` field_names_used)
1010           ]
1011     missing_ns_fields
1012         = [ fl | (fl, str) <- field_info,
1013                  not (isMarkedStrict str),
1014                  not (fieldLabelName fl `elem` field_names_used)
1015           ]
1016
1017     field_names_used = recBindFields rbinds
1018     field_labels     = dataConFieldLabels data_con
1019
1020     field_info = zipEqual "missingFields"
1021                           field_labels
1022                           field_strs
1023
1024     field_strs = dropList ex_theta (dataConStrictMarks data_con)
1025         -- The 'drop' is because dataConStrictMarks
1026         -- includes the existential dictionaries
1027     (_, _, _, ex_theta, _, _) = dataConSig data_con
1028 \end{code}
1029
1030 %************************************************************************
1031 %*                                                                      *
1032 \subsection{@tcMonoExprs@ typechecks a {\em list} of expressions}
1033 %*                                                                      *
1034 %************************************************************************
1035
1036 \begin{code}
1037 tcMonoExprs :: [RenamedHsExpr] -> [TcType] -> TcM [TcExpr]
1038
1039 tcMonoExprs [] [] = returnM []
1040 tcMonoExprs (expr:exprs) (ty:tys)
1041  = tcMonoExpr  expr  ty         `thenM` \ expr' ->
1042    tcMonoExprs exprs tys        `thenM` \ exprs' ->
1043    returnM (expr':exprs')
1044 \end{code}
1045
1046
1047 %************************************************************************
1048 %*                                                                      *
1049 \subsection{Literals}
1050 %*                                                                      *
1051 %************************************************************************
1052
1053 Overloaded literals.
1054
1055 \begin{code}
1056 tcLit :: HsLit -> TcType -> TcM TcExpr
1057 tcLit (HsLitLit s _) res_ty
1058   = tcLookupClass cCallableClassName                    `thenM` \ cCallableClass ->
1059     newDicts (LitLitOrigin (unpackFS s))
1060              [mkClassPred cCallableClass [res_ty]]      `thenM` \ dicts ->
1061     extendLIEs dicts                                    `thenM_`
1062     returnM (HsLit (HsLitLit s res_ty))
1063
1064 tcLit lit res_ty 
1065   = unifyTauTy res_ty (hsLitType lit)           `thenM_`
1066     returnM (HsLit lit)
1067 \end{code}
1068
1069
1070 %************************************************************************
1071 %*                                                                      *
1072 \subsection{Errors and contexts}
1073 %*                                                                      *
1074 %************************************************************************
1075
1076 Boring and alphabetical:
1077 \begin{code}
1078 arithSeqCtxt expr
1079   = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
1080
1081
1082 badStageErr id bind_lvl use_lvl
1083   = ptext SLIT("Stage error:") <+> quotes (ppr id) <+> 
1084         hsep   [ptext SLIT("is bound at stage") <+> ppr bind_lvl,
1085                 ptext SLIT("but used at stage") <+> ppr use_lvl]
1086
1087 parrSeqCtxt expr
1088   = hang (ptext SLIT("In a parallel array sequence:")) 4 (ppr expr)
1089
1090 caseCtxt expr
1091   = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
1092
1093 caseScrutCtxt expr
1094   = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
1095
1096 exprSigCtxt expr
1097   = hang (ptext SLIT("When checking the type signature of the expression:"))
1098          4 (ppr expr)
1099
1100 exprCtxt expr
1101   = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
1102
1103 fieldCtxt field_name
1104   = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1105
1106 funAppCtxt fun arg arg_no
1107   = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"), 
1108                     quotes (ppr fun) <> text ", namely"])
1109          4 (quotes (ppr arg))
1110
1111 listCtxt expr
1112   = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
1113
1114 parrCtxt expr
1115   = hang (ptext SLIT("In the parallel array element:")) 4 (ppr expr)
1116
1117 predCtxt expr
1118   = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1119
1120 illegalBracket level
1121   = ptext SLIT("Illegal bracket at level") <+> ppr level
1122
1123 appCtxt fun args
1124   = ptext SLIT("In the application") <+> quotes (ppr the_app)
1125   where
1126     the_app = foldl HsApp fun args      -- Used in error messages
1127
1128 lurkingRank2Err fun fun_ty
1129   = hang (hsep [ptext SLIT("Illegal use of"), quotes (ppr fun)])
1130          4 (vcat [ptext SLIT("It is applied to too few arguments"),  
1131                   ptext SLIT("so that the result type has for-alls in it:") <+> ppr fun_ty])
1132
1133 badFieldsUpd rbinds
1134   = hang (ptext SLIT("No constructor has all these fields:"))
1135          4 (pprQuotedList (recBindFields rbinds))
1136
1137 recordUpdCtxt expr = ptext SLIT("In the record update:") <+> ppr expr
1138 recordConCtxt expr = ptext SLIT("In the record construction:") <+> ppr expr
1139
1140 notSelector field
1141   = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1142
1143 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1144 missingStrictFields con fields
1145   = header <> rest
1146   where
1147     rest | null fields = empty  -- Happens for non-record constructors 
1148                                 -- with strict fields
1149          | otherwise   = colon <+> pprWithCommas ppr fields
1150
1151     header = ptext SLIT("Constructor") <+> quotes (ppr con) <+> 
1152              ptext SLIT("does not have the required strict field(s)") 
1153           
1154
1155 missingFields :: DataCon -> [FieldLabel] -> SDoc
1156 missingFields con fields
1157   = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:") 
1158         <+> pprWithCommas ppr fields
1159
1160 polySpliceErr :: Id -> SDoc
1161 polySpliceErr id
1162   = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)
1163
1164 wrongArgsCtxt too_many_or_few fun args
1165   = hang (ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1166                     <+> ptext SLIT("is applied to") <+> text too_many_or_few 
1167                     <+> ptext SLIT("arguments in the call"))
1168          4 (parens (ppr the_app))
1169   where
1170     the_app = foldl HsApp fun args      -- Used in error messages
1171 \end{code}