Skip to content

Commit f2b291d

Browse files
committed
Auto merge of rust-lang#156305 - JonathanBrouwer:rollup-xjiYS62, r=JonathanBrouwer
Rollup of 7 pull requests Successful merges: - rust-lang#156236 (resolve: Remove `MacroData`) - rust-lang#156298 (Rename the unstable integer `extend` function to `widen`) - rust-lang#154498 (turn some long-deprecated -C options into errors) - rust-lang#155734 (Reject outer attributes on `cfg_select` branches) - rust-lang#156123 (Simplify the creation of synthetic HIR.) - rust-lang#156175 (Dep graph cleanups) - rust-lang#156214 (Do not cache `lints_that_dont_need_to_run` across sessions)
2 parents 3e353d7 + 565ee37 commit f2b291d

36 files changed

Lines changed: 362 additions & 258 deletions

compiler/rustc_attr_parsing/src/attributes/cfg_select.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Token;
22
use rustc_ast::tokenstream::TokenStream;
33
use rustc_ast::{AttrStyle, NodeId, token};
44
use rustc_data_structures::fx::FxHashMap;
5-
use rustc_errors::Diagnostic;
5+
use rustc_errors::{Diagnostic, MultiSpan};
66
use rustc_feature::{AttributeTemplate, Features};
77
use rustc_hir::attrs::CfgEntry;
88
use rustc_hir::{AttrPath, Target};
@@ -76,8 +76,11 @@ pub fn parse_cfg_select(
7676
lint_node_id: NodeId,
7777
) -> Result<CfgSelectBranches, ErrorGuaranteed> {
7878
let mut branches = CfgSelectBranches::default();
79+
let mut branch_attr_error: Option<ErrorGuaranteed> = None;
7980

8081
while p.token != token::Eof {
82+
reject_branch_outer_attrs(p, &mut branch_attr_error)?;
83+
8184
if p.eat_keyword(exp!(Underscore)) {
8285
let underscore = p.prev_token;
8386
p.expect(exp!(FatArrow)).map_err(|e| e.emit())?;
@@ -131,6 +134,10 @@ pub fn parse_cfg_select(
131134
}
132135
}
133136

137+
if let Some(guar) = branch_attr_error {
138+
return Err(guar);
139+
}
140+
134141
let it = branches
135142
.reachable
136143
.iter()
@@ -143,6 +150,27 @@ pub fn parse_cfg_select(
143150
Ok(branches)
144151
}
145152

153+
fn reject_branch_outer_attrs(
154+
p: &mut Parser<'_>,
155+
branch_attr_error: &mut Option<ErrorGuaranteed>,
156+
) -> Result<(), ErrorGuaranteed> {
157+
let Some(spans) = p.parse_cfg_select_branch_outer_attrs().map_err(|e| e.emit())? else {
158+
return Ok(());
159+
};
160+
161+
for (spans, msg) in [
162+
(spans.doc_comments, "doc comments are not allowed on `cfg_select` branches"),
163+
(spans.attrs, "attributes are not allowed on `cfg_select` branches"),
164+
] {
165+
if !spans.is_empty() {
166+
branch_attr_error
167+
.get_or_insert(p.dcx().struct_span_err(MultiSpan::from_spans(spans), msg).emit());
168+
}
169+
}
170+
171+
Ok(())
172+
}
173+
146174
fn lint_unreachable(
147175
p: &mut Parser<'_>,
148176
predicates: impl Iterator<Item = CfgSelectPredicate>,

compiler/rustc_expand/src/mbe/macro_rules.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ pub struct MacroRulesMacroExpander {
170170
transparency: Transparency,
171171
kinds: MacroKinds,
172172
rules: Vec<MacroRule>,
173+
macro_rules: bool,
173174
}
174175

175176
impl MacroRulesMacroExpander {
@@ -189,6 +190,14 @@ impl MacroRulesMacroExpander {
189190
self.kinds
190191
}
191192

193+
pub fn nrules(&self) -> usize {
194+
self.rules.len()
195+
}
196+
197+
pub fn is_macro_rules(&self) -> bool {
198+
self.macro_rules
199+
}
200+
192201
pub fn expand_derive(
193202
&self,
194203
cx: &mut ExtCtxt<'_>,
@@ -714,13 +723,12 @@ pub fn compile_declarative_macro(
714723
span: Span,
715724
node_id: NodeId,
716725
edition: Edition,
717-
) -> (SyntaxExtension, usize) {
726+
) -> SyntaxExtension {
718727
let mk_syn_ext = |kind| {
719728
let is_local = is_defined_in_current_crate(node_id);
720729
SyntaxExtension::new(sess, kind, span, Vec::new(), edition, ident.name, attrs, is_local)
721730
};
722-
let dummy_syn_ext =
723-
|guar| (mk_syn_ext(SyntaxExtensionKind::Bang(Arc::new(DummyBang(guar)))), 0);
731+
let dummy_syn_ext = |guar| mk_syn_ext(SyntaxExtensionKind::Bang(Arc::new(DummyBang(guar))));
724732

725733
let macro_rules = macro_def.macro_rules;
726734
let exp_sep = if macro_rules { exp!(Semi) } else { exp!(Comma) };
@@ -857,9 +865,6 @@ pub fn compile_declarative_macro(
857865
return dummy_syn_ext(guar);
858866
}
859867

860-
// Return the number of rules for unused rule linting, if this is a local macro.
861-
let nrules = if is_defined_in_current_crate(node_id) { rules.len() } else { 0 };
862-
863868
let on_unmatch_args = find_attr!(
864869
attrs,
865870
OnUnmatchArgs { directive, .. } => directive.clone()
@@ -875,8 +880,9 @@ pub fn compile_declarative_macro(
875880
on_unmatch_args,
876881
transparency,
877882
rules,
883+
macro_rules,
878884
};
879-
(mk_syn_ext(SyntaxExtensionKind::MacroRules(Arc::new(exp))), nrules)
885+
mk_syn_ext(SyntaxExtensionKind::MacroRules(Arc::new(exp)))
880886
}
881887

882888
fn check_no_eof(sess: &Session, p: &Parser<'_>, msg: &'static str) -> Option<ErrorGuaranteed> {

compiler/rustc_hir/src/hir.rs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1595,6 +1595,20 @@ impl<'tcx> OwnerNodes<'tcx> {
15951595
// Indexing must ensure it is an OwnerNode.
15961596
self.nodes[ItemLocalId::ZERO].node.as_owner().unwrap()
15971597
}
1598+
1599+
/// Return an instance of `OwnerNodes` suitable for definitions that have no corresponding AST.
1600+
pub fn synthetic() -> OwnerNodes<'tcx> {
1601+
OwnerNodes {
1602+
// There is no reason to bother computing a hash for a synthetic body.
1603+
// Just use a constant value.
1604+
opt_hash_including_bodies: Some(Fingerprint::ZERO),
1605+
nodes: IndexVec::from_elem_n(
1606+
ParentedNode { parent: ItemLocalId::INVALID, node: OwnerNode::Synthetic.into() },
1607+
1,
1608+
),
1609+
bodies: SortedMap::new(),
1610+
}
1611+
}
15981612
}
15991613

16001614
impl fmt::Debug for OwnerNodes<'_> {

compiler/rustc_interface/src/tests.rs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -578,19 +578,16 @@ fn test_codegen_options_tracking_hash() {
578578

579579
// Make sure that changing an [UNTRACKED] option leaves the hash unchanged.
580580
// tidy-alphabetical-start
581-
untracked!(ar, String::from("abc"));
582581
untracked!(codegen_units, Some(42));
583582
untracked!(default_linker_libraries, true);
584583
untracked!(dlltool, Some(PathBuf::from("custom_dlltool.exe")));
585584
untracked!(extra_filename, String::from("extra-filename"));
586585
untracked!(incremental, Some(String::from("abc")));
587-
untracked!(inline_threshold, Some(0xf007ba11));
588586
// `link_arg` is omitted because it just forwards to `link_args`.
589587
untracked!(link_args, vec![String::from("abc"), String::from("def")]);
590588
untracked!(link_self_contained, LinkSelfContained::on());
591589
untracked!(linker, Some(PathBuf::from("linker")));
592590
untracked!(linker_flavor, Some(LinkerFlavorCli::Gcc));
593-
untracked!(no_stack_check, true);
594591
untracked!(remark, Passes::Some(vec![String::from("pass1"), String::from("pass2")]));
595592
untracked!(rpath, true);
596593
untracked!(save_temps, true);

compiler/rustc_middle/src/dep_graph/graph.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -331,16 +331,15 @@ impl DepGraphData {
331331
format!("forcing query with already existing `DepNode`: {dep_node:?}")
332332
});
333333

334-
let with_deps = |task_deps| with_deps(task_deps, op);
335334
let (result, edges) = if tcx.is_eval_always(dep_node.kind) {
336-
(with_deps(TaskDepsRef::EvalAlways), EdgesVec::new())
335+
(with_deps(TaskDepsRef::EvalAlways, op), EdgesVec::new())
337336
} else {
338337
let task_deps = Lock::new(TaskDeps::new(
339338
#[cfg(debug_assertions)]
340339
Some(dep_node),
341340
0,
342341
));
343-
(with_deps(TaskDepsRef::Allow(&task_deps)), task_deps.into_inner().reads)
342+
(with_deps(TaskDepsRef::Allow(&task_deps), op), task_deps.into_inner().reads)
344343
};
345344

346345
let dep_node_index =
@@ -396,10 +395,10 @@ impl DepGraphData {
396395
}
397396
_ => {
398397
// The dep node indices are hashed here instead of hashing the dep nodes of the
399-
// dependencies. These indices may refer to different nodes per session, but this isn't
400-
// a problem here because we that ensure the final dep node hash is per session only by
401-
// combining it with the per session random number `anon_id_seed`. This hash only need
402-
// to map the dependencies to a single value on a per session basis.
398+
// dependencies. These indices may refer to different nodes per session, but this
399+
// isn't a problem here because we that ensure the final dep node hash is per
400+
// session only by combining it with the per session `anon_id_seed`. This hash only
401+
// need to map the dependencies to a single value on a per session basis.
403402
let mut hasher = StableHasher::new();
404403
reads.hash(&mut hasher);
405404

@@ -1223,13 +1222,14 @@ pub struct TaskDeps {
12231222
#[cfg(debug_assertions)]
12241223
node: Option<DepNode>,
12251224

1226-
/// A vector of `DepNodeIndex`, basically.
1225+
/// A vector of `DepNodeIndex`, basically. Contains no duplicates.
12271226
reads: EdgesVec,
12281227

1229-
/// When adding new edges to `reads` in `DepGraph::read_index` we need to determine if the edge
1230-
/// has been seen before. If the number of elements in `reads` is small, we just do a linear
1231-
/// scan. If the number is higher, a hashset has better perf. This field is that hashset. It's
1232-
/// only used if the number of elements in `reads` exceeds `LINEAR_SCAN_MAX`.
1228+
/// When adding a new edge to `reads` in `DepGraph::read_index` we must determine if the edge
1229+
/// has been seen before. We just do a linear scan of `reads` if its length is less than or
1230+
/// equal to `LINEAR_SCAN_MAX`. Otherwise, we use this hashset for better performance. Note:
1231+
/// `reads` is always the canonical edges representation; this field is just to speed up the
1232+
/// seen-before test.
12331233
read_set: FxHashSet<DepNodeIndex>,
12341234
}
12351235

compiler/rustc_middle/src/queries.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,9 @@ rustc_queries! {
565565

566566
query lints_that_dont_need_to_run(_: ()) -> &'tcx UnordSet<LintId> {
567567
arena_cache
568+
// This depends on the lint store, which includes internal lints when the
569+
// untracked `-Zunstable-options` flag is set.
570+
eval_always
568571
desc { "Computing all lints that are explicitly enabled or with a default level greater than Allow" }
569572
}
570573

compiler/rustc_middle/src/ty/context.rs

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -627,23 +627,8 @@ impl<'tcx> TyCtxtFeed<'tcx, LocalDefId> {
627627
// Fills in all the important parts needed by HIR queries
628628
pub fn feed_hir(&self) {
629629
self.local_def_id_to_hir_id(HirId::make_owner(self.def_id()));
630-
631-
let node = hir::OwnerNode::Synthetic;
632-
let bodies = Default::default();
633-
let attrs = hir::AttributeMap::EMPTY;
634-
635-
let rustc_middle::hir::Hashes { opt_hash_including_bodies, .. } =
636-
self.tcx.hash_owner_nodes(node, &bodies, &attrs.map, attrs.define_opaque);
637-
let node = node.into();
638-
self.opt_hir_owner_nodes(Some(self.tcx.arena.alloc(hir::OwnerNodes {
639-
opt_hash_including_bodies,
640-
nodes: IndexVec::from_elem_n(
641-
hir::ParentedNode { parent: hir::ItemLocalId::INVALID, node },
642-
1,
643-
),
644-
bodies,
645-
})));
646-
self.feed_owner_id().hir_attr_map(attrs);
630+
self.opt_hir_owner_nodes(Some(self.tcx.arena.alloc(hir::OwnerNodes::synthetic())));
631+
self.feed_owner_id().hir_attr_map(hir::AttributeMap::EMPTY);
647632
}
648633
}
649634

compiler/rustc_parse/src/parser/cfg_select.rs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
1-
use rustc_ast::token;
21
use rustc_ast::tokenstream::{TokenStream, TokenTree};
32
use rustc_ast::util::classify;
3+
use rustc_ast::{AttrKind, token};
44
use rustc_errors::PResult;
5+
use rustc_span::Span;
56

67
use crate::exp;
78
use crate::parser::{AttrWrapper, ForceCollect, Parser, Restrictions, Trailing, UsePreAttrPos};
89

10+
#[derive(Default)]
11+
pub struct CfgSelectBranchAttrSpans {
12+
pub attrs: Vec<Span>,
13+
pub doc_comments: Vec<Span>,
14+
}
15+
916
impl<'a> Parser<'a> {
1017
/// Parses a `TokenTree` consisting either of `{ /* ... */ }` optionally followed by a comma
1118
/// (and strip the braces and the optional comma) or an expression followed by a comma
@@ -36,4 +43,33 @@ impl<'a> Parser<'a> {
3643
}
3744
Ok(TokenStream::from_ast(&expr))
3845
}
46+
47+
/// Parses outer attributes before a `cfg_select!` branch for recovery.
48+
pub fn parse_cfg_select_branch_outer_attrs(
49+
&mut self,
50+
) -> PResult<'a, Option<CfgSelectBranchAttrSpans>> {
51+
let attrs = self.parse_outer_attributes()?;
52+
if attrs.is_empty() {
53+
return Ok(None);
54+
}
55+
56+
let mut spans = CfgSelectBranchAttrSpans::default();
57+
for attr in attrs.take_for_recovery(self.psess) {
58+
match attr.kind {
59+
AttrKind::Normal(..) => spans.attrs.push(attr.span),
60+
// `parse_outer_attributes` already emitted E0753 for inner doc comments before
61+
// recovering them as outer doc-comment attributes.
62+
AttrKind::DocComment(comment_kind, _)
63+
if self.span_to_snippet(attr.span).ok().is_some_and(
64+
|snippet| match comment_kind {
65+
token::CommentKind::Line => snippet.starts_with("//!"),
66+
token::CommentKind::Block => snippet.starts_with("/*!"),
67+
},
68+
) => {}
69+
AttrKind::DocComment(..) => spans.doc_comments.push(attr.span),
70+
}
71+
}
72+
73+
Ok(Some(spans))
74+
}
3975
}

compiler/rustc_resolve/src/build_reduced_graph.rs

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_ast::{
1414
TyAlias,
1515
};
1616
use rustc_attr_parsing::AttributeParser;
17-
use rustc_expand::base::ResolverExpand;
17+
use rustc_expand::base::{ResolverExpand, SyntaxExtension, SyntaxExtensionKind};
1818
use rustc_hir::Attribute;
1919
use rustc_hir::attrs::{AttributeKind, MacroUseArgs};
2020
use rustc_hir::def::{self, *};
@@ -37,9 +37,8 @@ use crate::macros::{MacroRulesDecl, MacroRulesScope, MacroRulesScopeRef};
3737
use crate::ref_mut::CmCell;
3838
use crate::{
3939
BindingKey, Decl, DeclData, DeclKind, DelayedVisResolutionError, ExternModule,
40-
ExternPreludeEntry, Finalize, IdentKey, LocalModule, MacroData, Module, ModuleKind,
41-
ModuleOrUniformRoot, ParentScope, PathResult, Res, Resolver, Segment, SyntaxExtension, Used,
42-
VisResolutionError, errors,
40+
ExternPreludeEntry, Finalize, IdentKey, LocalModule, Module, ModuleKind, ModuleOrUniformRoot,
41+
ParentScope, PathResult, Res, Resolver, Segment, Used, VisResolutionError, errors,
4342
};
4443

4544
impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
@@ -208,28 +207,28 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
208207
}
209208

210209
/// Gets the `SyntaxExtension` corresponding to `res`.
211-
pub(crate) fn get_macro(&self, res: Res) -> Option<&Arc<SyntaxExtension>> {
210+
pub(crate) fn get_macro(&self, res: Res) -> Option<&'ra Arc<SyntaxExtension>> {
212211
match res {
213-
Res::Def(DefKind::Macro(..), def_id) => Some(&self.get_macro_by_def_id(def_id).ext),
214-
Res::NonMacroAttr(_) => Some(&self.non_macro_attr),
212+
Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)),
213+
Res::NonMacroAttr(_) => Some(self.non_macro_attr),
215214
_ => None,
216215
}
217216
}
218217

219-
pub(crate) fn get_macro_by_def_id(&self, def_id: DefId) -> &'ra MacroData {
218+
pub(crate) fn get_macro_by_def_id(&self, def_id: DefId) -> &'ra Arc<SyntaxExtension> {
220219
// Local macros are always compiled.
221220
match def_id.as_local() {
222221
Some(local_def_id) => self.local_macro_map[&local_def_id],
223-
None => *self.extern_macro_map.borrow_mut().entry(def_id).or_insert_with(|| {
222+
None => self.extern_macro_map.borrow_mut().entry(def_id).or_insert_with(|| {
224223
let loaded_macro = self.cstore().load_macro_untracked(self.tcx, def_id);
225-
let macro_data = match loaded_macro {
224+
let ext = match loaded_macro {
226225
LoadedMacro::MacroDef { def, ident, attrs, span, edition } => {
227226
self.compile_macro(&def, ident, &attrs, span, ast::DUMMY_NODE_ID, edition)
228227
}
229-
LoadedMacro::ProcMacro(ext) => MacroData::new(Arc::new(ext)),
228+
LoadedMacro::ProcMacro(ext) => ext,
230229
};
231230

232-
self.arenas.alloc_macro(macro_data)
231+
self.arenas.alloc_macro(ext)
233232
}),
234233
}
235234
}
@@ -1277,8 +1276,10 @@ impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
12771276
fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) {
12781277
if !ident.as_str().starts_with('_') {
12791278
self.r.unused_macros.insert(def_id, (node_id, ident));
1280-
let nrules = self.r.local_macro_map[&def_id].nrules;
1281-
self.r.unused_macro_rules.insert(node_id, (def_id, DenseBitSet::new_filled(nrules)));
1279+
if let SyntaxExtensionKind::MacroRules(mr) = &self.r.local_macro_map[&def_id].kind {
1280+
let value = (def_id, DenseBitSet::new_filled(mr.nrules()));
1281+
self.r.unused_macro_rules.insert(node_id, value);
1282+
}
12821283
}
12831284
}
12841285

@@ -1299,8 +1300,7 @@ impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> {
12991300
Some((macro_kind, ident, span)) => {
13001301
let macro_kinds = macro_kind.into();
13011302
let res = Res::Def(DefKind::Macro(macro_kinds), def_id.to_def_id());
1302-
let macro_data = MacroData::new(self.r.dummy_ext(macro_kind));
1303-
self.r.new_local_macro(def_id, macro_data);
1303+
self.r.local_macro_map.insert(def_id, self.r.dummy_ext(macro_kind));
13041304
self.r.proc_macro_stubs.insert(def_id);
13051305
(res, ident, span, false)
13061306
}

0 commit comments

Comments
 (0)