Skip to content

Commit 6380899

Browse files
committed
Auto merge of #147842 - matthiaskrgr:rollup-b4gp4p4, r=matthiaskrgr
Rollup of 6 pull requests Successful merges: - #146509 (Result/Option layout guarantee clarifications) - #147494 (std::thread spawn: Docs: Link to Builder::spawn; Make same.) - #147532 ( Port `#[cfg_attr]` to the new attribute parsing infrastructure) - #147783 (bootstrap: migrate to object 0.37) - #147792 (Fix autodiff incorrectly applying fat-lto to proc-macro crates ) - #147809 (rustdoc: Fix passes order so intra-doc links are collected after stripping passes) Failed merges: - #147813 (Warn on unused_attributes in uitests ) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 0c0f27a + 27b0018 commit 6380899

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+721
-265
lines changed

compiler/rustc_attr_parsing/messages.ftl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ attr_parsing_as_needed_compatibility =
44
attr_parsing_bundle_needs_static =
55
linking modifier `bundle` is only compatible with `static` linking kind
66
7+
attr_parsing_cfg_attr_bad_delim = wrong `cfg_attr` delimiters
8+
79
attr_parsing_cfg_predicate_identifier =
810
`cfg` predicate key must be an identifier
911

compiler/rustc_attr_parsing/src/attributes/cfg.rs

Lines changed: 139 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,41 @@
1-
use rustc_ast::{LitKind, NodeId};
1+
use rustc_ast::token::Delimiter;
2+
use rustc_ast::tokenstream::DelimSpan;
3+
use rustc_ast::{AttrItem, Attribute, CRATE_NODE_ID, LitKind, NodeId, ast, token};
4+
use rustc_errors::{Applicability, PResult};
25
use rustc_feature::{AttributeTemplate, Features, template};
3-
use rustc_hir::RustcVersion;
46
use rustc_hir::attrs::CfgEntry;
7+
use rustc_hir::{AttrPath, RustcVersion};
8+
use rustc_parse::parser::{ForceCollect, Parser};
9+
use rustc_parse::{exp, parse_in};
510
use rustc_session::Session;
611
use rustc_session::config::ExpectedValues;
712
use rustc_session::lint::BuiltinLintDiag;
813
use rustc_session::lint::builtin::UNEXPECTED_CFGS;
9-
use rustc_session::parse::feature_err;
14+
use rustc_session::parse::{ParseSess, feature_err};
1015
use rustc_span::{Span, Symbol, sym};
1116
use thin_vec::ThinVec;
1217

1318
use crate::context::{AcceptContext, ShouldEmit, Stage};
1419
use crate::parser::{ArgParser, MetaItemListParser, MetaItemOrLitParser, NameValueParser};
20+
use crate::session_diagnostics::{
21+
AttributeParseError, AttributeParseErrorReason, CfgAttrBadDelim, MetaBadDelimSugg,
22+
};
1523
use crate::{
16-
CfgMatchesLintEmitter, fluent_generated, parse_version, session_diagnostics, try_gate_cfg,
24+
AttributeParser, CfgMatchesLintEmitter, fluent_generated, parse_version, session_diagnostics,
25+
try_gate_cfg,
1726
};
1827

1928
pub const CFG_TEMPLATE: AttributeTemplate = template!(
2029
List: &["predicate"],
2130
"https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute"
2231
);
2332

