1use std::iter;
4
5use rustc_ast::attr::data_structures::CfgEntry;
6use rustc_ast::token::{Delimiter, Token, TokenKind};
7use rustc_ast::tokenstream::{
8 AttrTokenStream, AttrTokenTree, LazyAttrTokenStream, Spacing, TokenTree, WithTokens,
9};
10use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, NodeId, SyntheticAttr};
11use rustc_attr_ir::target::Target;
12use rustc_attr_ir::{self as attrs, AttributeKind};
13use rustc_attr_parsing::parser::AllowExprMetavar;
14use rustc_attr_parsing::{
15 self as attr, AttributeParser, AttributeSafety, CFG_TEMPLATE, EvalConfigResult, ShouldEmit,
16 eval_config_entry, parse_cfg,
17};
18use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
19use rustc_errors::msg;
20use rustc_feature::{
21 ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature, Features, REMOVED_LANG_FEATURES,
22 UNSTABLE_LANG_FEATURES,
23};
24use rustc_lint_defs::builtin::UNUSED_ATTRIBUTES;
25use rustc_parse::parser::Recovery;
26use rustc_session::Session;
27use rustc_session::diagnostics::feature_err;
28use rustc_span::{STDLIB_STABLE_CRATES, Span, Symbol, sym};
29use tracing::instrument;
30
31use crate::diagnostics::{
32 CrateNameInCfgAttr, CrateTypeInCfgAttr, FeatureNotAllowed, FeatureRemoved,
33 FeatureRemovedReason, RemoveExprNotSupported,
34};
35
36pub struct StripUnconfigured<'a> {
38 pub sess: &'a Session,
39 pub features: Option<&'a Features>,
40 pub config_tokens: bool,
44 pub lint_node_id: NodeId,
45}
46
47pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) -> Features {
48 let mut features = Features::default();
49
50 if let Some(attrs::Attribute::Parsed(AttributeKind::Feature(feature_idents, _))) =
51 AttributeParser::parse_limited_sym(sess, krate_attrs, &[sym::feature])
52 {
53 for feature_ident in feature_idents {
54 if let Some(f) =
56 REMOVED_LANG_FEATURES.iter().find(|f| feature_ident.name == f.feature.name)
57 {
58 let pull_note = if let Some(pull) = f.pull {
59 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("; see <https://github.com/rust-lang/rust/pull/{0}> for more information",
pull))
})format!(
60 "; see <https://github.com/rust-lang/rust/pull/{pull}> for more information",
61 )
62 } else {
63 "".to_owned()
64 };
65 sess.dcx().emit_err(FeatureRemoved {
66 span: feature_ident.span,
67 reason: f.reason.map(|reason| FeatureRemovedReason { reason }),
68 removed_rustc_version: f.feature.since,
69 pull_note,
70 });
71 continue;
72 }
73
74 if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| feature_ident.name == f.name) {
76 features.set_enabled_lang_feature(EnabledLangFeature {
77 gate_name: feature_ident.name,
78 attr_sp: feature_ident.span,
79 stable_since: Some(Symbol::intern(f.since)),
80 });
81 continue;
82 }
83
84 if let Some(allowed) = sess.opts.unstable_opts.allow_features.as_ref() {
88 if allowed.iter().all(|f| feature_ident.name.as_str() != f) {
89 sess.dcx().emit_err(FeatureNotAllowed {
90 span: feature_ident.span,
91 name: feature_ident.name,
92 });
93 continue;
94 }
95 }
96
97 if UNSTABLE_LANG_FEATURES.iter().find(|f| feature_ident.name == f.name).is_some() {
99 features.set_enabled_lang_feature(EnabledLangFeature {
100 gate_name: feature_ident.name,
101 attr_sp: feature_ident.span,
102 stable_since: None,
103 });
104 } else {
105 features.set_enabled_lib_feature(EnabledLibFeature {
108 gate_name: feature_ident.name,
109 attr_sp: feature_ident.span,
110 });
111 }
112
113 if features.internal(feature_ident.name) && !STDLIB_STABLE_CRATES.contains(&crate_name)
118 {
119 sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed);
120 }
121 }
122 }
123
124 features
125}
126
127pub fn pre_configure_attrs(sess: &Session, attrs: &[Attribute]) -> ast::AttrVec {
128 let strip_unconfigured = StripUnconfigured {
129 sess,
130 features: None,
131 config_tokens: false,
132 lint_node_id: ast::CRATE_NODE_ID,
133 };
134 attrs
135 .iter()
136 .flat_map(|attr| strip_unconfigured.process_cfg_attr(attr))
137 .take_while(|attr| {
138 !is_cfg(attr) || strip_unconfigured.cfg_true(attr, ShouldEmit::Nothing).as_bool()
139 })
140 .collect()
141}
142
143#[macro_export]
144macro_rules! configure {
145 ($this:ident, $node:ident) => {
146 match $this.configure($node) {
147 Some(node) => node,
148 None => return Default::default(),
149 }
150 };
151}
152
153impl<'a> StripUnconfigured<'a> {
154 pub fn configure<T: HasTokens>(&self, mut node: T) -> Option<T> {
155 self.process_cfg_attrs(&mut node);
156 self.in_cfg(node.attrs()).then(|| {
157 self.try_configure_tokens(&mut node);
158 node
159 })
160 }
161
162 fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
163 if self.config_tokens {
164 if let Some(Some(tokens)) = node.tokens_mut() {
165 let attr_stream = tokens.to_attr_token_stream();
166 *tokens = LazyAttrTokenStream::new_direct(self.configure_tokens(&attr_stream));
167 }
168 }
169 }
170
171 fn configure_tokens(&self, stream: &AttrTokenStream) -> AttrTokenStream {
176 fn can_skip(stream: &AttrTokenStream) -> bool {
177 stream.0.iter().all(|tree| match tree {
178 AttrTokenTree::AttrsTarget(_) => false,
179 AttrTokenTree::Token(..) => true,
180 AttrTokenTree::Delimited(.., inner) => can_skip(inner),
181 })
182 }
183
184 if can_skip(stream) {
185 return stream.clone();
186 }
187
188 let trees: Vec<_> = stream
189 .0
190 .iter()
191 .filter_map(|tree| match tree.clone() {
192 AttrTokenTree::AttrsTarget(mut target) => {
193 target.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
195
196 if self.in_cfg(&target.attrs) {
197 target.tokens = LazyAttrTokenStream::new_direct(
198 self.configure_tokens(&target.tokens.to_attr_token_stream()),
199 );
200 Some(AttrTokenTree::AttrsTarget(target))
201 } else {
202 None
205 }
206 }
207 AttrTokenTree::Delimited(sp, spacing, delim, mut inner) => {
208 inner = self.configure_tokens(&inner);
209 Some(AttrTokenTree::Delimited(sp, spacing, delim, inner))
210 }
211 AttrTokenTree::Token(Token { kind, .. }, _) if kind.is_delim() => {
212 {
::core::panicking::panic_fmt(format_args!("Should be `AttrTokenTree::Delimited`, not delim tokens: {0:?}",
tree));
};panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tree);
213 }
214 AttrTokenTree::Token(token, spacing) => Some(AttrTokenTree::Token(token, spacing)),
215 })
216 .collect();
217 AttrTokenStream::new(trees)
218 }
219
220 fn process_cfg_attrs<T: HasAttrs>(&self, node: &mut T) {
227 node.visit_attrs(|attrs| {
228 attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
229 });
230 }
231
232 fn process_cfg_attr(&self, attr: &Attribute) -> Vec<Attribute> {
233 if attr.has_name(sym::cfg_attr) {
234 self.expand_cfg_attr(attr, true)
235 } else {
236 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[attr.clone()]))vec![attr.clone()]
237 }
238 }
239
240 pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec<Attribute> {
248 let Some((cfg_predicate, expanded_attrs)) = rustc_attr_parsing::parse_cfg_attr(
249 cfg_attr,
250 self.sess,
251 self.features,
252 self.lint_node_id,
253 ) else {
254 let trace_attr = cfg_attr.clone().convert_normal_to_synthetic(
255 SyntheticAttr::CfgAttrTrace(CfgEntry::Bool(true, cfg_attr.span)),
256 );
257 return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[trace_attr]))vec![trace_attr];
258 };
259
260 if expanded_attrs.is_empty() {
262 self.sess.psess.buffer_lint(
263 UNUSED_ATTRIBUTES,
264 cfg_attr.span,
265 ast::CRATE_NODE_ID,
266 crate::diagnostics::CfgAttrNoAttributes,
267 );
268 }
269
270 let cfg_eval = attr::eval_config_entry(self.sess, &cfg_predicate).as_bool();
271
272 let trace_attr = cfg_attr
275 .clone()
276 .convert_normal_to_synthetic(SyntheticAttr::CfgAttrTrace(cfg_predicate));
277
278 if !cfg_eval {
279 return ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[trace_attr]))vec![trace_attr];
280 }
281
282 if recursive {
283 let expanded_attrs = expanded_attrs
287 .into_iter()
288 .flat_map(|item| self.process_cfg_attr(&self.expand_cfg_attr_item(cfg_attr, item)));
289 iter::once(trace_attr).chain(expanded_attrs).collect()
290 } else {
291 let expanded_attrs =
292 expanded_attrs.into_iter().map(|item| self.expand_cfg_attr_item(cfg_attr, item));
293 iter::once(trace_attr).chain(expanded_attrs).collect()
294 }
295 }
296
297 fn expand_cfg_attr_item(
298 &self,
299 cfg_attr: &Attribute,
300 (attr_item, attr_item_span): (WithTokens<ast::AttrItem>, Span),
301 ) -> Attribute {
302 let mut orig_trees = cfg_attr.token_trees().into_iter();
306 let Some(TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _)) =
307 orig_trees.next()
308 else {
309 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
310 };
311
312 let mut trees = if cfg_attr.style == AttrStyle::Inner {
314 let Some(TokenTree::Token(bang_token @ Token { kind: TokenKind::Bang, .. }, _)) =
315 orig_trees.next()
316 else {
317 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
318 };
319 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[AttrTokenTree::Token(pound_token, Spacing::Joint),
AttrTokenTree::Token(bang_token, Spacing::JointHidden)]))vec![
320 AttrTokenTree::Token(pound_token, Spacing::Joint),
321 AttrTokenTree::Token(bang_token, Spacing::JointHidden),
322 ]
323 } else {
324 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[AttrTokenTree::Token(pound_token, Spacing::JointHidden)]))vec![AttrTokenTree::Token(pound_token, Spacing::JointHidden)]
325 };
326
327 let Some(TokenTree::Delimited(delim_span, delim_spacing, Delimiter::Bracket, _)) =
329 orig_trees.next()
330 else {
331 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
332 };
333 trees.push(AttrTokenTree::Delimited(
334 delim_span,
335 delim_spacing,
336 Delimiter::Bracket,
337 attr_item
338 .tokens
339 .as_ref()
340 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing tokens for {0:?}",
attr_item.node));
}panic!("Missing tokens for {:?}", attr_item.node))
341 .to_attr_token_stream(),
342 ));
343
344 let attr_item_path_span = attr_item.node.path.span;
345 let attr_tokens = Some(LazyAttrTokenStream::new_direct(AttrTokenStream::new(trees)));
346 let attr = ast::attr::mk_attr_from_item(
347 &self.sess.psess.attr_id_generator,
348 attr_item.node,
349 attr_tokens,
350 cfg_attr.style,
351 attr_item_span,
352 );
353 if attr.has_name(sym::crate_type) {
354 self.sess.dcx().emit_err(CrateTypeInCfgAttr { span: attr_item_path_span });
355 }
356 if attr.has_name(sym::crate_name) {
357 self.sess.dcx().emit_err(CrateNameInCfgAttr { span: attr_item_path_span });
358 }
359 attr
360 }
361
362 fn in_cfg(&self, attrs: &[Attribute]) -> bool {
364 attrs.iter().all(|attr| {
365 !is_cfg(attr)
366 || self
367 .cfg_true(attr, ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed })
368 .as_bool()
369 })
370 }
371
372 pub(crate) fn cfg_true(&self, attr: &Attribute, emit_errors: ShouldEmit) -> EvalConfigResult {
373 let Some(cfg) = AttributeParser::parse_single(
374 self.sess,
375 attr,
376 attr.span,
377 self.lint_node_id,
378 Target::Crate,
380 self.features,
381 emit_errors,
382 parse_cfg,
383 &CFG_TEMPLATE,
384 AllowExprMetavar::Yes,
385 AttributeSafety::Normal,
386 ) else {
387 return EvalConfigResult::True;
389 };
390
391 eval_config_entry(self.sess, &cfg)
392 }
393
394 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("maybe_emit_expr_attr_err",
"rustc_expand::config", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/config.rs"),
::tracing_core::__macro_support::Option::Some(395u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::config"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("attr")
}> =
::tracing::__macro_support::FieldName::new("attr");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&attr)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if self.features.is_some_and(|features|
!features.stmt_expr_attributes()) &&
!attr.span.allows_unstable(sym::stmt_expr_attributes) {
let mut err =
feature_err(self.sess, sym::stmt_expr_attributes, attr.span,
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("attributes on expressions are experimental")));
if attr.is_doc_comment() {
err.help(if attr.style == AttrStyle::Outer {
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`///` is used for outer documentation comments; for a plain comment, use `//`"))
} else {
rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`"))
});
}
err.emit();
}
}
}
}#[instrument(level = "trace", skip(self))]
396 pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
397 if self.features.is_some_and(|features| !features.stmt_expr_attributes())
398 && !attr.span.allows_unstable(sym::stmt_expr_attributes)
399 {
400 let mut err = feature_err(
401 self.sess,
402 sym::stmt_expr_attributes,
403 attr.span,
404 msg!("attributes on expressions are experimental"),
405 );
406
407 if attr.is_doc_comment() {
408 err.help(if attr.style == AttrStyle::Outer {
409 msg!("`///` is used for outer documentation comments; for a plain comment, use `//`")
410 } else {
411 msg!("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`")
412 });
413 }
414
415 err.emit();
416 }
417 }
418
419 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("configure_expr",
"rustc_expand::config", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_expand/src/config.rs"),
::tracing_core::__macro_support::Option::Some(419u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::config"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expr")
}> =
::tracing::__macro_support::FieldName::new("expr");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("method_receiver")
}> =
::tracing::__macro_support::FieldName::new("method_receiver");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&method_receiver
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
if !method_receiver {
for attr in expr.attrs.iter() {
self.maybe_emit_expr_attr_err(attr);
}
}
if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
self.sess.dcx().emit_err(RemoveExprNotSupported {
span: attr.span,
});
}
self.process_cfg_attrs(expr);
self.try_configure_tokens(&mut *expr);
}
}
}#[instrument(level = "trace", skip(self))]
420 pub fn configure_expr(&self, expr: &mut ast::Expr, method_receiver: bool) {
421 if !method_receiver {
422 for attr in expr.attrs.iter() {
423 self.maybe_emit_expr_attr_err(attr);
424 }
425 }
426
427 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
435 self.sess.dcx().emit_err(RemoveExprNotSupported { span: attr.span });
436 }
437
438 self.process_cfg_attrs(expr);
439 self.try_configure_tokens(&mut *expr);
440 }
441}
442
443fn is_cfg(attr: &Attribute) -> bool {
444 attr.has_name(sym::cfg)
445}