[project @ 2004-03-11 14:34:22 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcExpr]{Typecheck an expression}
5
6 \begin{code}
7 module TcExpr ( tcCheckSigma, tcCheckRho, tcInferRho, tcMonoExpr ) where
8
9 #include "HsVersions.h"
10
11 #ifdef GHCI     /* Only if bootstrapped */
12 import {-# SOURCE #-}   TcSplice( tcSpliceExpr, tcBracket )
13 import Id               ( Id )
14 import TcType           ( isTauTy )
15 import TcEnv            ( checkWellStaged )
16 import HsSyn            ( nlHsApp )
17 import qualified DsMeta
18 #endif
19
20 import HsSyn            ( HsExpr(..), LHsExpr, HsLit(..), ArithSeqInfo(..), recBindFields,
21                           HsMatchContext(..), HsRecordBinds, mkHsApp, nlHsVar )
22 import TcHsSyn          ( hsLitType, mkHsDictApp, mkHsTyApp, (<$>) )
23 import TcRnMonad
24 import TcUnify          ( Expected(..), newHole, zapExpectedType, zapExpectedTo, tcSubExp, tcGen,
25                           unifyFunTy, zapToListTy, zapToPArrTy, zapToTupleTy )
26 import BasicTypes       ( isMarkedStrict )
27 import Inst             ( InstOrigin(..), 
28                           newOverloadedLit, newMethodFromName, newIPDict,
29                           newDicts, newMethodWithGivenTy, 
30                           instToId, tcInstCall, tcInstDataCon
31                         )
32 import TcBinds          ( tcBindsAndThen )
33 import TcEnv            ( tcLookup, tcLookupId, checkProcLevel,
34                           tcLookupDataCon, tcLookupGlobalId
35                         )
36 import TcArrows         ( tcProc )
37 import TcMatches        ( tcMatchesCase, tcMatchLambda, tcDoStmts, tcThingWithSig, TcMatchCtxt(..) )
38 import TcHsType         ( tcHsSigType, UserTypeCtxt(..) )
39 import TcPat            ( badFieldCon )
40 import TcMType          ( tcInstTyVars, tcInstType, newTyVarTy, zonkTcType )
41 import TcType           ( TcType, TcSigmaType, TcRhoType, TyVarDetails(VanillaTv),
42                           tcSplitFunTys, tcSplitTyConApp, mkTyVarTys,
43                           isSigmaTy, mkFunTy, mkFunTys,
44                           mkTyConApp, tyVarsOfTypes, isLinearPred,
45                           tcSplitSigmaTy, tidyOpenType
46                         )
47 import Kind             ( openTypeKind, liftedTypeKind, argTypeKind )
48
49 import FieldLabel       ( FieldLabel, fieldLabelName, fieldLabelType, fieldLabelTyCon )
50 import Id               ( idType, recordSelectorFieldLabel, isRecordSelector )
51 import DataCon          ( DataCon, dataConFieldLabels, dataConStrictMarks, dataConWrapId )
52 import Name             ( Name )
53 import TyCon            ( TyCon, tyConTyVars, tyConTheta, tyConDataCons )
54 import Subst            ( mkTopTyVarSubst, substTheta, substTy )
55 import VarSet           ( emptyVarSet, elemVarSet )
56 import TysWiredIn       ( boolTy )
57 import PrelNames        ( enumFromName, enumFromThenName, 
58                           enumFromToName, enumFromThenToName,
59                           enumFromToPName, enumFromThenToPName
60                         )
61 import ListSetOps       ( minusList )
62 import CmdLineOpts
63 import HscTypes         ( TyThing(..) )
64 import SrcLoc           ( Located(..), unLoc, getLoc )
65 import Util
66 import Outputable
67 import FastString
68
69 #ifdef DEBUG
70 import TyCon            ( isAlgTyCon )
71 #endif
72 \end{code}
73
74 %************************************************************************
75 %*                                                                      *
76 \subsection{Main wrappers}
77 %*                                                                      *
78 %************************************************************************
79
80 \begin{code}
81 -- tcCheckSigma does type *checking*; it's passed the expected type of the result
82 tcCheckSigma :: LHsExpr Name            -- Expession to type check
83              -> TcSigmaType             -- Expected type (could be a polytpye)
84              -> TcM (LHsExpr TcId)      -- Generalised expr with expected type
85
86 tcCheckSigma expr expected_ty 
87   = traceTc (text "tcExpr" <+> (ppr expected_ty $$ ppr expr)) `thenM_`
88     tc_expr' expr expected_ty
89
90 tc_expr' expr sigma_ty
91   | isSigmaTy sigma_ty
92   = tcGen sigma_ty emptyVarSet (
93         \ rho_ty -> tcCheckRho expr rho_ty
94     )                           `thenM` \ (gen_fn, expr') ->
95     returnM (L (getLoc expr') (gen_fn <$> unLoc expr'))
96
97 tc_expr' expr rho_ty    -- Monomorphic case
98   = tcCheckRho expr rho_ty
99 \end{code}
100
101 Typecheck expression which in most cases will be an Id.
102 The expression can return a higher-ranked type, such as
103         (forall a. a->a) -> Int
104 so we must create a hole to pass in as the expected tyvar.
105
106 \begin{code}
107 tcCheckRho :: LHsExpr Name -> TcRhoType -> TcM (LHsExpr TcId)
108 tcCheckRho expr rho_ty = tcMonoExpr expr (Check rho_ty)
109
110 tcInferRho :: LHsExpr Name -> TcM (LHsExpr TcId, TcRhoType)
111 tcInferRho (L loc (HsVar name)) = addSrcSpan loc $ 
112                                   do { (e,ty) <- tcId name; return (L loc e, ty)}
113 tcInferRho expr                 = newHole                       `thenM` \ hole ->
114                                   tcMonoExpr expr (Infer hole)  `thenM` \ expr' ->
115                                   readMutVar hole               `thenM` \ rho_ty ->
116                                   returnM (expr', rho_ty) 
117 \end{code}
118
119
120
121 %************************************************************************
122 %*                                                                      *
123 \subsection{The TAUT rules for variables}TcExpr
124 %*                                                                      *
125 %************************************************************************
126
127 \begin{code}
128 tcMonoExpr :: LHsExpr Name              -- Expession to type check
129            -> Expected TcRhoType        -- Expected type (could be a type variable)
130                                         -- Definitely no foralls at the top
131                                         -- Can be a 'hole'.
132            -> TcM (LHsExpr TcId)
133
134 tcMonoExpr (L loc expr) res_ty
135   = addSrcSpan loc (do { expr' <- tc_expr expr res_ty
136                        ; return (L loc expr') })
137
138 tc_expr :: HsExpr Name -> Expected TcRhoType -> TcM (HsExpr TcId)
139 tc_expr (HsVar name) res_ty
140   = tcId name                   `thenM` \ (expr', id_ty) ->
141     tcSubExp res_ty id_ty       `thenM` \ co_fn ->
142     returnM (co_fn <$> expr')
143
144 tc_expr (HsIPVar ip) res_ty
145   =     -- Implicit parameters must have a *tau-type* not a 
146         -- type scheme.  We enforce this by creating a fresh
147         -- type variable as its type.  (Because res_ty may not
148         -- be a tau-type.)
149     newTyVarTy argTypeKind              `thenM` \ ip_ty ->
150         -- argTypeKind: it can't be an unboxed tuple
151     newIPDict (IPOccOrigin ip) ip ip_ty `thenM` \ (ip', inst) ->
152     extendLIE inst                      `thenM_`
153     tcSubExp res_ty ip_ty               `thenM` \ co_fn ->
154     returnM (co_fn <$> HsIPVar ip')
155 \end{code}
156
157
158 %************************************************************************
159 %*                                                                      *
160 \subsection{Expressions type signatures}
161 %*                                                                      *
162 %************************************************************************
163
164 \begin{code}
165 tc_expr in_expr@(ExprWithTySig expr poly_ty) res_ty
166  = addErrCtxt (exprCtxt in_expr)                        $
167    tcHsSigType ExprSigCtxt poly_ty                      `thenM` \ sig_tc_ty ->
168    tcThingWithSig sig_tc_ty (tcCheckRho expr) res_ty    `thenM` \ (co_fn, expr') ->
169    returnM (co_fn <$> unLoc expr')
170         -- ToDo: nasty unLoc
171
172 tc_expr (HsType ty) res_ty
173   = failWithTc (text "Can't handle type argument:" <+> ppr ty)
174         -- This is the syntax for type applications that I was planning
175         -- but there are difficulties (e.g. what order for type args)
176         -- so it's not enabled yet.
177         -- Can't eliminate it altogether from the parser, because the
178         -- same parser parses *patterns*.
179 \end{code}
180
181
182 %************************************************************************
183 %*                                                                      *
184 \subsection{Other expression forms}
185 %*                                                                      *
186 %************************************************************************
187
188 \begin{code}
189 tc_expr (HsPar expr)    res_ty  = tcMonoExpr expr res_ty        `thenM` \ expr' -> 
190                                   returnM (HsPar expr')
191 tc_expr (HsSCC lbl expr) res_ty = tcMonoExpr expr res_ty        `thenM` \ expr' ->
192                                   returnM (HsSCC lbl expr')
193 tc_expr (HsCoreAnn lbl expr) res_ty = tcMonoExpr expr res_ty `thenM` \ expr' ->  -- hdaume: core annotation
194                                          returnM (HsCoreAnn lbl expr')
195
196 tc_expr (HsLit lit) res_ty  = tcLit lit res_ty
197
198 tc_expr (HsOverLit lit) res_ty  
199   = zapExpectedType res_ty liftedTypeKind               `thenM` \ res_ty' ->
200     newOverloadedLit (LiteralOrigin lit) lit res_ty'    `thenM` \ lit_expr ->
201     returnM (unLoc lit_expr)    -- ToDo: nasty unLoc
202
203 tc_expr (NegApp expr neg_name) res_ty
204   = tc_expr (HsApp (nlHsVar neg_name) expr) res_ty
205         -- ToDo: use tcSyntaxName
206
207 tc_expr (HsLam match) res_ty
208   = tcMatchLambda match res_ty          `thenM` \ match' ->
209     returnM (HsLam match')
210
211 tc_expr (HsApp e1 e2) res_ty 
212   = tcApp e1 [e2] res_ty
213 \end{code}
214
215 Note that the operators in sections are expected to be binary, and
216 a type error will occur if they aren't.
217
218 \begin{code}
219 -- Left sections, equivalent to
220 --      \ x -> e op x,
221 -- or
222 --      \ x -> op e x,
223 -- or just
224 --      op e
225
226 tc_expr in_expr@(SectionL arg1 op) res_ty
227   = tcInferRho op                               `thenM` \ (op', op_ty) ->
228     split_fun_ty op_ty 2 {- two args -}         `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
229     tcArg op (arg1, arg1_ty, 1)                 `thenM` \ arg1' ->
230     addErrCtxt (exprCtxt in_expr)               $
231     tcSubExp res_ty (mkFunTy arg2_ty op_res_ty) `thenM` \ co_fn ->
232     returnM (co_fn <$> SectionL arg1' op')
233
234 -- Right sections, equivalent to \ x -> x op expr, or
235 --      \ x -> op x expr
236
237 tc_expr in_expr@(SectionR op arg2) res_ty
238   = tcInferRho op                               `thenM` \ (op', op_ty) ->
239     split_fun_ty op_ty 2 {- two args -}         `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
240     tcArg op (arg2, arg2_ty, 2)                 `thenM` \ arg2' ->
241     addErrCtxt (exprCtxt in_expr)               $
242     tcSubExp res_ty (mkFunTy arg1_ty op_res_ty) `thenM` \ co_fn ->
243     returnM (co_fn <$> SectionR op' arg2')
244
245 -- equivalent to (op e1) e2:
246
247 tc_expr in_expr@(OpApp arg1 op fix arg2) res_ty
248   = tcInferRho op                               `thenM` \ (op', op_ty) ->
249     split_fun_ty op_ty 2 {- two args -}         `thenM` \ ([arg1_ty, arg2_ty], op_res_ty) ->
250     tcArg op (arg1, arg1_ty, 1)                 `thenM` \ arg1' ->
251     tcArg op (arg2, arg2_ty, 2)                 `thenM` \ arg2' ->
252     addErrCtxt (exprCtxt in_expr)               $
253     tcSubExp res_ty op_res_ty                   `thenM` \ co_fn ->
254     returnM (OpApp arg1' op' fix arg2')
255 \end{code}
256
257 \begin{code}
258 tc_expr (HsLet binds (L loc expr)) res_ty
259   = tcBindsAndThen
260         glue
261         binds                   -- Bindings to check
262         (tc_expr expr res_ty)
263   where
264     glue bind expr = HsLet [bind] (L loc expr)
265
266 tc_expr in_expr@(HsCase scrut matches) res_ty
267   = addErrCtxt (caseCtxt in_expr)       $
268
269         -- Typecheck the case alternatives first.
270         -- The case patterns tend to give good type info to use
271         -- when typechecking the scrutinee.  For example
272         --      case (map f) of
273         --        (x:xs) -> ...
274         -- will report that map is applied to too few arguments
275
276     tcMatchesCase match_ctxt matches res_ty     `thenM`    \ (scrut_ty, matches') ->
277
278     addErrCtxt (caseScrutCtxt scrut)    (
279       tcCheckRho scrut scrut_ty
280     )                                   `thenM`    \ scrut' ->
281
282     returnM (HsCase scrut' matches')
283   where
284     match_ctxt = MC { mc_what = CaseAlt,
285                       mc_body = tcMonoExpr }
286
287 tc_expr (HsIf pred b1 b2) res_ty
288   = addErrCtxt (predCtxt pred) (
289     tcCheckRho pred boolTy      )       `thenM`    \ pred' ->
290
291     zapExpectedType res_ty openTypeKind `thenM`    \ res_ty' ->
292         -- C.f. the call to zapToType in TcMatches.tcMatches
293
294     tcCheckRho b1 res_ty'               `thenM`    \ b1' ->
295     tcCheckRho b2 res_ty'               `thenM`    \ b2' ->
296     returnM (HsIf pred' b1' b2')
297
298 tc_expr (HsDo do_or_lc stmts method_names _) res_ty
299   = zapExpectedType res_ty liftedTypeKind               `thenM` \ res_ty' ->
300         -- All comprehensions yield a monotype of kind *
301     tcDoStmts do_or_lc stmts method_names res_ty'       `thenM` \ (stmts', methods') ->
302     returnM (HsDo do_or_lc stmts' methods' res_ty')
303
304 tc_expr in_expr@(ExplicitList _ exprs) res_ty   -- Non-empty list
305   = zapToListTy res_ty                `thenM` \ elt_ty ->  
306     mappM (tc_elt elt_ty) exprs       `thenM` \ exprs' ->
307     returnM (ExplicitList elt_ty exprs')
308   where
309     tc_elt elt_ty expr
310       = addErrCtxt (listCtxt expr) $
311         tcCheckRho expr elt_ty
312
313 tc_expr in_expr@(ExplicitPArr _ exprs) res_ty   -- maybe empty
314   = zapToPArrTy res_ty                `thenM` \ elt_ty ->  
315     mappM (tc_elt elt_ty) exprs       `thenM` \ exprs' ->
316     returnM (ExplicitPArr elt_ty exprs')
317   where
318     tc_elt elt_ty expr
319       = addErrCtxt (parrCtxt expr) $
320         tcCheckRho expr elt_ty
321
322 tc_expr (ExplicitTuple exprs boxity) res_ty
323   = zapToTupleTy boxity (length exprs) res_ty   `thenM` \ arg_tys ->
324     tcCheckRhos exprs arg_tys                   `thenM` \ exprs' ->
325     returnM (ExplicitTuple exprs' boxity)
326
327 tc_expr (HsProc pat cmd) res_ty
328   = tcProc pat cmd res_ty                       `thenM` \ (pat', cmd') ->
329     returnM (HsProc pat' cmd')
330 \end{code}
331
332 %************************************************************************
333 %*                                                                      *
334                 Record construction and update
335 %*                                                                      *
336 %************************************************************************
337
338 \begin{code}
339 tc_expr expr@(RecordCon con@(L _ con_name) rbinds) res_ty
340   = addErrCtxt (recordConCtxt expr)             $
341     addLocM tcId con                    `thenM` \ (con_expr, con_tau) ->
342     let
343         (_, record_ty)   = tcSplitFunTys con_tau
344         (tycon, ty_args) = tcSplitTyConApp record_ty
345     in
346     ASSERT( isAlgTyCon tycon )
347     zapExpectedTo res_ty record_ty      `thenM_`
348
349         -- Check that the record bindings match the constructor
350         -- con_name is syntactically constrained to be a data constructor
351     tcLookupDataCon con_name            `thenM` \ data_con ->
352     let
353         bad_fields = badFields rbinds data_con
354     in
355     if notNull bad_fields then
356         mappM (addErrTc . badFieldCon data_con) bad_fields      `thenM_`
357         failM   -- Fail now, because tcRecordBinds will crash on a bad field
358     else
359
360         -- Typecheck the record bindings
361     tcRecordBinds tycon ty_args rbinds          `thenM` \ rbinds' ->
362     
363         -- Check for missing fields
364     checkMissingFields data_con rbinds          `thenM_` 
365
366     getSrcSpanM                                 `thenM` \ loc ->
367     returnM (RecordConOut data_con (L loc con_expr) rbinds')
368
369 -- The main complication with RecordUpd is that we need to explicitly
370 -- handle the *non-updated* fields.  Consider:
371 --
372 --      data T a b = MkT1 { fa :: a, fb :: b }
373 --                 | MkT2 { fa :: a, fc :: Int -> Int }
374 --                 | MkT3 { fd :: a }
375 --      
376 --      upd :: T a b -> c -> T a c
377 --      upd t x = t { fb = x}
378 --
379 -- The type signature on upd is correct (i.e. the result should not be (T a b))
380 -- because upd should be equivalent to:
381 --
382 --      upd t x = case t of 
383 --                      MkT1 p q -> MkT1 p x
384 --                      MkT2 a b -> MkT2 p b
385 --                      MkT3 d   -> error ...
386 --
387 -- So we need to give a completely fresh type to the result record,
388 -- and then constrain it by the fields that are *not* updated ("p" above).
389 --
390 -- Note that because MkT3 doesn't contain all the fields being updated,
391 -- its RHS is simply an error, so it doesn't impose any type constraints
392 --
393 -- All this is done in STEP 4 below.
394
395 tc_expr expr@(RecordUpd record_expr rbinds) res_ty
396   = addErrCtxt (recordUpdCtxt   expr)           $
397
398         -- STEP 0
399         -- Check that the field names are really field names
400     ASSERT( notNull rbinds )
401     let 
402         field_names = map fst rbinds
403     in
404     mappM (tcLookupGlobalId.unLoc) field_names  `thenM` \ sel_ids ->
405         -- The renamer has already checked that they
406         -- are all in scope
407     let
408         bad_guys = [ addSrcSpan loc $ addErrTc (notSelector field_name) 
409                    | (L loc field_name, sel_id) <- field_names `zip` sel_ids,
410                      not (isRecordSelector sel_id)      -- Excludes class ops
411                    ]
412     in
413     checkM (null bad_guys) (sequenceM bad_guys `thenM_` failM)  `thenM_`
414     
415         -- STEP 1
416         -- Figure out the tycon and data cons from the first field name
417     let
418                 -- It's OK to use the non-tc splitters here (for a selector)
419         sel_id : _   = sel_ids
420         field_lbl    = recordSelectorFieldLabel sel_id  -- We've failed already if
421         tycon        = fieldLabelTyCon field_lbl        -- it's not a field label
422         data_cons    = tyConDataCons tycon
423         tycon_tyvars = tyConTyVars tycon                -- The data cons use the same type vars
424     in
425     tcInstTyVars VanillaTv tycon_tyvars         `thenM` \ (_, result_inst_tys, inst_env) ->
426
427         -- STEP 2
428         -- Check that at least one constructor has all the named fields
429         -- i.e. has an empty set of bad fields returned by badFields
430     checkTc (any (null . badFields rbinds) data_cons)
431             (badFieldsUpd rbinds)               `thenM_`
432
433         -- STEP 3
434         -- Typecheck the update bindings.
435         -- (Do this after checking for bad fields in case there's a field that
436         --  doesn't match the constructor.)
437     let
438         result_record_ty = mkTyConApp tycon result_inst_tys
439     in
440     zapExpectedTo res_ty result_record_ty       `thenM_`
441     tcRecordBinds tycon result_inst_tys rbinds  `thenM` \ rbinds' ->
442
443         -- STEP 4
444         -- Use the un-updated fields to find a vector of booleans saying
445         -- which type arguments must be the same in updatee and result.
446         --
447         -- WARNING: this code assumes that all data_cons in a common tycon
448         -- have FieldLabels abstracted over the same tyvars.
449     let
450         upd_field_lbls      = map recordSelectorFieldLabel (recBindFields rbinds')
451         con_field_lbls_s    = map dataConFieldLabels data_cons
452
453                 -- A constructor is only relevant to this process if
454                 -- it contains all the fields that are being updated
455         relevant_field_lbls_s      = filter is_relevant con_field_lbls_s
456         is_relevant con_field_lbls = all (`elem` con_field_lbls) upd_field_lbls
457
458         non_upd_field_lbls  = concat relevant_field_lbls_s `minusList` upd_field_lbls
459         common_tyvars       = tyVarsOfTypes (map fieldLabelType non_upd_field_lbls)
460
461         mk_inst_ty tyvar result_inst_ty 
462           | tyvar `elemVarSet` common_tyvars = returnM result_inst_ty   -- Same as result type
463           | otherwise                        = newTyVarTy liftedTypeKind        -- Fresh type
464     in
465     zipWithM mk_inst_ty tycon_tyvars result_inst_tys    `thenM` \ inst_tys ->
466
467         -- STEP 5
468         -- Typecheck the expression to be updated
469     let
470         record_ty = mkTyConApp tycon inst_tys
471     in
472     tcCheckRho record_expr record_ty            `thenM` \ record_expr' ->
473
474         -- STEP 6
475         -- Figure out the LIE we need.  We have to generate some 
476         -- dictionaries for the data type context, since we are going to
477         -- do pattern matching over the data cons.
478         --
479         -- What dictionaries do we need?  
480         -- We just take the context of the type constructor
481     let
482         theta' = substTheta inst_env (tyConTheta tycon)
483     in
484     newDicts RecordUpdOrigin theta'     `thenM` \ dicts ->
485     extendLIEs dicts                    `thenM_`
486
487         -- Phew!
488     returnM (RecordUpdOut record_expr' record_ty result_record_ty rbinds') 
489 \end{code}
490
491
492 %************************************************************************
493 %*                                                                      *
494         Arithmetic sequences                    e.g. [a,b..]
495         and their parallel-array counterparts   e.g. [: a,b.. :]
496                 
497 %*                                                                      *
498 %************************************************************************
499
500 \begin{code}
501 tc_expr (ArithSeqIn seq@(From expr)) res_ty
502   = zapToListTy res_ty                          `thenM` \ elt_ty ->  
503     tcCheckRho expr elt_ty                      `thenM` \ expr' ->
504
505     newMethodFromName (ArithSeqOrigin seq) 
506                       elt_ty enumFromName       `thenM` \ enum_from ->
507
508     returnM (ArithSeqOut (nlHsVar enum_from) (From expr'))
509
510 tc_expr in_expr@(ArithSeqIn seq@(FromThen expr1 expr2)) res_ty
511   = addErrCtxt (arithSeqCtxt in_expr) $ 
512     zapToListTy  res_ty                                 `thenM`    \ elt_ty ->  
513     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
514     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
515     newMethodFromName (ArithSeqOrigin seq) 
516                       elt_ty enumFromThenName           `thenM` \ enum_from_then ->
517
518     returnM (ArithSeqOut (nlHsVar enum_from_then) (FromThen expr1' expr2'))
519
520
521 tc_expr in_expr@(ArithSeqIn seq@(FromTo expr1 expr2)) res_ty
522   = addErrCtxt (arithSeqCtxt in_expr) $
523     zapToListTy  res_ty                                 `thenM`    \ elt_ty ->  
524     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
525     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
526     newMethodFromName (ArithSeqOrigin seq) 
527                       elt_ty enumFromToName             `thenM` \ enum_from_to ->
528
529     returnM (ArithSeqOut (nlHsVar enum_from_to) (FromTo expr1' expr2'))
530
531 tc_expr in_expr@(ArithSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
532   = addErrCtxt  (arithSeqCtxt in_expr) $
533     zapToListTy  res_ty                                 `thenM`    \ elt_ty ->  
534     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
535     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
536     tcCheckRho expr3 elt_ty                             `thenM`    \ expr3' ->
537     newMethodFromName (ArithSeqOrigin seq) 
538                       elt_ty enumFromThenToName         `thenM` \ eft ->
539
540     returnM (ArithSeqOut (nlHsVar eft) (FromThenTo expr1' expr2' expr3'))
541
542 tc_expr in_expr@(PArrSeqIn seq@(FromTo expr1 expr2)) res_ty
543   = addErrCtxt (parrSeqCtxt in_expr) $
544     zapToPArrTy  res_ty                                 `thenM`    \ elt_ty ->  
545     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
546     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
547     newMethodFromName (PArrSeqOrigin seq) 
548                       elt_ty enumFromToPName            `thenM` \ enum_from_to ->
549
550     returnM (PArrSeqOut (nlHsVar enum_from_to) (FromTo expr1' expr2'))
551
552 tc_expr in_expr@(PArrSeqIn seq@(FromThenTo expr1 expr2 expr3)) res_ty
553   = addErrCtxt  (parrSeqCtxt in_expr) $
554     zapToPArrTy  res_ty                                 `thenM`    \ elt_ty ->  
555     tcCheckRho expr1 elt_ty                             `thenM`    \ expr1' ->
556     tcCheckRho expr2 elt_ty                             `thenM`    \ expr2' ->
557     tcCheckRho expr3 elt_ty                             `thenM`    \ expr3' ->
558     newMethodFromName (PArrSeqOrigin seq)
559                       elt_ty enumFromThenToPName        `thenM` \ eft ->
560
561     returnM (PArrSeqOut (nlHsVar eft) (FromThenTo expr1' expr2' expr3'))
562
563 tc_expr (PArrSeqIn _) _ 
564   = panic "TcExpr.tcMonoExpr: Infinite parallel array!"
565     -- the parser shouldn't have generated it and the renamer shouldn't have
566     -- let it through
567 \end{code}
568
569
570 %************************************************************************
571 %*                                                                      *
572                 Template Haskell
573 %*                                                                      *
574 %************************************************************************
575
576 \begin{code}
577 #ifdef GHCI     /* Only if bootstrapped */
578         -- Rename excludes these cases otherwise
579 tc_expr (HsSpliceE splice) res_ty = tcSpliceExpr splice res_ty
580 tc_expr (HsBracket brack)  res_ty = do  { e <- tcBracket brack res_ty
581                                         ; return (unLoc e) }
582 #endif /* GHCI */
583 \end{code}
584
585
586 %************************************************************************
587 %*                                                                      *
588                 Catch-all
589 %*                                                                      *
590 %************************************************************************
591
592 \begin{code}
593 tc_expr other _ = pprPanic "tcMonoExpr" (ppr other)
594 \end{code}
595
596
597 %************************************************************************
598 %*                                                                      *
599 \subsection{@tcApp@ typchecks an application}
600 %*                                                                      *
601 %************************************************************************
602
603 \begin{code}
604
605 tcApp :: LHsExpr Name -> [LHsExpr Name]         -- Function and args
606       -> Expected TcRhoType                     -- Expected result type of application
607       -> TcM (HsExpr TcId)                              -- Translated fun and args
608
609 tcApp (L _ (HsApp e1 e2)) args res_ty 
610   = tcApp e1 (e2:args) res_ty           -- Accumulate the arguments
611
612 tcApp fun args res_ty
613   =     -- First type-check the function
614     tcInferRho fun                              `thenM` \ (fun', fun_ty) ->
615
616     addErrCtxt (wrongArgsCtxt "too many" fun args) (
617         traceTc (text "tcApp" <+> (ppr fun $$ ppr fun_ty))      `thenM_`
618         split_fun_ty fun_ty (length args)
619     )                                           `thenM` \ (expected_arg_tys, actual_result_ty) ->
620
621         -- Unify with expected result before (was: after) type-checking the args
622         -- so that the info from res_ty (was: args) percolates to args (was actual_result_ty).
623         -- This is when we might detect a too-few args situation.
624         -- (One can think of cases when the opposite order would give
625         -- a better error message.)
626         -- [March 2003: I'm experimenting with putting this first.  Here's an 
627         --              example where it actually makes a real difference
628         --    class C t a b | t a -> b
629         --    instance C Char a Bool
630         --
631         --    data P t a = forall b. (C t a b) => MkP b
632         --    data Q t   = MkQ (forall a. P t a)
633     
634         --    f1, f2 :: Q Char;
635         --    f1 = MkQ (MkP True)
636         --    f2 = MkQ (MkP True :: forall a. P Char a)
637         --
638         -- With the change, f1 will type-check, because the 'Char' info from
639         -- the signature is propagated into MkQ's argument. With the check
640         -- in the other order, the extra signature in f2 is reqd.]
641
642     addErrCtxtM (checkArgsCtxt fun args res_ty actual_result_ty)
643                 (tcSubExp res_ty actual_result_ty)      `thenM` \ co_fn ->
644
645         -- Now typecheck the args
646     mappM (tcArg fun)
647           (zip3 args expected_arg_tys [1..])    `thenM` \ args' ->
648
649     returnM (co_fn <$> unLoc (foldl mkHsApp fun' args'))
650
651
652 -- If an error happens we try to figure out whether the
653 -- function has been given too many or too few arguments,
654 -- and say so.
655 -- The ~(Check...) is because in the Infer case the tcSubExp 
656 -- definitely won't fail, so we can be certain we're in the Check branch
657 checkArgsCtxt fun args (Infer _) actual_res_ty tidy_env
658   = return (tidy_env, ptext SLIT("Urk infer"))
659
660 checkArgsCtxt fun args (Check expected_res_ty) actual_res_ty tidy_env
661   = zonkTcType expected_res_ty    `thenM` \ exp_ty' ->
662     zonkTcType actual_res_ty      `thenM` \ act_ty' ->
663     let
664       (env1, exp_ty'') = tidyOpenType tidy_env exp_ty'
665       (env2, act_ty'') = tidyOpenType env1     act_ty'
666       (exp_args, _)    = tcSplitFunTys exp_ty''
667       (act_args, _)    = tcSplitFunTys act_ty''
668
669       len_act_args     = length act_args
670       len_exp_args     = length exp_args
671
672       message | len_exp_args < len_act_args = wrongArgsCtxt "too few" fun args
673               | len_exp_args > len_act_args = wrongArgsCtxt "too many" fun args
674               | otherwise                   = appCtxt fun args
675     in
676     returnM (env2, message)
677
678
679 split_fun_ty :: TcRhoType       -- The type of the function
680              -> Int             -- Number of arguments
681              -> TcM ([TcType],  -- Function argument types
682                      TcType)    -- Function result types
683
684 split_fun_ty fun_ty 0 
685   = returnM ([], fun_ty)
686
687 split_fun_ty fun_ty n
688   =     -- Expect the function to have type A->B
689     unifyFunTy fun_ty           `thenM` \ (arg_ty, res_ty) ->
690     split_fun_ty res_ty (n-1)   `thenM` \ (arg_tys, final_res_ty) ->
691     returnM (arg_ty:arg_tys, final_res_ty)
692 \end{code}
693
694 \begin{code}
695 tcArg :: LHsExpr Name                           -- The function (for error messages)
696       -> (LHsExpr Name, TcSigmaType, Int)       -- Actual argument and expected arg type
697       -> TcM (LHsExpr TcId)                     -- Resulting argument
698
699 tcArg the_fun (arg, expected_arg_ty, arg_no)
700   = addErrCtxt (funAppCtxt the_fun arg arg_no) $
701     tcCheckSigma arg expected_arg_ty
702 \end{code}
703
704
705 %************************************************************************
706 %*                                                                      *
707 \subsection{@tcId@ typchecks an identifier occurrence}
708 %*                                                                      *
709 %************************************************************************
710
711 tcId instantiates an occurrence of an Id.
712 The instantiate_it loop runs round instantiating the Id.
713 It has to be a loop because we are now prepared to entertain
714 types like
715         f:: forall a. Eq a => forall b. Baz b => tau
716 We want to instantiate this to
717         f2::tau         {f2 = f1 b (Baz b), f1 = f a (Eq a)}
718
719 The -fno-method-sharing flag controls what happens so far as the LIE
720 is concerned.  The default case is that for an overloaded function we 
721 generate a "method" Id, and add the Method Inst to the LIE.  So you get
722 something like
723         f :: Num a => a -> a
724         f = /\a (d:Num a) -> let m = (+) a d in \ (x:a) -> m x x
725 If you specify -fno-method-sharing, the dictionary application 
726 isn't shared, so we get
727         f :: Num a => a -> a
728         f = /\a (d:Num a) (x:a) -> (+) a d x x
729 This gets a bit less sharing, but
730         a) it's better for RULEs involving overloaded functions
731         b) perhaps fewer separated lambdas
732
733 \begin{code}
734 tcId :: Name -> TcM (HsExpr TcId, TcRhoType)
735 tcId name       -- Look up the Id and instantiate its type
736   =     -- First check whether it's a DataCon
737         -- Reason: we must not forget to chuck in the
738         --         constraints from their "silly context"
739     tcLookup name               `thenM` \ thing ->
740     case thing of {
741         AGlobal (ADataCon data_con)  -> inst_data_con data_con 
742     ;   AGlobal (AnId id)            -> loop (HsVar id) (idType id)
743                 -- A global cannot possibly be ill-staged
744                 -- nor does it need the 'lifting' treatment
745
746     ;   ATcId id th_level proc_level -> tc_local_id id th_level proc_level
747     ;   other                        -> pprPanic "tcId" (ppr name $$ ppr thing)
748     }
749   where
750
751 #ifndef GHCI
752     tc_local_id id th_bind_lvl proc_lvl                 -- Non-TH case
753         = checkProcLevel id proc_lvl    `thenM_`
754           loop (HsVar id) (idType id)
755
756 #else /* GHCI and TH is on */
757     tc_local_id id th_bind_lvl proc_lvl                 -- TH case
758         = checkProcLevel id proc_lvl    `thenM_`
759
760         -- Check for cross-stage lifting
761           getStage                              `thenM` \ use_stage -> 
762           case use_stage of
763               Brack use_lvl ps_var lie_var
764                 | use_lvl > th_bind_lvl 
765                 ->      -- E.g. \x -> [| h x |]
766                 -- We must behave as if the reference to x was
767
768                 --      h $(lift x)     
769                 -- We use 'x' itself as the splice proxy, used by 
770                 -- the desugarer to stitch it all back together.
771                 -- If 'x' occurs many times we may get many identical
772                 -- bindings of the same splice proxy, but that doesn't
773                 -- matter, although it's a mite untidy.
774                 let
775                     id_ty = idType id
776                 in
777                 checkTc (isTauTy id_ty) (polySpliceErr id)      `thenM_` 
778                     -- If x is polymorphic, its occurrence sites might
779                     -- have different instantiations, so we can't use plain
780                     -- 'x' as the splice proxy name.  I don't know how to 
781                     -- solve this, and it's probably unimportant, so I'm
782                     -- just going to flag an error for now
783
784                 setLIEVar lie_var       (
785                 newMethodFromName orig id_ty DsMeta.liftName    `thenM` \ lift ->
786                         -- Put the 'lift' constraint into the right LIE
787         
788                 -- Update the pending splices
789                 readMutVar ps_var                       `thenM` \ ps ->
790                 writeMutVar ps_var ((name, nlHsApp (nlHsVar lift) (nlHsVar id)) : ps)   `thenM_`
791         
792                 returnM (HsVar id, id_ty))
793
794               other -> 
795                 checkWellStaged (quotes (ppr id)) th_bind_lvl use_stage `thenM_`
796                 loop (HsVar id) (idType id)
797 #endif /* GHCI */
798
799     loop (HsVar fun_id) fun_ty
800         | want_method_inst fun_ty
801         = tcInstType VanillaTv fun_ty           `thenM` \ (tyvars, theta, tau) ->
802           newMethodWithGivenTy orig fun_id 
803                 (mkTyVarTys tyvars) theta tau   `thenM` \ meth_id ->
804           loop (HsVar meth_id) tau
805
806     loop fun fun_ty 
807         | isSigmaTy fun_ty
808         = tcInstCall orig fun_ty        `thenM` \ (inst_fn, tau) ->
809           loop (inst_fn <$> fun) tau
810
811         | otherwise
812         = returnM (fun, fun_ty)
813
814         --      Hack Alert (want_method_inst)!
815         -- If   f :: (%x :: T) => Int -> Int
816         -- Then if we have two separate calls, (f 3, f 4), we cannot
817         -- make a method constraint that then gets shared, thus:
818         --      let m = f %x in (m 3, m 4)
819         -- because that loses the linearity of the constraint.
820         -- The simplest thing to do is never to construct a method constraint
821         -- in the first place that has a linear implicit parameter in it.
822     want_method_inst fun_ty 
823         | opt_NoMethodSharing = False   
824         | otherwise           = case tcSplitSigmaTy fun_ty of
825                                   (_,[],_)    -> False  -- Not overloaded
826                                   (_,theta,_) -> not (any isLinearPred theta)
827
828
829         -- We treat data constructors differently, because we have to generate
830         -- constraints for their silly theta, which no longer appears in
831         -- the type of dataConWrapId (see note on "stupid context" in DataCon.lhs
832         -- It's dual to TcPat.tcConstructor
833     inst_data_con data_con
834       = tcInstDataCon orig data_con     `thenM` \ (ty_args, ex_dicts, arg_tys, result_ty, _) ->
835         extendLIEs ex_dicts             `thenM_`
836         getSrcSpanM                     `thenM` \ loc ->
837         returnM (unLoc (mkHsDictApp (mkHsTyApp (L loc (HsVar (dataConWrapId data_con))) ty_args) 
838                              (map instToId ex_dicts)), 
839                  mkFunTys arg_tys result_ty)
840         -- ToDo: nasty loc/unloc stuff here
841
842     orig = OccurrenceOf name
843 \end{code}
844
845 %************************************************************************
846 %*                                                                      *
847 \subsection{Record bindings}
848 %*                                                                      *
849 %************************************************************************
850
851 Game plan for record bindings
852 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
853 1. Find the TyCon for the bindings, from the first field label.
854
855 2. Instantiate its tyvars and unify (T a1 .. an) with expected_ty.
856
857 For each binding field = value
858
859 3. Instantiate the field type (from the field label) using the type
860    envt from step 2.
861
862 4  Type check the value using tcArg, passing the field type as 
863    the expected argument type.
864
865 This extends OK when the field types are universally quantified.
866
867         
868 \begin{code}
869 tcRecordBinds
870         :: TyCon                -- Type constructor for the record
871         -> [TcType]             -- Args of this type constructor
872         -> HsRecordBinds Name
873         -> TcM (HsRecordBinds TcId)
874
875 tcRecordBinds tycon ty_args rbinds
876   = mappM do_bind rbinds
877   where
878     tenv = mkTopTyVarSubst (tyConTyVars tycon) ty_args
879
880     do_bind (L loc field_lbl_name, rhs)
881       = addErrCtxt (fieldCtxt field_lbl_name)   $
882         tcLookupId field_lbl_name               `thenM` \ sel_id ->
883         let
884             field_lbl = recordSelectorFieldLabel sel_id
885             field_ty  = substTy tenv (fieldLabelType field_lbl)
886         in
887         ASSERT( isRecordSelector sel_id )
888                 -- This lookup and assertion will surely succeed, because
889                 -- we check that the fields are indeed record selectors
890                 -- before calling tcRecordBinds
891         ASSERT2( fieldLabelTyCon field_lbl == tycon, ppr field_lbl )
892                 -- The caller of tcRecordBinds has already checked
893                 -- that all the fields come from the same type
894
895         tcCheckSigma rhs field_ty               `thenM` \ rhs' ->
896
897         returnM (L loc sel_id, rhs')
898
899 badFields rbinds data_con
900   = filter (not . (`elem` field_names)) (recBindFields rbinds)
901   where
902     field_names = map fieldLabelName (dataConFieldLabels data_con)
903
904 checkMissingFields :: DataCon -> HsRecordBinds Name -> TcM ()
905 checkMissingFields data_con rbinds
906   | null field_labels   -- Not declared as a record;
907                         -- But C{} is still valid if no strict fields
908   = if any isMarkedStrict field_strs then
909         -- Illegal if any arg is strict
910         addErrTc (missingStrictFields data_con [])
911     else
912         returnM ()
913                         
914   | otherwise           -- A record
915   = checkM (null missing_s_fields)
916            (addErrTc (missingStrictFields data_con missing_s_fields))   `thenM_`
917
918     doptM Opt_WarnMissingFields         `thenM` \ warn ->
919     checkM (not (warn && notNull missing_ns_fields))
920            (warnTc True (missingFields data_con missing_ns_fields))
921
922   where
923     missing_s_fields
924         = [ fl | (fl, str) <- field_info,
925                  isMarkedStrict str,
926                  not (fieldLabelName fl `elem` field_names_used)
927           ]
928     missing_ns_fields
929         = [ fl | (fl, str) <- field_info,
930                  not (isMarkedStrict str),
931                  not (fieldLabelName fl `elem` field_names_used)
932           ]
933
934     field_names_used = recBindFields rbinds
935     field_labels     = dataConFieldLabels data_con
936
937     field_info = zipEqual "missingFields"
938                           field_labels
939                           field_strs
940
941     field_strs = dataConStrictMarks data_con
942 \end{code}
943
944 %************************************************************************
945 %*                                                                      *
946 \subsection{@tcCheckRhos@ typechecks a {\em list} of expressions}
947 %*                                                                      *
948 %************************************************************************
949
950 \begin{code}
951 tcCheckRhos :: [LHsExpr Name] -> [TcType] -> TcM [LHsExpr TcId]
952
953 tcCheckRhos [] [] = returnM []
954 tcCheckRhos (expr:exprs) (ty:tys)
955  = tcCheckRho  expr  ty         `thenM` \ expr' ->
956    tcCheckRhos exprs tys        `thenM` \ exprs' ->
957    returnM (expr':exprs')
958 \end{code}
959
960
961 %************************************************************************
962 %*                                                                      *
963 \subsection{Literals}
964 %*                                                                      *
965 %************************************************************************
966
967 Overloaded literals.
968
969 \begin{code}
970 tcLit :: HsLit -> Expected TcRhoType -> TcM (HsExpr TcId)
971 tcLit lit res_ty 
972   = zapExpectedTo res_ty (hsLitType lit)                `thenM_`
973     returnM (HsLit lit)
974 \end{code}
975
976
977 %************************************************************************
978 %*                                                                      *
979 \subsection{Errors and contexts}
980 %*                                                                      *
981 %************************************************************************
982
983 Boring and alphabetical:
984 \begin{code}
985 arithSeqCtxt expr
986   = hang (ptext SLIT("In an arithmetic sequence:")) 4 (ppr expr)
987
988 parrSeqCtxt expr
989   = hang (ptext SLIT("In a parallel array sequence:")) 4 (ppr expr)
990
991 caseCtxt expr
992   = hang (ptext SLIT("In the case expression:")) 4 (ppr expr)
993
994 caseScrutCtxt expr
995   = hang (ptext SLIT("In the scrutinee of a case expression:")) 4 (ppr expr)
996
997 exprCtxt expr
998   = hang (ptext SLIT("In the expression:")) 4 (ppr expr)
999
1000 fieldCtxt field_name
1001   = ptext SLIT("In the") <+> quotes (ppr field_name) <+> ptext SLIT("field of a record")
1002
1003 funAppCtxt fun arg arg_no
1004   = hang (hsep [ ptext SLIT("In the"), speakNth arg_no, ptext SLIT("argument of"), 
1005                     quotes (ppr fun) <> text ", namely"])
1006          4 (quotes (ppr arg))
1007
1008 listCtxt expr
1009   = hang (ptext SLIT("In the list element:")) 4 (ppr expr)
1010
1011 parrCtxt expr
1012   = hang (ptext SLIT("In the parallel array element:")) 4 (ppr expr)
1013
1014 predCtxt expr
1015   = hang (ptext SLIT("In the predicate expression:")) 4 (ppr expr)
1016
1017 appCtxt fun args
1018   = ptext SLIT("In the application") <+> quotes (ppr the_app)
1019   where
1020     the_app = foldl mkHsApp fun args    -- Used in error messages
1021
1022 badFieldsUpd rbinds
1023   = hang (ptext SLIT("No constructor has all these fields:"))
1024          4 (pprQuotedList (recBindFields rbinds))
1025
1026 recordUpdCtxt expr = ptext SLIT("In the record update:") <+> ppr expr
1027 recordConCtxt expr = ptext SLIT("In the record construction:") <+> ppr expr
1028
1029 notSelector field
1030   = hsep [quotes (ppr field), ptext SLIT("is not a record selector")]
1031
1032 missingStrictFields :: DataCon -> [FieldLabel] -> SDoc
1033 missingStrictFields con fields
1034   = header <> rest
1035   where
1036     rest | null fields = empty  -- Happens for non-record constructors 
1037                                 -- with strict fields
1038          | otherwise   = colon <+> pprWithCommas ppr fields
1039
1040     header = ptext SLIT("Constructor") <+> quotes (ppr con) <+> 
1041              ptext SLIT("does not have the required strict field(s)") 
1042           
1043 missingFields :: DataCon -> [FieldLabel] -> SDoc
1044 missingFields con fields
1045   = ptext SLIT("Fields of") <+> quotes (ppr con) <+> ptext SLIT("not initialised:") 
1046         <+> pprWithCommas ppr fields
1047
1048 wrongArgsCtxt too_many_or_few fun args
1049   = hang (ptext SLIT("Probable cause:") <+> quotes (ppr fun)
1050                     <+> ptext SLIT("is applied to") <+> text too_many_or_few 
1051                     <+> ptext SLIT("arguments in the call"))
1052          4 (parens (ppr the_app))
1053   where
1054     the_app = foldl mkHsApp fun args    -- Used in error messages
1055
1056 #ifdef GHCI
1057 polySpliceErr :: Id -> SDoc
1058 polySpliceErr id
1059   = ptext SLIT("Can't splice the polymorphic local variable") <+> quotes (ppr id)
1060 #endif
1061 \end{code}