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