Completely new treatment of INLINE pragmas (big patch)
[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 \end{code}
284
285 \begin{code}
286 tcExpr (HsLet binds expr) res_ty
287   = do  { (binds', expr') <- tcLocalBinds binds $
288                              tcMonoExpr expr res_ty   
289         ; return (HsLet binds' expr') }
290
291 tcExpr (HsCase scrut matches) exp_ty
292   = do  {  -- We used to typecheck the case alternatives first.
293            -- The case patterns tend to give good type info to use
294            -- when typechecking the scrutinee.  For example
295            --   case (map f) of
296            --     (x:xs) -> ...
297            -- will report that map is applied to too few arguments
298            --
299            -- But now, in the GADT world, we need to typecheck the scrutinee
300            -- first, to get type info that may be refined in the case alternatives
301           (scrut', scrut_ty) <- tcInferRho scrut
302
303         ; traceTc (text "HsCase" <+> ppr scrut_ty)
304         ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
305         ; return (HsCase scrut' matches') }
306  where
307     match_ctxt = MC { mc_what = CaseAlt,
308                       mc_body = tcBody }
309
310 tcExpr (HsIf pred b1 b2) res_ty
311   = do  { pred' <- tcMonoExpr pred boolTy
312         ; b1' <- tcMonoExpr b1 res_ty
313         ; b2' <- tcMonoExpr b2 res_ty
314         ; return (HsIf pred' b1' b2') }
315
316 tcExpr (HsDo do_or_lc stmts body _) res_ty
317   = tcDoStmts do_or_lc stmts body res_ty
318
319 tcExpr in_expr@(ExplicitList _ exprs) res_ty
320   = do  { (elt_ty, coi) <- boxySplitListTy res_ty
321         ; exprs' <- mapM (tc_elt elt_ty) exprs
322         ; when (null exprs) (zapToMonotype elt_ty >> return ())
323                 -- If there are no expressions in the comprehension
324                 -- we must still fill in the box
325                 --
326                 -- The GHC front end never generates an empty ExplicitList
327                 -- (instead it generates the [] data constructor) but
328                 -- Template Haskell might.  We could fix the bit of 
329                 -- TH that generates ExplicitList, but it seems less
330                 -- fragile to just handle the case here.
331         ; return $ mkHsWrapCoI coi (ExplicitList elt_ty exprs') }
332   where
333     tc_elt elt_ty expr = tcPolyExpr expr elt_ty
334
335 tcExpr in_expr@(ExplicitPArr _ exprs) res_ty    -- maybe empty
336   = do  { (elt_ty, coi) <- boxySplitPArrTy res_ty
337         ; exprs' <- mapM (tc_elt elt_ty) exprs  
338         ; when (null exprs) (zapToMonotype elt_ty >> return ())
339                 -- If there are no expressions in the comprehension
340                 -- we must still fill in the box
341                 -- (Not needed for [] and () becuase they happen
342                 --  to parse as data constructors.)
343         ; return $ mkHsWrapCoI coi (ExplicitPArr elt_ty exprs') }
344   where
345     tc_elt elt_ty expr = tcPolyExpr expr elt_ty
346
347 -- For tuples, take care to preserve rigidity
348 -- E.g.         case (x,y) of ....
349 --         The scrutinee should have a rigid type if x,y do
350 -- The general scheme is the same as in tcIdApp
351 tcExpr (ExplicitTuple exprs boxity) res_ty
352   = do  { let kind = case boxity of { Boxed   -> liftedTypeKind
353                                     ; Unboxed -> argTypeKind }
354         ; tvs <- newBoxyTyVars [kind | e <- exprs]
355         ; let tup_tc     = tupleTyCon boxity (length exprs)
356               tup_res_ty = mkTyConApp tup_tc (mkTyVarTys tvs)
357         ; checkWiredInTyCon tup_tc      -- Ensure instances are available
358         ; arg_tys  <- preSubType tvs (mkVarSet tvs) tup_res_ty res_ty
359         ; exprs'   <- tcPolyExprs exprs arg_tys
360         ; arg_tys' <- mapM refineBox arg_tys
361         ; co_fn    <- tcSubExp TupleOrigin (mkTyConApp tup_tc arg_tys') res_ty
362         ; return (mkHsWrap co_fn (ExplicitTuple exprs' boxity)) }
363
364 tcExpr (HsProc pat cmd) res_ty
365   = do  { (pat', cmd', coi) <- tcProc pat cmd res_ty
366         ; return $ mkHsWrapCoI coi (HsProc pat' cmd') }
367
368 tcExpr e@(HsArrApp _ _ _ _ _) _
369   = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e), 
370                       ptext (sLit "was found where an expression was expected")])
371
372 tcExpr e@(HsArrForm _ _ _) _
373   = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e), 
374                       ptext (sLit "was found where an expression was expected")])
375 \end{code}
376
377 %************************************************************************
378 %*                                                                      *
379                 Record construction and update
380 %*                                                                      *
381 %************************************************************************
382
383 \begin{code}
384 tcExpr expr@(RecordCon (L loc con_name) _ rbinds) res_ty
385   = do  { data_con <- tcLookupDataCon con_name
386
387         -- Check for missing fields
388         ; checkMissingFields data_con rbinds
389
390         ; let arity = dataConSourceArity data_con
391               check_fields qtvs qtys arg_tys 
392                   = do  { let arg_tys' = substTys (zipOpenTvSubst qtvs qtys) arg_tys
393                         ; rbinds' <- tcRecordBinds data_con arg_tys' rbinds
394                         ; qtys' <- mapM refineBoxToTau qtys
395                         ; return (qtys', rbinds') }
396                 -- The refineBoxToTau ensures that all the boxes in arg_tys are indeed
397                 -- filled, which is the invariant expected by tcIdApp
398                 -- How could this not be the case?  Consider a record construction
399                 -- that does not mention all the fields.
400
401         ; (con_expr, rbinds') <- tcIdApp con_name arity check_fields res_ty
402
403         ; return (RecordCon (L loc (dataConWrapId data_con)) con_expr rbinds') }
404 \end{code}
405
406 Note [Type of a record update]
407 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
408 The main complication with RecordUpd is that we need to explicitly
409 handle the *non-updated* fields.  Consider:
410
411         data T a b = MkT1 { fa :: a, fb :: b }
412                    | MkT2 { fa :: a, fc :: Int -> Int }
413                    | MkT3 { fd :: a }
414         
415         upd :: T a b -> c -> T a c
416         upd t x = t { fb = x}
417
418 The type signature on upd is correct (i.e. the result should not be (T a b))
419 because upd should be equivalent to:
420
421         upd t x = case t of 
422                         MkT1 p q -> MkT1 p x
423                         MkT2 a b -> MkT2 p b
424                         MkT3 d   -> error ...
425
426 So we need to give a completely fresh type to the result record,
427 and then constrain it by the fields that are *not* updated ("p" above).
428
429 Note that because MkT3 doesn't contain all the fields being updated,
430 its RHS is simply an error, so it doesn't impose any type constraints
431
432 Note [Implict type sharing]
433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
434 We also take into account any "implicit" non-update fields.  For example
435         data T a b where { MkT { f::a } :: T a a; ... }
436 So the "real" type of MkT is: forall ab. (a~b) => a -> T a b
437
438 Then consider
439         upd t x = t { f=x }
440 We infer the type
441         upd :: T a b -> a -> T a b
442         upd (t::T a b) (x::a)
443            = case t of { MkT (co:a~b) (_:a) -> MkT co x }
444 We can't give it the more general type
445         upd :: T a b -> c -> T c b
446
447 Note [Criteria for update]
448 ~~~~~~~~~~~~~~~~~~~~~~~~~~
449 We want to allow update for existentials etc, provided the updated
450 field isn't part of the existential. For example, this should be ok.
451   data T a where { MkT { f1::a, f2::b->b } :: T a }
452   f :: T a -> b -> T b
453   f t b = t { f1=b }
454 The criterion we use is this:
455
456   The types of the updated fields
457   mention only the universally-quantified type variables
458   of the data constructor
459
460 In principle one could go further, and allow
461   g :: T a -> T a
462   g t = t { f2 = \x -> x }
463 because the expression is polymorphic...but that seems a bridge too far.
464
465 Note [Data family example]
466 ~~~~~~~~~~~~~~~~~~~~~~~~~~
467     data instance T (a,b) = MkT { x::a, y::b }
468   --->
469     data :TP a b = MkT { a::a, y::b }
470     coTP a b :: T (a,b) ~ :TP a b
471
472 Suppose r :: T (t1,t2), e :: t3
473 Then  r { x=e } :: T (t3,t1)
474   --->
475       case r |> co1 of
476         MkT x y -> MkT e y |> co2
477       where co1 :: T (t1,t2) ~ :TP t1 t2
478             co2 :: :TP t3 t2 ~ T (t3,t2)
479 The wrapping with co2 is done by the constructor wrapper for MkT
480
481 Outgoing invariants
482 ~~~~~~~~~~~~~~~~~~~
483 In the outgoing (HsRecordUpd scrut binds cons in_inst_tys out_inst_tys):
484
485   * cons are the data constructors to be updated
486
487   * in_inst_tys, out_inst_tys have same length, and instantiate the
488         *representation* tycon of the data cons.  In Note [Data 
489         family example], in_inst_tys = [t1,t2], out_inst_tys = [t3,t2]
490         
491 \begin{code}
492 tcExpr expr@(RecordUpd record_expr rbinds _ _ _) res_ty
493   = do  {
494         -- STEP 0
495         -- Check that the field names are really field names
496           let upd_fld_names = hsRecFields rbinds
497         ; MASSERT( notNull upd_fld_names )
498         ; sel_ids <- mapM tcLookupField upd_fld_names
499                         -- The renamer has already checked that
500                         -- selectors are all in scope
501         ; let bad_guys = [ setSrcSpan loc $ addErrTc (notSelector fld_name) 
502                          | (fld, sel_id) <- rec_flds rbinds `zip` sel_ids,
503                            not (isRecordSelector sel_id),       -- Excludes class ops
504                            let L loc fld_name = hsRecFieldId fld ]
505         ; unless (null bad_guys) (sequence bad_guys >> failM)
506     
507         -- STEP 1
508         -- Figure out the tycon and data cons from the first field name
509         ; let   -- It's OK to use the non-tc splitters here (for a selector)
510               sel_id : _  = sel_ids
511               (tycon, _)  = recordSelectorFieldLabel sel_id     -- We've failed already if
512               data_cons   = tyConDataCons tycon                 -- it's not a field label
513                 -- NB: for a data type family, the tycon is the instance tycon
514
515               relevant_cons   = filter is_relevant data_cons
516               is_relevant con = all (`elem` dataConFieldLabels con) upd_fld_names
517                 -- A constructor is only relevant to this process if
518                 -- it contains *all* the fields that are being updated
519                 -- Other ones will cause a runtime error if they occur
520
521                 -- Take apart a representative constructor
522               con1 = ASSERT( not (null relevant_cons) ) head relevant_cons
523               (con1_tvs, _, _, _, _, con1_arg_tys, _) = dataConFullSig con1
524               con1_flds = dataConFieldLabels con1
525               con1_res_ty = mkFamilyTyConApp tycon (mkTyVarTys con1_tvs)
526               
527         -- STEP 2
528         -- Check that at least one constructor has all the named fields
529         -- i.e. has an empty set of bad fields returned by badFields
530         ; checkTc (not (null relevant_cons)) (badFieldsUpd rbinds)
531
532         -- STEP 3    Note [Criteria for update]
533         -- Check that each updated field is polymorphic; that is, its type
534         -- mentions only the universally-quantified variables of the data con
535         ; let flds_w_tys = zipEqual "tcExpr:RecConUpd" con1_flds con1_arg_tys
536               (upd_flds_w_tys, fixed_flds_w_tys) = partition is_updated flds_w_tys
537               is_updated (fld,ty) = fld `elem` upd_fld_names
538
539               bad_upd_flds = filter bad_fld upd_flds_w_tys
540               con1_tv_set = mkVarSet con1_tvs
541               bad_fld (fld, ty) = fld `elem` upd_fld_names &&
542                                       not (tyVarsOfType ty `subVarSet` con1_tv_set)
543         ; checkTc (null bad_upd_flds) (badFieldTypes bad_upd_flds)
544
545         -- STEP 4  Note [Type of a record update]
546         -- Figure out types for the scrutinee and result
547         -- Both are of form (T a b c), with fresh type variables, but with
548         -- common variables where the scrutinee and result must have the same type
549         -- These are variables that appear anywhere *except* in the updated fields
550         ; let common_tvs = exactTyVarsOfTypes (map snd fixed_flds_w_tys)
551                            `unionVarSet` constrainedTyVars con1_tvs relevant_cons
552               is_common_tv tv = tv `elemVarSet` common_tvs
553
554               mk_inst_ty tv result_inst_ty 
555                 | is_common_tv tv = return result_inst_ty           -- Same as result type
556                 | otherwise       = newFlexiTyVarTy (tyVarKind tv)  -- Fresh type, of correct kind
557
558         ; (_, result_inst_tys, result_inst_env) <- tcInstTyVars con1_tvs
559         ; scrut_inst_tys <- zipWithM mk_inst_ty con1_tvs result_inst_tys
560
561         ; let result_ty     = substTy result_inst_env con1_res_ty
562               con1_arg_tys' = map (substTy result_inst_env) con1_arg_tys
563               scrut_subst   = zipTopTvSubst con1_tvs scrut_inst_tys
564               scrut_ty      = substTy scrut_subst con1_res_ty
565
566         -- STEP 5
567         -- Typecheck the thing to be updated, and the bindings
568         ; record_expr' <- tcMonoExpr record_expr scrut_ty
569         ; rbinds'      <- tcRecordBinds con1 con1_arg_tys' rbinds
570         
571         ; let origin = RecordUpdOrigin
572         ; co_fn <- tcSubExp origin result_ty res_ty
573
574         -- STEP 6: Deal with the stupid theta
575         ; let theta' = substTheta scrut_subst (dataConStupidTheta con1)
576         ; instStupidTheta origin theta'
577
578         -- Step 7: make a cast for the scrutinee, in the case that it's from a type family
579         ; let scrut_co | Just co_con <- tyConFamilyCoercion_maybe tycon 
580                        = WpCast $ mkTyConApp co_con scrut_inst_tys
581                        | otherwise
582                        = idHsWrapper
583
584         -- Phew!
585         ; return (mkHsWrap co_fn (RecordUpd (mkLHsWrap scrut_co record_expr') rbinds'
586                                         relevant_cons scrut_inst_tys result_inst_tys)) }
587   where
588     constrainedTyVars :: [TyVar] -> [DataCon] -> TyVarSet
589     -- Universally-quantified tyvars that appear in any of the 
590     -- *implicit* arguments to the constructor
591     -- These tyvars must not change across the updates
592     -- See Note [Implict type sharing]
593     constrainedTyVars tvs1 cons
594       = mkVarSet [tv1 | con <- cons
595                       , let (tvs, theta, _, _) = dataConSig con
596                             bad_tvs = tyVarsOfTheta theta
597                       , (tv1,tv) <- tvs1 `zip` tvs      -- Discards existentials in tvs
598                       , tv `elemVarSet` bad_tvs ]
599 \end{code}
600
601 %************************************************************************
602 %*                                                                      *
603         Arithmetic sequences                    e.g. [a,b..]
604         and their parallel-array counterparts   e.g. [: a,b.. :]
605                 
606 %*                                                                      *
607 %************************************************************************
608
609 \begin{code}
610 tcExpr (ArithSeq _ seq@(From expr)) res_ty
611   = do  { (elt_ty, coi) <- boxySplitListTy res_ty
612         ; expr' <- tcPolyExpr expr elt_ty
613         ; enum_from <- newMethodFromName (ArithSeqOrigin seq) 
614                               elt_ty enumFromName
615         ; return $ mkHsWrapCoI coi (ArithSeq (HsVar enum_from) (From expr')) }
616
617 tcExpr in_expr@(ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
618   = do  { (elt_ty, coi) <- boxySplitListTy res_ty
619         ; expr1' <- tcPolyExpr expr1 elt_ty
620         ; expr2' <- tcPolyExpr expr2 elt_ty
621         ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq) 
622                               elt_ty enumFromThenName
623         ; return $ mkHsWrapCoI coi 
624                     (ArithSeq (HsVar enum_from_then) (FromThen expr1' expr2')) }
625
626 tcExpr in_expr@(ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
627   = do  { (elt_ty, coi) <- boxySplitListTy res_ty
628         ; expr1' <- tcPolyExpr expr1 elt_ty
629         ; expr2' <- tcPolyExpr expr2 elt_ty
630         ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq) 
631                               elt_ty enumFromToName
632         ; return $ mkHsWrapCoI coi 
633                      (ArithSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
634
635 tcExpr in_expr@(ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
636   = do  { (elt_ty, coi) <- boxySplitListTy res_ty
637         ; expr1' <- tcPolyExpr expr1 elt_ty
638         ; expr2' <- tcPolyExpr expr2 elt_ty
639         ; expr3' <- tcPolyExpr expr3 elt_ty
640         ; eft <- newMethodFromName (ArithSeqOrigin seq) 
641                       elt_ty enumFromThenToName
642         ; return $ mkHsWrapCoI coi 
643                      (ArithSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
644
645 tcExpr in_expr@(PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
646   = do  { (elt_ty, coi) <- boxySplitPArrTy res_ty
647         ; expr1' <- tcPolyExpr expr1 elt_ty
648         ; expr2' <- tcPolyExpr expr2 elt_ty
649         ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq) 
650                                       elt_ty enumFromToPName
651         ; return $ mkHsWrapCoI coi 
652                      (PArrSeq (HsVar enum_from_to) (FromTo expr1' expr2')) }
653
654 tcExpr in_expr@(PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
655   = do  { (elt_ty, coi) <- boxySplitPArrTy res_ty
656         ; expr1' <- tcPolyExpr expr1 elt_ty
657         ; expr2' <- tcPolyExpr expr2 elt_ty
658         ; expr3' <- tcPolyExpr expr3 elt_ty
659         ; eft <- newMethodFromName (PArrSeqOrigin seq)
660                       elt_ty enumFromThenToPName
661         ; return $ mkHsWrapCoI coi 
662                      (PArrSeq (HsVar eft) (FromThenTo expr1' expr2' expr3')) }
663
664 tcExpr (PArrSeq _ _) _ 
665   = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
666     -- the parser shouldn't have generated it and the renamer shouldn't have
667     -- let it through
668 \end{code}
669
670
671 %************************************************************************
672 %*                                                                      *
673                 Template Haskell
674 %*                                                                      *
675 %************************************************************************
676
677 \begin{code}
678 #ifdef GHCI     /* Only if bootstrapped */
679         -- Rename excludes these cases otherwise
680 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
681 tcExpr (HsBracket brack)  res_ty = do   { e <- tcBracket brack res_ty
682                                         ; return (unLoc e) }
683 tcExpr e@(HsQuasiQuoteE _) res_ty =
684     pprPanic "Should never see HsQuasiQuoteE in type checker" (ppr e)
685 #endif /* GHCI */
686 \end{code}
687
688
689 %************************************************************************
690 %*                                                                      *
691                 Catch-all
692 %*                                                                      *
693 %************************************************************************
694
695 \begin{code}
696 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
697 \end{code}
698
699
700 %************************************************************************
701 %*                                                                      *
702                 Applications
703 %*                                                                      *
704 %************************************************************************
705
706 \begin{code}
707 ---------------------------
708 tcApp :: HsExpr Name                            -- Function
709       -> Arity                                  -- Number of args reqd
710       -> ArgChecker results
711       -> BoxyRhoType                            -- Result type
712       -> TcM (HsExpr TcId, results)             
713
714 -- (tcFun fun n_args arg_checker res_ty)
715 -- The argument type checker, arg_checker, will be passed exactly n_args types
716
717 tcApp (HsVar fun_name) n_args arg_checker res_ty
718   = tcIdApp fun_name n_args arg_checker res_ty
719
720 tcApp fun n_args arg_checker res_ty     -- The vanilla case (rula APP)
721   = do  { arg_boxes  <- newBoxyTyVars (replicate n_args argTypeKind)
722         ; fun'       <- tcExpr fun (mkFunTys (mkTyVarTys arg_boxes) res_ty)
723         ; arg_tys'   <- mapM readFilledBox arg_boxes
724         ; (_, args') <- arg_checker [] [] arg_tys'      -- Yuk
725         ; return (fun', args') }
726
727 ---------------------------
728 tcIdApp :: Name                                 -- Function
729         -> Arity                                -- Number of args reqd
730         -> ArgChecker results   -- The arg-checker guarantees to fill all boxes in the arg types
731         -> BoxyRhoType                          -- Result type
732         -> TcM (HsExpr TcId, results)           
733
734 -- Call         (f e1 ... en) :: res_ty
735 -- Type         f :: forall a b c. theta => fa_1 -> ... -> fa_k -> fres
736 --                      (where k <= n; fres has the rest)
737 -- NB:  if k < n then the function doesn't have enough args, and
738 --      presumably fres is a type variable that we are going to 
739 --      instantiate with a function type
740 --
741 -- Then         fres <= bx_(k+1) -> ... -> bx_n -> res_ty
742
743 tcIdApp fun_name n_args arg_checker res_ty
744   = do  { let orig = OccurrenceOf fun_name
745         ; (fun, fun_ty) <- lookupFun orig fun_name
746
747         -- Split up the function type
748         ; let (tv_theta_prs, rho) = tcMultiSplitSigmaTy fun_ty
749               (fun_arg_tys, fun_res_ty) = tcSplitFunTysN rho n_args
750
751               qtvs = concatMap fst tv_theta_prs         -- Quantified tyvars
752               arg_qtvs = exactTyVarsOfTypes fun_arg_tys
753               res_qtvs = exactTyVarsOfType fun_res_ty
754                 -- NB: exactTyVarsOfType.  See Note [Silly type synonyms in smart-app]
755               tau_qtvs = arg_qtvs `unionVarSet` res_qtvs
756               k              = length fun_arg_tys       -- k <= n_args
757               n_missing_args = n_args - k               -- Always >= 0
758
759         -- Match the result type of the function with the
760         -- result type of the context, to get an inital substitution
761         ; extra_arg_boxes <- newBoxyTyVars (replicate n_missing_args argTypeKind)
762         ; let extra_arg_tys' = mkTyVarTys extra_arg_boxes
763               res_ty'        = mkFunTys extra_arg_tys' res_ty
764         ; qtys' <- preSubType qtvs tau_qtvs fun_res_ty res_ty'
765
766         -- Typecheck the arguments!
767         -- Doing so will fill arg_qtvs and extra_arg_tys'
768         ; (qtys'', args') <- arg_checker qtvs qtys' (fun_arg_tys ++ extra_arg_tys')
769
770         -- Strip boxes from the qtvs that have been filled in by the arg checking
771         ; extra_arg_tys'' <- mapM readFilledBox extra_arg_boxes
772
773         -- Result subsumption
774         -- This fills in res_qtvs
775         ; let res_subst = zipOpenTvSubst qtvs qtys''
776               fun_res_ty'' = substTy res_subst fun_res_ty
777               res_ty'' = mkFunTys extra_arg_tys'' res_ty
778         ; co_fn <- tcSubExp orig fun_res_ty'' res_ty''
779                             
780         -- And pack up the results
781         -- By applying the coercion just to the *function* we can make
782         -- tcFun work nicely for OpApp and Sections too
783         ; fun' <- instFun orig fun res_subst tv_theta_prs
784         ; co_fn' <- wrapFunResCoercion (substTys res_subst fun_arg_tys) co_fn
785         ; traceTc (text "tcIdApp: " <+> ppr (mkHsWrap co_fn' fun') <+> ppr tv_theta_prs <+> ppr co_fn' <+> ppr fun')
786         ; return (mkHsWrap co_fn' fun', args') }
787 \end{code}
788
789 Note [Silly type synonyms in smart-app]
790 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
791 When we call sripBoxyType, all of the boxes should be filled
792 in.  But we need to be careful about type synonyms:
793         type T a = Int
794         f :: T a -> Int
795         ...(f x)...
796 In the call (f x) we'll typecheck x, expecting it to have type
797 (T box).  Usually that would fill in the box, but in this case not;
798 because 'a' is discarded by the silly type synonym T.  So we must
799 use exactTyVarsOfType to figure out which type variables are free 
800 in the argument type.
801
802 \begin{code}
803 -- tcId is a specialisation of tcIdApp when there are no arguments
804 -- tcId f ty = do { (res, _) <- tcIdApp f [] (\[] -> return ()) ty
805 --                ; return res }
806
807 tcId :: InstOrigin
808      -> Name                                    -- Function
809      -> BoxyRhoType                             -- Result type
810      -> TcM (HsExpr TcId)
811 tcId orig fun_name res_ty
812   = do  { (fun, fun_ty) <- lookupFun orig fun_name
813         ; traceTc (text "tcId" <+> ppr fun_name <+> (ppr fun_ty $$ ppr res_ty))
814         
815         -- Split up the function type
816         ; let (tv_theta_prs, fun_tau) = tcMultiSplitSigmaTy fun_ty
817               qtvs = concatMap fst tv_theta_prs         -- Quantified tyvars
818               tau_qtvs = exactTyVarsOfType fun_tau      -- Mentioned in the tau part
819         ; qtv_tys <- preSubType qtvs tau_qtvs fun_tau res_ty
820
821         -- Do the subsumption check wrt the result type
822         ; let res_subst = zipTopTvSubst qtvs qtv_tys
823               fun_tau'  = substTy res_subst fun_tau
824
825         ; traceTc (text "tcId2" <+> ppr fun_name <+> (ppr qtvs $$ ppr qtv_tys))
826
827         ; co_fn <- tcSubExp orig fun_tau' res_ty
828
829         -- And pack up the results
830         ; fun' <- instFun orig fun res_subst tv_theta_prs 
831         ; traceTc (text "tcId yields" <+> ppr (mkHsWrap co_fn fun'))
832         ; return (mkHsWrap co_fn fun') }
833
834 --      Note [Push result type in]
835 --
836 -- Unify with expected result before (was: after) type-checking the args
837 -- so that the info from res_ty (was: args) percolates to args (was actual_res_ty).
838 -- This is when we might detect a too-few args situation.
839 -- (One can think of cases when the opposite order would give
840 -- a better error message.)
841 -- [March 2003: I'm experimenting with putting this first.  Here's an 
842 --              example where it actually makes a real difference
843 --    class C t a b | t a -> b
844 --    instance C Char a Bool
845 --
846 --    data P t a = forall b. (C t a b) => MkP b
847 --    data Q t   = MkQ (forall a. P t a)
848
849 --    f1, f2 :: Q Char;
850 --    f1 = MkQ (MkP True)
851 --    f2 = MkQ (MkP True :: forall a. P Char a)
852 --
853 -- With the change, f1 will type-check, because the 'Char' info from
854 -- the signature is propagated into MkQ's argument. With the check
855 -- in the other order, the extra signature in f2 is reqd.]
856
857 ---------------------------
858 tcSyntaxOp :: InstOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
859 -- Typecheck a syntax operator, checking that it has the specified type
860 -- The operator is always a variable at this stage (i.e. renamer output)
861 tcSyntaxOp orig (HsVar op) ty = tcId orig op ty
862 tcSyntaxOp orig other      ty = pprPanic "tcSyntaxOp" (ppr other)
863
864 ---------------------------
865 instFun :: InstOrigin
866         -> HsExpr TcId
867         -> TvSubst                -- The instantiating substitution
868         -> [([TyVar], ThetaType)] -- Stuff to instantiate
869         -> TcM (HsExpr TcId)    
870
871 instFun orig fun subst []
872   = return fun          -- Common short cut
873
874 instFun orig fun subst tv_theta_prs
875   = do  { let ty_theta_prs' = map subst_pr tv_theta_prs
876         ; traceTc (text "instFun" <+> ppr ty_theta_prs')
877                 -- Make two ad-hoc checks 
878         ; doStupidChecks fun ty_theta_prs'
879
880                 -- Now do normal instantiation
881         ; method_sharing <- doptM Opt_MethodSharing
882         ; result <- go method_sharing True fun ty_theta_prs' 
883         ; traceTc (text "instFun result" <+> ppr result)
884         ; return result
885         }
886   where
887     subst_pr (tvs, theta) 
888         = (substTyVars subst tvs, substTheta subst theta)
889
890     go _ _ fun [] = do {traceTc (text "go _ _ fun [] returns" <+> ppr fun) ; return fun }
891
892     go method_sharing True (HsVar fun_id) ((tys,theta) : prs)
893         | want_method_inst method_sharing theta
894         = do { traceTc (text "go (HsVar fun_id) ((tys,theta) : prs) | want_method_inst theta")
895              ; meth_id <- newMethodWithGivenTy orig fun_id tys
896              ; go method_sharing False (HsVar meth_id) prs }
897                 -- Go round with 'False' to prevent further use
898                 -- of newMethod: see Note [Multiple instantiation]
899
900     go method_sharing _ fun ((tys, theta) : prs)
901         = do { co_fn <- instCall orig tys theta
902              ; traceTc (text "go yields co_fn" <+> ppr co_fn)
903              ; go method_sharing False (HsWrap co_fn fun) prs }
904
905         -- See Note [No method sharing]
906     want_method_inst method_sharing theta =  not (null theta)   -- Overloaded
907                                           && method_sharing
908 \end{code}
909
910 Note [Multiple instantiation]
911 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
912 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
913 For example, consider
914         f :: forall a. Eq a => forall b. Ord b => a -> b
915 At a call to f, at say [Int, Bool], it's tempting to translate the call to 
916
917         f_m1
918   where
919         f_m1 :: forall b. Ord b => Int -> b
920         f_m1 = f Int dEqInt
921
922         f_m2 :: Int -> Bool
923         f_m2 = f_m1 Bool dOrdBool
924
925 But notice that f_m2 has f_m1 as its meth_id.  Now the danger is that if we do
926 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
927         f_m1 = f_mx
928 But it's entirely possible that f_m2 will continue to float out, because it
929 mentions no type variables.  Result, f_m1 isn't in scope.
930
931 Here's a concrete example that does this (test tc200):
932
933     class C a where
934       f :: Eq b => b -> a -> Int
935       baz :: Eq a => Int -> a -> Int
936
937     instance C Int where
938       baz = f
939
940 Current solution: only do the "method sharing" thing for the first type/dict
941 application, not for the iterated ones.  A horribly subtle point.
942
943 Note [No method sharing]
944 ~~~~~~~~~~~~~~~~~~~~~~~~
945 The -fno-method-sharing flag controls what happens so far as the LIE
946 is concerned.  The default case is that for an overloaded function we 
947 generate a "method" Id, and add the Method Inst to the LIE.  So you get
948 something like
949         f :: Num a => a -> a
950         f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
951 If you specify -fno-method-sharing, the dictionary application 
952 isn't shared, so we get
953         f :: Num a => a -> a
954         f = /\a (d:Num a) (x:a) -> (+) a d x x
955 This gets a bit less sharing, but
956         a) it's better for RULEs involving overloaded functions
957         b) perhaps fewer separated lambdas
958
959 Note [Left to right]
960 ~~~~~~~~~~~~~~~~~~~~
961 tcArgs implements a left-to-right order, which goes beyond what is described in the
962 impredicative type inference paper.  In particular, it allows
963         runST $ foo
964 where runST :: (forall s. ST s a) -> a
965 When typechecking the application of ($)::(a->b) -> a -> b, we first check that
966 runST has type (a->b), thereby filling in a=forall s. ST s a.  Then we un-box this type
967 before checking foo.  The left-to-right order really helps here.
968
969 \begin{code}
970 tcArgs :: LHsExpr Name                          -- The function (for error messages)
971        -> [LHsExpr Name]                        -- Actual args
972        -> ArgChecker [LHsExpr TcId]
973
974 type ArgChecker results
975    = [TyVar] -> [TcSigmaType]           -- Current instantiation
976    -> [TcSigmaType]                     -- Expected arg types (**before** applying the instantiation)
977    -> TcM ([TcSigmaType], results)      -- Resulting instaniation and args
978
979 tcArgs fun args qtvs qtys arg_tys
980   = go 1 qtys args arg_tys
981   where
982     go n qtys [] [] = return (qtys, [])
983     go n qtys (arg:args) (arg_ty:arg_tys)
984         = do { arg' <- tcArg fun n arg qtvs qtys arg_ty
985              ; qtys' <- mapM refineBox qtys     -- Exploit new info
986              ; (qtys'', args') <- go (n+1) qtys' args arg_tys
987              ; return (qtys'', arg':args') }
988     go n qtys args arg_tys = panic "tcArgs"
989
990 tcArg :: LHsExpr Name                           -- The function
991       -> Int                                    --   and arg number (for error messages)
992       -> LHsExpr Name
993       -> [TyVar] -> [TcSigmaType]               -- Instantiate the arg type like this
994       -> BoxySigmaType
995       -> TcM (LHsExpr TcId)                     -- Resulting argument
996 tcArg fun arg_no arg qtvs qtys ty
997   = addErrCtxt (funAppCtxt fun arg arg_no) $
998     tcPolyExprNC arg (substTyWith qtvs qtys ty)
999 \end{code}
1000
1001
1002 Note [tagToEnum#]
1003 ~~~~~~~~~~~~~~~~~
1004 Nasty check to ensure that tagToEnum# is applied to a type that is an
1005 enumeration TyCon.  Unification may refine the type later, but this
1006 check won't see that, alas.  It's crude but it works.
1007
1008 Here's are two cases that should fail
1009         f :: forall a. a
1010         f = tagToEnum# 0        -- Can't do tagToEnum# at a type variable
1011
1012         g :: Int
1013         g = tagToEnum# 0        -- Int is not an enumeration
1014
1015
1016 \begin{code}
1017 doStupidChecks :: HsExpr TcId
1018                -> [([TcType], ThetaType)]
1019                -> TcM ()
1020 -- Check two tiresome and ad-hoc cases
1021 -- (a) the "stupid theta" for a data con; add the constraints
1022 --     from the "stupid theta" of a data constructor (sigh)
1023 -- (b) deal with the tagToEnum# problem: see Note [tagToEnum#]
1024
1025 doStupidChecks (HsVar fun_id) ((tys,_):_)
1026   | Just con <- isDataConId_maybe fun_id   -- (a)
1027   = addDataConStupidTheta con tys
1028
1029   | fun_id `hasKey` tagToEnumKey           -- (b)
1030   = do  { tys' <- zonkTcTypes tys
1031         ; checkTc (ok tys') (tagToEnumError tys')
1032         }
1033   where
1034     ok []       = False
1035     ok (ty:tys) = case tcSplitTyConApp_maybe ty of
1036                         Just (tc,_) -> isEnumerationTyCon tc
1037                         Nothing     -> False
1038
1039 doStupidChecks fun tv_theta_prs
1040   = return () -- The common case
1041                                       
1042
1043 tagToEnumError tys
1044   = hang (ptext (sLit "Bad call to tagToEnum#") <+> at_type)
1045          2 (vcat [ptext (sLit "Specify the type by giving a type signature"),
1046                   ptext (sLit "e.g. (tagToEnum# x) :: Bool")])
1047   where
1048     at_type | null tys = empty  -- Probably never happens
1049             | otherwise = ptext (sLit "at type") <+> ppr (head tys)
1050 \end{code}
1051
1052 %************************************************************************
1053 %*                                                                      *
1054 \subsection{@tcId@ typechecks an identifier occurrence}
1055 %*                                                                      *
1056 %************************************************************************
1057
1058 \begin{code}
1059 lookupFun :: InstOrigin -> Name -> TcM (HsExpr TcId, TcType)
1060 lookupFun orig id_name
1061   = do  { thing <- tcLookup id_name
1062         ; case thing of
1063             AGlobal (ADataCon con) -> return (HsVar wrap_id, idType wrap_id)
1064                                    where
1065                                       wrap_id = dataConWrapId con
1066
1067             AGlobal (AnId id) 
1068                 | isNaughtyRecordSelector id -> failWithTc (naughtyRecordSel id)
1069                 | otherwise                  -> return (HsVar id, idType id)
1070                 -- A global cannot possibly be ill-staged
1071                 -- nor does it need the 'lifting' treatment
1072
1073             ATcId { tct_id = id, tct_type = ty, tct_co = mb_co, tct_level = lvl }
1074                 -> do { thLocalId orig id ty lvl
1075                       ; case mb_co of
1076                           Unrefineable    -> return (HsVar id, ty)
1077                           Rigid co        -> return (mkHsWrap co (HsVar id), ty)        
1078                           Wobbly          -> traceTc (text "lookupFun" <+> ppr id) >> return (HsVar id, ty)     -- Wobbly, or no free vars
1079                           WobblyInvisible -> failWithTc (ppr id_name <+> ptext (sLit " not in scope because it has a wobbly type (solution: add a type annotation)"))
1080                       }
1081
1082             other -> failWithTc (ppr other <+> ptext (sLit "used where a value identifer was expected"))
1083     }
1084
1085 #ifndef GHCI  /* GHCI and TH is off */
1086 --------------------------------------
1087 -- thLocalId : Check for cross-stage lifting
1088 thLocalId orig id id_ty th_bind_lvl
1089   = return ()
1090
1091 #else         /* GHCI and TH is on */
1092 thLocalId orig id id_ty th_bind_lvl 
1093   = do  { use_stage <- getStage -- TH case
1094         ; case use_stage of
1095             Brack use_lvl ps_var lie_var | use_lvl > th_bind_lvl
1096                   -> thBrackId orig id ps_var lie_var
1097             other -> do { checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage
1098                         ; return id }
1099         }
1100
1101 --------------------------------------
1102 thBrackId orig id ps_var lie_var
1103   | thTopLevelId id
1104   =     -- Top-level identifiers in this module,
1105         -- (which have External Names)
1106         -- are just like the imported case:
1107         -- no need for the 'lifting' treatment
1108         -- E.g.  this is fine:
1109         --   f x = x
1110         --   g y = [| f 3 |]
1111         -- But we do need to put f into the keep-alive
1112         -- set, because after desugaring the code will
1113         -- only mention f's *name*, not f itself.
1114     do  { keepAliveTc id; return id }
1115
1116   | otherwise
1117   =     -- Nested identifiers, such as 'x' in
1118         -- E.g. \x -> [| h x |]
1119         -- We must behave as if the reference to x was
1120         --      h $(lift x)     
1121         -- We use 'x' itself as the splice proxy, used by 
1122         -- the desugarer to stitch it all back together.
1123         -- If 'x' occurs many times we may get many identical
1124         -- bindings of the same splice proxy, but that doesn't
1125         -- matter, although it's a mite untidy.
1126     do  { let id_ty = idType id
1127         ; checkTc (isTauTy id_ty) (polySpliceErr id)
1128                -- If x is polymorphic, its occurrence sites might
1129                -- have different instantiations, so we can't use plain
1130                -- 'x' as the splice proxy name.  I don't know how to 
1131                -- solve this, and it's probably unimportant, so I'm
1132                -- just going to flag an error for now
1133    
1134         ; id_ty' <- zapToMonotype id_ty
1135                 -- The id_ty might have an OpenTypeKind, but we
1136                 -- can't instantiate the Lift class at that kind,
1137                 -- so we zap it to a LiftedTypeKind monotype
1138                 -- C.f. the call in TcPat.newLitInst
1139
1140         ; setLIEVar lie_var     $ do
1141         { lift <- newMethodFromName orig id_ty' DsMeta.liftName
1142                    -- Put the 'lift' constraint into the right LIE
1143            
1144                    -- Update the pending splices
1145         ; ps <- readMutVar ps_var
1146         ; writeMutVar ps_var ((idName id, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)
1147
1148         ; return id } }
1149 #endif /* GHCI */
1150 \end{code}
1151
1152
1153 %************************************************************************
1154 %*                                                                      *
1155 \subsection{Record bindings}
1156 %*                                                                      *
1157 %************************************************************************
1158
1159 Game plan for record bindings
1160 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1161 1. Find the TyCon for the bindings, from the first field label.
1162
1163 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1164
1165 For each binding field = value
1166
1167 3. Instantiate the field type (from the field label) using the type
1168    envt from step 2.
1169
1170 4  Type check the value using tcArg, passing the field type as 
1171    the expected argument type.
1172
1173 This extends OK when the field types are universally quantified.
1174
1175         
1176 \begin{code}
1177 tcRecordBinds
1178         :: DataCon
1179         -> [TcType]     -- Expected type for each field
1180         -> HsRecordBinds Name
1181         -> TcM (HsRecordBinds TcId)
1182
1183 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1184   = do  { mb_binds <- mapM do_bind rbinds
1185         ; return (HsRecFields (catMaybes mb_binds) dd) }
1186   where
1187     flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1188     do_bind fld@(HsRecField { hsRecFieldId = L loc field_lbl, hsRecFieldArg = rhs })
1189       | Just field_ty <- assocMaybe flds_w_tys field_lbl
1190       = addErrCtxt (fieldCtxt field_lbl)        $
1191         do { rhs' <- tcPolyExprNC rhs field_ty
1192            ; let field_id = mkUserLocal (nameOccName field_lbl)
1193                                         (nameUnique field_lbl)
1194                                         field_ty loc 
1195                 -- Yuk: the field_id has the *unique* of the selector Id
1196                 --          (so we can find it easily)
1197                 --      but is a LocalId with the appropriate type of the RHS
1198                 --          (so the desugarer knows the type of local binder to make)
1199            ; return (Just (fld { hsRecFieldId = L loc field_id, hsRecFieldArg = rhs' })) }
1200       | otherwise
1201       = do { addErrTc (badFieldCon data_con field_lbl)
1202            ; return Nothing }
1203
1204 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1205 checkMissingFields data_con rbinds
1206   | null field_labels   -- Not declared as a record;
1207                         -- But C{} is still valid if no strict fields
1208   = if any isMarkedStrict field_strs then
1209         -- Illegal if any arg is strict
1210         addErrTc (missingStrictFields data_con [])
1211     else
1212         return ()
1213                         
1214   | otherwise = do              -- A record
1215     unless (null missing_s_fields)
1216            (addErrTc (missingStrictFields data_con missing_s_fields))
1217
1218     warn <- doptM Opt_WarnMissingFields
1219     unless (not (warn && notNull missing_ns_fields))
1220            (warnTc True (missingFields data_con missing_ns_fields))
1221
1222   where
1223     missing_s_fields
1224         = [ fl | (fl, str) <- field_info,
1225                  isMarkedStrict str,
1226                  not (fl `elem` field_names_used)
1227           ]
1228     missing_ns_fields
1229         = [ fl | (fl, str) <- field_info,
1230                  not (isMarkedStrict str),
1231                  not (fl `elem` field_names_used)
1232           ]
1233
1234     field_names_used = hsRecFields rbinds
1235     field_labels     = dataConFieldLabels data_con
1236
1237     field_info = zipEqual "missingFields"
1238                           field_labels
1239                           field_strs
1240
1241     field_strs = dataConStrictMarks data_con
1242 \end{code}
1243
1244 %************************************************************************
1245 %*                                                                      *
1246 \subsection{Errors and contexts}
1247 %*                                                                      *
1248 %************************************************************************
1249
1250 Boring and alphabetical:
1251 \begin{code}
1252 addExprErrCtxt :: OutputableBndr id => LHsExpr id -> TcM a -> TcM a
1253 addExprErrCtxt expr = addErrCtxt (exprCtxt (unLoc expr))
1254
1255 exprCtxt expr
1256   = hang (ptext (sLit "In the expression:")) 4 (ppr expr)
1257
1258 fieldCtxt field_name
1259   = ptext (sLit "In the") <+> quotes (ppr field_name) <+> ptext (sLit "field of a record")
1260
1261 funAppCtxt fun arg arg_no
1262   = hang (hsep [ ptext (sLit "In the"), speakNth arg_no, ptext (sLit "argument of"), 
1263                     quotes (ppr fun) <> text ", namely"])
1264          4 (quotes (ppr arg))
1265
1266 badFieldTypes prs
1267   = hang (ptext (sLit "Record update for insufficiently polymorphic field")
1268                          <> plural prs <> colon)
1269        2 (vcat [ ppr f <+> dcolon <+> ppr ty | (f,ty) <- prs ])
1270
1271 badFieldsUpd rbinds
1272   = hang (ptext (sLit "No constructor has all these fields:"))
1273          4 (pprQuotedList (hsRecFields rbinds))
1274
1275 naughtyRecordSel sel_id
1276   = ptext (sLit "Cannot use record selector") <+> quotes (ppr sel_id) <+> 
1277     ptext (sLit "as a function due to escaped type variables") $$ 
1278     ptext (sLit "Probable fix: use pattern-matching syntax instead")
1279
1280 notSelector field
1281   = hsep [quotes (ppr field), ptext (sLit "is not a record selector")]
1282
1283 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1284 missingStrictFields con fields
1285   = header <> rest
1286   where
1287     rest | null fields = empty  -- Happens for non-record constructors 
1288                                 -- with strict fields
1289          | otherwise   = colon <+> pprWithCommas ppr fields
1290
1291     header = ptext (sLit "Constructor") <+> quotes (ppr con) <+> 
1292              ptext (sLit "does not have the required strict field(s)") 
1293           
1294 missingFields :: DataCon -> [FieldLabel] -> SDoc
1295 missingFields con fields
1296   = ptext (sLit "Fields of") <+> quotes (ppr con) <+> ptext (sLit "not initialised:") 
1297         <+> pprWithCommas ppr fields
1298
1299 -- callCtxt fun args = ptext (sLit "In the call") <+> parens (ppr (foldl mkHsApp fun args))
1300
1301 #ifdef GHCI
1302 polySpliceErr :: Id -> SDoc
1303 polySpliceErr id
1304   = ptext (sLit "Can't splice the polymorphic local variable") <+> quotes (ppr id)
1305 #endif
1306 \end{code}