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