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