24-
pub fn parse_cfg_attr<'c, S: Stage>(
33+
const CFG_ATTR_TEMPLATE: AttributeTemplate = template!(
34+
List: &["predicate, attr1, attr2, ..."],
35+
"https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute"
36+
);
37+
38+
pub fn parse_cfg<'c, S: Stage>(
2539
cx: &'c mut AcceptContext<'_, '_, S>,
2640
args: &'c ArgParser<'_>,
2741
) -> Option<CfgEntry> {
@@ -70,9 +84,7 @@ pub(crate) fn parse_cfg_entry<S: Stage>(
7084
},
7185
a @ (ArgParser::NoArgs | ArgParser::NameValue(_)) => {
7286
let Some(name) = meta.path().word_sym() else {
73-
cx.emit_err(session_diagnostics::CfgPredicateIdentifier {
74-
span: meta.path().span(),
75-
});
87+
cx.expected_identifier(meta.path().span());
7688
return None;
7789
};
7890
parse_name_value(name, meta.path().span(), a.name_value(), meta.span(), cx)?
@@ -81,7 +93,7 @@ pub(crate) fn parse_cfg_entry<S: Stage>(
8193
MetaItemOrLitParser::Lit(lit) => match lit.kind {
8294
LitKind::Bool(b) => CfgEntry::Bool(b, lit.span),
8395
_ => {
84-
cx.emit_err(session_diagnostics::CfgPredicateIdentifier { span: lit.span });
96+
cx.expected_identifier(lit.span);
8597
return None;
8698
}
8799
},
@@ -149,9 +161,7 @@ fn parse_cfg_entry_target<S: Stage>(
149161

150162
// Then, parse it as a name-value item
151163
let Some(name) = sub_item.path().word_sym() else {
152-
cx.emit_err(session_diagnostics::CfgPredicateIdentifier {
153-
span: sub_item.path().span(),
154-
});
164+
cx.expected_identifier(sub_item.path().span());
155165
return None;
156166
};
157167
let name = Symbol::intern(&format!("target_{name}"));
@@ -300,3 +310,120 @@ impl EvalConfigResult {
300310
}
301311
}
302312
}
313+
314+
pub fn parse_cfg_attr(
315+
cfg_attr: &Attribute,
316+
sess: &Session,
317+
features: Option<&Features>,
318+
) -> Option<(CfgEntry, Vec<(AttrItem, Span)>)> {
319+
match cfg_attr.get_normal_item().args {
320+
ast::AttrArgs::Delimited(ast::DelimArgs { dspan, delim, ref tokens })
321+
if !tokens.is_empty() =>
322+
{
323+
check_cfg_attr_bad_delim(&sess.psess, dspan, delim);
324+
match parse_in(&sess.psess, tokens.clone(), "`cfg_attr` input", |p| {
325+
parse_cfg_attr_internal(p, sess, features, cfg_attr)
326+
}) {
327+
Ok(r) => return Some(r),
328+
Err(e) => {
329+
let suggestions = CFG_ATTR_TEMPLATE.suggestions(cfg_attr.style, sym::cfg_attr);
330+
e.with_span_suggestions(
331+
cfg_attr.span,
332+
"must be of the form",
333+
suggestions,
334+
Applicability::HasPlaceholders,
335+
)
336+
.with_note(format!(
337+
"for more information, visit <{}>",
338+
CFG_ATTR_TEMPLATE.docs.expect("cfg_attr has docs")
339+
))
340+
.emit();
341+
}
342+
}
343+
}
344+
_ => {
345+
let (span, reason) = if let ast::AttrArgs::Delimited(ast::DelimArgs { dspan, .. }) =
346+
cfg_attr.get_normal_item().args
347+
{
348+
(dspan.entire(), AttributeParseErrorReason::ExpectedAtLeastOneArgument)
349+
} else {
350+
(cfg_attr.span, AttributeParseErrorReason::ExpectedList)
351+
};
352+
353+
sess.dcx().emit_err(AttributeParseError {
354+
span,
355+
attr_span: cfg_attr.span,
356+
template: CFG_ATTR_TEMPLATE,
357+
attribute: AttrPath::from_ast(&cfg_attr.get_normal_item().path),
358+
reason,
359+
attr_style: cfg_attr.style,
360+
});
361+
}
362+
}
363+
None
364+
}
365+
366+
fn check_cfg_attr_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) {
367+
if let Delimiter::Parenthesis = delim {
368+
return;
369+
}
370+
psess.dcx().emit_err(CfgAttrBadDelim {
371+
span: span.entire(),
372+
sugg: MetaBadDelimSugg { open: span.open, close: span.close },
373+
});
374+
}
375+
376+
/// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
377+
fn parse_cfg_attr_internal<'a>(
378+
parser: &mut Parser<'a>,
379+
sess: &'a Session,
380+
features: Option<&Features>,
381+
attribute: &Attribute,
382+
) -> PResult<'a, (CfgEntry, Vec<(ast::AttrItem, Span)>)> {
383+
// Parse cfg predicate
384+
let pred_start = parser.token.span;
385+
let meta = MetaItemOrLitParser::parse_single(parser, ShouldEmit::ErrorsAndLints)?;
386+
let pred_span = pred_start.with_hi(parser.token.span.hi());
387+
388+
let cfg_predicate = AttributeParser::parse_single_args(
389+
sess,
390+
attribute.span,
391+
attribute.style,
392+
AttrPath {
393+
segments: attribute
394+
.ident_path()
395+
.expect("cfg_attr is not a doc comment")
396+
.into_boxed_slice(),
397+
span: attribute.span,
398+
},
399+
pred_span,
400+
CRATE_NODE_ID,
401+
features,
402+
ShouldEmit::ErrorsAndLints,
403+
&meta,
404+
parse_cfg_entry,
405+
&CFG_ATTR_TEMPLATE,
406+
)
407+
.ok_or_else(|| {
408+
let mut diag = sess.dcx().struct_err(
409+
"cfg_entry parsing failing with `ShouldEmit::ErrorsAndLints` should emit a error.",
410+
);
411+
diag.downgrade_to_delayed_bug();
412+
diag
413+
})?;
414+
415+
parser.expect(exp!(Comma))?;
416+
417+
// Presumably, the majority of the time there will only be one attr.
418+
let mut expanded_attrs = Vec::with_capacity(1);
419+
while parser.token != token::Eof {
420+
let lo = parser.token.span;
421+
let item = parser.parse_attr_item(ForceCollect::Yes)?;
422+
expanded_attrs.push((item, lo.to(parser.prev_token.span)));
423+
if !parser.eat(exp!(Comma)) {
424+
break;
425+
}
426+
}
427+
428+
Ok((cfg_predicate, expanded_attrs))
429+
}

