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