2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnSource]{Main pass of renamer}
8 rnSrcDecls, addTcgDUs, rnTyClDecls
11 #include "HsVersions.h"
13 import {-# SOURCE #-} RnExpr( rnLExpr )
16 import RdrName ( RdrName, isRdrDataCon, elemLocalRdrEnv, rdrNameOcc )
17 import RdrHsSyn ( extractGenericPatTyVars, extractHsRhoRdrTyVars )
19 import RnTypes ( rnLHsType, rnLHsTypes, rnHsSigType, rnHsTypeFVs, rnContext, rnConDeclFields )
20 import RnBinds ( rnTopBindsLHS, rnTopBindsRHS, rnMethodBinds, renameSigs, mkSigTvFn,
22 import RnEnv ( lookupLocalDataTcNames, lookupLocatedOccRn,
23 lookupTopBndrRn, lookupLocatedTopBndrRn,
24 lookupOccRn, newLocalBndrsRn, bindLocalNamesFV,
25 bindLocatedLocalsFV, bindPatSigTyVarsFV,
26 bindTyVarsRn, extendTyVarEnvFVRn,
27 bindLocalNames, checkDupRdrNames, mapFvRn
29 import RnNames ( getLocalNonValBinders, extendGlobalRdrEnvRn )
30 import HscTypes ( GenAvailInfo(..), availsToNameSet )
31 import RnHsDoc ( rnHsDoc, rnMbLHsDoc )
34 import HscTypes ( Warnings(..), plusWarns )
35 import Class ( FunDep )
36 import Name ( Name, nameOccName )
42 import Util ( filterOut )
44 import DynFlags ( DynFlag(..) )
45 import BasicTypes ( Boxity(..) )
46 import ListSetOps ( findDupsEq )
54 thenM :: Monad a => a b -> (b -> a c) -> a c
57 thenM_ :: Monad a => a b -> a c -> a c
61 @rnSourceDecl@ `renames' declarations.
62 It simultaneously performs dependency analysis and precedence parsing.
63 It also does the following error checks:
66 Checks that tyvars are used properly. This includes checking
67 for undefined tyvars, and tyvars in contexts that are ambiguous.
68 (Some of this checking has now been moved to module @TcMonoType@,
69 since we don't have functional dependency information at this point.)
71 Checks that all variable occurences are defined.
73 Checks the @(..)@ etc constraints in the export list.
78 -- Brings the binders of the group into scope in the appropriate places;
79 -- does NOT assume that anything is in scope already
80 rnSrcDecls :: HsGroup RdrName -> RnM (TcGblEnv, HsGroup Name)
81 -- Rename a HsGroup; used for normal source files *and* hs-boot files
82 rnSrcDecls group@(HsGroup {hs_valds = val_decls,
83 hs_tyclds = tycl_decls,
84 hs_instds = inst_decls,
85 hs_derivds = deriv_decls,
87 hs_warnds = warn_decls,
89 hs_fords = foreign_decls,
90 hs_defds = default_decls,
91 hs_ruleds = rule_decls,
94 -- (A) Process the fixity declarations, creating a mapping from
95 -- FastStrings to FixItems.
96 -- Also checks for duplcates.
97 local_fix_env <- makeMiniFixityEnv fix_decls;
99 -- (B) Bring top level binders (and their fixities) into scope,
100 -- *except* for the value bindings, which get brought in below.
101 -- However *do* include class ops, data constructors
102 -- And for hs-boot files *do* include the value signatures
103 tc_avails <- getLocalNonValBinders group ;
104 tc_envs <- extendGlobalRdrEnvRn tc_avails local_fix_env ;
105 setEnvs tc_envs $ do {
107 failIfErrsM ; -- No point in continuing if (say) we have duplicate declarations
109 -- (C) Extract the mapping from data constructors to field names and
110 -- extend the record field env.
111 -- This depends on the data constructors and field names being in
112 -- scope from (B) above
113 inNewEnv (extendRecordFieldEnv tycl_decls inst_decls) $ \ _ -> do {
115 -- (D) Rename the left-hand sides of the value bindings.
116 -- This depends on everything from (B) being in scope,
117 -- and on (C) for resolving record wild cards.
118 -- It uses the fixity env from (A) to bind fixities for view patterns.
119 new_lhs <- rnTopBindsLHS local_fix_env val_decls ;
120 -- bind the LHSes (and their fixities) in the global rdr environment
121 let { val_binders = map unLoc $ collectHsValBinders new_lhs ;
122 val_bndr_set = mkNameSet val_binders ;
123 all_bndr_set = val_bndr_set `unionNameSets` availsToNameSet tc_avails ;
124 val_avails = map Avail val_binders
126 (tcg_env, tcl_env) <- extendGlobalRdrEnvRn val_avails local_fix_env ;
127 setEnvs (tcg_env, tcl_env) $ do {
129 -- Now everything is in scope, as the remaining renaming assumes.
131 -- (E) Rename type and class decls
132 -- (note that value LHSes need to be in scope for default methods)
134 -- You might think that we could build proper def/use information
135 -- for type and class declarations, but they can be involved
136 -- in mutual recursion across modules, and we only do the SCC
137 -- analysis for them in the type checker.
138 -- So we content ourselves with gathering uses only; that
139 -- means we'll only report a declaration as unused if it isn't
140 -- mentioned at all. Ah well.
141 traceRn (text "Start rnTyClDecls") ;
142 (rn_tycl_decls, src_fvs1) <- rnList rnTyClDecl tycl_decls ;
144 -- (F) Rename Value declarations right-hand sides
145 traceRn (text "Start rnmono") ;
146 (rn_val_decls, bind_dus) <- rnTopBindsRHS val_bndr_set new_lhs ;
147 traceRn (text "finish rnmono" <+> ppr rn_val_decls) ;
149 -- (G) Rename Fixity and deprecations
151 -- Rename fixity declarations and error if we try to
152 -- fix something from another module (duplicates were checked in (A))
153 rn_fix_decls <- rnSrcFixityDecls all_bndr_set fix_decls ;
155 -- Rename deprec decls;
156 -- check for duplicates and ensure that deprecated things are defined locally
157 -- at the moment, we don't keep these around past renaming
158 rn_warns <- rnSrcWarnDecls all_bndr_set warn_decls ;
160 -- (H) Rename Everything else
162 (rn_inst_decls, src_fvs2) <- rnList rnSrcInstDecl inst_decls ;
163 (rn_rule_decls, src_fvs3) <- setOptM Opt_ScopedTypeVariables $
164 rnList rnHsRuleDecl rule_decls ;
165 -- Inside RULES, scoped type variables are on
166 (rn_foreign_decls, src_fvs4) <- rnList rnHsForeignDecl foreign_decls ;
167 (rn_ann_decls, src_fvs5) <- rnList rnAnnDecl ann_decls ;
168 (rn_default_decls, src_fvs6) <- rnList rnDefaultDecl default_decls ;
169 (rn_deriv_decls, src_fvs7) <- rnList rnSrcDerivDecl deriv_decls ;
170 -- Haddock docs; no free vars
171 rn_docs <- mapM (wrapLocM rnDocDecl) docs ;
173 -- (I) Compute the results and return
174 let {rn_group = HsGroup { hs_valds = rn_val_decls,
175 hs_tyclds = rn_tycl_decls,
176 hs_instds = rn_inst_decls,
177 hs_derivds = rn_deriv_decls,
178 hs_fixds = rn_fix_decls,
179 hs_warnds = [], -- warns are returned in the tcg_env
180 -- (see below) not in the HsGroup
181 hs_fords = rn_foreign_decls,
182 hs_annds = rn_ann_decls,
183 hs_defds = rn_default_decls,
184 hs_ruleds = rn_rule_decls,
185 hs_docs = rn_docs } ;
187 other_fvs = plusFVs [src_fvs1, src_fvs2, src_fvs3, src_fvs4,
188 src_fvs5, src_fvs6, src_fvs7] ;
189 src_dus = bind_dus `plusDU` usesOnly other_fvs;
190 -- Note: src_dus will contain *uses* for locally-defined types
191 -- and classes, but no *defs* for them. (Because rnTyClDecl
192 -- returns only the uses.) This is a little
193 -- surprising but it doesn't actually matter at all.
195 final_tcg_env = let tcg_env' = (tcg_env `addTcgDUs` src_dus)
196 in -- we return the deprecs in the env, not in the HsGroup above
197 tcg_env' { tcg_warns = tcg_warns tcg_env' `plusWarns` rn_warns };
200 traceRn (text "finish rnSrc" <+> ppr rn_group) ;
201 traceRn (text "finish Dus" <+> ppr src_dus ) ;
202 return (final_tcg_env , rn_group)
205 -- some utils because we do this a bunch above
206 -- compute and install the new env
207 inNewEnv :: TcM TcGblEnv -> (TcGblEnv -> TcM a) -> TcM a
208 inNewEnv env cont = do e <- env
211 rnTyClDecls :: [LTyClDecl RdrName] -> RnM [LTyClDecl Name]
212 -- Used for external core
213 rnTyClDecls tycl_decls = do (decls', _fvs) <- rnList rnTyClDecl tycl_decls
216 addTcgDUs :: TcGblEnv -> DefUses -> TcGblEnv
217 -- This function could be defined lower down in the module hierarchy,
218 -- but there doesn't seem anywhere very logical to put it.
219 addTcgDUs tcg_env dus = tcg_env { tcg_dus = tcg_dus tcg_env `plusDU` dus }
221 rnList :: (a -> RnM (b, FreeVars)) -> [Located a] -> RnM ([Located b], FreeVars)
222 rnList f xs = mapFvRn (wrapLocFstM f) xs
226 %*********************************************************
230 %*********************************************************
233 rnDocDecl :: DocDecl -> RnM DocDecl
234 rnDocDecl (DocCommentNext doc) = do
235 rn_doc <- rnHsDoc doc
236 return (DocCommentNext rn_doc)
237 rnDocDecl (DocCommentPrev doc) = do
238 rn_doc <- rnHsDoc doc
239 return (DocCommentPrev rn_doc)
240 rnDocDecl (DocCommentNamed str doc) = do
241 rn_doc <- rnHsDoc doc
242 return (DocCommentNamed str rn_doc)
243 rnDocDecl (DocGroup lev doc) = do
244 rn_doc <- rnHsDoc doc
245 return (DocGroup lev rn_doc)
249 %*********************************************************
251 Source-code fixity declarations
253 %*********************************************************
256 rnSrcFixityDecls :: NameSet -> [LFixitySig RdrName] -> RnM [LFixitySig Name]
257 -- Rename the fixity decls, so we can put
258 -- the renamed decls in the renamed syntax tree
259 -- Errors if the thing being fixed is not defined locally.
261 -- The returned FixitySigs are not actually used for anything,
262 -- except perhaps the GHCi API
263 rnSrcFixityDecls bound_names fix_decls
264 = do fix_decls <- mapM rn_decl fix_decls
265 return (concat fix_decls)
267 rn_decl :: LFixitySig RdrName -> RnM [LFixitySig Name]
268 -- GHC extension: look up both the tycon and data con
269 -- for con-like things; hence returning a list
270 -- If neither are in scope, report an error; otherwise
271 -- return a fixity sig for each (slightly odd)
272 rn_decl (L loc (FixitySig (L name_loc rdr_name) fixity))
273 = setSrcSpan name_loc $
274 -- this lookup will fail if the definition isn't local
275 do names <- lookupLocalDataTcNames bound_names what rdr_name
276 return [ L loc (FixitySig (L name_loc name) fixity)
278 what = ptext (sLit "fixity signature")
282 %*********************************************************
284 Source-code deprecations declarations
286 %*********************************************************
288 Check that the deprecated names are defined, are defined locally, and
289 that there are no duplicate deprecations.
291 It's only imported deprecations, dealt with in RnIfaces, that we
292 gather them together.
295 -- checks that the deprecations are defined locally, and that there are no duplicates
296 rnSrcWarnDecls :: NameSet -> [LWarnDecl RdrName] -> RnM Warnings
297 rnSrcWarnDecls _bound_names []
300 rnSrcWarnDecls bound_names decls
301 = do { -- check for duplicates
302 ; mapM_ (\ (L loc rdr:lrdr':_) -> addErrAt loc (dupWarnDecl lrdr' rdr))
304 ; pairs_s <- mapM (addLocM rn_deprec) decls
305 ; return (WarnSome ((concat pairs_s))) }
307 rn_deprec (Warning rdr_name txt)
308 -- ensures that the names are defined locally
309 = lookupLocalDataTcNames bound_names what rdr_name `thenM` \ names ->
310 return [(nameOccName name, txt) | name <- names]
312 what = ptext (sLit "deprecation")
314 -- look for duplicates among the OccNames;
315 -- we check that the names are defined above
316 -- invt: the lists returned by findDupsEq always have at least two elements
317 warn_rdr_dups = findDupsEq (\ x -> \ y -> rdrNameOcc (unLoc x) == rdrNameOcc (unLoc y))
318 (map (\ (L loc (Warning rdr_name _)) -> L loc rdr_name) decls)
320 dupWarnDecl :: Located RdrName -> RdrName -> SDoc
321 -- Located RdrName -> DeprecDecl RdrName -> SDoc
322 dupWarnDecl (L loc _) rdr_name
323 = vcat [ptext (sLit "Multiple warning declarations for") <+> quotes (ppr rdr_name),
324 ptext (sLit "also at ") <+> ppr loc]
328 %*********************************************************
330 \subsection{Annotation declarations}
332 %*********************************************************
335 rnAnnDecl :: AnnDecl RdrName -> RnM (AnnDecl Name, FreeVars)
336 rnAnnDecl (HsAnnotation provenance expr) = do
337 (provenance', provenance_fvs) <- rnAnnProvenance provenance
338 (expr', expr_fvs) <- rnLExpr expr
339 return (HsAnnotation provenance' expr', provenance_fvs `plusFV` expr_fvs)
341 rnAnnProvenance :: AnnProvenance RdrName -> RnM (AnnProvenance Name, FreeVars)
342 rnAnnProvenance provenance = do
343 provenance' <- modifyAnnProvenanceNameM lookupTopBndrRn provenance
344 return (provenance', maybe emptyFVs unitFV (annProvenanceName_maybe provenance'))
347 %*********************************************************
349 \subsection{Default declarations}
351 %*********************************************************
354 rnDefaultDecl :: DefaultDecl RdrName -> RnM (DefaultDecl Name, FreeVars)
355 rnDefaultDecl (DefaultDecl tys)
356 = mapFvRn (rnHsTypeFVs doc_str) tys `thenM` \ (tys', fvs) ->
357 return (DefaultDecl tys', fvs)
359 doc_str = text "In a `default' declaration"
362 %*********************************************************
364 \subsection{Foreign declarations}
366 %*********************************************************
369 rnHsForeignDecl :: ForeignDecl RdrName -> RnM (ForeignDecl Name, FreeVars)
370 rnHsForeignDecl (ForeignImport name ty spec)
371 = lookupLocatedTopBndrRn name `thenM` \ name' ->
372 rnHsTypeFVs (fo_decl_msg name) ty `thenM` \ (ty', fvs) ->
373 return (ForeignImport name' ty' spec, fvs)
375 rnHsForeignDecl (ForeignExport name ty spec)
376 = lookupLocatedOccRn name `thenM` \ name' ->
377 rnHsTypeFVs (fo_decl_msg name) ty `thenM` \ (ty', fvs) ->
378 return (ForeignExport name' ty' spec, fvs `addOneFV` unLoc name')
379 -- NB: a foreign export is an *occurrence site* for name, so
380 -- we add it to the free-variable list. It might, for example,
381 -- be imported from another module
383 fo_decl_msg :: Located RdrName -> SDoc
384 fo_decl_msg name = ptext (sLit "In the foreign declaration for") <+> ppr name
388 %*********************************************************
390 \subsection{Instance declarations}
392 %*********************************************************
395 rnSrcInstDecl :: InstDecl RdrName -> RnM (InstDecl Name, FreeVars)
396 rnSrcInstDecl (InstDecl inst_ty mbinds uprags ats)
397 -- Used for both source and interface file decls
398 = rnHsSigType (text "an instance decl") inst_ty `thenM` \ inst_ty' ->
400 -- Rename the bindings
401 -- The typechecker (not the renamer) checks that all
402 -- the bindings are for the right class
404 meth_names = collectHsBindLocatedBinders mbinds
405 (inst_tyvars, _, cls,_) = splitHsInstDeclTy (unLoc inst_ty')
407 checkDupRdrNames meth_names `thenM_`
408 -- Check that the same method is not given twice in the
409 -- same instance decl instance C T where
413 -- We must use checkDupRdrNames because the Name of the
414 -- method is the Name of the class selector, whose SrcSpan
415 -- points to the class declaration
417 extendTyVarEnvForMethodBinds inst_tyvars (
418 -- (Slightly strangely) the forall-d tyvars scope over
419 -- the method bindings too
420 rnMethodBinds cls (\_ -> []) -- No scoped tyvars
422 ) `thenM` \ (mbinds', meth_fvs) ->
423 -- Rename the associated types
424 -- The typechecker (not the renamer) checks that all
425 -- the declarations are for the right class
427 at_names = map (head . tyClDeclNames . unLoc) ats
429 checkDupRdrNames at_names `thenM_`
430 -- See notes with checkDupRdrNames for methods, above
432 rnATInsts ats `thenM` \ (ats', at_fvs) ->
434 -- Rename the prags and signatures.
435 -- Note that the type variables are not in scope here,
436 -- so that instance Eq a => Eq (T a) where
437 -- {-# SPECIALISE instance Eq a => Eq (T [a]) #-}
440 -- But the (unqualified) method names are in scope
442 binders = collectHsBindBinders mbinds'
443 bndr_set = mkNameSet binders
445 bindLocalNames binders
446 (renameSigs (Just bndr_set) okInstDclSig uprags) `thenM` \ uprags' ->
448 return (InstDecl inst_ty' mbinds' uprags' ats',
449 meth_fvs `plusFV` at_fvs
450 `plusFV` hsSigsFVs uprags'
451 `plusFV` extractHsTyNames inst_ty')
452 -- We return the renamed associated data type declarations so
453 -- that they can be entered into the list of type declarations
454 -- for the binding group, but we also keep a copy in the instance.
455 -- The latter is needed for well-formedness checks in the type
456 -- checker (eg, to ensure that all ATs of the instance actually
457 -- receive a declaration).
458 -- NB: Even the copies in the instance declaration carry copies of
459 -- the instance context after renaming. This is a bit
460 -- strange, but should not matter (and it would be more work
461 -- to remove the context).
464 Renaming of the associated types in instances.
467 rnATInsts :: [LTyClDecl RdrName] -> RnM ([LTyClDecl Name], FreeVars)
468 rnATInsts atDecls = rnList rnATInst atDecls
470 rnATInst tydecl@TyData {} = rnTyClDecl tydecl
471 rnATInst tydecl@TySynonym {} = rnTyClDecl tydecl
473 pprPanic "RnSource.rnATInsts: invalid AT instance"
474 (ppr (tcdName tydecl))
477 For the method bindings in class and instance decls, we extend the
478 type variable environment iff -fglasgow-exts
481 extendTyVarEnvForMethodBinds :: [LHsTyVarBndr Name]
482 -> RnM (Bag (LHsBind Name), FreeVars)
483 -> RnM (Bag (LHsBind Name), FreeVars)
484 extendTyVarEnvForMethodBinds tyvars thing_inside
485 = do { scoped_tvs <- doptM Opt_ScopedTypeVariables
487 extendTyVarEnvFVRn (map hsLTyVarName tyvars) thing_inside
492 %*********************************************************
494 \subsection{Stand-alone deriving declarations}
496 %*********************************************************
499 rnSrcDerivDecl :: DerivDecl RdrName -> RnM (DerivDecl Name, FreeVars)
500 rnSrcDerivDecl (DerivDecl ty)
501 = do { standalone_deriv_ok <- doptM Opt_StandaloneDeriving
502 ; unless standalone_deriv_ok (addErr standaloneDerivErr)
503 ; ty' <- rnLHsType (text "a deriving decl") ty
504 ; let fvs = extractHsTyNames ty'
505 ; return (DerivDecl ty', fvs) }
507 standaloneDerivErr :: SDoc
509 = hang (ptext (sLit "Illegal standalone deriving declaration"))
510 2 (ptext (sLit "Use -XStandaloneDeriving to enable this extension"))
513 %*********************************************************
517 %*********************************************************
520 rnHsRuleDecl :: RuleDecl RdrName -> RnM (RuleDecl Name, FreeVars)
521 rnHsRuleDecl (HsRule rule_name act vars lhs _fv_lhs rhs _fv_rhs)
522 = bindPatSigTyVarsFV (collectRuleBndrSigTys vars) $
523 bindLocatedLocalsFV (map get_var vars) $ \ ids ->
524 do { (vars', fv_vars) <- mapFvRn rn_var (vars `zip` ids)
525 -- NB: The binders in a rule are always Ids
526 -- We don't (yet) support type variables
528 ; (lhs', fv_lhs') <- rnLExpr lhs
529 ; (rhs', fv_rhs') <- rnLExpr rhs
531 ; checkValidRule rule_name ids lhs' fv_lhs'
533 ; return (HsRule rule_name act vars' lhs' fv_lhs' rhs' fv_rhs',
534 fv_vars `plusFV` fv_lhs' `plusFV` fv_rhs') }
536 doc = text "In the transformation rule" <+> ftext rule_name
538 get_var (RuleBndr v) = v
539 get_var (RuleBndrSig v _) = v
541 rn_var (RuleBndr (L loc _), id)
542 = return (RuleBndr (L loc id), emptyFVs)
543 rn_var (RuleBndrSig (L loc _) t, id)
544 = rnHsTypeFVs doc t `thenM` \ (t', fvs) ->
545 return (RuleBndrSig (L loc id) t', fvs)
547 badRuleVar :: FastString -> Name -> SDoc
549 = sep [ptext (sLit "Rule") <+> doubleQuotes (ftext name) <> colon,
550 ptext (sLit "Forall'd variable") <+> quotes (ppr var) <+>
551 ptext (sLit "does not appear on left hand side")]
554 Note [Rule LHS validity checking]
555 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
556 Check the shape of a transformation rule LHS. Currently we only allow
557 LHSs of the form @(f e1 .. en)@, where @f@ is not one of the
558 @forall@'d variables.
560 We used restrict the form of the 'ei' to prevent you writing rules
561 with LHSs with a complicated desugaring (and hence unlikely to match);
562 (e.g. a case expression is not allowed: too elaborate.)
564 But there are legitimate non-trivial args ei, like sections and
565 lambdas. So it seems simmpler not to check at all, and that is why
566 check_e is commented out.
569 checkValidRule :: FastString -> [Name] -> LHsExpr Name -> NameSet -> RnM ()
570 checkValidRule rule_name ids lhs' fv_lhs'
571 = do { -- Check for the form of the LHS
572 case (validRuleLhs ids lhs') of
574 Just bad -> failWithTc (badRuleLhsErr rule_name lhs' bad)
576 -- Check that LHS vars are all bound
577 ; let bad_vars = [var | var <- ids, not (var `elemNameSet` fv_lhs')]
578 ; mapM_ (addErr . badRuleVar rule_name) bad_vars }
580 validRuleLhs :: [Name] -> LHsExpr Name -> Maybe (HsExpr Name)
582 -- Just e => Not ok, and e is the offending expression
583 validRuleLhs foralls lhs
586 checkl (L _ e) = check e
588 check (OpApp e1 op _ e2) = checkl op `mplus` checkl_e e1 `mplus` checkl_e e2
589 check (HsApp e1 e2) = checkl e1 `mplus` checkl_e e2
590 check (HsVar v) | v `notElem` foralls = Nothing
591 check other = Just other -- Failure
594 checkl_e (L _ _e) = Nothing -- Was (check_e e); see Note [Rule LHS validity checking]
596 {- Commented out; see Note [Rule LHS validity checking] above
597 check_e (HsVar v) = Nothing
598 check_e (HsPar e) = checkl_e e
599 check_e (HsLit e) = Nothing
600 check_e (HsOverLit e) = Nothing
602 check_e (OpApp e1 op _ e2) = checkl_e e1 `mplus` checkl_e op `mplus` checkl_e e2
603 check_e (HsApp e1 e2) = checkl_e e1 `mplus` checkl_e e2
604 check_e (NegApp e _) = checkl_e e
605 check_e (ExplicitList _ es) = checkl_es es
606 check_e other = Just other -- Fails
608 checkl_es es = foldr (mplus . checkl_e) Nothing es
611 badRuleLhsErr :: FastString -> LHsExpr Name -> HsExpr Name -> SDoc
612 badRuleLhsErr name lhs bad_e
613 = sep [ptext (sLit "Rule") <+> ftext name <> colon,
614 nest 4 (vcat [ptext (sLit "Illegal expression:") <+> ppr bad_e,
615 ptext (sLit "in left-hand side:") <+> ppr lhs])]
617 ptext (sLit "LHS must be of form (f e1 .. en) where f is not forall'd")
621 %*********************************************************
623 \subsection{Type, class and iface sig declarations}
625 %*********************************************************
627 @rnTyDecl@ uses the `global name function' to create a new type
628 declaration in which local names have been replaced by their original
629 names, reporting any unknown names.
631 Renaming type variables is a pain. Because they now contain uniques,
632 it is necessary to pass in an association list which maps a parsed
633 tyvar to its @Name@ representation.
634 In some cases (type signatures of values),
635 it is even necessary to go over the type first
636 in order to get the set of tyvars used by it, make an assoc list,
637 and then go over it again to rename the tyvars!
638 However, we can also do some scoping checks at the same time.
641 rnTyClDecl :: TyClDecl RdrName -> RnM (TyClDecl Name, FreeVars)
642 rnTyClDecl (ForeignType {tcdLName = name, tcdExtName = ext_name})
643 = lookupLocatedTopBndrRn name `thenM` \ name' ->
644 return (ForeignType {tcdLName = name', tcdExtName = ext_name},
647 -- all flavours of type family declarations ("type family", "newtype fanily",
648 -- and "data family")
649 rnTyClDecl (tydecl@TyFamily {}) =
650 rnFamily tydecl bindTyVarsRn
652 -- "data", "newtype", "data instance, and "newtype instance" declarations
653 rnTyClDecl tydecl@TyData {tcdND = new_or_data, tcdCtxt = context,
654 tcdLName = tycon, tcdTyVars = tyvars,
655 tcdTyPats = typatsMaybe, tcdCons = condecls,
656 tcdKindSig = sig, tcdDerivs = derivs}
657 = do { tycon' <- if isFamInstDecl tydecl
658 then lookupLocatedOccRn tycon -- may be imported family
659 else lookupLocatedTopBndrRn tycon
660 ; checkTc (h98_style || null (unLoc context))
661 (badGadtStupidTheta tycon)
662 ; (tyvars', context', typats', derivs', deriv_fvs)
663 <- bindTyVarsRn tyvars $ \ tyvars' -> do
664 -- Checks for distinct tyvars
665 { typats' <- rnTyPats data_doc typatsMaybe
666 ; context' <- rnContext data_doc context
667 ; (derivs', deriv_fvs) <- rn_derivs derivs
668 ; return (tyvars', context', typats', derivs', deriv_fvs) }
669 -- For GADTs, the type variables in the declaration
670 -- do not scope over the constructor signatures
671 -- data T a where { T1 :: forall b. b-> b }
673 -- For the constructor declarations, bring into scope the tyvars
674 -- bound by the header, but *only* in the H98 case
675 ; let tc_tvs_in_scope | h98_style = hsLTyVarNames tyvars'
677 ; (condecls', con_fvs) <- bindLocalNamesFV tc_tvs_in_scope $
679 -- No need to check for duplicate constructor decls
680 -- since that is done by RnNames.extendGlobalRdrEnvRn
682 ; return (TyData {tcdND = new_or_data, tcdCtxt = context',
683 tcdLName = tycon', tcdTyVars = tyvars',
684 tcdTyPats = typats', tcdKindSig = sig,
685 tcdCons = condecls', tcdDerivs = derivs'},
688 (if isFamInstDecl tydecl
689 then unitFV (unLoc tycon') -- type instance => use
693 h98_style = case condecls of
694 L _ (ConDecl { con_res = ResTyH98 }) : _ -> True
696 data_doc = text "In the data type declaration for" <+> quotes (ppr tycon)
698 rn_derivs Nothing = return (Nothing, emptyFVs)
699 rn_derivs (Just ds) = rnLHsTypes data_doc ds `thenM` \ ds' ->
700 return (Just ds', extractHsTyNames_s ds')
702 -- "type" and "type instance" declarations
703 rnTyClDecl tydecl@(TySynonym {tcdLName = name, tcdTyVars = tyvars,
704 tcdTyPats = typatsMaybe, tcdSynRhs = ty})
705 = bindTyVarsRn tyvars $ \ tyvars' -> do
706 { -- Checks for distinct tyvars
707 name' <- if isFamInstDecl tydecl
708 then lookupLocatedOccRn name -- may be imported family
709 else lookupLocatedTopBndrRn name
710 ; typats' <- rnTyPats syn_doc typatsMaybe
711 ; (ty', fvs) <- rnHsTypeFVs syn_doc ty
712 ; return (TySynonym { tcdLName = name', tcdTyVars = tyvars'
713 , tcdTyPats = typats', tcdSynRhs = ty'},
714 delFVs (map hsLTyVarName tyvars') $
716 (if isFamInstDecl tydecl
717 then unitFV (unLoc name') -- type instance => use
721 syn_doc = text "In the declaration for type synonym" <+> quotes (ppr name)
723 rnTyClDecl (ClassDecl {tcdCtxt = context, tcdLName = cname,
724 tcdTyVars = tyvars, tcdFDs = fds, tcdSigs = sigs,
725 tcdMeths = mbinds, tcdATs = ats, tcdDocs = docs})
726 = do { cname' <- lookupLocatedTopBndrRn cname
728 -- Tyvars scope over superclass context and method signatures
729 ; (tyvars', context', fds', ats', ats_fvs, sigs')
730 <- bindTyVarsRn tyvars $ \ tyvars' -> do
731 -- Checks for distinct tyvars
732 { context' <- rnContext cls_doc context
733 ; fds' <- rnFds cls_doc fds
734 ; (ats', ats_fvs) <- rnATs ats
735 ; sigs' <- renameSigs Nothing okClsDclSig sigs
736 ; return (tyvars', context', fds', ats', ats_fvs, sigs') }
738 -- No need to check for duplicate associated type decls
739 -- since that is done by RnNames.extendGlobalRdrEnvRn
741 -- Check the signatures
742 -- First process the class op sigs (op_sigs), then the fixity sigs (non_op_sigs).
743 ; let sig_rdr_names_w_locs = [op | L _ (TypeSig op _) <- sigs]
744 ; checkDupRdrNames sig_rdr_names_w_locs
745 -- Typechecker is responsible for checking that we only
746 -- give default-method bindings for things in this class.
747 -- The renamer *could* check this for class decls, but can't
748 -- for instance decls.
750 -- The newLocals call is tiresome: given a generic class decl
753 -- op {| x+y |} (Inl a) = ...
754 -- op {| x+y |} (Inr b) = ...
755 -- op {| a*b |} (a*b) = ...
756 -- we want to name both "x" tyvars with the same unique, so that they are
757 -- easy to group together in the typechecker.
758 ; (mbinds', meth_fvs)
759 <- extendTyVarEnvForMethodBinds tyvars' $ do
760 { name_env <- getLocalRdrEnv
761 ; let gen_rdr_tyvars_w_locs = [ tv | tv <- extractGenericPatTyVars mbinds,
762 not (unLoc tv `elemLocalRdrEnv` name_env) ]
763 -- No need to check for duplicate method signatures
764 -- since that is done by RnNames.extendGlobalRdrEnvRn
765 -- and the methods are already in scope
766 ; gen_tyvars <- newLocalBndrsRn gen_rdr_tyvars_w_locs
767 ; rnMethodBinds (unLoc cname') (mkSigTvFn sigs') gen_tyvars mbinds }
770 ; docs' <- mapM (wrapLocM rnDocDecl) docs
772 ; return (ClassDecl { tcdCtxt = context', tcdLName = cname',
773 tcdTyVars = tyvars', tcdFDs = fds', tcdSigs = sigs',
774 tcdMeths = mbinds', tcdATs = ats', tcdDocs = docs'},
776 delFVs (map hsLTyVarName tyvars') $
777 extractHsCtxtTyNames context' `plusFV`
778 plusFVs (map extractFunDepNames (map unLoc fds')) `plusFV`
779 hsSigsFVs sigs' `plusFV`
783 cls_doc = text "In the declaration for class" <+> ppr cname
785 badGadtStupidTheta :: Located RdrName -> SDoc
787 = vcat [ptext (sLit "No context is allowed on a GADT-style data declaration"),
788 ptext (sLit "(You can put a context on each contructor, though.)")]
792 %*********************************************************
794 \subsection{Support code for type/data declarations}
796 %*********************************************************
799 rnTyPats :: SDoc -> Maybe [LHsType RdrName] -> RnM (Maybe [LHsType Name])
800 -- Although, we are processing type patterns here, all type variables will
801 -- already be in scope (they are the same as in the 'tcdTyVars' field of the
802 -- type declaration to which these patterns belong)
803 rnTyPats _ Nothing = return Nothing
804 rnTyPats doc (Just typats) = liftM Just $ rnLHsTypes doc typats
806 rnConDecls :: [LConDecl RdrName] -> RnM ([LConDecl Name], FreeVars)
808 = do { condecls' <- mapM (wrapLocM rnConDecl) condecls
809 ; return (condecls', plusFVs (map conDeclFVs condecls')) }
811 rnConDecl :: ConDecl RdrName -> RnM (ConDecl Name)
812 rnConDecl decl@(ConDecl { con_name = name, con_qvars = tvs
813 , con_cxt = cxt, con_details = details
814 , con_res = res_ty, con_doc = mb_doc
815 , con_old_rec = old_rec, con_explicit = expl })
816 = do { addLocM checkConName name
817 ; when old_rec (addWarn (deprecRecSyntax decl))
818 ; new_name <- lookupLocatedTopBndrRn name
820 -- For H98 syntax, the tvs are the existential ones
821 -- For GADT syntax, the tvs are all the quantified tyvars
822 -- Hence the 'filter' in the ResTyH98 case only
823 ; rdr_env <- getLocalRdrEnv
824 ; let in_scope = (`elemLocalRdrEnv` rdr_env) . unLoc
825 arg_tys = hsConDeclArgTys details
826 implicit_tvs = case res_ty of
827 ResTyH98 -> filterOut in_scope (get_rdr_tvs arg_tys)
828 ResTyGADT ty -> get_rdr_tvs (ty : arg_tys)
829 new_tvs = case expl of
831 Implicit -> userHsTyVarBndrs implicit_tvs
833 ; mb_doc' <- rnMbLHsDoc mb_doc
835 ; bindTyVarsRn new_tvs $ \new_tyvars -> do
836 { new_context <- rnContext doc cxt
837 ; new_details <- rnConDeclDetails doc details
838 ; (new_details', new_res_ty) <- rnConResult doc new_details res_ty
839 ; return (decl { con_name = new_name, con_qvars = new_tyvars, con_cxt = new_context
840 , con_details = new_details', con_res = new_res_ty, con_doc = mb_doc' }) }}
842 doc = text "In the definition of data constructor" <+> quotes (ppr name)
843 get_rdr_tvs tys = extractHsRhoRdrTyVars cxt (noLoc (HsTupleTy Boxed tys))
846 -> HsConDetails (LHsType Name) [ConDeclField Name]
848 -> RnM (HsConDetails (LHsType Name) [ConDeclField Name],
850 rnConResult _ details ResTyH98 = return (details, ResTyH98)
851 rnConResult doc details (ResTyGADT ty)
852 = do { ty' <- rnLHsType doc ty
853 ; let (arg_tys, res_ty) = splitHsFunType ty'
854 -- We can finally split it up,
855 -- now the renamer has dealt with fixities
856 -- See Note [Sorting out the result type] in RdrHsSyn
858 details' = case details of
860 PrefixCon {} -> PrefixCon arg_tys
861 InfixCon {} -> pprPanic "rnConResult" (ppr ty)
862 -- See Note [Sorting out the result type] in RdrHsSyn
864 ; when (not (null arg_tys) && case details of { RecCon {} -> True; _ -> False })
865 (addErr (badRecResTy doc))
866 ; return (details', ResTyGADT res_ty) }
868 rnConDeclDetails :: SDoc
869 -> HsConDetails (LHsType RdrName) [ConDeclField RdrName]
870 -> RnM (HsConDetails (LHsType Name) [ConDeclField Name])
871 rnConDeclDetails doc (PrefixCon tys)
872 = mapM (rnLHsType doc) tys `thenM` \ new_tys ->
873 return (PrefixCon new_tys)
875 rnConDeclDetails doc (InfixCon ty1 ty2)
876 = rnLHsType doc ty1 `thenM` \ new_ty1 ->
877 rnLHsType doc ty2 `thenM` \ new_ty2 ->
878 return (InfixCon new_ty1 new_ty2)
880 rnConDeclDetails doc (RecCon fields)
881 = do { new_fields <- rnConDeclFields doc fields
882 -- No need to check for duplicate fields
883 -- since that is done by RnNames.extendGlobalRdrEnvRn
884 ; return (RecCon new_fields) }
886 -- Rename family declarations
888 -- * This function is parametrised by the routine handling the index
889 -- variables. On the toplevel, these are defining occurences, whereas they
890 -- are usage occurences for associated types.
892 rnFamily :: TyClDecl RdrName
893 -> ([LHsTyVarBndr RdrName] ->
894 ([LHsTyVarBndr Name] -> RnM (TyClDecl Name, FreeVars)) ->
895 RnM (TyClDecl Name, FreeVars))
896 -> RnM (TyClDecl Name, FreeVars)
898 rnFamily (tydecl@TyFamily {tcdFlavour = flavour,
899 tcdLName = tycon, tcdTyVars = tyvars})
901 do { bindIdxVars tyvars $ \tyvars' -> do {
902 ; tycon' <- lookupLocatedTopBndrRn tycon
903 ; return (TyFamily {tcdFlavour = flavour, tcdLName = tycon',
904 tcdTyVars = tyvars', tcdKind = tcdKind tydecl},
907 rnFamily d _ = pprPanic "rnFamily" (ppr d)
909 -- Rename associated type declarations (in classes)
911 -- * This can be family declarations and (default) type instances
913 rnATs :: [LTyClDecl RdrName] -> RnM ([LTyClDecl Name], FreeVars)
914 rnATs ats = mapFvRn (wrapLocFstM rn_at) ats
916 rn_at (tydecl@TyFamily {}) = rnFamily tydecl lookupIdxVars
917 rn_at (tydecl@TySynonym {}) =
919 unless (isNothing (tcdTyPats tydecl)) $ addErr noPatterns
921 rn_at _ = panic "RnSource.rnATs: invalid TyClDecl"
923 lookupIdxVars tyvars cont =
924 do { checkForDups tyvars;
925 ; tyvars' <- mapM lookupIdxVar tyvars
928 -- Type index variables must be class parameters, which are the only
929 -- type variables in scope at this point.
930 lookupIdxVar (L l tyvar) =
932 name' <- lookupOccRn (hsTyVarName tyvar)
933 return $ L l (replaceTyVarName tyvar name')
935 -- Type variable may only occur once.
937 checkForDups [] = return ()
938 checkForDups (L loc tv:ltvs) =
939 do { setSrcSpan loc $
940 when (hsTyVarName tv `ltvElem` ltvs) $
941 addErr (repeatedTyVar tv)
945 _ `ltvElem` [] = False
946 rdrName `ltvElem` (L _ tv:ltvs)
947 | rdrName == hsTyVarName tv = True
948 | otherwise = rdrName `ltvElem` ltvs
950 deprecRecSyntax :: ConDecl RdrName -> SDoc
952 = vcat [ ptext (sLit "Declaration of") <+> quotes (ppr (con_name decl))
953 <+> ptext (sLit "uses deprecated syntax")
954 , ptext (sLit "Instead, use the form")
955 , nest 2 (ppr decl) ] -- Pretty printer uses new form
957 badRecResTy :: SDoc -> SDoc
958 badRecResTy doc = ptext (sLit "Malformed constructor signature") $$ doc
961 noPatterns = text "Default definition for an associated synonym cannot have"
962 <+> text "type pattern"
964 repeatedTyVar :: HsTyVarBndr RdrName -> SDoc
965 repeatedTyVar tv = ptext (sLit "Illegal repeated type variable") <+>
968 -- This data decl will parse OK
970 -- treating "a" as the constructor.
971 -- It is really hard to make the parser spot this malformation.
972 -- So the renamer has to check that the constructor is legal
974 -- We can get an operator as the constructor, even in the prefix form:
975 -- data T = :% Int Int
976 -- from interface files, which always print in prefix form
978 checkConName :: RdrName -> TcRn ()
979 checkConName name = checkErr (isRdrDataCon name) (badDataCon name)
981 badDataCon :: RdrName -> SDoc
983 = hsep [ptext (sLit "Illegal data constructor name"), quotes (ppr name)]
987 %*********************************************************
989 \subsection{Support code for type/data declarations}
991 %*********************************************************
993 Get the mapping from constructors to fields for this module.
994 It's convenient to do this after the data type decls have been renamed
996 extendRecordFieldEnv :: [LTyClDecl RdrName] -> [LInstDecl RdrName] -> TcM TcGblEnv
997 extendRecordFieldEnv tycl_decls inst_decls
998 = do { tcg_env <- getGblEnv
999 ; field_env' <- foldrM get_con (tcg_field_env tcg_env) all_data_cons
1000 ; return (tcg_env { tcg_field_env = field_env' }) }
1002 -- we want to lookup:
1003 -- (a) a datatype constructor
1004 -- (b) a record field
1005 -- knowing that they're from this module.
1006 -- lookupLocatedTopBndrRn does this, because it does a lookupGreLocalRn,
1007 -- which keeps only the local ones.
1008 lookup x = do { x' <- lookupLocatedTopBndrRn x
1009 ; return $ unLoc x'}
1011 all_data_cons :: [ConDecl RdrName]
1012 all_data_cons = [con | L _ (TyData { tcdCons = cons }) <- all_tycl_decls
1014 all_tycl_decls = at_tycl_decls ++ tycl_decls
1015 at_tycl_decls = [at | L _ (InstDecl _ _ _ ats) <- inst_decls, at <- ats]
1016 -- Do not forget associated types!
1018 get_con (ConDecl { con_name = con, con_details = RecCon flds })
1019 (RecFields env fld_set)
1020 = do { con' <- lookup con
1021 ; flds' <- mapM lookup (map cd_fld_name flds)
1022 ; let env' = extendNameEnv env con' flds'
1023 fld_set' = addListToNameSet fld_set flds'
1024 ; return $ (RecFields env' fld_set') }
1025 get_con _ env = return env
1028 %*********************************************************
1030 \subsection{Support code to rename types}
1032 %*********************************************************
1035 rnFds :: SDoc -> [Located (FunDep RdrName)] -> RnM [Located (FunDep Name)]
1038 = mapM (wrapLocM rn_fds) fds
1041 = rnHsTyVars doc tys1 `thenM` \ tys1' ->
1042 rnHsTyVars doc tys2 `thenM` \ tys2' ->
1043 return (tys1', tys2')
1045 rnHsTyVars :: SDoc -> [RdrName] -> RnM [Name]
1046 rnHsTyVars doc tvs = mapM (rnHsTyVar doc) tvs
1048 rnHsTyVar :: SDoc -> RdrName -> RnM Name
1049 rnHsTyVar _doc tyvar = lookupOccRn tyvar