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