handle stage-(n+1) literals properly by expanding them in the typechecker
[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 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 -- for details
13
14 module TcExpr ( tcPolyExpr, tcPolyExprNC, tcMonoExpr, tcMonoExprNC, 
15                 tcInferRho, tcInferRhoNC, 
16                 tcSyntaxOp, tcCheckId,
17                 addExprErrCtxt ) where
18
19 #include "HsVersions.h"
20
21 #ifdef GHCI     /* Only if bootstrapped */
22 import {-# SOURCE #-}   TcSplice( tcSpliceExpr, tcBracket )
23 import qualified DsMeta
24 #endif
25
26 import HsSyn
27 import TcHsSyn
28 import TcRnMonad
29 import TcUnify
30 import BasicTypes
31 import Inst
32 import TcBinds
33 import TcEnv
34 import TcArrows
35 import TcMatches
36 import TcHsType
37 import TcPat
38 import TcMType
39 import TcType
40 import Id
41 import DataCon
42 import Name
43 import TyCon
44 import Type
45 import TypeRep
46 import Coercion
47 import Var
48 import VarSet
49 import TysWiredIn
50 import TysPrim( intPrimTy )
51 import PrimOp( tagToEnumKey )
52 import PrelNames
53 import Module
54 import DynFlags
55 import SrcLoc
56 import Util
57 import ListSetOps
58 import Maybes
59 import Outputable
60 import FastString
61 import Control.Monad
62 \end{code}
63
64 %************************************************************************
65 %*                                                                      *
66 \subsection{Main wrappers}
67 %*                                                                      *
68 %************************************************************************
69
70 \begin{code}
71 tcPolyExpr, tcPolyExprNC
72          :: LHsExpr Name        -- Expression to type check
73          -> TcSigmaType         -- Expected type (could be a polytpye)
74          -> TcM (LHsExpr TcId)  -- Generalised expr with expected type
75
76 -- tcPolyExpr is a convenient place (frequent but not too frequent)
77 -- place to add context information.
78 -- The NC version does not do so, usually because the caller wants
79 -- to do so himself.
80
81 tcPolyExpr expr res_ty  
82   = addExprErrCtxt expr $
83     do { traceTc "tcPolyExpr" (ppr res_ty); tcPolyExprNC expr res_ty }
84
85 tcPolyExprNC expr res_ty
86   = do { traceTc "tcPolyExprNC" (ppr res_ty)
87        ; (gen_fn, expr') <- tcGen GenSigCtxt res_ty $ \ _ rho ->
88                             tcMonoExprNC expr rho
89        ; return (mkLHsWrap gen_fn expr') }
90
91 ---------------
92 tcMonoExpr, tcMonoExprNC 
93     :: LHsExpr Name      -- Expression to type check
94     -> TcRhoType         -- Expected type (could be a type variable)
95                          -- Definitely no foralls at the top
96     -> TcM (LHsExpr TcId)
97
98 tcMonoExpr expr res_ty
99   = addErrCtxt (exprCtxt expr) $
100     tcMonoExprNC expr res_ty
101
102 tcMonoExprNC (L loc expr) res_ty
103   = ASSERT( not (isSigmaTy res_ty) )
104     setSrcSpan loc $
105     do  { expr' <- tcExpr expr res_ty
106         ; return (L loc expr') }
107
108 ---------------
109 tcInferRho, tcInferRhoNC :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
110 -- Infer a *rho*-type.  This is, in effect, a special case
111 -- for ids and partial applications, so that if
112 --     f :: Int -> (forall a. a -> a) -> Int
113 -- then we can infer
114 --     f 3 :: (forall a. a -> a) -> Int
115 -- And that in turn is useful 
116 --  (a) for the function part of any application (see tcApp)
117 --  (b) for the special rule for '$'
118 tcInferRho expr = addErrCtxt (exprCtxt expr) (tcInferRhoNC expr)
119
120 tcInferRhoNC (L loc expr)
121   = setSrcSpan loc $
122     do { (expr', rho) <- tcInfExpr expr
123        ; return (L loc expr', rho) }
124
125 tcInfExpr :: HsExpr Name -> TcM (HsExpr TcId, TcRhoType)
126 tcInfExpr (HsVar f)     = tcInferId f
127 tcInfExpr (HsPar e)     = do { (e', ty) <- tcInferRhoNC e
128                              ; return (HsPar e', ty) }
129 tcInfExpr (HsApp e1 e2) = tcInferApp e1 [e2]                                  
130 tcInfExpr e             = tcInfer (tcExpr e)
131 \end{code}
132
133
134 %************************************************************************
135 %*                                                                      *
136         tcExpr: the main expression typechecker
137 %*                                                                      *
138 %************************************************************************
139
140 \begin{code}
141
142 updHetMetLevel :: ([TyVar] -> [TyVar]) -> TcM a -> TcM a
143 updHetMetLevel f comp =
144     updEnv
145       (\oldenv -> let oldlev = (case oldenv of Env { env_lcl = e' } -> case e' of TcLclEnv { tcl_hetMetLevel = x } -> x)
146                   in (oldenv { env_lcl = (env_lcl oldenv) { tcl_hetMetLevel = f oldlev } }))
147                   
148       comp
149
150 addEscapes :: [TyVar] -> HsExpr Name -> HsExpr Name
151 addEscapes []     e = e
152 addEscapes (t:ts) e = HsHetMetEsc (TyVarTy t) placeHolderType (noLoc (addEscapes ts e))
153
154 getIdLevel :: Name -> TcM [TyVar]
155 getIdLevel name
156        = do { thing <- tcLookup name
157             ; case thing of
158                  ATcId { tct_hetMetLevel = variable_hetMetLevel } -> return $ variable_hetMetLevel
159                  _ -> return []
160             }
161
162 tcExpr :: HsExpr Name -> TcRhoType -> TcM (HsExpr TcId)
163 tcExpr e res_ty | debugIsOn && isSigmaTy res_ty     -- Sanity check
164                 = pprPanic "tcExpr: sigma" (ppr res_ty $$ ppr e)
165
166 tcExpr (HsVar name)  res_ty = tcCheckId name res_ty
167
168 tcExpr (HsHetMetBrak _ e) res_ty =
169     do { (coi, [inferred_name,elt_ty]) <- matchExpectedTyConApp hetMetCodeTypeTyCon res_ty
170        ; fresh_ec_name <- newFlexiTyVar liftedTypeKind
171        ; expr' <-  updHetMetLevel (\old_lev -> (fresh_ec_name:old_lev))
172                    $ tcPolyExpr e elt_ty
173        ; unifyType (TyVarTy fresh_ec_name) inferred_name
174        ; return $ mkHsWrapCoI coi (HsHetMetBrak (TyVarTy fresh_ec_name) expr') }
175 tcExpr (HsHetMetEsc _ _ e) res_ty =
176     do { cur_level <- getHetMetLevel
177        ; expr' <-  updHetMetLevel (\old_lev -> tail old_lev)
178                    $ tcExpr (unLoc e) (mkTyConApp hetMetCodeTypeTyCon [(TyVarTy $ head cur_level),res_ty])
179        ; ty' <- zonkTcType res_ty
180        ; return $ mkHsWrapCoI (ACo res_ty) (HsHetMetEsc (TyVarTy $ head cur_level) ty' (noLoc expr')) }
181 tcExpr (HsHetMetCSP _ e) res_ty =
182     do { cur_level <- getHetMetLevel
183        ; expr' <-  updHetMetLevel (\old_lev -> tail old_lev)
184                    $ tcExpr (unLoc e) res_ty
185        ; return $ mkHsWrapCoI (ACo res_ty) (HsHetMetCSP (TyVarTy $ head cur_level) (noLoc expr')) }
186
187 tcExpr (HsApp e1 e2) res_ty = tcApp e1 [e2] res_ty
188
189 tcExpr (HsLit lit)   res_ty =
190   getHetMetLevel >>= \lev ->
191    case lev of
192     []        -> do { let lit_ty = hsLitType lit
193                     ; tcWrapResult (HsLit lit) lit_ty res_ty }
194     (ec:rest) -> let n = case lit of
195                                 (HsChar c)       -> hetmet_guest_char_literal_name
196                                 (HsString str)   -> hetmet_guest_string_literal_name
197                                 (HsInteger i _)  -> hetmet_guest_integer_literal_name
198                                 (HsInt i)        -> hetmet_guest_integer_literal_name
199                                 _                -> error "literals of this sort are not allowed at depth >0"
200                  in  tcExpr (HsHetMetEsc (TyVarTy ec) placeHolderType $ noLoc $ HsApp (noLoc $ HsVar n) (noLoc $ HsLit lit)) res_ty
201   
202 tcExpr (HsPar expr)  res_ty = do { expr' <- tcMonoExprNC expr res_ty
203                                  ; return (HsPar expr') }
204
205 tcExpr (HsSCC lbl expr) res_ty 
206   = do { expr' <- tcMonoExpr expr res_ty
207        ; return (HsSCC lbl expr') }
208
209 tcExpr (HsTickPragma info expr) res_ty 
210   = do { expr' <- tcMonoExpr expr res_ty
211        ; return (HsTickPragma info expr') }
212
213 tcExpr (HsCoreAnn lbl expr) res_ty
214   = do  { expr' <- tcMonoExpr expr res_ty
215         ; return (HsCoreAnn lbl expr') }
216
217 tcExpr (HsOverLit lit) res_ty  
218   = do  { lit' <- newOverloadedLit (LiteralOrigin lit) lit res_ty
219         ; return (HsOverLit lit') }
220
221 tcExpr (NegApp expr neg_expr) res_ty
222   = do  { neg_expr' <- tcSyntaxOp NegateOrigin neg_expr
223                                   (mkFunTy res_ty res_ty)
224         ; expr' <- tcMonoExpr expr res_ty
225         ; return (NegApp expr' neg_expr') }
226
227 tcExpr (HsIPVar ip) res_ty
228   = do  { let origin = IPOccOrigin ip
229                 -- Implicit parameters must have a *tau-type* not a 
230                 -- type scheme.  We enforce this by creating a fresh
231                 -- type variable as its type.  (Because res_ty may not
232                 -- be a tau-type.)
233         ; ip_ty <- newFlexiTyVarTy argTypeKind  -- argTypeKind: it can't be an unboxed tuple
234         ; ip_var <- emitWanted origin (mkIPPred ip ip_ty)
235         ; tcWrapResult (HsIPVar (IPName ip_var)) ip_ty res_ty }
236
237 tcExpr (HsLam match) res_ty
238   = do  { (co_fn, match') <- tcMatchLambda match res_ty
239         ; return (mkHsWrap co_fn (HsLam match')) }
240
241 tcExpr (ExprWithTySig expr sig_ty) res_ty
242  = do { sig_tc_ty <- tcHsSigType ExprSigCtxt sig_ty
243
244       -- Remember to extend the lexical type-variable environment
245       ; (gen_fn, expr') 
246             <- tcGen ExprSigCtxt sig_tc_ty $ \ skol_tvs res_ty ->
247                tcExtendTyVarEnv2 (hsExplicitTvs sig_ty `zip` mkTyVarTys skol_tvs) $
248                                 -- See Note [More instantiated than scoped] in TcBinds
249                tcMonoExprNC expr res_ty
250
251       ; let inner_expr = ExprWithTySigOut (mkLHsWrap gen_fn expr') sig_ty
252
253       ; (inst_wrap, rho) <- deeplyInstantiate ExprSigOrigin sig_tc_ty
254       ; tcWrapResult (mkHsWrap inst_wrap inner_expr) rho res_ty }
255
256 tcExpr (HsType ty) _
257   = failWithTc (text "Can't handle type argument:" <+> ppr ty)
258         -- This is the syntax for type applications that I was planning
259         -- but there are difficulties (e.g. what order for type args)
260         -- so it's not enabled yet.
261         -- Can't eliminate it altogether from the parser, because the
262         -- same parser parses *patterns*.
263 \end{code}
264
265
266 %************************************************************************
267 %*                                                                      *
268                 Infix operators and sections
269 %*                                                                      *
270 %************************************************************************
271
272 Note [Left sections]
273 ~~~~~~~~~~~~~~~~~~~~
274 Left sections, like (4 *), are equivalent to
275         \ x -> (*) 4 x,
276 or, if PostfixOperators is enabled, just
277         (*) 4
278 With PostfixOperators we don't actually require the function to take
279 two arguments at all.  For example, (x `not`) means (not x); you get
280 postfix operators!  Not Haskell 98, but it's less work and kind of
281 useful.
282
283 Note [Typing rule for ($)]
284 ~~~~~~~~~~~~~~~~~~~~~~~~~~
285 People write 
286    runST $ blah
287 so much, where 
288    runST :: (forall s. ST s a) -> a
289 that I have finally given in and written a special type-checking
290 rule just for saturated appliations of ($).  
291   * Infer the type of the first argument
292   * Decompose it; should be of form (arg2_ty -> res_ty), 
293        where arg2_ty might be a polytype
294   * Use arg2_ty to typecheck arg2
295
296 Note [Typing rule for seq]
297 ~~~~~~~~~~~~~~~~~~~~~~~~~~
298 We want to allow
299        x `seq` (# p,q #)
300 which suggests this type for seq:
301    seq :: forall (a:*) (b:??). a -> b -> b, 
302 with (b:??) meaning that be can be instantiated with an unboxed tuple.
303 But that's ill-kinded!  Function arguments can't be unboxed tuples.
304 And indeed, you could not expect to do this with a partially-applied
305 'seq'; it's only going to work when it's fully applied.  so it turns
306 into 
307     case x of _ -> (# p,q #)
308
309 For a while I slid by by giving 'seq' an ill-kinded type, but then
310 the simplifier eta-reduced an application of seq and Lint blew up 
311 with a kind error.  It seems more uniform to treat 'seq' as it it
312 was a language construct.  
313
314 See Note [seqId magic] in MkId, and 
315
316
317 \begin{code}
318 tcExpr (OpApp arg1 op fix arg2) res_ty
319   | (L loc (HsVar op_name)) <- op
320   , op_name `hasKey` seqIdKey           -- Note [Typing rule for seq]
321   = do { arg1_ty <- newFlexiTyVarTy liftedTypeKind
322        ; let arg2_ty = res_ty
323        ; arg1' <- tcArg op (arg1, arg1_ty, 1)
324        ; arg2' <- tcArg op (arg2, arg2_ty, 2)
325        ; op_id <- tcLookupId op_name
326        ; let op' = L loc (HsWrap (mkWpTyApps [arg1_ty, arg2_ty]) (HsVar op_id))
327        ; return $ OpApp arg1' op' fix arg2' }
328
329   | (L loc (HsVar op_name)) <- op
330   , op_name `hasKey` dollarIdKey        -- Note [Typing rule for ($)]
331   = do { traceTc "Application rule" (ppr op)
332        ; (arg1', arg1_ty) <- tcInferRho arg1
333        ; let doc = ptext (sLit "The first argument of ($) takes")
334        ; (co_arg1, [arg2_ty], op_res_ty) <- matchExpectedFunTys doc 1 arg1_ty
335          -- arg2_ty maybe polymorphic; that's the point
336        ; arg2' <- tcArg op (arg2, arg2_ty, 2)
337        ; co_res <- unifyType op_res_ty res_ty
338        ; op_id <- tcLookupId op_name
339        ; let op' = L loc (HsWrap (mkWpTyApps [arg2_ty, op_res_ty]) (HsVar op_id))
340        ; return $ mkHsWrapCoI co_res $
341          OpApp (mkLHsWrapCoI co_arg1 arg1') op' fix arg2' }
342
343   | otherwise
344   = do { traceTc "Non Application rule" (ppr op)
345        ; (op', op_ty) <- tcInferFun op
346        ; (co_fn, arg_tys, op_res_ty) <- unifyOpFunTys op 2 op_ty
347        ; co_res <- unifyType op_res_ty res_ty
348        ; [arg1', arg2'] <- tcArgs op [arg1, arg2] arg_tys
349        ; return $ mkHsWrapCoI co_res $
350          OpApp arg1' (mkLHsWrapCoI co_fn op') fix arg2' }
351
352 -- Right sections, equivalent to \ x -> x `op` expr, or
353 --      \ x -> op x expr
354  
355 tcExpr (SectionR op arg2) res_ty
356   = do { (op', op_ty) <- tcInferFun op
357        ; (co_fn, [arg1_ty, arg2_ty], op_res_ty) <- unifyOpFunTys op 2 op_ty
358        ; co_res <- unifyType (mkFunTy arg1_ty op_res_ty) res_ty
359        ; arg2' <- tcArg op (arg2, arg2_ty, 2)
360        ; return $ mkHsWrapCoI co_res $
361          SectionR (mkLHsWrapCoI co_fn op') arg2' } 
362
363 tcExpr (SectionL arg1 op) res_ty
364   = do { (op', op_ty) <- tcInferFun op
365        ; dflags <- getDOpts         -- Note [Left sections]
366        ; let n_reqd_args | xopt Opt_PostfixOperators dflags = 1
367                          | otherwise                        = 2
368
369        ; (co_fn, (arg1_ty:arg_tys), op_res_ty) <- unifyOpFunTys op n_reqd_args op_ty
370        ; co_res <- unifyType (mkFunTys arg_tys op_res_ty) res_ty
371        ; arg1' <- tcArg op (arg1, arg1_ty, 1)
372        ; return $ mkHsWrapCoI co_res $
373          SectionL arg1' (mkLHsWrapCoI co_fn op') }
374
375 tcExpr (ExplicitTuple tup_args boxity) res_ty
376   | all tupArgPresent tup_args
377   = do { let tup_tc = tupleTyCon boxity (length tup_args)
378        ; (coi, arg_tys) <- matchExpectedTyConApp tup_tc res_ty
379        ; tup_args1 <- tcTupArgs tup_args arg_tys
380        ; return $ mkHsWrapCoI coi (ExplicitTuple tup_args1 boxity) }
381     
382   | otherwise
383   = -- The tup_args are a mixture of Present and Missing (for tuple sections)
384     do { let kind = case boxity of { Boxed   -> liftedTypeKind
385                                    ; Unboxed -> argTypeKind }
386              arity = length tup_args 
387              tup_tc = tupleTyCon boxity arity
388
389        ; arg_tys <- newFlexiTyVarTys (tyConArity tup_tc) kind
390        ; let actual_res_ty
391                  = mkFunTys [ty | (ty, Missing _) <- arg_tys `zip` tup_args]
392                             (mkTyConApp tup_tc arg_tys)
393
394        ; coi <- unifyType actual_res_ty res_ty
395
396        -- Handle tuple sections where
397        ; tup_args1 <- tcTupArgs tup_args arg_tys
398        
399        ; return $ mkHsWrapCoI coi (ExplicitTuple tup_args1 boxity) }
400
401 tcExpr (ExplicitList _ exprs) res_ty
402   = do  { (coi, elt_ty) <- matchExpectedListTy res_ty
403         ; exprs' <- mapM (tc_elt elt_ty) exprs
404         ; return $ mkHsWrapCoI coi (ExplicitList elt_ty exprs') }
405   where
406     tc_elt elt_ty expr = tcPolyExpr expr elt_ty
407
408 tcExpr (ExplicitPArr _ exprs) res_ty    -- maybe empty
409   = do  { (coi, elt_ty) <- matchExpectedPArrTy res_ty
410         ; exprs' <- mapM (tc_elt elt_ty) exprs  
411         ; return $ mkHsWrapCoI coi (ExplicitPArr elt_ty exprs') }
412   where
413     tc_elt elt_ty expr = tcPolyExpr expr elt_ty
414 \end{code}
415
416 %************************************************************************
417 %*                                                                      *
418                 Let, case, if, do
419 %*                                                                      *
420 %************************************************************************
421
422 \begin{code}
423 tcExpr (HsLet binds expr) res_ty
424   = do  { (binds', expr') <- tcLocalBinds binds $
425                              tcMonoExpr expr res_ty   
426         ; return (HsLet binds' expr') }
427
428 tcExpr (HsCase scrut matches) exp_ty
429   = do  {  -- We used to typecheck the case alternatives first.
430            -- The case patterns tend to give good type info to use
431            -- when typechecking the scrutinee.  For example
432            --   case (map f) of
433            --     (x:xs) -> ...
434            -- will report that map is applied to too few arguments
435            --
436            -- But now, in the GADT world, we need to typecheck the scrutinee
437            -- first, to get type info that may be refined in the case alternatives
438           (scrut', scrut_ty) <- tcInferRho scrut
439
440         ; traceTc "HsCase" (ppr scrut_ty)
441         ; matches' <- tcMatchesCase match_ctxt scrut_ty matches exp_ty
442         ; return (HsCase scrut' matches') }
443  where
444     match_ctxt = MC { mc_what = CaseAlt,
445                       mc_body = tcBody }
446
447 tcExpr (HsIf Nothing pred b1 b2) res_ty    -- Ordinary 'if'
448   = do { pred' <- tcMonoExpr pred boolTy
449        ; b1' <- tcMonoExpr b1 res_ty
450        ; b2' <- tcMonoExpr b2 res_ty
451        ; return (HsIf Nothing pred' b1' b2') }
452
453 tcExpr (HsIf (Just fun) pred b1 b2) res_ty   -- Note [Rebindable syntax for if]
454   = do { pred_ty <- newFlexiTyVarTy openTypeKind
455        ; b1_ty   <- newFlexiTyVarTy openTypeKind
456        ; b2_ty   <- newFlexiTyVarTy openTypeKind
457        ; let if_ty = mkFunTys [pred_ty, b1_ty, b2_ty] res_ty
458        ; fun'  <- tcSyntaxOp IfOrigin fun if_ty
459        ; pred' <- tcMonoExpr pred pred_ty
460        ; b1'   <- tcMonoExpr b1 b1_ty
461        ; b2'   <- tcMonoExpr b2 b2_ty
462        -- Fundamentally we are just typing (ifThenElse e1 e2 e3)
463        -- so maybe we should use the code for function applications
464        -- (which would allow ifThenElse to be higher rank).
465        -- But it's a little awkward, so I'm leaving it alone for now
466        -- and it maintains uniformity with other rebindable syntax
467        ; return (HsIf (Just fun') pred' b1' b2') }
468
469 tcExpr (HsDo do_or_lc stmts body _) res_ty
470   = tcDoStmts do_or_lc stmts body res_ty
471
472 tcExpr (HsProc pat cmd) res_ty
473   = do  { (pat', cmd', coi) <- tcProc pat cmd res_ty
474         ; return $ mkHsWrapCoI coi (HsProc pat' cmd') }
475
476 tcExpr e@(HsArrApp _ _ _ _ _) _
477   = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e), 
478                       ptext (sLit "was found where an expression was expected")])
479
480 tcExpr e@(HsArrForm _ _ _) _
481   = failWithTc (vcat [ptext (sLit "The arrow command"), nest 2 (ppr e), 
482                       ptext (sLit "was found where an expression was expected")])
483 \end{code}
484
485 Note [Rebindable syntax for if]
486 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
487 The rebindable syntax for 'if' uses the most flexible possible type
488 for conditionals:
489   ifThenElse :: p -> b1 -> b2 -> res
490 to support expressions like this:
491
492  ifThenElse :: Maybe a -> (a -> b) -> b -> b
493  ifThenElse (Just a) f _ = f a  ifThenElse Nothing  _ e = e
494
495  example :: String
496  example = if Just 2
497               then \v -> show v
498               else "No value"
499
500
501 %************************************************************************
502 %*                                                                      *
503                 Record construction and update
504 %*                                                                      *
505 %************************************************************************
506
507 \begin{code}
508 tcExpr (RecordCon (L loc con_name) _ rbinds) res_ty
509   = do  { data_con <- tcLookupDataCon con_name
510
511         -- Check for missing fields
512         ; checkMissingFields data_con rbinds
513
514         ; (con_expr, con_tau) <- tcInferId con_name
515         ; let arity = dataConSourceArity data_con
516               (arg_tys, actual_res_ty) = tcSplitFunTysN con_tau arity
517               con_id = dataConWrapId data_con
518
519         ; co_res <- unifyType actual_res_ty res_ty
520         ; rbinds' <- tcRecordBinds data_con arg_tys rbinds
521         ; return $ mkHsWrapCoI co_res $ 
522           RecordCon (L loc con_id) con_expr rbinds' } 
523 \end{code}
524
525 Note [Type of a record update]
526 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
527 The main complication with RecordUpd is that we need to explicitly
528 handle the *non-updated* fields.  Consider:
529
530         data T a b c = MkT1 { fa :: a, fb :: (b,c) }
531                      | MkT2 { fa :: a, fb :: (b,c), fc :: c -> c }
532                      | MkT3 { fd :: a }
533         
534         upd :: T a b c -> (b',c) -> T a b' c
535         upd t x = t { fb = x}
536
537 The result type should be (T a b' c)
538 not (T a b c),   because 'b' *is not* mentioned in a non-updated field
539 not (T a b' c'), becuase 'c' *is*     mentioned in a non-updated field
540 NB that it's not good enough to look at just one constructor; we must
541 look at them all; cf Trac #3219
542
543 After all, upd should be equivalent to:
544         upd t x = case t of 
545                         MkT1 p q -> MkT1 p x
546                         MkT2 a b -> MkT2 p b
547                         MkT3 d   -> error ...
548
549 So we need to give a completely fresh type to the result record,
550 and then constrain it by the fields that are *not* updated ("p" above).
551 We call these the "fixed" type variables, and compute them in getFixedTyVars.
552
553 Note that because MkT3 doesn't contain all the fields being updated,
554 its RHS is simply an error, so it doesn't impose any type constraints.
555 Hence the use of 'relevant_cont'.
556
557 Note [Implict type sharing]
558 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
559 We also take into account any "implicit" non-update fields.  For example
560         data T a b where { MkT { f::a } :: T a a; ... }
561 So the "real" type of MkT is: forall ab. (a~b) => a -> T a b
562
563 Then consider
564         upd t x = t { f=x }
565 We infer the type
566         upd :: T a b -> a -> T a b
567         upd (t::T a b) (x::a)
568            = case t of { MkT (co:a~b) (_:a) -> MkT co x }
569 We can't give it the more general type
570         upd :: T a b -> c -> T c b
571
572 Note [Criteria for update]
573 ~~~~~~~~~~~~~~~~~~~~~~~~~~
574 We want to allow update for existentials etc, provided the updated
575 field isn't part of the existential. For example, this should be ok.
576   data T a where { MkT { f1::a, f2::b->b } :: T a }
577   f :: T a -> b -> T b
578   f t b = t { f1=b }
579
580 The criterion we use is this:
581
582   The types of the updated fields
583   mention only the universally-quantified type variables
584   of the data constructor
585
586 NB: this is not (quite) the same as being a "naughty" record selector
587 (See Note [Naughty record selectors]) in TcTyClsDecls), at least 
588 in the case of GADTs. Consider
589    data T a where { MkT :: { f :: a } :: T [a] }
590 Then f is not "naughty" because it has a well-typed record selector.
591 But we don't allow updates for 'f'.  (One could consider trying to
592 allow this, but it makes my head hurt.  Badly.  And no one has asked
593 for it.)
594
595 In principle one could go further, and allow
596   g :: T a -> T a
597   g t = t { f2 = \x -> x }
598 because the expression is polymorphic...but that seems a bridge too far.
599
600 Note [Data family example]
601 ~~~~~~~~~~~~~~~~~~~~~~~~~~
602     data instance T (a,b) = MkT { x::a, y::b }
603   --->
604     data :TP a b = MkT { a::a, y::b }
605     coTP a b :: T (a,b) ~ :TP a b
606
607 Suppose r :: T (t1,t2), e :: t3
608 Then  r { x=e } :: T (t3,t1)
609   --->
610       case r |> co1 of
611         MkT x y -> MkT e y |> co2
612       where co1 :: T (t1,t2) ~ :TP t1 t2
613             co2 :: :TP t3 t2 ~ T (t3,t2)
614 The wrapping with co2 is done by the constructor wrapper for MkT
615
616 Outgoing invariants
617 ~~~~~~~~~~~~~~~~~~~
618 In the outgoing (HsRecordUpd scrut binds cons in_inst_tys out_inst_tys):
619
620   * cons are the data constructors to be updated
621
622   * in_inst_tys, out_inst_tys have same length, and instantiate the
623         *representation* tycon of the data cons.  In Note [Data 
624         family example], in_inst_tys = [t1,t2], out_inst_tys = [t3,t2]
625         
626 \begin{code}
627 tcExpr (RecordUpd record_expr rbinds _ _ _) res_ty
628   = ASSERT( notNull upd_fld_names )
629     do  {
630         -- STEP 0
631         -- Check that the field names are really field names
632         ; sel_ids <- mapM tcLookupField upd_fld_names
633                         -- The renamer has already checked that
634                         -- selectors are all in scope
635         ; let bad_guys = [ setSrcSpan loc $ addErrTc (notSelector fld_name) 
636                          | (fld, sel_id) <- rec_flds rbinds `zip` sel_ids,
637                            not (isRecordSelector sel_id),       -- Excludes class ops
638                            let L loc fld_name = hsRecFieldId fld ]
639         ; unless (null bad_guys) (sequence bad_guys >> failM)
640     
641         -- STEP 1
642         -- Figure out the tycon and data cons from the first field name
643         ; let   -- It's OK to use the non-tc splitters here (for a selector)
644               sel_id : _  = sel_ids
645               (tycon, _)  = recordSelectorFieldLabel sel_id     -- We've failed already if
646               data_cons   = tyConDataCons tycon                 -- it's not a field label
647                 -- NB: for a data type family, the tycon is the instance tycon
648
649               relevant_cons   = filter is_relevant data_cons
650               is_relevant con = all (`elem` dataConFieldLabels con) upd_fld_names
651                 -- A constructor is only relevant to this process if
652                 -- it contains *all* the fields that are being updated
653                 -- Other ones will cause a runtime error if they occur
654
655                 -- Take apart a representative constructor
656               con1 = ASSERT( not (null relevant_cons) ) head relevant_cons
657               (con1_tvs, _, _, _, _, con1_arg_tys, _) = dataConFullSig con1
658               con1_flds = dataConFieldLabels con1
659               con1_res_ty = mkFamilyTyConApp tycon (mkTyVarTys con1_tvs)
660               
661         -- Step 2
662         -- Check that at least one constructor has all the named fields
663         -- i.e. has an empty set of bad fields returned by badFields
664         ; checkTc (not (null relevant_cons)) (badFieldsUpd rbinds)
665
666         -- STEP 3    Note [Criteria for update]
667         -- Check that each updated field is polymorphic; that is, its type
668         -- mentions only the universally-quantified variables of the data con
669         ; let flds1_w_tys = zipEqual "tcExpr:RecConUpd" con1_flds con1_arg_tys
670               upd_flds1_w_tys = filter is_updated flds1_w_tys
671               is_updated (fld,_) = fld `elem` upd_fld_names
672
673               bad_upd_flds = filter bad_fld upd_flds1_w_tys
674               con1_tv_set = mkVarSet con1_tvs
675               bad_fld (fld, ty) = fld `elem` upd_fld_names &&
676                                       not (tyVarsOfType ty `subVarSet` con1_tv_set)
677         ; checkTc (null bad_upd_flds) (badFieldTypes bad_upd_flds)
678
679         -- STEP 4  Note [Type of a record update]
680         -- Figure out types for the scrutinee and result
681         -- Both are of form (T a b c), with fresh type variables, but with
682         -- common variables where the scrutinee and result must have the same type
683         -- These are variables that appear in *any* arg of *any* of the
684         -- relevant constructors *except* in the updated fields
685         -- 
686         ; let fixed_tvs = getFixedTyVars con1_tvs relevant_cons
687               is_fixed_tv tv = tv `elemVarSet` fixed_tvs
688               mk_inst_ty tv result_inst_ty 
689                 | is_fixed_tv tv = return result_inst_ty            -- Same as result type
690                 | otherwise      = newFlexiTyVarTy (tyVarKind tv)  -- Fresh type, of correct kind
691
692         ; (_, result_inst_tys, result_inst_env) <- tcInstTyVars con1_tvs
693         ; scrut_inst_tys <- zipWithM mk_inst_ty con1_tvs result_inst_tys
694
695         ; let rec_res_ty    = substTy result_inst_env con1_res_ty
696               con1_arg_tys' = map (substTy result_inst_env) con1_arg_tys
697               scrut_subst   = zipTopTvSubst con1_tvs scrut_inst_tys
698               scrut_ty      = substTy scrut_subst con1_res_ty
699
700         ; co_res <- unifyType rec_res_ty res_ty
701
702         -- STEP 5
703         -- Typecheck the thing to be updated, and the bindings
704         ; record_expr' <- tcMonoExpr record_expr scrut_ty
705         ; rbinds'      <- tcRecordBinds con1 con1_arg_tys' rbinds
706         
707         -- STEP 6: Deal with the stupid theta
708         ; let theta' = substTheta scrut_subst (dataConStupidTheta con1)
709         ; instStupidTheta RecordUpdOrigin theta'
710
711         -- Step 7: make a cast for the scrutinee, in the case that it's from a type family
712         ; let scrut_co | Just co_con <- tyConFamilyCoercion_maybe tycon 
713                        = WpCast $ mkTyConApp co_con scrut_inst_tys
714                        | otherwise
715                        = idHsWrapper
716         -- Phew!
717         ; return $ mkHsWrapCoI co_res $
718           RecordUpd (mkLHsWrap scrut_co record_expr') rbinds'
719                                    relevant_cons scrut_inst_tys result_inst_tys  }
720   where
721     upd_fld_names = hsRecFields rbinds
722
723     getFixedTyVars :: [TyVar] -> [DataCon] -> TyVarSet
724     -- These tyvars must not change across the updates
725     getFixedTyVars tvs1 cons
726       = mkVarSet [tv1 | con <- cons
727                       , let (tvs, theta, arg_tys, _) = dataConSig con
728                             flds = dataConFieldLabels con
729                             fixed_tvs = exactTyVarsOfTypes fixed_tys
730                                     -- fixed_tys: See Note [Type of a record update]
731                                         `unionVarSet` tyVarsOfTheta theta 
732                                     -- Universally-quantified tyvars that
733                                     -- appear in any of the *implicit*
734                                     -- arguments to the constructor are fixed
735                                     -- See Note [Implict type sharing]
736                                         
737                             fixed_tys = [ty | (fld,ty) <- zip flds arg_tys
738                                             , not (fld `elem` upd_fld_names)]
739                       , (tv1,tv) <- tvs1 `zip` tvs      -- Discards existentials in tvs
740                       , tv `elemVarSet` fixed_tvs ]
741 \end{code}
742
743 %************************************************************************
744 %*                                                                      *
745         Arithmetic sequences                    e.g. [a,b..]
746         and their parallel-array counterparts   e.g. [: a,b.. :]
747                 
748 %*                                                                      *
749 %************************************************************************
750
751 \begin{code}
752 tcExpr (ArithSeq _ seq@(From expr)) res_ty
753   = do  { (coi, elt_ty) <- matchExpectedListTy res_ty
754         ; expr' <- tcPolyExpr expr elt_ty
755         ; enum_from <- newMethodFromName (ArithSeqOrigin seq) 
756                               enumFromName elt_ty 
757         ; return $ mkHsWrapCoI coi (ArithSeq enum_from (From expr')) }
758
759 tcExpr (ArithSeq _ seq@(FromThen expr1 expr2)) res_ty
760   = do  { (coi, elt_ty) <- matchExpectedListTy res_ty
761         ; expr1' <- tcPolyExpr expr1 elt_ty
762         ; expr2' <- tcPolyExpr expr2 elt_ty
763         ; enum_from_then <- newMethodFromName (ArithSeqOrigin seq) 
764                               enumFromThenName elt_ty 
765         ; return $ mkHsWrapCoI coi 
766                     (ArithSeq enum_from_then (FromThen expr1' expr2')) }
767
768 tcExpr (ArithSeq _ seq@(FromTo expr1 expr2)) res_ty
769   = do  { (coi, elt_ty) <- matchExpectedListTy res_ty
770         ; expr1' <- tcPolyExpr expr1 elt_ty
771         ; expr2' <- tcPolyExpr expr2 elt_ty
772         ; enum_from_to <- newMethodFromName (ArithSeqOrigin seq) 
773                               enumFromToName elt_ty 
774         ; return $ mkHsWrapCoI coi 
775                      (ArithSeq enum_from_to (FromTo expr1' expr2')) }
776
777 tcExpr (ArithSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
778   = do  { (coi, elt_ty) <- matchExpectedListTy res_ty
779         ; expr1' <- tcPolyExpr expr1 elt_ty
780         ; expr2' <- tcPolyExpr expr2 elt_ty
781         ; expr3' <- tcPolyExpr expr3 elt_ty
782         ; eft <- newMethodFromName (ArithSeqOrigin seq) 
783                       enumFromThenToName elt_ty 
784         ; return $ mkHsWrapCoI coi 
785                      (ArithSeq eft (FromThenTo expr1' expr2' expr3')) }
786
787 tcExpr (PArrSeq _ seq@(FromTo expr1 expr2)) res_ty
788   = do  { (coi, elt_ty) <- matchExpectedPArrTy res_ty
789         ; expr1' <- tcPolyExpr expr1 elt_ty
790         ; expr2' <- tcPolyExpr expr2 elt_ty
791         ; enum_from_to <- newMethodFromName (PArrSeqOrigin seq) 
792                                  (enumFromToPName basePackageId) elt_ty    -- !!!FIXME: chak
793         ; return $ mkHsWrapCoI coi 
794                      (PArrSeq enum_from_to (FromTo expr1' expr2')) }
795
796 tcExpr (PArrSeq _ seq@(FromThenTo expr1 expr2 expr3)) res_ty
797   = do  { (coi, elt_ty) <- matchExpectedPArrTy res_ty
798         ; expr1' <- tcPolyExpr expr1 elt_ty
799         ; expr2' <- tcPolyExpr expr2 elt_ty
800         ; expr3' <- tcPolyExpr expr3 elt_ty
801         ; eft <- newMethodFromName (PArrSeqOrigin seq)
802                       (enumFromThenToPName basePackageId) elt_ty        -- !!!FIXME: chak
803         ; return $ mkHsWrapCoI coi 
804                      (PArrSeq eft (FromThenTo expr1' expr2' expr3')) }
805
806 tcExpr (PArrSeq _ _) _ 
807   = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
808     -- the parser shouldn't have generated it and the renamer shouldn't have
809     -- let it through
810 \end{code}
811
812
813 %************************************************************************
814 %*                                                                      *
815                 Template Haskell
816 %*                                                                      *
817 %************************************************************************
818
819 \begin{code}
820 #ifdef GHCI     /* Only if bootstrapped */
821         -- Rename excludes these cases otherwise
822 tcExpr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
823 tcExpr (HsBracket brack)  res_ty = do   { e <- tcBracket brack res_ty
824                                         ; return (unLoc e) }
825 tcExpr e@(HsQuasiQuoteE _) _ =
826     pprPanic "Should never see HsQuasiQuoteE in type checker" (ppr e)
827 #endif /* GHCI */
828 \end{code}
829
830
831 %************************************************************************
832 %*                                                                      *
833                 Catch-all
834 %*                                                                      *
835 %************************************************************************
836
837 \begin{code}
838 tcExpr other _ = pprPanic "tcMonoExpr" (ppr other)
839 \end{code}
840
841
842 %************************************************************************
843 %*                                                                      *
844                 Applications
845 %*                                                                      *
846 %************************************************************************
847
848 \begin{code}
849 tcApp :: LHsExpr Name -> [LHsExpr Name] -- Function and args
850       -> TcRhoType -> TcM (HsExpr TcId) -- Translated fun and args
851
852 tcApp (L _ (HsPar e)) args res_ty
853   = tcApp e args res_ty
854
855 tcApp (L _ (HsApp e1 e2)) args res_ty
856   = tcApp e1 (e2:args) res_ty   -- Accumulate the arguments
857
858 tcApp (L loc (HsVar fun)) args res_ty
859   | fun `hasKey` tagToEnumKey
860   , [arg] <- args
861   = tcTagToEnum loc fun arg res_ty
862
863 tcApp fun args res_ty
864   = do  {   -- Type-check the function
865         ; (fun1, fun_tau) <- tcInferFun fun
866
867             -- Extract its argument types
868         ; (co_fun, expected_arg_tys, actual_res_ty)
869               <- matchExpectedFunTys (mk_app_msg fun) (length args) fun_tau
870
871         -- Typecheck the result, thereby propagating 
872         -- info (if any) from result into the argument types
873         -- Both actual_res_ty and res_ty are deeply skolemised
874         ; co_res <- addErrCtxt (funResCtxt fun) $
875                     unifyType actual_res_ty res_ty
876
877         -- Typecheck the arguments
878         ; args1 <- tcArgs fun args expected_arg_tys
879
880         -- Assemble the result
881         ; let fun2 = mkLHsWrapCoI co_fun fun1
882               app  = mkLHsWrapCoI co_res (foldl mkHsApp fun2 args1)
883
884         ; return (unLoc app) }
885
886
887 mk_app_msg :: LHsExpr Name -> SDoc
888 mk_app_msg fun = sep [ ptext (sLit "The function") <+> quotes (ppr fun)
889                      , ptext (sLit "is applied to")]
890
891 ----------------
892 tcInferApp :: LHsExpr Name -> [LHsExpr Name] -- Function and args
893            -> TcM (HsExpr TcId, TcRhoType) -- Translated fun and args
894
895 tcInferApp (L _ (HsPar e))     args = tcInferApp e args
896 tcInferApp (L _ (HsApp e1 e2)) args = tcInferApp e1 (e2:args)
897 tcInferApp fun args
898   = -- Very like the tcApp version, except that there is
899     -- no expected result type passed in
900     do  { (fun1, fun_tau) <- tcInferFun fun
901         ; (co_fun, expected_arg_tys, actual_res_ty)
902               <- matchExpectedFunTys (mk_app_msg fun) (length args) fun_tau
903         ; args1 <- tcArgs fun args expected_arg_tys
904         ; let fun2 = mkLHsWrapCoI co_fun fun1
905               app  = foldl mkHsApp fun2 args1
906         ; return (unLoc app, actual_res_ty) }
907
908 ----------------
909 tcInferFun :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
910 -- Infer and instantiate the type of a function
911 tcInferFun (L loc (HsVar name)) 
912   = do { (fun, ty) <- setSrcSpan loc (tcInferId name)
913                -- Don't wrap a context around a plain Id
914        ; return (L loc fun, ty) }
915
916 tcInferFun fun
917   = do { (fun, fun_ty) <- tcInfer (tcMonoExpr fun)
918
919          -- Zonk the function type carefully, to expose any polymorphism
920          -- E.g. (( \(x::forall a. a->a). blah ) e)
921          -- We can see the rank-2 type of the lambda in time to genrealise e
922        ; fun_ty' <- zonkTcTypeCarefully fun_ty
923
924        ; (wrap, rho) <- deeplyInstantiate AppOrigin fun_ty'
925        ; return (mkLHsWrap wrap fun, rho) }
926
927 ----------------
928 tcArgs :: LHsExpr Name                          -- The function (for error messages)
929        -> [LHsExpr Name] -> [TcSigmaType]       -- Actual arguments and expected arg types
930        -> TcM [LHsExpr TcId]                    -- Resulting args
931
932 tcArgs fun args expected_arg_tys
933   = mapM (tcArg fun) (zip3 args expected_arg_tys [1..])
934
935 ----------------
936 tcArg :: LHsExpr Name                           -- The function (for error messages)
937        -> (LHsExpr Name, TcSigmaType, Int)      -- Actual argument and expected arg type
938        -> TcM (LHsExpr TcId)                    -- Resulting argument
939 tcArg fun (arg, ty, arg_no) = addErrCtxt (funAppCtxt fun arg arg_no)
940                                          (tcPolyExprNC arg ty)
941
942 ----------------
943 tcTupArgs :: [HsTupArg Name] -> [TcSigmaType] -> TcM [HsTupArg TcId]
944 tcTupArgs args tys 
945   = ASSERT( equalLength args tys ) mapM go (args `zip` tys)
946   where
947     go (Missing {},   arg_ty) = return (Missing arg_ty)
948     go (Present expr, arg_ty) = do { expr' <- tcPolyExpr expr arg_ty
949                                    ; return (Present expr') }
950
951 ----------------
952 unifyOpFunTys :: LHsExpr Name -> Arity -> TcRhoType
953               -> TcM (CoercionI, [TcSigmaType], TcRhoType)                      
954 -- A wrapper for matchExpectedFunTys
955 unifyOpFunTys op arity ty = matchExpectedFunTys herald arity ty
956   where
957     herald = ptext (sLit "The operator") <+> quotes (ppr op) <+> ptext (sLit "takes")
958
959 ---------------------------
960 tcSyntaxOp :: CtOrigin -> HsExpr Name -> TcType -> TcM (HsExpr TcId)
961 -- Typecheck a syntax operator, checking that it has the specified type
962 -- The operator is always a variable at this stage (i.e. renamer output)
963 -- This version assumes res_ty is a monotype
964 tcSyntaxOp orig (HsVar op) res_ty = do { (expr, rho) <- tcInferIdWithOrig orig op
965                                        ; tcWrapResult expr rho res_ty }
966 tcSyntaxOp _ other         _      = pprPanic "tcSyntaxOp" (ppr other) 
967 \end{code}
968
969
970 Note [Push result type in]
971 ~~~~~~~~~~~~~~~~~~~~~~~~~~
972 Unify with expected result before type-checking the args so that the
973 info from res_ty percolates to args.  This is when we might detect a
974 too-few args situation.  (One can think of cases when the opposite
975 order would give a better error message.) 
976 experimenting with putting this first.  
977
978 Here's an example where it actually makes a real difference
979
980    class C t a b | t a -> b
981    instance C Char a Bool
982
983    data P t a = forall b. (C t a b) => MkP b
984    data Q t   = MkQ (forall a. P t a)
985
986    f1, f2 :: Q Char;
987    f1 = MkQ (MkP True)
988    f2 = MkQ (MkP True :: forall a. P Char a)
989
990 With the change, f1 will type-check, because the 'Char' info from
991 the signature is propagated into MkQ's argument. With the check
992 in the other order, the extra signature in f2 is reqd.
993
994
995 %************************************************************************
996 %*                                                                      *
997                  tcInferId
998 %*                                                                      *
999 %************************************************************************
1000
1001 \begin{code}
1002 tcCheckId :: Name -> TcRhoType -> TcM (HsExpr TcId)
1003 tcCheckId name res_ty = do { (expr, rho) <- tcInferId name
1004                            ; tcWrapResult expr rho res_ty }
1005
1006 ------------------------
1007 tcInferId :: Name -> TcM (HsExpr TcId, TcRhoType)
1008 -- Infer type, and deeply instantiate
1009 tcInferId n = tcInferIdWithOrig (OccurrenceOf n) n
1010
1011 ------------------------
1012 tcInferIdWithOrig :: CtOrigin -> Name -> TcM (HsExpr TcId, TcRhoType)
1013 -- Look up an occurrence of an Id, and instantiate it (deeply)
1014
1015 tcInferIdWithOrig orig id_name =
1016  do { id_level  <- getIdLevel id_name
1017     ; cur_level <- getHetMetLevel
1018     ; if (length id_level < length cur_level)
1019       then do { (lhexp, tcrho) <-
1020                     tcInferRho (noLoc $ addEscapes (take ((length cur_level) - (length id_level)) cur_level) (HsVar id_name))
1021               ; return (unLoc lhexp, tcrho)
1022               }
1023       else tcInferIdWithOrig' orig id_name
1024     }
1025
1026 tcInferIdWithOrig' orig id_name =
1027   do { id <- lookup_id
1028      ; (id_expr, id_rho) <- instantiateOuter orig id
1029      ; (wrap, rho) <- deeplyInstantiate orig id_rho
1030      ; return (mkHsWrap wrap id_expr, rho) }
1031   where
1032     lookup_id :: TcM TcId
1033     lookup_id 
1034        = do { thing <- tcLookup id_name
1035             ; case thing of
1036                  ATcId { tct_id = id, tct_level = lvl, tct_hetMetLevel = variable_hetMetLevel }
1037                    -> do { check_naughty id        -- Note [Local record selectors]
1038                          ; checkThLocalId id lvl
1039                          ; current_hetMetLevel  <- getHetMetLevel
1040                          ; mapM
1041                              (\(name1,name2) -> unifyType (TyVarTy name1) (TyVarTy name2))
1042                              (zip variable_hetMetLevel current_hetMetLevel)
1043                          ; return id }
1044
1045                  AGlobal (AnId id) 
1046                    -> do { check_naughty id
1047                          ; return id }
1048                         -- A global cannot possibly be ill-staged in Template Haskell
1049                         -- nor does it need the 'lifting' treatment
1050                         -- hence no checkTh stuff here
1051
1052                  AGlobal (ADataCon con) -> return (dataConWrapId con)
1053
1054                  other -> failWithTc (bad_lookup other) }
1055
1056     bad_lookup thing = ppr thing <+> ptext (sLit "used where a value identifer was expected")
1057
1058     check_naughty id 
1059       | isNaughtyRecordSelector id = failWithTc (naughtyRecordSel id)
1060       | otherwise                  = return ()
1061
1062 ------------------------
1063 instantiateOuter :: CtOrigin -> TcId -> TcM (HsExpr TcId, TcSigmaType)
1064 -- Do just the first level of instantiation of an Id
1065 --   a) Deal with method sharing
1066 --   b) Deal with stupid checks
1067 -- Only look at the *outer level* of quantification
1068 -- See Note [Multiple instantiation]
1069
1070 instantiateOuter orig id
1071   | null tvs && null theta
1072   = return (HsVar id, tau)
1073
1074   | otherwise
1075   = do { (_, tys, subst) <- tcInstTyVars tvs
1076        ; doStupidChecks id tys
1077        ; let theta' = substTheta subst theta
1078        ; traceTc "Instantiating" (ppr id <+> text "with" <+> (ppr tys $$ ppr theta'))
1079        ; wrap <- instCall orig tys theta'
1080        ; return (mkHsWrap wrap (HsVar id), substTy subst tau) }
1081   where
1082     (tvs, theta, tau) = tcSplitSigmaTy (idType id)
1083 \end{code}
1084
1085 Note [Multiple instantiation]
1086 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1087 We are careful never to make a MethodInst that has, as its meth_id, another MethodInst.
1088 For example, consider
1089         f :: forall a. Eq a => forall b. Ord b => a -> b
1090 At a call to f, at say [Int, Bool], it's tempting to translate the call to 
1091
1092         f_m1
1093   where
1094         f_m1 :: forall b. Ord b => Int -> b
1095         f_m1 = f Int dEqInt
1096
1097         f_m2 :: Int -> Bool
1098         f_m2 = f_m1 Bool dOrdBool
1099
1100 But notice that f_m2 has f_m1 as its meth_id.  Now the danger is that if we do
1101 a tcSimplCheck with a Given f_mx :: f Int dEqInt, we may make a binding
1102         f_m1 = f_mx
1103 But it's entirely possible that f_m2 will continue to float out, because it
1104 mentions no type variables.  Result, f_m1 isn't in scope.
1105
1106 Here's a concrete example that does this (test tc200):
1107
1108     class C a where
1109       f :: Eq b => b -> a -> Int
1110       baz :: Eq a => Int -> a -> Int
1111
1112     instance C Int where
1113       baz = f
1114
1115 Current solution: only do the "method sharing" thing for the first type/dict
1116 application, not for the iterated ones.  A horribly subtle point.
1117
1118 Note [No method sharing]
1119 ~~~~~~~~~~~~~~~~~~~~~~~~
1120 The -fno-method-sharing flag controls what happens so far as the LIE
1121 is concerned.  The default case is that for an overloaded function we 
1122 generate a "method" Id, and add the Method Inst to the LIE.  So you get
1123 something like
1124         f :: Num a => a -> a
1125         f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
1126 If you specify -fno-method-sharing, the dictionary application 
1127 isn't shared, so we get
1128         f :: Num a => a -> a
1129         f = /\a (d:Num a) (x:a) -> (+) a d x x
1130 This gets a bit less sharing, but
1131         a) it's better for RULEs involving overloaded functions
1132         b) perhaps fewer separated lambdas
1133
1134 \begin{code}
1135 doStupidChecks :: TcId
1136                -> [TcType]
1137                -> TcM ()
1138 -- Check two tiresome and ad-hoc cases
1139 -- (a) the "stupid theta" for a data con; add the constraints
1140 --     from the "stupid theta" of a data constructor (sigh)
1141
1142 doStupidChecks fun_id tys
1143   | Just con <- isDataConId_maybe fun_id   -- (a)
1144   = addDataConStupidTheta con tys
1145
1146   | fun_id `hasKey` tagToEnumKey           -- (b)
1147   = failWithTc (ptext (sLit "tagToEnum# must appear applied to one argument"))
1148   
1149   | otherwise
1150   = return () -- The common case
1151 \end{code}
1152
1153 Note [tagToEnum#]
1154 ~~~~~~~~~~~~~~~~~
1155 Nasty check to ensure that tagToEnum# is applied to a type that is an
1156 enumeration TyCon.  Unification may refine the type later, but this
1157 check won't see that, alas.  It's crude, because it relies on our
1158 knowing *now* that the type is ok, which in turn relies on the
1159 eager-unification part of the type checker pushing enough information
1160 here.  In theory the Right Thing to do is to have a new form of 
1161 constraint but I definitely cannot face that!  And it works ok as-is.
1162
1163 Here's are two cases that should fail
1164         f :: forall a. a
1165         f = tagToEnum# 0        -- Can't do tagToEnum# at a type variable
1166
1167         g :: Int
1168         g = tagToEnum# 0        -- Int is not an enumeration
1169
1170 When data type families are involved it's a bit more complicated.
1171      data family F a
1172      data instance F [Int] = A | B | C
1173 Then we want to generate something like
1174      tagToEnum# R:FListInt 3# |> co :: R:FListInt ~ F [Int]
1175 Usually that coercion is hidden inside the wrappers for 
1176 constructors of F [Int] but here we have to do it explicitly.
1177
1178 It's all grotesquely complicated.
1179
1180 \begin{code}
1181 tcTagToEnum :: SrcSpan -> Name -> LHsExpr Name -> TcRhoType -> TcM (HsExpr TcId)
1182 -- tagToEnum# :: forall a. Int# -> a
1183 -- See Note [tagToEnum#]   Urgh!
1184 tcTagToEnum loc fun_name arg res_ty
1185   = do  { fun <- tcLookupId fun_name
1186         ; ty' <- zonkTcType res_ty
1187
1188         -- Check that the type is algebraic
1189         ; let mb_tc_app = tcSplitTyConApp_maybe ty'
1190               Just (tc, tc_args) = mb_tc_app
1191         ; checkTc (isJust mb_tc_app)
1192                   (tagToEnumError ty' doc1)
1193
1194         -- Look through any type family
1195         ; (coi, rep_tc, rep_args) <- get_rep_ty ty' tc tc_args
1196
1197         ; checkTc (isEnumerationTyCon rep_tc) 
1198                   (tagToEnumError ty' doc2)
1199
1200         ; arg' <- tcMonoExpr arg intPrimTy
1201         ; let fun' = L loc (HsWrap (WpTyApp rep_ty) (HsVar fun))
1202               rep_ty = mkTyConApp rep_tc rep_args
1203
1204         ; return (mkHsWrapCoI coi $ HsApp fun' arg') }
1205   where
1206     doc1 = vcat [ ptext (sLit "Specify the type by giving a type signature")
1207                 , ptext (sLit "e.g. (tagToEnum# x) :: Bool") ]
1208     doc2 = ptext (sLit "Result type must be an enumeration type")
1209     doc3 = ptext (sLit "No family instance for this type")
1210
1211     get_rep_ty :: TcType -> TyCon -> [TcType]
1212                -> TcM (CoercionI, TyCon, [TcType])
1213         -- Converts a family type (eg F [a]) to its rep type (eg FList a)
1214         -- and returns a coercion between the two
1215     get_rep_ty ty tc tc_args
1216       | not (isFamilyTyCon tc) 
1217       = return (IdCo ty, tc, tc_args)
1218       | otherwise 
1219       = do { mb_fam <- tcLookupFamInst tc tc_args
1220            ; case mb_fam of 
1221                Nothing -> failWithTc (tagToEnumError ty doc3)
1222                Just (rep_tc, rep_args) 
1223                    -> return ( ACo (mkSymCoercion (mkTyConApp co_tc rep_args))
1224                              , rep_tc, rep_args )
1225                  where
1226                    co_tc = expectJust "tcTagToEnum" $
1227                            tyConFamilyCoercion_maybe rep_tc }
1228
1229 tagToEnumError :: TcType -> SDoc -> SDoc
1230 tagToEnumError ty what
1231   = hang (ptext (sLit "Bad call to tagToEnum#") 
1232            <+> ptext (sLit "at type") <+> ppr ty) 
1233          2 what
1234 \end{code}
1235
1236
1237 %************************************************************************
1238 %*                                                                      *
1239                  Template Haskell checks
1240 %*                                                                      *
1241 %************************************************************************
1242
1243 \begin{code}
1244 checkThLocalId :: Id -> ThLevel -> TcM ()
1245 #ifndef GHCI  /* GHCI and TH is off */
1246 --------------------------------------
1247 -- Check for cross-stage lifting
1248 checkThLocalId _id _bind_lvl
1249   = return ()
1250
1251 #else         /* GHCI and TH is on */
1252 checkThLocalId id bind_lvl 
1253   = do  { use_stage <- getStage -- TH case
1254         ; let use_lvl = thLevel use_stage
1255         ; checkWellStaged (quotes (ppr id)) bind_lvl use_lvl
1256         ; traceTc "thLocalId" (ppr id <+> ppr bind_lvl <+> ppr use_stage <+> ppr use_lvl)
1257         ; when (use_lvl > bind_lvl) $
1258           checkCrossStageLifting id bind_lvl use_stage }
1259
1260 --------------------------------------
1261 checkCrossStageLifting :: Id -> ThLevel -> ThStage -> TcM ()
1262 -- We are inside brackets, and (use_lvl > bind_lvl)
1263 -- Now we must check whether there's a cross-stage lift to do
1264 -- Examples   \x -> [| x |]  
1265 --            [| map |]
1266
1267 checkCrossStageLifting _ _ Comp   = return ()
1268 checkCrossStageLifting _ _ Splice = return ()
1269
1270 checkCrossStageLifting id _ (Brack _ ps_var lie_var) 
1271   | thTopLevelId id
1272   =     -- Top-level identifiers in this module,
1273         -- (which have External Names)
1274         -- are just like the imported case:
1275         -- no need for the 'lifting' treatment
1276         -- E.g.  this is fine:
1277         --   f x = x
1278         --   g y = [| f 3 |]
1279         -- But we do need to put f into the keep-alive
1280         -- set, because after desugaring the code will
1281         -- only mention f's *name*, not f itself.
1282     keepAliveTc id
1283
1284   | otherwise   -- bind_lvl = outerLevel presumably,
1285                 -- but the Id is not bound at top level
1286   =     -- Nested identifiers, such as 'x' in
1287         -- E.g. \x -> [| h x |]
1288         -- We must behave as if the reference to x was
1289         --      h $(lift x)     
1290         -- We use 'x' itself as the splice proxy, used by 
1291         -- the desugarer to stitch it all back together.
1292         -- If 'x' occurs many times we may get many identical
1293         -- bindings of the same splice proxy, but that doesn't
1294         -- matter, although it's a mite untidy.
1295     do  { let id_ty = idType id
1296         ; checkTc (isTauTy id_ty) (polySpliceErr id)
1297                -- If x is polymorphic, its occurrence sites might
1298                -- have different instantiations, so we can't use plain
1299                -- 'x' as the splice proxy name.  I don't know how to 
1300                -- solve this, and it's probably unimportant, so I'm
1301                -- just going to flag an error for now
1302    
1303         ; lift <- if isStringTy id_ty then
1304                      do { sid <- tcLookupId DsMeta.liftStringName
1305                                      -- See Note [Lifting strings]
1306                         ; return (HsVar sid) }
1307                   else
1308                      setConstraintVar lie_var   $ do  
1309                           -- Put the 'lift' constraint into the right LIE
1310                      newMethodFromName (OccurrenceOf (idName id)) 
1311                                        DsMeta.liftName id_ty
1312            
1313                    -- Update the pending splices
1314         ; ps <- readMutVar ps_var
1315         ; writeMutVar ps_var ((idName id, nlHsApp (noLoc lift) (nlHsVar id)) : ps)
1316
1317         ; return () }
1318 #endif /* GHCI */
1319 \end{code}
1320
1321 Note [Lifting strings]
1322 ~~~~~~~~~~~~~~~~~~~~~~
1323 If we see $(... [| s |] ...) where s::String, we don't want to
1324 generate a mass of Cons (CharL 'x') (Cons (CharL 'y') ...)) etc.
1325 So this conditional short-circuits the lifting mechanism to generate
1326 (liftString "xy") in that case.  I didn't want to use overlapping instances
1327 for the Lift class in TH.Syntax, because that can lead to overlapping-instance
1328 errors in a polymorphic situation.  
1329
1330 If this check fails (which isn't impossible) we get another chance; see
1331 Note [Converting strings] in Convert.lhs 
1332
1333 Local record selectors
1334 ~~~~~~~~~~~~~~~~~~~~~~
1335 Record selectors for TyCons in this module are ordinary local bindings,
1336 which show up as ATcIds rather than AGlobals.  So we need to check for
1337 naughtiness in both branches.  c.f. TcTyClsBindings.mkAuxBinds.
1338
1339
1340 %************************************************************************
1341 %*                                                                      *
1342 \subsection{Record bindings}
1343 %*                                                                      *
1344 %************************************************************************
1345
1346 Game plan for record bindings
1347 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1348 1. Find the TyCon for the bindings, from the first field label.
1349
1350 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
1351
1352 For each binding field = value
1353
1354 3. Instantiate the field type (from the field label) using the type
1355    envt from step 2.
1356
1357 4  Type check the value using tcArg, passing the field type as 
1358    the expected argument type.
1359
1360 This extends OK when the field types are universally quantified.
1361
1362         
1363 \begin{code}
1364 tcRecordBinds
1365         :: DataCon
1366         -> [TcType]     -- Expected type for each field
1367         -> HsRecordBinds Name
1368         -> TcM (HsRecordBinds TcId)
1369
1370 tcRecordBinds data_con arg_tys (HsRecFields rbinds dd)
1371   = do  { mb_binds <- mapM do_bind rbinds
1372         ; return (HsRecFields (catMaybes mb_binds) dd) }
1373   where
1374     flds_w_tys = zipEqual "tcRecordBinds" (dataConFieldLabels data_con) arg_tys
1375     do_bind fld@(HsRecField { hsRecFieldId = L loc field_lbl, hsRecFieldArg = rhs })
1376       | Just field_ty <- assocMaybe flds_w_tys field_lbl
1377       = addErrCtxt (fieldCtxt field_lbl)        $
1378         do { rhs' <- tcPolyExprNC rhs field_ty
1379            ; let field_id = mkUserLocal (nameOccName field_lbl)
1380                                         (nameUnique field_lbl)
1381                                         field_ty loc 
1382                 -- Yuk: the field_id has the *unique* of the selector Id
1383                 --          (so we can find it easily)
1384                 --      but is a LocalId with the appropriate type of the RHS
1385                 --          (so the desugarer knows the type of local binder to make)
1386            ; return (Just (fld { hsRecFieldId = L loc field_id, hsRecFieldArg = rhs' })) }
1387       | otherwise
1388       = do { addErrTc (badFieldCon data_con field_lbl)
1389            ; return Nothing }
1390
1391 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
1392 checkMissingFields data_con rbinds
1393   | null field_labels   -- Not declared as a record;
1394                         -- But C{} is still valid if no strict fields
1395   = if any isBanged field_strs then
1396         -- Illegal if any arg is strict
1397         addErrTc (missingStrictFields data_con [])
1398     else
1399         return ()
1400                         
1401   | otherwise = do              -- A record
1402     unless (null missing_s_fields)
1403            (addErrTc (missingStrictFields data_con missing_s_fields))
1404
1405     warn <- doptM Opt_WarnMissingFields
1406     unless (not (warn && notNull missing_ns_fields))
1407            (warnTc True (missingFields data_con missing_ns_fields))
1408
1409   where
1410     missing_s_fields
1411         = [ fl | (fl, str) <- field_info,
1412                  isBanged str,
1413                  not (fl `elem` field_names_used)
1414           ]
1415     missing_ns_fields
1416         = [ fl | (fl, str) <- field_info,
1417                  not (isBanged str),
1418                  not (fl `elem` field_names_used)
1419           ]
1420
1421     field_names_used = hsRecFields rbinds
1422     field_labels     = dataConFieldLabels data_con
1423
1424     field_info = zipEqual "missingFields"
1425                           field_labels
1426                           field_strs
1427
1428     field_strs = dataConStrictMarks data_con
1429 \end{code}
1430
1431 %************************************************************************
1432 %*                                                                      *
1433 \subsection{Errors and contexts}
1434 %*                                                                      *
1435 %************************************************************************
1436
1437 Boring and alphabetical:
1438 \begin{code}
1439 addExprErrCtxt :: LHsExpr Name -> TcM a -> TcM a
1440 addExprErrCtxt expr = addErrCtxt (exprCtxt expr)
1441
1442 exprCtxt :: LHsExpr Name -> SDoc
1443 exprCtxt expr
1444   = hang (ptext (sLit "In the expression:")) 2 (ppr expr)
1445
1446 fieldCtxt :: Name -> SDoc
1447 fieldCtxt field_name
1448   = ptext (sLit "In the") <+> quotes (ppr field_name) <+> ptext (sLit "field of a record")
1449
1450 funAppCtxt :: LHsExpr Name -> LHsExpr Name -> Int -> SDoc
1451 funAppCtxt fun arg arg_no
1452   = hang (hsep [ ptext (sLit "In the"), speakNth arg_no, ptext (sLit "argument of"), 
1453                     quotes (ppr fun) <> text ", namely"])
1454        2 (quotes (ppr arg))
1455
1456 funResCtxt :: LHsExpr Name -> SDoc
1457 funResCtxt fun
1458   = ptext (sLit "In the return type of a call of") <+> quotes (ppr fun)
1459
1460 badFieldTypes :: [(Name,TcType)] -> SDoc
1461 badFieldTypes prs
1462   = hang (ptext (sLit "Record update for insufficiently polymorphic field")
1463                          <> plural prs <> colon)
1464        2 (vcat [ ppr f <+> dcolon <+> ppr ty | (f,ty) <- prs ])
1465
1466 badFieldsUpd :: HsRecFields Name a -> SDoc
1467 badFieldsUpd rbinds
1468   = hang (ptext (sLit "No constructor has all these fields:"))
1469        2 (pprQuotedList (hsRecFields rbinds))
1470
1471 naughtyRecordSel :: TcId -> SDoc
1472 naughtyRecordSel sel_id
1473   = ptext (sLit "Cannot use record selector") <+> quotes (ppr sel_id) <+> 
1474     ptext (sLit "as a function due to escaped type variables") $$ 
1475     ptext (sLit "Probable fix: use pattern-matching syntax instead")
1476
1477 notSelector :: Name -> SDoc
1478 notSelector field
1479   = hsep [quotes (ppr field), ptext (sLit "is not a record selector")]
1480
1481 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1482 missingStrictFields con fields
1483   = header <> rest
1484   where
1485     rest | null fields = empty  -- Happens for non-record constructors 
1486                                 -- with strict fields
1487          | otherwise   = colon <+> pprWithCommas ppr fields
1488
1489     header = ptext (sLit "Constructor") <+> quotes (ppr con) <+> 
1490              ptext (sLit "does not have the required strict field(s)") 
1491           
1492 missingFields :: DataCon -> [FieldLabel] -> SDoc
1493 missingFields con fields
1494   = ptext (sLit "Fields of") <+> quotes (ppr con) <+> ptext (sLit "not initialised:") 
1495         <+> pprWithCommas ppr fields
1496
1497 -- callCtxt fun args = ptext (sLit "In the call") <+> parens (ppr (foldl mkHsApp fun args))
1498
1499 #ifdef GHCI
1500 polySpliceErr :: Id -> SDoc
1501 polySpliceErr id
1502   = ptext (sLit "Can't splice the polymorphic local variable") <+> quotes (ppr id)
1503 #endif
1504 \end{code}