9653bdc0f3ccb4b74d3637d5c06936e017393d99
[ghc-hetmet.git] / 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 ( 
8         rnSrcDecls, addTcgDUs, 
9         rnTyClDecls, checkModDeprec,
10         rnSplice, checkTH
11     ) where
12
13 #include "HsVersions.h"
14
15 import {-# SOURCE #-} RnExpr( rnLExpr )
16
17 import HsSyn
18 import RdrName          ( RdrName, isRdrDataCon, elemLocalRdrEnv, 
19                           globalRdrEnvElts, GlobalRdrElt(..), isLocalGRE )
20 import RdrHsSyn         ( extractGenericPatTyVars, extractHsRhoRdrTyVars )
21 import RnHsSyn
22 import RnTypes          ( rnLHsType, rnLHsTypes, rnHsSigType, rnHsTypeFVs, rnContext )
23 import RnBinds          ( rnTopBinds, rnMethodBinds, renameSigs, mkSigTvFn )
24 import RnEnv            ( lookupLocalDataTcNames,
25                           lookupLocatedTopBndrRn, lookupLocatedOccRn,
26                           lookupOccRn, lookupTopBndrRn, newLocalsRn, 
27                           bindLocatedLocalsFV, bindPatSigTyVarsFV,
28                           bindTyVarsRn, extendTyVarEnvFVRn,
29                           bindLocalNames, checkDupNames, mapFvRn
30                         )
31 import RnHsDoc          ( rnHsDoc, rnMbLHsDoc )
32 import TcRnMonad
33
34 import HscTypes         ( FixityEnv, FixItem(..),
35                           Deprecations, Deprecs(..), DeprecTxt, plusDeprecs )
36 import Class            ( FunDep )
37 import Name             ( Name, nameOccName )
38 import NameSet
39 import NameEnv
40 import OccName          ( occEnvElts )
41 import Outputable
42 import SrcLoc           ( Located(..), unLoc, noLoc )
43 import DynFlags ( DynFlag(..) )
44 import Maybes           ( seqMaybe )
45 import Maybe            ( isNothing, isJust )
46 import Monad            ( liftM, when )
47 import BasicTypes       ( Boxity(..) )
48 \end{code}
49
50 @rnSourceDecl@ `renames' declarations.
51 It simultaneously performs dependency analysis and precedence parsing.
52 It also does the following error checks:
53 \begin{enumerate}
54 \item
55 Checks that tyvars are used properly. This includes checking
56 for undefined tyvars, and tyvars in contexts that are ambiguous.
57 (Some of this checking has now been moved to module @TcMonoType@,
58 since we don't have functional dependency information at this point.)
59 \item
60 Checks that all variable occurences are defined.
61 \item 
62 Checks the @(..)@ etc constraints in the export list.
63 \end{enumerate}
64
65
66 \begin{code}
67 rnSrcDecls :: HsGroup RdrName -> RnM (TcGblEnv, HsGroup Name)
68
69 rnSrcDecls (HsGroup { hs_valds  = val_decls,
70                       hs_tyclds = tycl_decls,
71                       hs_instds = inst_decls,
72                       hs_derivds = deriv_decls,
73                       hs_fixds  = fix_decls,
74                       hs_depds  = deprec_decls,
75                       hs_fords  = foreign_decls,
76                       hs_defds  = default_decls,
77                       hs_ruleds = rule_decls,
78                       hs_docs   = docs })
79
80  = do {         -- Deal with deprecations (returns only the extra deprecations)
81         deprecs <- rnSrcDeprecDecls deprec_decls ;
82         updGblEnv (\gbl -> gbl { tcg_deprecs = tcg_deprecs gbl `plusDeprecs` deprecs })
83                   $ do {
84
85                 -- Deal with top-level fixity decls 
86                 -- (returns the total new fixity env)
87         rn_fix_decls <- rnSrcFixityDecls fix_decls ;
88         fix_env <- rnSrcFixityDeclsEnv rn_fix_decls ;
89         updGblEnv (\gbl -> gbl { tcg_fix_env = fix_env })
90                   $ do {
91
92                 -- Rename other declarations
93         traceRn (text "Start rnmono") ;
94         (rn_val_decls, bind_dus) <- rnTopBinds val_decls ;
95         traceRn (text "finish rnmono" <+> ppr rn_val_decls) ;
96
97                 -- You might think that we could build proper def/use information
98                 -- for type and class declarations, but they can be involved
99                 -- in mutual recursion across modules, and we only do the SCC
100                 -- analysis for them in the type checker.
101                 -- So we content ourselves with gathering uses only; that
102                 -- means we'll only report a declaration as unused if it isn't
103                 -- mentioned at all.  Ah well.
104         traceRn (text "Start rnTyClDecls") ;
105         (rn_tycl_decls,    src_fvs1)
106            <- mapFvRn (wrapLocFstM rnTyClDecl) tycl_decls ;
107         traceRn (text "finish rnTyClDecls") ;
108         (rn_inst_decls,    src_fvs2)
109            <- mapFvRn (wrapLocFstM rnSrcInstDecl) inst_decls ;
110         (rn_deriv_decls,    src_fvs_deriv)
111            <- mapFvRn (wrapLocFstM rnSrcDerivDecl) deriv_decls ;
112         (rn_rule_decls,    src_fvs3)
113            <- mapFvRn (wrapLocFstM rnHsRuleDecl) rule_decls ;
114         (rn_foreign_decls, src_fvs4)
115            <- mapFvRn (wrapLocFstM rnHsForeignDecl) foreign_decls ;
116         (rn_default_decls, src_fvs5)
117            <- mapFvRn (wrapLocFstM rnDefaultDecl) default_decls ;
118
119         rn_docs <- rnDocEntities docs ;
120
121         let {
122            rn_group = HsGroup { hs_valds  = rn_val_decls,
123                                 hs_tyclds = rn_tycl_decls,
124                                 hs_instds = rn_inst_decls,
125                                 hs_derivds = rn_deriv_decls,
126                                 hs_fixds  = rn_fix_decls,
127                                 hs_depds  = [],
128                                 hs_fords  = rn_foreign_decls,
129                                 hs_defds  = rn_default_decls,
130                                 hs_ruleds = rn_rule_decls,
131                                 hs_docs   = rn_docs } ;
132
133            other_fvs = plusFVs [src_fvs1, src_fvs2, src_fvs_deriv, src_fvs3, 
134                                 src_fvs4, src_fvs5] ;
135            src_dus = bind_dus `plusDU` usesOnly other_fvs 
136                 -- Note: src_dus will contain *uses* for locally-defined types
137                 -- and classes, but no *defs* for them.  (Because rnTyClDecl 
138                 -- returns only the uses.)  This is a little 
139                 -- surprising but it doesn't actually matter at all.
140         } ;
141
142         traceRn (text "finish rnSrc" <+> ppr rn_group) ;
143         traceRn (text "finish Dus" <+> ppr src_dus ) ;
144         tcg_env <- getGblEnv ;
145         return (tcg_env `addTcgDUs` src_dus, rn_group)
146     }}}
147
148 rnTyClDecls :: [LTyClDecl RdrName] -> RnM [LTyClDecl Name]
149 rnTyClDecls tycl_decls = do 
150   (decls', fvs) <- mapFvRn (wrapLocFstM rnTyClDecl) tycl_decls
151   return decls'
152
153 addTcgDUs :: TcGblEnv -> DefUses -> TcGblEnv 
154 addTcgDUs tcg_env dus = tcg_env { tcg_dus = tcg_dus tcg_env `plusDU` dus }
155 \end{code}
156
157
158 %*********************************************************
159 %*                                                       *
160         HsDoc stuff
161 %*                                                       *
162 %*********************************************************
163
164 \begin{code}
165 rnDocEntities :: [DocEntity RdrName] -> RnM [DocEntity Name]
166 rnDocEntities ents
167   = ifErrsM (return []) $
168         -- Yuk: stop if we have found errors.  Otherwise
169         -- the rnDocEntity stuff reports the errors again.
170     mapM rnDocEntity ents 
171
172 rnDocEntity :: DocEntity RdrName -> RnM (DocEntity Name)
173 rnDocEntity (DocEntity docdecl) = do
174   rn_docdecl <- rnDocDecl docdecl
175   return (DocEntity rn_docdecl)
176 rnDocEntity (DeclEntity name) = do
177   rn_name <- lookupTopBndrRn name
178   return (DeclEntity rn_name)
179
180 rnDocDecl :: DocDecl RdrName -> RnM (DocDecl Name)
181 rnDocDecl (DocCommentNext doc) = do 
182   rn_doc <- rnHsDoc doc
183   return (DocCommentNext rn_doc)
184 rnDocDecl (DocCommentPrev doc) = do 
185   rn_doc <- rnHsDoc doc
186   return (DocCommentPrev rn_doc)
187 rnDocDecl (DocCommentNamed str doc) = do
188   rn_doc <- rnHsDoc doc
189   return (DocCommentNamed str rn_doc)
190 rnDocDecl (DocGroup lev doc) = do
191   rn_doc <- rnHsDoc doc
192   return (DocGroup lev rn_doc)
193 \end{code}
194
195
196 %*********************************************************
197 %*                                                       *
198         Source-code fixity declarations
199 %*                                                       *
200 %*********************************************************
201
202 \begin{code}
203 rnSrcFixityDecls :: [LFixitySig RdrName] -> RnM [LFixitySig Name]
204 rnSrcFixityDecls fix_decls
205     = do fix_decls <- mapM rnFixityDecl fix_decls
206          return (concat fix_decls)
207
208 rnFixityDecl :: LFixitySig RdrName -> RnM [LFixitySig Name]
209 rnFixityDecl (L loc (FixitySig (L nameLoc rdr_name) fixity))
210     = setSrcSpan nameLoc $
211         -- GHC extension: look up both the tycon and data con 
212         -- for con-like things
213         -- If neither are in scope, report an error; otherwise
214         -- add both to the fixity env
215       do names <- lookupLocalDataTcNames rdr_name
216          return [ L loc (FixitySig (L nameLoc name) fixity)
217                       | name <- names ]
218
219 rnSrcFixityDeclsEnv :: [LFixitySig Name] -> RnM FixityEnv
220 rnSrcFixityDeclsEnv fix_decls
221   = getGblEnv                                   `thenM` \ gbl_env ->
222     foldlM rnFixityDeclEnv (tcg_fix_env gbl_env) 
223             fix_decls                                   `thenM` \ fix_env ->
224     traceRn (text "fixity env" <+> pprFixEnv fix_env)   `thenM_`
225     returnM fix_env
226
227 rnFixityDeclEnv :: FixityEnv -> LFixitySig Name -> RnM FixityEnv
228 rnFixityDeclEnv fix_env (L loc (FixitySig (L nameLoc name) fixity))
229   = case lookupNameEnv fix_env name of
230       Just (FixItem _ _ loc') 
231           -> do addLocErr (L nameLoc name) (dupFixityDecl loc')
232                 return fix_env
233       Nothing
234           -> return (extendNameEnv fix_env name fix_item)
235     where fix_item = FixItem (nameOccName name) fixity nameLoc
236
237 pprFixEnv :: FixityEnv -> SDoc
238 pprFixEnv env 
239   = pprWithCommas (\ (FixItem n f _) -> ppr f <+> ppr n)
240                   (nameEnvElts env)
241
242 dupFixityDecl loc rdr_name
243   = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
244           ptext SLIT("also at ") <+> ppr loc
245         ]
246 \end{code}
247
248
249 %*********************************************************
250 %*                                                       *
251         Source-code deprecations declarations
252 %*                                                       *
253 %*********************************************************
254
255 For deprecations, all we do is check that the names are in scope.
256 It's only imported deprecations, dealt with in RnIfaces, that we
257 gather them together.
258
259 \begin{code}
260 rnSrcDeprecDecls :: [LDeprecDecl RdrName] -> RnM Deprecations
261 rnSrcDeprecDecls [] 
262   = returnM NoDeprecs
263
264 rnSrcDeprecDecls decls
265   = mappM (addLocM rn_deprec) decls     `thenM` \ pairs_s ->
266     returnM (DeprecSome (mkNameEnv (concat pairs_s)))
267  where
268    rn_deprec (Deprecation rdr_name txt)
269      = lookupLocalDataTcNames rdr_name  `thenM` \ names ->
270        returnM [(name, (nameOccName name, txt)) | name <- names]
271
272 checkModDeprec :: Maybe DeprecTxt -> Deprecations
273 -- Check for a module deprecation; done once at top level
274 checkModDeprec Nothing    = NoDeprecs
275 checkModDeprec (Just txt) = DeprecAll txt
276 \end{code}
277
278 %*********************************************************
279 %*                                                      *
280 \subsection{Source code declarations}
281 %*                                                      *
282 %*********************************************************
283
284 \begin{code}
285 rnDefaultDecl (DefaultDecl tys)
286   = mapFvRn (rnHsTypeFVs doc_str) tys   `thenM` \ (tys', fvs) ->
287     returnM (DefaultDecl tys', fvs)
288   where
289     doc_str = text "In a `default' declaration"
290 \end{code}
291
292 %*********************************************************
293 %*                                                      *
294 \subsection{Foreign declarations}
295 %*                                                      *
296 %*********************************************************
297
298 \begin{code}
299 rnHsForeignDecl (ForeignImport name ty spec)
300   = lookupLocatedTopBndrRn name         `thenM` \ name' ->
301     rnHsTypeFVs (fo_decl_msg name) ty   `thenM` \ (ty', fvs) ->
302     returnM (ForeignImport name' ty' spec, fvs)
303
304 rnHsForeignDecl (ForeignExport name ty spec)
305   = lookupLocatedOccRn name             `thenM` \ name' ->
306     rnHsTypeFVs (fo_decl_msg name) ty   `thenM` \ (ty', fvs) ->
307     returnM (ForeignExport name' ty' spec, fvs )
308         -- NB: a foreign export is an *occurrence site* for name, so 
309         --     we add it to the free-variable list.  It might, for example,
310         --     be imported from another module
311
312 fo_decl_msg name = ptext SLIT("In the foreign declaration for") <+> ppr name
313 \end{code}
314
315
316 %*********************************************************
317 %*                                                      *
318 \subsection{Instance declarations}
319 %*                                                      *
320 %*********************************************************
321
322 \begin{code}
323 rnSrcInstDecl (InstDecl inst_ty mbinds uprags ats)
324         -- Used for both source and interface file decls
325   = rnHsSigType (text "an instance decl") inst_ty       `thenM` \ inst_ty' ->
326
327         -- Rename the associated types
328         -- The typechecker (not the renamer) checks that all 
329         -- the declarations are for the right class
330     let
331         at_doc   = text "In the associated types of an instance declaration"
332         at_names = map (head . tyClDeclNames . unLoc) ats
333     in
334     checkDupNames at_doc at_names               `thenM_`
335     rnATInsts ats                               `thenM` \ (ats', at_fvs) ->
336
337         -- Rename the bindings
338         -- The typechecker (not the renamer) checks that all 
339         -- the bindings are for the right class
340     let
341         meth_doc    = text "In the bindings in an instance declaration"
342         meth_names  = collectHsBindLocatedBinders mbinds
343         (inst_tyvars, _, cls,_) = splitHsInstDeclTy (unLoc inst_ty')
344     in
345     checkDupNames meth_doc meth_names   `thenM_`
346     extendTyVarEnvForMethodBinds inst_tyvars (          
347         -- (Slightly strangely) the forall-d tyvars scope over
348         -- the method bindings too
349         rnMethodBinds cls (\n->[])      -- No scoped tyvars
350                       [] mbinds
351     )                                           `thenM` \ (mbinds', meth_fvs) ->
352         -- Rename the prags and signatures.
353         -- Note that the type variables are not in scope here,
354         -- so that      instance Eq a => Eq (T a) where
355         --                      {-# SPECIALISE instance Eq a => Eq (T [a]) #-}
356         -- works OK. 
357         --
358         -- But the (unqualified) method names are in scope
359     let 
360         binders = collectHsBindBinders mbinds'
361         ok_sig  = okInstDclSig (mkNameSet binders)
362     in
363     bindLocalNames binders (renameSigs ok_sig uprags)   `thenM` \ uprags' ->
364
365     returnM (InstDecl inst_ty' mbinds' uprags' ats',
366              meth_fvs `plusFV` at_fvs
367                       `plusFV` hsSigsFVs uprags'
368                       `plusFV` extractHsTyNames inst_ty')
369              -- We return the renamed associated data type declarations so
370              -- that they can be entered into the list of type declarations
371              -- for the binding group, but we also keep a copy in the instance.
372              -- The latter is needed for well-formedness checks in the type
373              -- checker (eg, to ensure that all ATs of the instance actually
374              -- receive a declaration). 
375              -- NB: Even the copies in the instance declaration carry copies of
376              --     the instance context after renaming.  This is a bit
377              --     strange, but should not matter (and it would be more work
378              --     to remove the context).
379 \end{code}
380
381 Renaming of the associated types in instances.  
382
383 * We raise an error if we encounter a kind signature in an instance.
384
385 \begin{code}
386 rnATInsts :: [LTyClDecl RdrName] -> RnM ([LTyClDecl Name], FreeVars)
387 rnATInsts atDecls = 
388   mapFvRn (wrapLocFstM rnATInst) atDecls
389   where
390     rnATInst tydecl@TyFunction {} = 
391       do
392         addErr noKindSig
393         rnTyClDecl tydecl
394     rnATInst tydecl@TySynonym  {} = rnTyClDecl tydecl
395     rnATInst tydecl@TyData     {} = 
396       do
397         checkM (not . isKindSigDecl $ tydecl) $ addErr noKindSig
398         rnTyClDecl tydecl
399     rnATInst _                    =
400       panic "RnSource.rnATInsts: not a type declaration"
401
402 noKindSig = text "Instances cannot have kind signatures"
403 \end{code}
404
405 For the method bindings in class and instance decls, we extend the 
406 type variable environment iff -fglasgow-exts
407
408 \begin{code}
409 extendTyVarEnvForMethodBinds tyvars thing_inside
410   = doptM Opt_GlasgowExts                       `thenM` \ opt_GlasgowExts ->
411     if opt_GlasgowExts then
412         extendTyVarEnvFVRn (map hsLTyVarName tyvars) thing_inside
413     else
414         thing_inside
415 \end{code}
416
417 %*********************************************************
418 %*                                                      *
419 \subsection{Stand-alone deriving declarations}
420 %*                                                      *
421 %*********************************************************
422
423 \begin{code}
424 rnSrcDerivDecl :: DerivDecl RdrName -> RnM (DerivDecl Name, FreeVars)
425 rnSrcDerivDecl (DerivDecl ty)
426   = do ty' <- rnLHsType (text "a deriving decl") ty
427        let fvs = extractHsTyNames ty'
428        return (DerivDecl ty', fvs)
429 \end{code}
430
431 %*********************************************************
432 %*                                                      *
433 \subsection{Rules}
434 %*                                                      *
435 %*********************************************************
436
437 \begin{code}
438 rnHsRuleDecl (HsRule rule_name act vars lhs fv_lhs rhs fv_rhs)
439   = bindPatSigTyVarsFV (collectRuleBndrSigTys vars)     $
440
441     bindLocatedLocalsFV doc (map get_var vars)          $ \ ids ->
442     mapFvRn rn_var (vars `zip` ids)             `thenM` \ (vars', fv_vars) ->
443
444     rnLExpr lhs                                 `thenM` \ (lhs', fv_lhs') ->
445     rnLExpr rhs                                 `thenM` \ (rhs', fv_rhs') ->
446
447     checkValidRule rule_name ids lhs' fv_lhs'   `thenM_`
448
449     returnM (HsRule rule_name act vars' lhs' fv_lhs' rhs' fv_rhs',
450              fv_vars `plusFV` fv_lhs' `plusFV` fv_rhs')
451   where
452     doc = text "In the transformation rule" <+> ftext rule_name
453   
454     get_var (RuleBndr v)      = v
455     get_var (RuleBndrSig v _) = v
456
457     rn_var (RuleBndr (L loc v), id)
458         = returnM (RuleBndr (L loc id), emptyFVs)
459     rn_var (RuleBndrSig (L loc v) t, id)
460         = rnHsTypeFVs doc t     `thenM` \ (t', fvs) ->
461           returnM (RuleBndrSig (L loc id) t', fvs)
462
463 badRuleVar name var
464   = sep [ptext SLIT("Rule") <+> doubleQuotes (ftext name) <> colon,
465          ptext SLIT("Forall'd variable") <+> quotes (ppr var) <+> 
466                 ptext SLIT("does not appear on left hand side")]
467 \end{code}
468
469 Note [Rule LHS validity checking]
470 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
471 Check the shape of a transformation rule LHS.  Currently we only allow
472 LHSs of the form @(f e1 .. en)@, where @f@ is not one of the
473 @forall@'d variables.  
474
475 We used restrict the form of the 'ei' to prevent you writing rules
476 with LHSs with a complicated desugaring (and hence unlikely to match);
477 (e.g. a case expression is not allowed: too elaborate.)
478
479 But there are legitimate non-trivial args ei, like sections and
480 lambdas.  So it seems simmpler not to check at all, and that is why
481 check_e is commented out.
482         
483 \begin{code}
484 checkValidRule rule_name ids lhs' fv_lhs'
485   = do  {       -- Check for the form of the LHS
486           case (validRuleLhs ids lhs') of
487                 Nothing  -> return ()
488                 Just bad -> failWithTc (badRuleLhsErr rule_name lhs' bad)
489
490                 -- Check that LHS vars are all bound
491         ; let bad_vars = [var | var <- ids, not (var `elemNameSet` fv_lhs')]
492         ; mappM (addErr . badRuleVar rule_name) bad_vars }
493
494 validRuleLhs :: [Name] -> LHsExpr Name -> Maybe (HsExpr Name)
495 -- Nothing => OK
496 -- Just e  => Not ok, and e is the offending expression
497 validRuleLhs foralls lhs
498   = checkl lhs
499   where
500     checkl (L loc e) = check e
501
502     check (OpApp e1 op _ e2)              = checkl op `seqMaybe` checkl_e e1 `seqMaybe` checkl_e e2
503     check (HsApp e1 e2)                   = checkl e1 `seqMaybe` checkl_e e2
504     check (HsVar v) | v `notElem` foralls = Nothing
505     check other                           = Just other  -- Failure
506
507         -- Check an argument
508     checkl_e (L loc e) = Nothing        -- Was (check_e e); see Note [Rule LHS validity checking]
509
510 {-      Commented out; see Note [Rule LHS validity checking] above 
511     check_e (HsVar v)     = Nothing
512     check_e (HsPar e)     = checkl_e e
513     check_e (HsLit e)     = Nothing
514     check_e (HsOverLit e) = Nothing
515
516     check_e (OpApp e1 op _ e2)   = checkl_e e1 `seqMaybe` checkl_e op `seqMaybe` checkl_e e2
517     check_e (HsApp e1 e2)        = checkl_e e1 `seqMaybe` checkl_e e2
518     check_e (NegApp e _)         = checkl_e e
519     check_e (ExplicitList _ es)  = checkl_es es
520     check_e (ExplicitTuple es _) = checkl_es es
521     check_e other                = Just other   -- Fails
522
523     checkl_es es = foldr (seqMaybe . checkl_e) Nothing es
524 -}
525
526 badRuleLhsErr name lhs bad_e
527   = sep [ptext SLIT("Rule") <+> ftext name <> colon,
528          nest 4 (vcat [ptext SLIT("Illegal expression:") <+> ppr bad_e, 
529                        ptext SLIT("in left-hand side:") <+> ppr lhs])]
530     $$
531     ptext SLIT("LHS must be of form (f e1 .. en) where f is not forall'd")
532 \end{code}
533
534
535 %*********************************************************
536 %*                                                      *
537 \subsection{Type, class and iface sig declarations}
538 %*                                                      *
539 %*********************************************************
540
541 @rnTyDecl@ uses the `global name function' to create a new type
542 declaration in which local names have been replaced by their original
543 names, reporting any unknown names.
544
545 Renaming type variables is a pain. Because they now contain uniques,
546 it is necessary to pass in an association list which maps a parsed
547 tyvar to its @Name@ representation.
548 In some cases (type signatures of values),
549 it is even necessary to go over the type first
550 in order to get the set of tyvars used by it, make an assoc list,
551 and then go over it again to rename the tyvars!
552 However, we can also do some scoping checks at the same time.
553
554 \begin{code}
555 rnTyClDecl (ForeignType {tcdLName = name, tcdFoType = fo_type, tcdExtName = ext_name})
556   = lookupLocatedTopBndrRn name         `thenM` \ name' ->
557     returnM (ForeignType {tcdLName = name', tcdFoType = fo_type, tcdExtName = ext_name},
558              emptyFVs)
559
560 rnTyClDecl (tydecl@TyData {tcdND = new_or_data, tcdCtxt = context, 
561                            tcdLName = tycon, tcdTyVars = tyvars, 
562                            tcdTyPats = typatsMaybe, tcdCons = condecls, 
563                            tcdKindSig = sig, tcdDerivs = derivs})
564   | isKindSigDecl tydecl  -- kind signature of indexed type
565   = rnTySig tydecl bindTyVarsRn
566   | is_vanilla            -- Normal Haskell data type decl
567   = ASSERT( isNothing sig )     -- In normal H98 form, kind signature on the 
568                                 -- data type is syntactically illegal
569     bindTyVarsRn data_doc tyvars                $ \ tyvars' ->
570     do  { tycon' <- if isIdxTyDecl tydecl
571                     then lookupLocatedOccRn     tycon -- may be imported family
572                     else lookupLocatedTopBndrRn tycon
573         ; context' <- rnContext data_doc context
574         ; typats' <- rnTyPats data_doc typatsMaybe
575         ; (derivs', deriv_fvs) <- rn_derivs derivs
576         ; checkDupNames data_doc con_names
577         ; condecls' <- rnConDecls (unLoc tycon') condecls
578         ; returnM (TyData {tcdND = new_or_data, tcdCtxt = context', 
579                            tcdLName = tycon', tcdTyVars = tyvars', 
580                            tcdTyPats = typats', tcdKindSig = Nothing, 
581                            tcdCons = condecls', tcdDerivs = derivs'}, 
582                    delFVs (map hsLTyVarName tyvars')    $
583                    extractHsCtxtTyNames context'        `plusFV`
584                    plusFVs (map conDeclFVs condecls')   `plusFV`
585                    deriv_fvs                            `plusFV`
586                    (if isIdxTyDecl tydecl
587                    then unitFV (unLoc tycon')   -- type instance => use
588                    else emptyFVs)) 
589         }
590
591   | otherwise             -- GADT
592   = ASSERT( none typatsMaybe )    -- GADTs cannot have type patterns for now
593     do  { tycon' <- if isIdxTyDecl tydecl
594                     then lookupLocatedOccRn     tycon -- may be imported family
595                     else lookupLocatedTopBndrRn tycon
596         ; checkTc (null (unLoc context)) (badGadtStupidTheta tycon)
597         ; tyvars' <- bindTyVarsRn data_doc tyvars 
598                                   (\ tyvars' -> return tyvars')
599                 -- For GADTs, the type variables in the declaration 
600                 -- do not scope over the constructor signatures
601                 --      data T a where { T1 :: forall b. b-> b }
602         ; (derivs', deriv_fvs) <- rn_derivs derivs
603         ; checkDupNames data_doc con_names
604         ; condecls' <- rnConDecls (unLoc tycon') condecls
605         ; returnM (TyData {tcdND = new_or_data, tcdCtxt = noLoc [], 
606                            tcdLName = tycon', tcdTyVars = tyvars', 
607                            tcdTyPats = Nothing, tcdKindSig = sig,
608                            tcdCons = condecls', tcdDerivs = derivs'}, 
609                    plusFVs (map conDeclFVs condecls') `plusFV` 
610                    deriv_fvs                          `plusFV`
611                    (if isIdxTyDecl tydecl
612                    then unitFV (unLoc tycon')   -- type instance => use
613                    else emptyFVs))
614         }
615   where
616     is_vanilla = case condecls of       -- Yuk
617                      []                    -> True
618                      L _ (ConDecl { con_res = ResTyH98 }) : _  -> True
619                      other                 -> False
620
621     none Nothing   = True
622     none (Just []) = True
623     none _         = False
624
625     data_doc = text "In the data type declaration for" <+> quotes (ppr tycon)
626     con_names = map con_names_helper condecls
627
628     con_names_helper (L _ c) = con_name c
629
630     rn_derivs Nothing   = returnM (Nothing, emptyFVs)
631     rn_derivs (Just ds) = rnLHsTypes data_doc ds        `thenM` \ ds' -> 
632                           returnM (Just ds', extractHsTyNames_s ds')
633
634 rnTyClDecl (tydecl@TyFunction {}) =
635   rnTySig tydecl bindTyVarsRn
636
637 rnTyClDecl tydecl@(TySynonym {tcdLName = name, tcdTyVars = tyvars,
638                               tcdTyPats = typatsMaybe, tcdSynRhs = ty})
639   = bindTyVarsRn syn_doc tyvars                 $ \ tyvars' ->
640     do { name' <- if isIdxTyDecl tydecl
641                   then lookupLocatedOccRn     name -- may be imported family
642                   else lookupLocatedTopBndrRn name
643        ; typats' <- rnTyPats syn_doc typatsMaybe
644        ; (ty', fvs) <- rnHsTypeFVs syn_doc ty
645        ; returnM (TySynonym {tcdLName = name', tcdTyVars = tyvars', 
646                              tcdTyPats = typats', tcdSynRhs = ty'},
647                   delFVs (map hsLTyVarName tyvars') $
648                   fvs                         `plusFV`
649                    (if isIdxTyDecl tydecl
650                    then unitFV (unLoc name')    -- type instance => use
651                    else emptyFVs))
652        }
653   where
654     syn_doc = text "In the declaration for type synonym" <+> quotes (ppr name)
655
656 rnTyClDecl (ClassDecl {tcdCtxt = context, tcdLName = cname, 
657                        tcdTyVars = tyvars, tcdFDs = fds, tcdSigs = sigs, 
658                        tcdMeths = mbinds, tcdATs = ats, tcdDocs = docs})
659   = do  { cname' <- lookupLocatedTopBndrRn cname
660
661         -- Tyvars scope over superclass context and method signatures
662         ; (tyvars', context', fds', ats', ats_fvs, sigs')
663             <- bindTyVarsRn cls_doc tyvars $ \ tyvars' -> do
664              { context' <- rnContext cls_doc context
665              ; fds' <- rnFds cls_doc fds
666              ; (ats', ats_fvs) <- rnATs ats
667              ; sigs' <- renameSigs okClsDclSig sigs
668              ; return   (tyvars', context', fds', ats', ats_fvs, sigs') }
669
670         -- Check for duplicates among the associated types
671         ; let at_rdr_names_w_locs = [tcdLName ty | L _ ty <- ats]
672         ; checkDupNames at_doc at_rdr_names_w_locs
673
674         -- Check the signatures
675         -- First process the class op sigs (op_sigs), then the fixity sigs (non_op_sigs).
676         ; let sig_rdr_names_w_locs = [op | L _ (TypeSig op _) <- sigs]
677         ; checkDupNames sig_doc sig_rdr_names_w_locs
678                 -- Typechecker is responsible for checking that we only
679                 -- give default-method bindings for things in this class.
680                 -- The renamer *could* check this for class decls, but can't
681                 -- for instance decls.
682
683         -- The newLocals call is tiresome: given a generic class decl
684         --      class C a where
685         --        op :: a -> a
686         --        op {| x+y |} (Inl a) = ...
687         --        op {| x+y |} (Inr b) = ...
688         --        op {| a*b |} (a*b)   = ...
689         -- we want to name both "x" tyvars with the same unique, so that they are
690         -- easy to group together in the typechecker.  
691         ; (mbinds', meth_fvs) 
692             <- extendTyVarEnvForMethodBinds tyvars' $ do
693             { name_env <- getLocalRdrEnv
694             ; let meth_rdr_names_w_locs = collectHsBindLocatedBinders mbinds
695                   gen_rdr_tyvars_w_locs = [ tv | tv <- extractGenericPatTyVars mbinds,
696                                                  not (unLoc tv `elemLocalRdrEnv` name_env) ]
697             ; checkDupNames meth_doc meth_rdr_names_w_locs
698             ; gen_tyvars <- newLocalsRn gen_rdr_tyvars_w_locs
699             ; rnMethodBinds (unLoc cname') (mkSigTvFn sigs') gen_tyvars mbinds }
700
701         -- Sigh.  Check the Haddock docs after the methods, to avoid duplicate errors
702         -- Example: class { op :: a->a;  op2 x = x }
703         --      Don't want a duplicate complait about op2
704         ; docs' <- bindLocalNames (map hsLTyVarName tyvars') $ rnDocEntities docs
705
706         ; return (ClassDecl { tcdCtxt = context', tcdLName = cname', 
707                               tcdTyVars = tyvars', tcdFDs = fds', tcdSigs = sigs',
708                               tcdMeths = mbinds', tcdATs = ats', tcdDocs = docs'},
709
710                   delFVs (map hsLTyVarName tyvars')     $
711                   extractHsCtxtTyNames context'         `plusFV`
712                   plusFVs (map extractFunDepNames (map unLoc fds'))  `plusFV`
713                   hsSigsFVs sigs'                       `plusFV`
714                   meth_fvs                              `plusFV`
715                   ats_fvs) }
716   where
717     meth_doc = text "In the default-methods for class"  <+> ppr cname
718     cls_doc  = text "In the declaration for class"      <+> ppr cname
719     sig_doc  = text "In the signatures for class"       <+> ppr cname
720     at_doc   = text "In the associated types for class" <+> ppr cname
721
722 badGadtStupidTheta tycon
723   = vcat [ptext SLIT("No context is allowed on a GADT-style data declaration"),
724           ptext SLIT("(You can put a context on each contructor, though.)")]
725 \end{code}
726
727 %*********************************************************
728 %*                                                      *
729 \subsection{Support code for type/data declarations}
730 %*                                                      *
731 %*********************************************************
732
733 \begin{code}
734 -- Although, we are processing type patterns here, all type variables will
735 -- already be in scope (they are the same as in the 'tcdTyVars' field of the
736 -- type declaration to which these patterns belong)
737 --
738 rnTyPats :: SDoc -> Maybe [LHsType RdrName] -> RnM (Maybe [LHsType Name])
739 rnTyPats _   Nothing       = return Nothing
740 rnTyPats doc (Just typats) = liftM Just $ rnLHsTypes doc typats
741
742 rnConDecls :: Name -> [LConDecl RdrName] -> RnM [LConDecl Name]
743 rnConDecls tycon condecls
744   = mappM (wrapLocM rnConDecl) condecls
745
746 rnConDecl :: ConDecl RdrName -> RnM (ConDecl Name)
747 rnConDecl (ConDecl name expl tvs cxt details res_ty mb_doc)
748   = do  { addLocM checkConName name
749
750         ; new_name <- lookupLocatedTopBndrRn name
751         ; name_env <- getLocalRdrEnv
752         
753         -- For H98 syntax, the tvs are the existential ones
754         -- For GADT syntax, the tvs are all the quantified tyvars
755         -- Hence the 'filter' in the ResTyH98 case only
756         ; let not_in_scope  = not . (`elemLocalRdrEnv` name_env) . unLoc
757               arg_tys       = hsConArgs details
758               implicit_tvs  = case res_ty of
759                                 ResTyH98 -> filter not_in_scope $
760                                                 get_rdr_tvs arg_tys
761                                 ResTyGADT ty -> get_rdr_tvs (ty : arg_tys)
762               tvs' = case expl of
763                         Explicit -> tvs
764                         Implicit -> userHsTyVarBndrs implicit_tvs
765
766         ; mb_doc' <- rnMbLHsDoc mb_doc 
767
768         ; bindTyVarsRn doc tvs' $ \new_tyvars -> do
769         { new_context <- rnContext doc cxt
770         ; new_details <- rnConDetails doc details
771         ; (new_details', new_res_ty)  <- rnConResult doc new_details res_ty
772         ; return (ConDecl new_name expl new_tyvars new_context new_details' new_res_ty mb_doc') }}
773  where
774     doc = text "In the definition of data constructor" <+> quotes (ppr name)
775     get_rdr_tvs tys  = extractHsRhoRdrTyVars cxt (noLoc (HsTupleTy Boxed tys))
776
777 rnConResult _ details ResTyH98 = return (details, ResTyH98)
778
779 rnConResult doc details (ResTyGADT ty) = do
780     ty' <- rnHsSigType doc ty
781     let (arg_tys, res_ty) = splitHsFunType ty'
782         -- We can split it up, now the renamer has dealt with fixities
783     case details of
784         PrefixCon _xs -> ASSERT( null _xs ) return (PrefixCon arg_tys, ResTyGADT res_ty)
785         RecCon fields -> return (details, ResTyGADT ty')
786         InfixCon {}   -> panic "rnConResult"
787
788 rnConDetails doc (PrefixCon tys)
789   = mappM (rnLHsType doc) tys   `thenM` \ new_tys  ->
790     returnM (PrefixCon new_tys)
791
792 rnConDetails doc (InfixCon ty1 ty2)
793   = rnLHsType doc ty1           `thenM` \ new_ty1 ->
794     rnLHsType doc ty2           `thenM` \ new_ty2 ->
795     returnM (InfixCon new_ty1 new_ty2)
796
797 rnConDetails doc (RecCon fields)
798   = checkDupNames doc field_names       `thenM_`
799     mappM (rnField doc) fields          `thenM` \ new_fields ->
800     returnM (RecCon new_fields)
801   where
802     field_names = [ name | HsRecField name _ _ <- fields ]
803
804 -- Document comments are renamed to Nothing here
805 rnField doc (HsRecField name ty haddock_doc)
806   = lookupLocatedTopBndrRn name `thenM` \ new_name ->
807     rnLHsType doc ty            `thenM` \ new_ty ->
808     rnMbLHsDoc haddock_doc      `thenM` \ new_haddock_doc ->
809     returnM (HsRecField new_name new_ty new_haddock_doc) 
810
811 -- Rename kind signatures (signatures of indexed data types/newtypes and
812 -- signatures of type functions)
813 --
814 -- * This function is parametrised by the routine handling the index
815 --   variables.  On the toplevel, these are defining occurences, whereas they
816 --   are usage occurences for associated types.
817 --
818 rnTySig :: TyClDecl RdrName 
819         -> (SDoc -> [LHsTyVarBndr RdrName] -> 
820             ([LHsTyVarBndr Name] -> RnM (TyClDecl Name, FreeVars)) ->
821             RnM (TyClDecl Name, FreeVars))
822         -> RnM (TyClDecl Name, FreeVars)
823
824 rnTySig (tydecl@TyData {tcdCtxt = context, tcdLName = tycon, 
825                         tcdTyVars = tyvars, tcdTyPats = mb_typats,
826                         tcdCons = condecls, tcdKindSig = sig, 
827                         tcdDerivs = derivs}) 
828         bindIdxVars =
829       ASSERT( null condecls )       -- won't have constructors
830       ASSERT( isNothing mb_typats ) -- won't have type patterns
831       ASSERT( isNothing derivs )    -- won't have deriving
832       ASSERT( isJust sig )          -- will have kind signature
833       do { bindIdxVars (ksig_doc tycon) tyvars $ \tyvars' -> do {
834          ; tycon' <- lookupLocatedTopBndrRn tycon
835          ; context' <- rnContext (ksig_doc tycon) context
836          ; returnM (TyData {tcdND = tcdND tydecl, tcdCtxt = context', 
837                             tcdLName = tycon', tcdTyVars = tyvars',
838                             tcdTyPats = Nothing, tcdKindSig = sig, 
839                             tcdCons = [], tcdDerivs = Nothing}, 
840                     delFVs (map hsLTyVarName tyvars') $
841                     extractHsCtxtTyNames context') 
842          } }
843       where
844
845 rnTySig (tydecl@TyFunction {tcdLName = tycon, tcdTyVars = tyvars, 
846                             tcdKind = sig}) 
847         bindIdxVars =
848       do { checkM (not . null $ tyvars) $ addErr needOneIdx   -- #indexes >= 1
849          ; bindIdxVars (ksig_doc tycon) tyvars $ \tyvars' -> do {
850          ; tycon' <- lookupLocatedTopBndrRn tycon
851          ; returnM (TyFunction {tcdLName = tycon', tcdTyVars = tyvars',
852                                 tcdIso = tcdIso tydecl, tcdKind = sig}, 
853                     emptyFVs) 
854          } }
855
856 ksig_doc tycon = text "In the kind signature for" <+> quotes (ppr tycon)
857 needOneIdx = text "Kind signature requires at least one type index"
858
859 -- Rename associated type declarations (in classes)
860 --
861 -- * This can be kind signatures and (default) type function equations.
862 --
863 rnATs :: [LTyClDecl RdrName] -> RnM ([LTyClDecl Name], FreeVars)
864 rnATs ats = mapFvRn (wrapLocFstM rn_at) ats
865   where
866     rn_at (tydecl@TyData     {}) = rnTySig tydecl lookupIdxVars
867     rn_at (tydecl@TyFunction {}) = rnTySig tydecl lookupIdxVars
868     rn_at (tydecl@TySynonym  {}) = 
869       do
870         checkM (isNothing (tcdTyPats tydecl)) $ addErr noPatterns
871         rnTyClDecl tydecl
872     rn_at _                      = panic "RnSource.rnATs: invalid TyClDecl"
873
874     lookupIdxVars _ tyvars cont = 
875       do { checkForDups tyvars;
876          ; tyvars' <- mappM lookupIdxVar tyvars
877          ; cont tyvars'
878          }
879     -- Type index variables must be class parameters, which are the only
880     -- type variables in scope at this point.
881     lookupIdxVar (L l tyvar) =
882       do
883         name' <- lookupOccRn (hsTyVarName tyvar)
884         return $ L l (replaceTyVarName tyvar name')
885
886     -- Type variable may only occur once.
887     --
888     checkForDups [] = return ()
889     checkForDups (L loc tv:ltvs) = 
890       do { setSrcSpan loc $
891              when (hsTyVarName tv `ltvElem` ltvs) $
892                addErr (repeatedTyVar tv)
893          ; checkForDups ltvs
894          }
895
896     rdrName `ltvElem` [] = False
897     rdrName `ltvElem` (L _ tv:ltvs)
898       | rdrName == hsTyVarName tv = True
899       | otherwise                 = rdrName `ltvElem` ltvs
900
901 noPatterns = text "Default definition for an associated synonym cannot have"
902              <+> text "type pattern"
903
904 repeatedTyVar tv = ptext SLIT("Illegal repeated type variable") <+>
905                    quotes (ppr tv)
906
907 -- This data decl will parse OK
908 --      data T = a Int
909 -- treating "a" as the constructor.
910 -- It is really hard to make the parser spot this malformation.
911 -- So the renamer has to check that the constructor is legal
912 --
913 -- We can get an operator as the constructor, even in the prefix form:
914 --      data T = :% Int Int
915 -- from interface files, which always print in prefix form
916
917 checkConName name = checkErr (isRdrDataCon name) (badDataCon name)
918
919 badDataCon name
920    = hsep [ptext SLIT("Illegal data constructor name"), quotes (ppr name)]
921 \end{code}
922
923
924 %*********************************************************
925 %*                                                      *
926 \subsection{Support code to rename types}
927 %*                                                      *
928 %*********************************************************
929
930 \begin{code}
931 rnFds :: SDoc -> [Located (FunDep RdrName)] -> RnM [Located (FunDep Name)]
932
933 rnFds doc fds
934   = mappM (wrapLocM rn_fds) fds
935   where
936     rn_fds (tys1, tys2)
937       = rnHsTyVars doc tys1             `thenM` \ tys1' ->
938         rnHsTyVars doc tys2             `thenM` \ tys2' ->
939         returnM (tys1', tys2')
940
941 rnHsTyVars doc tvs  = mappM (rnHsTyvar doc) tvs
942 rnHsTyvar doc tyvar = lookupOccRn tyvar
943 \end{code}
944
945
946 %*********************************************************
947 %*                                                      *
948                 Splices
949 %*                                                      *
950 %*********************************************************
951
952 Note [Splices]
953 ~~~~~~~~~~~~~~
954 Consider
955         f = ...
956         h = ...$(thing "f")...
957
958 The splice can expand into literally anything, so when we do dependency
959 analysis we must assume that it might mention 'f'.  So we simply treat
960 all locally-defined names as mentioned by any splice.  This is terribly
961 brutal, but I don't see what else to do.  For example, it'll mean
962 that every locally-defined thing will appear to be used, so no unused-binding
963 warnings.  But if we miss the dependency, then we might typecheck 'h' before 'f',
964 and that will crash the type checker because 'f' isn't in scope.
965
966 Currently, I'm not treating a splice as also mentioning every import,
967 which is a bit inconsistent -- but there are a lot of them.  We might
968 thereby get some bogus unused-import warnings, but we won't crash the
969 type checker.  Not very satisfactory really.
970
971 \begin{code}
972 rnSplice :: HsSplice RdrName -> RnM (HsSplice Name, FreeVars)
973 rnSplice (HsSplice n expr)
974   = do  { checkTH expr "splice"
975         ; loc  <- getSrcSpanM
976         ; [n'] <- newLocalsRn [L loc n]
977         ; (expr', fvs) <- rnLExpr expr
978
979         -- Ugh!  See Note [Splices] above
980         ; lcl_rdr <- getLocalRdrEnv
981         ; gbl_rdr <- getGlobalRdrEnv
982         ; let gbl_names = mkNameSet [gre_name gre | gre <- globalRdrEnvElts gbl_rdr, 
983                                                     isLocalGRE gre]
984               lcl_names = mkNameSet (occEnvElts lcl_rdr)
985
986         ; return (HsSplice n' expr', fvs `plusFV` lcl_names `plusFV` gbl_names) }
987
988 #ifdef GHCI 
989 checkTH e what = returnM ()     -- OK
990 #else
991 checkTH e what  -- Raise an error in a stage-1 compiler
992   = addErr (vcat [ptext SLIT("Template Haskell") <+> text what <+>  
993                   ptext SLIT("illegal in a stage-1 compiler"),
994                   nest 2 (ppr e)])
995 #endif   
996 \end{code}