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