[project @ 1999-07-15 14:08:03 by keithw]
[ghc-hetmet.git] / ghc / compiler / rename / RnSource.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnSource]{Main pass of renamer}
5
6 \begin{code}
7 module RnSource ( rnDecl, rnSourceDecls, rnHsType, rnHsSigType ) where
8
9 #include "HsVersions.h"
10
11 import RnExpr
12 import HsSyn
13 import HsPragmas
14 import HsTypes          ( getTyVarName, pprClassAssertion, cmpHsTypes )
15 import RdrName          ( RdrName, isRdrDataCon, rdrNameOcc, isRdrTyVar )
16 import RdrHsSyn         ( RdrNameContext, RdrNameHsType, RdrNameConDecl,
17                           extractRuleBndrsTyVars, extractHsTyRdrTyVars
18                         )
19 import RnHsSyn
20 import HsCore
21
22 import RnBinds          ( rnTopBinds, rnMethodBinds, renameSigs, unknownSigErr )
23 import RnEnv            ( bindTyVarsRn, lookupBndrRn, lookupOccRn, 
24                           lookupImplicitOccRn, 
25                           bindLocalsRn, bindLocalRn, bindLocalsFVRn, bindUVarRn,
26                           bindTyVarsFVRn, bindTyVarsFV2Rn, extendTyVarEnvFVRn,
27                           bindCoreLocalFVRn, bindCoreLocalsFVRn,
28                           checkDupOrQualNames, checkDupNames,
29                           mkImportedGlobalName, mkImportedGlobalFromRdrName,
30                           newDFunName, getDFunKey, newImplicitBinder,
31                           FreeVars, emptyFVs, plusFV, plusFVs, unitFV, addOneFV, mapFvRn
32                         )
33 import RnMonad
34
35 import Name             ( Name, OccName,
36                           ExportFlag(..), Provenance(..), 
37                           nameOccName, NamedThing(..)
38                         )
39 import NameSet
40 import OccName          ( mkDefaultMethodOcc )
41 import BasicTypes       ( TopLevelFlag(..) )
42 import FiniteMap        ( elemFM )
43 import PrelInfo         ( derivableClassKeys,
44                           deRefStablePtr_NAME, makeStablePtr_NAME, bindIO_NAME
45                         )
46 import Bag              ( bagToList )
47 import List             ( partition, nub )
48 import Outputable
49 import SrcLoc           ( SrcLoc )
50 import CmdLineOpts      ( opt_WarnUnusedMatches )       -- Warn of unused for-all'd tyvars
51 import Unique           ( Uniquable(..) )
52 import UniqFM           ( lookupUFM )
53 import Maybes           ( maybeToBool, catMaybes )
54 import Util
55 \end{code}
56
57 @rnDecl@ `renames' declarations.
58 It simultaneously performs dependency analysis and precedence parsing.
59 It also does the following error checks:
60 \begin{enumerate}
61 \item
62 Checks that tyvars are used properly. This includes checking
63 for undefined tyvars, and tyvars in contexts that are ambiguous.
64 \item
65 Checks that all variable occurences are defined.
66 \item 
67 Checks the @(..)@ etc constraints in the export list.
68 \end{enumerate}
69
70
71 %*********************************************************
72 %*                                                      *
73 \subsection{Value declarations}
74 %*                                                      *
75 %*********************************************************
76
77 \begin{code}
78 rnSourceDecls :: [RdrNameHsDecl] -> RnMS ([RenamedHsDecl], FreeVars)
79         -- The decls get reversed, but that's ok
80
81 rnSourceDecls decls
82   = go emptyFVs [] decls
83   where
84         -- Fixity decls have been dealt with already; ignore them
85     go fvs ds' []          = returnRn (ds', fvs)
86     go fvs ds' (FixD _:ds) = go fvs ds' ds
87     go fvs ds' (d:ds)      = rnDecl d   `thenRn` \(d', fvs') ->
88                              go (fvs `plusFV` fvs') (d':ds') ds
89 \end{code}
90
91
92 %*********************************************************
93 %*                                                      *
94 \subsection{Value declarations}
95 %*                                                      *
96 %*********************************************************
97
98 \begin{code}
99 -- rnDecl does all the work
100 rnDecl :: RdrNameHsDecl -> RnMS (RenamedHsDecl, FreeVars)
101
102 rnDecl (ValD binds) = rnTopBinds binds  `thenRn` \ (new_binds, fvs) ->
103                       returnRn (ValD new_binds, fvs)
104
105
106 rnDecl (SigD (IfaceSig name ty id_infos loc))
107   = pushSrcLocRn loc $
108     lookupBndrRn name           `thenRn` \ name' ->
109     rnHsType doc_str ty         `thenRn` \ (ty',fvs1) ->
110     mapFvRn rnIdInfo id_infos   `thenRn` \ (id_infos', fvs2) -> 
111     returnRn (SigD (IfaceSig name' ty' id_infos' loc), fvs1 `plusFV` fvs2)
112   where
113     doc_str = text "the interface signature for" <+> quotes (ppr name)
114 \end{code}
115
116 %*********************************************************
117 %*                                                      *
118 \subsection{Type declarations}
119 %*                                                      *
120 %*********************************************************
121
122 @rnTyDecl@ uses the `global name function' to create a new type
123 declaration in which local names have been replaced by their original
124 names, reporting any unknown names.
125
126 Renaming type variables is a pain. Because they now contain uniques,
127 it is necessary to pass in an association list which maps a parsed
128 tyvar to its @Name@ representation.
129 In some cases (type signatures of values),
130 it is even necessary to go over the type first
131 in order to get the set of tyvars used by it, make an assoc list,
132 and then go over it again to rename the tyvars!
133 However, we can also do some scoping checks at the same time.
134
135 \begin{code}
136 rnDecl (TyClD (TyData new_or_data context tycon tyvars condecls derivings pragmas src_loc))
137   = pushSrcLocRn src_loc $
138     lookupBndrRn tycon                          `thenRn` \ tycon' ->
139     bindTyVarsFVRn data_doc tyvars              $ \ tyvars' ->
140     rnContext data_doc context                  `thenRn` \ (context', cxt_fvs) ->
141     checkDupOrQualNames data_doc con_names      `thenRn_`
142     mapFvRn rnConDecl condecls                  `thenRn` \ (condecls', con_fvs) ->
143     rnDerivs derivings                          `thenRn` \ (derivings', deriv_fvs) ->
144     ASSERT(isNoDataPragmas pragmas)
145     returnRn (TyClD (TyData new_or_data context' tycon' tyvars' condecls'
146                      derivings' noDataPragmas src_loc),
147               cxt_fvs `plusFV` con_fvs `plusFV` deriv_fvs)
148   where
149     data_doc = text "the data type declaration for" <+> quotes (ppr tycon)
150     con_names = map conDeclName condecls
151
152 rnDecl (TyClD (TySynonym name tyvars ty src_loc))
153   = pushSrcLocRn src_loc $
154     lookupBndrRn name                           `thenRn` \ name' ->
155     bindTyVarsFVRn syn_doc tyvars               $ \ tyvars' ->
156     rnHsType syn_doc ty                         `thenRn` \ (ty', ty_fvs) ->
157     returnRn (TyClD (TySynonym name' tyvars' ty' src_loc), ty_fvs)
158   where
159     syn_doc = text "the declaration for type synonym" <+> quotes (ppr name)
160
161 rnDecl (TyClD (ClassDecl context cname tyvars sigs mbinds pragmas
162                tname dname snames src_loc))
163   = pushSrcLocRn src_loc $
164
165     lookupBndrRn cname                                  `thenRn` \ cname' ->
166
167         -- Deal with the implicit tycon and datacon name
168         -- They aren't in scope (because they aren't visible to the user)
169         -- and what we want to do is simply look them up in the cache;
170         -- we jolly well ought to get a 'hit' there!
171         -- So the 'Imported' part of this call is not relevant. 
172         -- Unclean; but since these two are the only place this happens
173         -- I can't work up the energy to do it more beautifully
174     mkImportedGlobalFromRdrName tname                   `thenRn` \ tname' ->
175     mkImportedGlobalFromRdrName dname                   `thenRn` \ dname' ->
176     mapRn mkImportedGlobalFromRdrName snames            `thenRn` \ snames' ->
177
178         -- Tyvars scope over bindings and context
179     bindTyVarsFV2Rn cls_doc tyvars              ( \ clas_tyvar_names tyvars' ->
180
181         -- Check the superclasses
182     rnContext cls_doc context                   `thenRn` \ (context', cxt_fvs) ->
183
184         -- Check the signatures
185     let
186             -- First process the class op sigs, then the fixity sigs.
187           (op_sigs, non_op_sigs) = partition isClassOpSig sigs
188           (fix_sigs, non_sigs)   = partition isFixitySig  non_op_sigs
189     in
190     checkDupOrQualNames sig_doc sig_rdr_names_w_locs    `thenRn_` 
191     mapFvRn (rn_op cname' clas_tyvar_names) op_sigs
192     `thenRn` \ (sigs', sig_fvs) ->
193     mapRn_  (unknownSigErr) non_sigs                    `thenRn_`
194     let
195      binders = mkNameSet [ nm | (ClassOpSig nm _ _ _) <- sigs' ]
196     in
197     renameSigs False binders lookupOccRn fix_sigs
198     `thenRn` \ (fixs', fix_fvs) ->
199
200         -- Check the methods
201     checkDupOrQualNames meth_doc meth_rdr_names_w_locs  `thenRn_`
202     rnMethodBinds mbinds
203     `thenRn` \ (mbinds', meth_fvs) ->
204
205         -- Typechecker is responsible for checking that we only
206         -- give default-method bindings for things in this class.
207         -- The renamer *could* check this for class decls, but can't
208         -- for instance decls.
209
210     ASSERT(isNoClassPragmas pragmas)
211     returnRn (TyClD (ClassDecl context' cname' tyvars' (fixs' ++ sigs') mbinds'
212                                NoClassPragmas tname' dname' snames' src_loc),
213               sig_fvs   `plusFV`
214               fix_fvs   `plusFV`
215               cxt_fvs   `plusFV`
216               meth_fvs
217              )
218     )
219   where
220     cls_doc  = text "the declaration for class"         <+> ppr cname
221     sig_doc  = text "the signatures for class"          <+> ppr cname
222     meth_doc = text "the default-methods for class"     <+> ppr cname
223
224     sig_rdr_names_w_locs  = [(op,locn) | ClassOpSig op _ _ locn <- sigs]
225     meth_rdr_names_w_locs = bagToList (collectMonoBinders mbinds)
226     meth_rdr_names        = map fst meth_rdr_names_w_locs
227
228     rn_op clas clas_tyvars sig@(ClassOpSig op maybe_dm ty locn)
229       = pushSrcLocRn locn $
230         lookupBndrRn op                         `thenRn` \ op_name ->
231
232                 -- Check the signature
233         rnHsSigType (quotes (ppr op)) ty        `thenRn` \ (new_ty, op_ty_fvs)  ->
234         let
235             check_in_op_ty clas_tyvar =
236                  checkRn (clas_tyvar `elemNameSet` op_ty_fvs)
237                          (classTyVarNotInOpTyErr clas_tyvar sig)
238         in
239         mapRn_ check_in_op_ty clas_tyvars                `thenRn_`
240
241                 -- Make the default-method name
242         getModeRn                                       `thenRn` \ mode ->
243         (case (mode, maybe_dm) of 
244             (SourceMode, _)
245                 | op `elem` meth_rdr_names
246                 -> -- Source class decl with an explicit method decl
247                    newImplicitBinder (mkDefaultMethodOcc (rdrNameOcc op)) locn
248                    `thenRn` \ dm_name ->
249                    returnRn (Just dm_name, emptyFVs)
250
251                 | otherwise     
252                 ->      -- Source class dec, no explicit method decl
253                         returnRn (Nothing, emptyFVs)
254
255             (InterfaceMode, Just dm_rdr_name)
256                 ->      -- Imported class that has a default method decl
257                         -- See comments with tname, snames, above
258                     lookupImplicitOccRn dm_rdr_name     `thenRn` \ dm_name ->
259                     returnRn (Just dm_name, unitFV dm_name)
260                             -- An imported class decl mentions, rather than defines,
261                             -- the default method, so we must arrange to pull it in
262
263             (InterfaceMode, Nothing)
264                         -- Imported class with no default metho
265                 ->      returnRn (Nothing, emptyFVs)
266         )                                               `thenRn` \ (maybe_dm_name, dm_fvs) ->
267
268         returnRn (ClassOpSig op_name maybe_dm_name new_ty locn, op_ty_fvs `plusFV` dm_fvs)
269 \end{code}
270
271
272 %*********************************************************
273 %*                                                      *
274 \subsection{Instance declarations}
275 %*                                                      *
276 %*********************************************************
277
278 \begin{code}
279 rnDecl (InstD (InstDecl inst_ty mbinds uprags dfun_rdr_name src_loc))
280   = pushSrcLocRn src_loc $
281     rnHsSigType (text "an instance decl") inst_ty `thenRn` \ (inst_ty', inst_fvs) ->
282     let
283         inst_tyvars = case inst_ty' of
284                         HsForAllTy (Just inst_tyvars) _ _ -> inst_tyvars
285                         other                             -> []
286         -- (Slightly strangely) the forall-d tyvars scope over
287         -- the method bindings too
288     in
289
290         -- Rename the bindings
291         -- NB meth_names can be qualified!
292     checkDupNames meth_doc meth_names           `thenRn_`
293     extendTyVarEnvFVRn inst_tyvars (            
294         rnMethodBinds mbinds
295     )                                           `thenRn` \ (mbinds', meth_fvs) ->
296     let 
297         binders = mkNameSet (map fst (bagToList (collectMonoBinders mbinds')))
298
299         -- Delete sigs (&report) sigs that aren't allowed inside an
300         -- instance decl:
301         --
302         --  + type signatures
303         --  + fixity decls
304         --
305         (ok_sigs, not_ok_idecl_sigs) = partition okInInstDecl uprags
306         
307         okInInstDecl (FixSig _)  = False
308         okInInstDecl (Sig _ _ _) = False
309         okInInstDecl _           = True
310         
311     in
312       -- You can't have fixity decls & type signatures
313       -- within an instance declaration.
314     mapRn_ unknownSigErr not_ok_idecl_sigs       `thenRn_`
315
316         -- Rename the prags and signatures.
317         -- Note that the type variables are not in scope here,
318         -- so that      instance Eq a => Eq (T a) where
319         --                      {-# SPECIALISE instance Eq a => Eq (T [a]) #-}
320         -- works OK. 
321     renameSigs False binders lookupOccRn ok_sigs `thenRn` \ (new_uprags, prag_fvs) ->
322
323     getModeRn           `thenRn` \ mode ->
324     (case mode of
325         InterfaceMode -> lookupImplicitOccRn dfun_rdr_name      `thenRn` \ dfun_name ->
326                          returnRn (dfun_name, unitFV dfun_name)
327         SourceMode    -> newDFunName (getDFunKey inst_ty') src_loc
328                          `thenRn` \ dfun_name ->
329                          returnRn (dfun_name, emptyFVs)
330     )
331     `thenRn` \ (dfun_name, dfun_fv) ->
332
333     -- The typechecker checks that all the bindings are for the right class.
334     returnRn (InstD (InstDecl inst_ty' mbinds' new_uprags dfun_name src_loc),
335               inst_fvs `plusFV` meth_fvs `plusFV` prag_fvs `plusFV` dfun_fv)
336   where
337     meth_doc = text "the bindings in an instance declaration"
338     meth_names   = bagToList (collectMonoBinders mbinds)
339 \end{code}
340
341 %*********************************************************
342 %*                                                      *
343 \subsection{Default declarations}
344 %*                                                      *
345 %*********************************************************
346
347 \begin{code}
348 rnDecl (DefD (DefaultDecl tys src_loc))
349   = pushSrcLocRn src_loc $
350     rnHsTypes doc_str tys               `thenRn` \ (tys', fvs) ->
351     returnRn (DefD (DefaultDecl tys' src_loc), fvs)
352   where
353     doc_str = text "a `default' declaration"
354 \end{code}
355
356 %*********************************************************
357 %*                                                      *
358 \subsection{Foreign declarations}
359 %*                                                      *
360 %*********************************************************
361
362 \begin{code}
363 rnDecl (ForD (ForeignDecl name imp_exp ty ext_nm cconv src_loc))
364   = pushSrcLocRn src_loc $
365     lookupOccRn name                    `thenRn` \ name' ->
366     let 
367         fvs1 = case imp_exp of
368                 FoImport _ | not isDyn  -> emptyFVs
369                 FoLabel                 -> emptyFVs
370                 FoExport   | isDyn      -> mkNameSet [makeStablePtr_NAME,
371                                                       deRefStablePtr_NAME,
372                                                       bindIO_NAME]
373                            | otherwise  -> mkNameSet [name']
374                 _ -> emptyFVs
375     in
376     rnHsSigType fo_decl_msg ty                  `thenRn` \ (ty', fvs2) ->
377     returnRn (ForD (ForeignDecl name' imp_exp ty' ext_nm cconv src_loc), 
378               fvs1 `plusFV` fvs2)
379  where
380   fo_decl_msg = ptext SLIT("a foreign declaration")
381   isDyn       = isDynamic ext_nm
382 \end{code}
383
384 %*********************************************************
385 %*                                                      *
386 \subsection{Rules}
387 %*                                                      *
388 %*********************************************************
389
390 \begin{code}
391 rnDecl (RuleD (IfaceRuleDecl var body src_loc))
392   = pushSrcLocRn src_loc                        $
393     lookupOccRn var             `thenRn` \ var' ->
394     rnRuleBody body             `thenRn` \ (body', fvs) ->
395     returnRn (RuleD (IfaceRuleDecl var' body' src_loc), fvs `addOneFV` var')
396
397 rnDecl (RuleD (RuleDecl rule_name tvs vars lhs rhs src_loc))
398   = ASSERT( null tvs )
399     pushSrcLocRn src_loc                        $
400
401     bindTyVarsFV2Rn doc (map UserTyVar sig_tvs) $ \ sig_tvs' _ ->
402     bindLocalsFVRn doc (map get_var vars)       $ \ ids ->
403     mapFvRn rn_var (vars `zip` ids)             `thenRn` \ (vars', fv_vars) ->
404
405     rnExpr lhs                                  `thenRn` \ (lhs', fv_lhs) ->
406     rnExpr rhs                                  `thenRn` \ (rhs', fv_rhs) ->
407     checkRn (validRuleLhs ids lhs')
408             (badRuleLhsErr rule_name lhs')      `thenRn_`
409     let
410         bad_vars = [var | var <- ids, not (var `elemNameSet` fv_lhs)]
411     in
412     mapRn (addErrRn . badRuleVar rule_name) bad_vars    `thenRn_`
413     returnRn (RuleD (RuleDecl rule_name sig_tvs' vars' lhs' rhs' src_loc),
414               fv_vars `plusFV` fv_lhs `plusFV` fv_rhs)
415   where
416     doc = text "the transformation rule" <+> ptext rule_name
417     sig_tvs = extractRuleBndrsTyVars vars
418   
419     get_var (RuleBndr v)      = v
420     get_var (RuleBndrSig v _) = v
421
422     rn_var (RuleBndr v, id)      = returnRn (RuleBndr id, emptyFVs)
423     rn_var (RuleBndrSig v t, id) = rnHsType doc t       `thenRn` \ (t', fvs) ->
424                                    returnRn (RuleBndrSig id t', fvs)
425 \end{code}
426
427
428 %*********************************************************
429 %*                                                      *
430 \subsection{Support code for type/data declarations}
431 %*                                                      *
432 %*********************************************************
433
434 \begin{code}
435 rnDerivs :: Maybe [RdrName] -> RnMS (Maybe [Name], FreeVars)
436
437 rnDerivs Nothing -- derivs not specified
438   = returnRn (Nothing, emptyFVs)
439
440 rnDerivs (Just clss)
441   = mapRn do_one clss   `thenRn` \ clss' ->
442     returnRn (Just clss', mkNameSet clss')
443   where
444     do_one cls = lookupOccRn cls        `thenRn` \ clas_name ->
445                  checkRn (getUnique clas_name `elem` derivableClassKeys)
446                          (derivingNonStdClassErr clas_name)     `thenRn_`
447                  returnRn clas_name
448 \end{code}
449
450 \begin{code}
451 conDeclName :: RdrNameConDecl -> (RdrName, SrcLoc)
452 conDeclName (ConDecl n _ _ _ l) = (n,l)
453
454 rnConDecl :: RdrNameConDecl -> RnMS (RenamedConDecl, FreeVars)
455 rnConDecl (ConDecl name tvs cxt details locn)
456   = pushSrcLocRn locn $
457     checkConName name                   `thenRn_` 
458     lookupBndrRn name                   `thenRn` \ new_name ->
459     bindTyVarsFVRn doc tvs              $ \ new_tyvars ->
460     rnContext doc cxt                   `thenRn` \ (new_context, cxt_fvs) ->
461     rnConDetails doc locn details       `thenRn` \ (new_details, det_fvs) -> 
462     returnRn (ConDecl new_name new_tyvars new_context new_details locn,
463               cxt_fvs `plusFV` det_fvs)
464   where
465     doc = text "the definition of data constructor" <+> quotes (ppr name)
466
467 rnConDetails doc locn (VanillaCon tys)
468   = mapFvRn (rnBangTy doc) tys  `thenRn` \ (new_tys, fvs)  ->
469     returnRn (VanillaCon new_tys, fvs)
470
471 rnConDetails doc locn (InfixCon ty1 ty2)
472   = rnBangTy doc ty1            `thenRn` \ (new_ty1, fvs1) ->
473     rnBangTy doc ty2            `thenRn` \ (new_ty2, fvs2) ->
474     returnRn (InfixCon new_ty1 new_ty2, fvs1 `plusFV` fvs2)
475
476 rnConDetails doc locn (NewCon ty mb_field)
477   = rnHsType doc ty                     `thenRn` \ (new_ty, fvs) ->
478     rn_field mb_field                   `thenRn` \ new_mb_field  ->
479     returnRn (NewCon new_ty new_mb_field, fvs)
480   where
481     rn_field Nothing  = returnRn Nothing
482     rn_field (Just f) =
483        lookupBndrRn f       `thenRn` \ new_f ->
484        returnRn (Just new_f)
485
486 rnConDetails doc locn (RecCon fields)
487   = checkDupOrQualNames doc field_names `thenRn_`
488     mapFvRn (rnField doc) fields        `thenRn` \ (new_fields, fvs) ->
489     returnRn (RecCon new_fields, fvs)
490   where
491     field_names = [(fld, locn) | (flds, _) <- fields, fld <- flds]
492
493 rnField doc (names, ty)
494   = mapRn lookupBndrRn names    `thenRn` \ new_names ->
495     rnBangTy doc ty             `thenRn` \ (new_ty, fvs) ->
496     returnRn ((new_names, new_ty), fvs) 
497
498 rnBangTy doc (Banged ty)
499   = rnHsType doc ty             `thenRn` \ (new_ty, fvs) ->
500     returnRn (Banged new_ty, fvs)
501
502 rnBangTy doc (Unbanged ty)
503   = rnHsType doc ty             `thenRn` \ (new_ty, fvs) ->
504     returnRn (Unbanged new_ty, fvs)
505
506 rnBangTy doc (Unpacked ty)
507   = rnHsType doc ty             `thenRn` \ (new_ty, fvs) ->
508     returnRn (Unpacked new_ty, fvs)
509
510 -- This data decl will parse OK
511 --      data T = a Int
512 -- treating "a" as the constructor.
513 -- It is really hard to make the parser spot this malformation.
514 -- So the renamer has to check that the constructor is legal
515 --
516 -- We can get an operator as the constructor, even in the prefix form:
517 --      data T = :% Int Int
518 -- from interface files, which always print in prefix form
519
520 checkConName name
521   = checkRn (isRdrDataCon name)
522             (badDataCon name)
523 \end{code}
524
525
526 %*********************************************************
527 %*                                                      *
528 \subsection{Support code to rename types}
529 %*                                                      *
530 %*********************************************************
531
532 \begin{code}
533 rnHsSigType :: SDoc -> RdrNameHsType -> RnMS (RenamedHsType, FreeVars)
534         -- rnHsSigType is used for source-language type signatures,
535         -- which use *implicit* universal quantification.
536 rnHsSigType doc_str ty
537   = rnHsType (text "the type signature for" <+> doc_str) ty
538     
539 rnForAll doc forall_tyvars ctxt ty
540   = bindTyVarsFVRn doc forall_tyvars    $ \ new_tyvars ->
541     rnContext doc ctxt                  `thenRn` \ (new_ctxt, cxt_fvs) ->
542     rnHsType doc ty                     `thenRn` \ (new_ty, ty_fvs) ->
543     returnRn (mkHsForAllTy new_tyvars new_ctxt new_ty,
544               cxt_fvs `plusFV` ty_fvs)
545
546 -- Check that each constraint mentions at least one of the forall'd type variables
547 -- Since the forall'd type variables are a subset of the free tyvars
548 -- of the tau-type part, this guarantees that every constraint mentions
549 -- at least one of the free tyvars in ty
550 checkConstraints explicit_forall doc forall_tyvars ctxt ty
551    = mapRn check ctxt                   `thenRn` \ maybe_ctxt' ->
552      returnRn (catMaybes maybe_ctxt')
553             -- Remove problem ones, to avoid duplicate error message.
554    where
555      check ct@(_,tys)
556         | forall_mentioned = returnRn (Just ct)
557         | otherwise        = addErrRn (ctxtErr explicit_forall doc forall_tyvars ct ty)
558                              `thenRn_` returnRn Nothing
559         where
560           forall_mentioned = foldr ((||) . any (`elem` forall_tyvars) . extractHsTyRdrTyVars)
561                              False
562                              tys
563
564 rnHsType :: SDoc -> RdrNameHsType -> RnMS (RenamedHsType, FreeVars)
565
566 rnHsType doc (HsForAllTy Nothing ctxt ty)
567         -- From source code (no kinds on tyvars)
568         -- Given the signature  C => T  we universally quantify 
569         -- over FV(T) \ {in-scope-tyvars} 
570   = getLocalNameEnv             `thenRn` \ name_env ->
571     let
572         mentioned_in_tau = extractHsTyRdrTyVars ty
573         forall_tyvars    = filter (not . (`elemFM` name_env)) mentioned_in_tau
574     in
575     checkConstraints False doc forall_tyvars ctxt ty    `thenRn` \ ctxt' ->
576     rnForAll doc (map UserTyVar forall_tyvars) ctxt' ty
577
578 rnHsType doc (HsForAllTy (Just forall_tyvars) ctxt tau)
579         -- Explicit quantification.
580         -- Check that the forall'd tyvars are a subset of the
581         -- free tyvars in the tau-type part
582         -- That's only a warning... unless the tyvar is constrained by a 
583         -- context in which case it's an error
584   = let
585         mentioned_in_tau  = extractHsTyRdrTyVars tau
586         mentioned_in_ctxt = nub [tv | (_,tys) <- ctxt,
587                                       ty <- tys,
588                                       tv <- extractHsTyRdrTyVars ty]
589
590         dubious_guys          = filter (`notElem` mentioned_in_tau) forall_tyvar_names
591                 -- dubious = explicitly quantified but not mentioned in tau type
592
593         (bad_guys, warn_guys) = partition (`elem` mentioned_in_ctxt) dubious_guys
594                 -- bad  = explicitly quantified and constrained, but not mentioned in tau
595                 -- warn = explicitly quantified but not mentioned in ctxt or tau
596  
597         forall_tyvar_names    = map getTyVarName forall_tyvars
598     in
599     mapRn_ (forAllErr doc tau) bad_guys                         `thenRn_`
600     mapRn_ (forAllWarn doc tau) warn_guys                       `thenRn_`
601     checkConstraints True doc forall_tyvar_names ctxt tau       `thenRn` \ ctxt' ->
602     rnForAll doc forall_tyvars ctxt' tau
603
604 rnHsType doc (MonoTyVar tyvar)
605   = lookupOccRn tyvar           `thenRn` \ tyvar' ->
606     returnRn (MonoTyVar tyvar', unitFV tyvar')
607
608 rnHsType doc (MonoFunTy ty1 ty2)
609   = rnHsType doc ty1    `thenRn` \ (ty1', fvs1) ->
610     rnHsType doc ty2    `thenRn` \ (ty2', fvs2) ->
611     returnRn (MonoFunTy ty1' ty2', fvs1 `plusFV` fvs2)
612
613 rnHsType doc (MonoListTy ty)
614   = rnHsType doc ty                             `thenRn` \ (ty', fvs) ->
615     returnRn (MonoListTy ty', fvs `addOneFV` listTyCon_name)
616
617 rnHsType doc (MonoTupleTy tys boxed)
618   = rnHsTypes doc tys                   `thenRn` \ (tys', fvs) ->
619     returnRn (MonoTupleTy tys' boxed, fvs `addOneFV` tup_con_name)
620   where
621     tup_con_name = tupleTyCon_name boxed (length tys)
622
623 rnHsType doc (MonoTyApp ty1 ty2)
624   = rnHsType doc ty1            `thenRn` \ (ty1', fvs1) ->
625     rnHsType doc ty2            `thenRn` \ (ty2', fvs2) ->
626     returnRn (MonoTyApp ty1' ty2', fvs1 `plusFV` fvs2)
627
628 rnHsType doc (MonoDictTy clas tys)
629   = lookupOccRn clas            `thenRn` \ clas' ->
630     rnHsTypes doc tys           `thenRn` \ (tys', fvs) ->
631     returnRn (MonoDictTy clas' tys', fvs `addOneFV` clas')
632
633 rnHsType doc (MonoUsgForAllTy uv_rdr ty)
634   = bindUVarRn doc uv_rdr $ \ uv_name ->
635     rnHsType doc ty       `thenRn` \ (ty', fvs) ->
636     returnRn (MonoUsgForAllTy uv_name ty',
637               fvs )
638
639 rnHsType doc (MonoUsgTy usg ty)
640   = newUsg usg                          `thenRn` \ (usg', usg_fvs) ->
641     rnHsType doc ty                     `thenRn` \ (ty', ty_fvs) ->
642     returnRn (MonoUsgTy usg' ty',
643               usg_fvs `plusFV` ty_fvs)
644   where
645     newUsg usg = case usg of
646                    MonoUsOnce       -> returnRn (MonoUsOnce, emptyFVs)
647                    MonoUsMany       -> returnRn (MonoUsMany, emptyFVs)
648                    MonoUsVar uv_rdr -> lookupOccRn uv_rdr `thenRn` \ uv_name ->
649                                        returnRn (MonoUsVar uv_name, emptyFVs)
650
651 rnHsTypes doc tys = mapFvRn (rnHsType doc) tys
652 \end{code}
653
654
655 \begin{code}
656 rnContext :: SDoc -> RdrNameContext -> RnMS (RenamedContext, FreeVars)
657
658 rnContext doc ctxt
659   = mapAndUnzipRn rn_ctxt ctxt          `thenRn` \ (theta, fvs_s) ->
660     let
661         (_, dup_asserts) = removeDups cmp_assert theta
662     in
663         -- Check for duplicate assertions
664         -- If this isn't an error, then it ought to be:
665     mapRn_ (addWarnRn . dupClassAssertWarn theta) dup_asserts   `thenRn_`
666
667     returnRn (theta, plusFVs fvs_s)
668   where
669     rn_ctxt (clas, tys)
670       = lookupOccRn clas                `thenRn` \ clas_name ->
671         rnHsTypes doc tys               `thenRn` \ (tys', fvs) ->
672         returnRn ((clas_name, tys'), fvs `addOneFV` clas_name)
673
674     cmp_assert (c1,tys1) (c2,tys2)
675       = (c1 `compare` c2) `thenCmp` (cmpHsTypes compare tys1 tys2)
676 \end{code}
677
678
679 %*********************************************************
680 %*                                                       *
681 \subsection{IdInfo}
682 %*                                                       *
683 %*********************************************************
684
685 \begin{code}
686 rnIdInfo (HsStrictness str) = returnRn (HsStrictness str, emptyFVs)
687
688 rnIdInfo (HsWorker worker)
689   = lookupOccRn worker                  `thenRn` \ worker' ->
690     returnRn (HsWorker worker', unitFV worker')
691
692 rnIdInfo (HsUnfold inline (Just expr))  = rnCoreExpr expr `thenRn` \ (expr', fvs) ->
693                                           returnRn (HsUnfold inline (Just expr'), fvs)
694 rnIdInfo (HsUnfold inline Nothing)      = returnRn (HsUnfold inline Nothing, emptyFVs)
695 rnIdInfo (HsArity arity)        = returnRn (HsArity arity, emptyFVs)
696 rnIdInfo (HsUpdate update)      = returnRn (HsUpdate update, emptyFVs)
697 rnIdInfo (HsNoCafRefs)          = returnRn (HsNoCafRefs, emptyFVs)
698 rnIdInfo (HsCprInfo cpr_info)   = returnRn (HsCprInfo cpr_info, emptyFVs)
699 rnIdInfo (HsSpecialise rule_body) = rnRuleBody rule_body
700                                     `thenRn` \ (rule_body', fvs) ->
701                                     returnRn (HsSpecialise rule_body', fvs)
702
703 rnRuleBody (UfRuleBody str vars args rhs)
704   = rnCoreBndrs vars            $ \ vars' ->
705     mapFvRn rnCoreExpr args     `thenRn` \ (args', fvs1) ->
706     rnCoreExpr rhs              `thenRn` \ (rhs',  fvs2) ->
707     returnRn (UfRuleBody str vars' args' rhs', fvs1 `plusFV` fvs2)
708 \end{code}
709
710 @UfCore@ expressions.
711
712 \begin{code}
713 rnCoreExpr (UfType ty)
714   = rnHsType (text "unfolding type") ty `thenRn` \ (ty', fvs) ->
715     returnRn (UfType ty', fvs)
716
717 rnCoreExpr (UfVar v)
718   = lookupOccRn v       `thenRn` \ v' ->
719     returnRn (UfVar v', unitFV v')
720
721 rnCoreExpr (UfCon con args) 
722   = rnUfCon con                 `thenRn` \ (con', fvs1) ->
723     mapFvRn rnCoreExpr args     `thenRn` \ (args', fvs2) ->
724     returnRn (UfCon con' args', fvs1 `plusFV` fvs2)
725
726 rnCoreExpr (UfTuple con args) 
727   = lookupOccRn con             `thenRn` \ con' ->
728     mapFvRn rnCoreExpr args     `thenRn` \ (args', fvs) ->
729     returnRn (UfTuple con' args', fvs `addOneFV` con')
730
731 rnCoreExpr (UfApp fun arg)
732   = rnCoreExpr fun              `thenRn` \ (fun', fv1) ->
733     rnCoreExpr arg              `thenRn` \ (arg', fv2) ->
734     returnRn (UfApp fun' arg', fv1 `plusFV` fv2)
735
736 rnCoreExpr (UfCase scrut bndr alts)
737   = rnCoreExpr scrut                    `thenRn` \ (scrut', fvs1) ->
738     bindCoreLocalFVRn bndr              ( \ bndr' ->
739         mapFvRn rnCoreAlt alts          `thenRn` \ (alts', fvs2) ->
740         returnRn (UfCase scrut' bndr' alts', fvs2)
741     )                                           `thenRn` \ (case', fvs3) ->
742     returnRn (case', fvs1 `plusFV` fvs3)
743
744 rnCoreExpr (UfNote note expr) 
745   = rnNote note                 `thenRn` \ (note', fvs1) ->
746     rnCoreExpr expr             `thenRn` \ (expr', fvs2) ->
747     returnRn  (UfNote note' expr', fvs1 `plusFV` fvs2) 
748
749 rnCoreExpr (UfLam bndr body)
750   = rnCoreBndr bndr             $ \ bndr' ->
751     rnCoreExpr body             `thenRn` \ (body', fvs) ->
752     returnRn (UfLam bndr' body', fvs)
753
754 rnCoreExpr (UfLet (UfNonRec bndr rhs) body)
755   = rnCoreExpr rhs              `thenRn` \ (rhs', fvs1) ->
756     rnCoreBndr bndr             ( \ bndr' ->
757         rnCoreExpr body         `thenRn` \ (body', fvs2) ->
758         returnRn (UfLet (UfNonRec bndr' rhs') body', fvs2)
759     )                           `thenRn` \ (result, fvs3) ->
760     returnRn (result, fvs1 `plusFV` fvs3)
761
762 rnCoreExpr (UfLet (UfRec pairs) body)
763   = rnCoreBndrs bndrs           $ \ bndrs' ->
764     mapFvRn rnCoreExpr rhss     `thenRn` \ (rhss', fvs1) ->
765     rnCoreExpr body             `thenRn` \ (body', fvs2) ->
766     returnRn (UfLet (UfRec (bndrs' `zip` rhss')) body', fvs1 `plusFV` fvs2)
767   where
768     (bndrs, rhss) = unzip pairs
769 \end{code}
770
771 \begin{code}
772 rnCoreBndr (UfValBinder name ty) thing_inside
773   = rnHsType doc ty             `thenRn` \ (ty', fvs1) ->
774     bindCoreLocalFVRn name      ( \ name' ->
775             thing_inside (UfValBinder name' ty')
776     )                           `thenRn` \ (result, fvs2) ->
777     returnRn (result, fvs1 `plusFV` fvs2)
778   where
779     doc = text "unfolding id"
780     
781 rnCoreBndr (UfTyBinder name kind) thing_inside
782   = bindCoreLocalFVRn name              $ \ name' ->
783     thing_inside (UfTyBinder name' kind)
784     
785 rnCoreBndrs []     thing_inside = thing_inside []
786 rnCoreBndrs (b:bs) thing_inside = rnCoreBndr b          $ \ name' ->
787                                   rnCoreBndrs bs        $ \ names' ->
788                                   thing_inside (name':names')
789 \end{code}    
790
791 \begin{code}
792 rnCoreAlt (con, bndrs, rhs)
793   = rnUfCon con                         `thenRn` \ (con', fvs1) ->
794     bindCoreLocalsFVRn bndrs            ( \ bndrs' ->
795         rnCoreExpr rhs                  `thenRn` \ (rhs', fvs2) ->
796         returnRn ((con', bndrs', rhs'), fvs2)
797     )                                   `thenRn` \ (result, fvs3) ->
798     returnRn (result, fvs1 `plusFV` fvs3)
799
800 rnNote (UfCoerce ty)
801   = rnHsType (text "unfolding coerce") ty       `thenRn` \ (ty', fvs) ->
802     returnRn (UfCoerce ty', fvs)
803
804 rnNote (UfSCC cc)   = returnRn (UfSCC cc, emptyFVs)
805 rnNote UfInlineCall = returnRn (UfInlineCall, emptyFVs)
806 rnNote UfInlineMe   = returnRn (UfInlineMe, emptyFVs)
807
808
809 rnUfCon UfDefault
810   = returnRn (UfDefault, emptyFVs)
811
812 rnUfCon (UfDataCon con)
813   = lookupOccRn con             `thenRn` \ con' ->
814     returnRn (UfDataCon con', unitFV con')
815
816 rnUfCon (UfLitCon lit)
817   = returnRn (UfLitCon lit, emptyFVs)
818
819 rnUfCon (UfLitLitCon lit ty)
820   = rnHsType (text "litlit") ty         `thenRn` \ (ty', fvs) ->
821     returnRn (UfLitLitCon lit ty', fvs)
822
823 rnUfCon (UfPrimOp op)
824   = lookupOccRn op              `thenRn` \ op' ->
825     returnRn (UfPrimOp op', emptyFVs)
826
827 rnUfCon (UfCCallOp str is_dyn casm gc)
828   = returnRn (UfCCallOp str is_dyn casm gc, emptyFVs)
829 \end{code}
830
831 %*********************************************************
832 %*                                                       *
833 \subsection{Rule shapes}
834 %*                                                       *
835 %*********************************************************
836
837 Check the shape of a transformation rule LHS.  Currently
838 we only allow LHSs of the form @(f e1 .. en)@, where @f@ is
839 not one of the @forall@'d variables.
840
841 \begin{code}
842 validRuleLhs foralls lhs
843   = check lhs
844   where
845     check (HsApp e1 e2)                   = check e1
846     check (HsVar v) | v `notElem` foralls = True
847     check other                           = False
848 \end{code}
849
850
851 %*********************************************************
852 %*                                                       *
853 \subsection{Errors}
854 %*                                                       *
855 %*********************************************************
856
857 \begin{code}
858 derivingNonStdClassErr clas
859   = hsep [ptext SLIT("non-standard class"), ppr clas, ptext SLIT("in deriving clause")]
860
861 classTyVarNotInOpTyErr clas_tyvar sig
862   = hang (hsep [ptext SLIT("Class type variable"),
863                        quotes (ppr clas_tyvar),
864                        ptext SLIT("does not appear in method signature")])
865          4 (ppr sig)
866
867 dupClassAssertWarn ctxt (assertion : dups)
868   = sep [hsep [ptext SLIT("Duplicate class assertion"), 
869                quotes (pprClassAssertion assertion),
870                ptext SLIT("in the context:")],
871          nest 4 (pprContext ctxt <+> ptext SLIT("..."))]
872
873 badDataCon name
874    = hsep [ptext SLIT("Illegal data constructor name"), quotes (ppr name)]
875
876 forAllWarn doc ty tyvar
877   | not opt_WarnUnusedMatches = returnRn ()
878   | otherwise
879   = getModeRn           `thenRn` \ mode ->
880     case mode of {
881 #ifndef DEBUG
882         InterfaceMode -> returnRn () ;  -- Don't warn of unused tyvars in interface files
883                                         -- unless DEBUG is on, in which case it is slightly
884                                         -- informative.  They can arise from mkRhsTyLam,
885 #endif                                  -- leading to (say)     f :: forall a b. [b] -> [b]
886         other ->
887
888     addWarnRn (
889       sep [ptext SLIT("The universally quantified type variable") <+> quotes (ppr tyvar),
890            nest 4 (ptext SLIT("does not appear in the type") <+> quotes (ppr ty))]
891       $$
892       (ptext SLIT("In") <+> doc))
893     }
894
895 forAllErr doc ty tyvar
896   = addErrRn (
897       sep [ptext SLIT("The constrained type variable") <+> quotes (ppr tyvar),
898            nest 4 (ptext SLIT("does not appear in the type") <+> quotes (ppr ty))]
899       $$
900       (ptext SLIT("In") <+> doc))
901
902 ctxtErr explicit_forall doc tyvars constraint ty
903   = sep [ptext SLIT("None of the type variable(s) in the constraint")
904           <+> quotes (pprClassAssertion constraint),
905          if explicit_forall then
906            nest 4 (ptext SLIT("is universally quantified (i.e. bound by the forall)"))
907          else
908            nest 4 (ptext SLIT("appears in the type") <+> quotes (ppr ty))
909     ]
910     $$
911     (ptext SLIT("In") <+> doc)
912
913 badRuleLhsErr name lhs
914   = sep [ptext SLIT("Rule") <+> ptext name <> colon,
915          nest 4 (ptext SLIT("Illegal left-hand side:") <+> ppr lhs)]
916     $$
917     ptext SLIT("LHS must be of form (f e1 .. en) where f is not forall'd")
918
919 badRuleVar name var
920   = sep [ptext SLIT("Rule") <+> ptext name <> colon,
921          ptext SLIT("Forall'd variable") <+> quotes (ppr var) <+> 
922                 ptext SLIT("does not appear on left hand side")]
923 \end{code}