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