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