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