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