compiler/rustc_attr_parsing/src/interface.rs

Lines changed: 52 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::borrow::Cow;
22

33
use rustc_ast as ast;
4-
use rustc_ast::NodeId;
4+
use rustc_ast::{AttrStyle, NodeId};
55
use rustc_errors::DiagCtxtHandle;
66
use rustc_feature::{AttributeTemplate, Features};
77
use rustc_hir::attrs::AttributeKind;
@@ -62,7 +62,8 @@ impl<'sess> AttributeParser<'sess, Early> {
6262
)
6363
}
6464

65-
/// Usually you want `parse_limited`, which defaults to no errors.
65+
/// This does the same as `parse_limited`, except it has a `should_emit` parameter which allows it to emit errors.
66+
/// Usually you want `parse_limited`, which emits no errors.
6667
pub fn parse_limited_should_emit(
6768
sess: &'sess Session,
6869
attrs: &[ast::Attribute],
@@ -86,6 +87,13 @@ impl<'sess> AttributeParser<'sess, Early> {
8687
parsed.pop()
8788
}
8889

90+
/// This method allows you to parse a list of attributes *before* `rustc_ast_lowering`.
91+
/// This can be used for attributes that would be removed before `rustc_ast_lowering`, such as attributes on macro calls.
92+
///
93+
/// Try to use this as little as possible. Attributes *should* be lowered during
94+
/// `rustc_ast_lowering`. Some attributes require access to features to parse, which would
95+
/// crash if you tried to do so through [`parse_limited_all`](Self::parse_limited_all).
96+
/// Therefore, if `parse_only` is None, then features *must* be provided.
8997
pub fn parse_limited_all(
9098
sess: &'sess Session,
9199
attrs: &[ast::Attribute],
@@ -111,6 +119,8 @@ impl<'sess> AttributeParser<'sess, Early> {
111119
)
112120
}
113121

122+
/// This method parses a single attribute, using `parse_fn`.
123+
/// This is useful if you already know what exact attribute this is, and want to parse it.
114124
pub fn parse_single<T>(
115125
sess: &'sess Session,
116126
attr: &ast::Attribute,
@@ -121,13 +131,6 @@ impl<'sess> AttributeParser<'sess, Early> {
121131
parse_fn: fn(cx: &mut AcceptContext<'_, '_, Early>, item: &ArgParser<'_>) -> Option<T>,
122132
template: &AttributeTemplate,
123133
) -> Option<T> {
124-
let mut parser = Self {
125-
features,
126-
tools: Vec::new(),
127-
parse_only: None,
128-
sess,
129-
stage: Early { emit_errors },
130-
};
131134
let ast::AttrKind::Normal(normal_attr) = &attr.kind else {
132135
panic!("parse_single called on a doc attr")
133136
};
@@ -136,6 +139,43 @@ impl<'sess> AttributeParser<'sess, Early> {
136139
let meta_parser = MetaItemParser::from_attr(normal_attr, &parts, &sess.psess, emit_errors)?;
137140
let path = meta_parser.path();
138141
let args = meta_parser.args();
142+
Self::parse_single_args(
143+
sess,
144+
attr.span,
145+
attr.style,
146+
path.get_attribute_path(),
147+
target_span,
148+
target_node_id,
149+
features,
150+
emit_errors,
151+
args,
152+
parse_fn,
153+
template,
154+
)
155+
}
156+
157+
/// This method is equivalent to `parse_single`, but parses arguments using `parse_fn` using manually created `args`.
158+
/// This is useful when you want to parse other things than attributes using attribute parsers.
159+
pub fn parse_single_args<T, I>(
160+
sess: &'sess Session,
161+
attr_span: Span,
162+
attr_style: AttrStyle,
163+
attr_path: AttrPath,
164+
target_span: Span,
165+
target_node_id: NodeId,
166+
features: Option<&'sess Features>,
167+
emit_errors: ShouldEmit,
168+
args: &I,
169+
parse_fn: fn(cx: &mut AcceptContext<'_, '_, Early>, item: &I) -> Option<T>,
170+
template: &AttributeTemplate,
171+
) -> Option<T> {
172+
let mut parser = Self {
173+
features,
174+
tools: Vec::new(),
175+
parse_only: None,
176+
sess,
177+
stage: Early { emit_errors },
178+
};
139179
let mut cx: AcceptContext<'_, 'sess, Early> = AcceptContext {
140180
shared: SharedContext {
141181
cx: &mut parser,
@@ -145,10 +185,10 @@ impl<'sess> AttributeParser<'sess, Early> {
145185
crate::lints::emit_attribute_lint(&lint, sess);
146186
},
147187
},
148-
attr_span: attr.span,
149-
attr_style: attr.style,
188+
attr_span,
189+
attr_style,
150190
template,
151-
attr_path: path.get_attribute_path(),
191+
attr_path,
152192
};
153193
parse_fn(&mut cx, args)
154194
}

compiler/rustc_attr_parsing/src/lib.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,9 @@ mod session_diagnostics;
105105
mod target_checking;
106106
pub mod validate_attr;
107107

108-
pub use attributes::cfg::{CFG_TEMPLATE, EvalConfigResult, eval_config_entry, parse_cfg_attr};
108+
pub use attributes::cfg::{
109+
CFG_TEMPLATE, EvalConfigResult, eval_config_entry, parse_cfg, parse_cfg_attr,
110+
};
109111
pub use attributes::cfg_old::*;
110112
pub use attributes::util::{is_builtin_attr, is_doc_alias_attrs_contain_symbol, parse_version};
111113
pub use context::{Early, Late, OmitDoc, ShouldEmit};

0 commit comments

Comments
 (0)