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