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::{
11 self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, MetaItem, MetaItemInner, NodeId,
12 SyntheticAttr,
13};
14use rustc_attr_parsing::parser::AllowExprMetavar;
15use rustc_attr_parsing::{
16 self as attr, AttributeParser, AttributeSafety, CFG_TEMPLATE, EvalConfigResult, ShouldEmit,
17 eval_config_entry, parse_cfg,
18};
19use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
20use rustc_errors::msg;
21use rustc_feature::{
22 ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature, Features, REMOVED_LANG_FEATURES,
23 UNSTABLE_LANG_FEATURES,
24};
25use rustc_hir::attrs::AttributeKind;
26use rustc_hir::{
27 Target, {self as hir},
28};
29use rustc_parse::parser::Recovery;
30use rustc_session::Session;
31use rustc_session::diagnostics::feature_err;
32use rustc_span::{STDLIB_STABLE_CRATES, Span, Symbol, sym};
33use tracing::instrument;
34
35use crate::diagnostics::{
36 CrateNameInCfgAttr, CrateTypeInCfgAttr, FeatureNotAllowed, FeatureRemoved,
37 FeatureRemovedReason, InvalidCfg, RemoveExprNotSupported,
38};
39
40pub struct StripUnconfigured<'a> {
42 pub sess: &'a Session,
43 pub features: Option<&'a Features>,
44 pub config_tokens: bool,
48 pub lint_node_id: NodeId,
49}
50
51pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) -> Features {
52 let mut features = Features::default();
53
54 if let Some(hir::Attribute::Parsed(AttributeKind::Feature(feature_idents, _))) =
55 AttributeParser::parse_limited_sym(sess, krate_attrs, &[sym::feature])
56 {
57 for feature_ident in feature_idents {
58 if let Some(f) =
60 REMOVED_LANG_FEATURES.iter().find(|f| feature_ident.name == f.feature.name)
61 {
62 let pull_note = if let Some(pull) = f.pull {
63 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("; see <https://github.com/rust-lang/rust/pull/{0}> for more information",
pull))
})format!(
64 "; see <https://github.com/rust-lang/rust/pull/{pull}> for more information",
65 )
66 } else {
67 "".to_owned()
68 };
69 sess.dcx().emit_err(FeatureRemoved {
70 span: feature_ident.span,
71 reason: f.reason.map(|reason| FeatureRemovedReason { reason }),
72 removed_rustc_version: f.feature.since,
73 pull_note,
74 });
75 continue;
76 }
77
78 if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| feature_ident.name == f.name) {
80 features.set_enabled_lang_feature(EnabledLangFeature {
81 gate_name: feature_ident.name,
82 attr_sp: feature_ident.span,
83 stable_since: Some(Symbol::intern(f.since)),
84 });
85 continue;
86 }
87
88 if let Some(allowed) = sess.opts.unstable_opts.allow_features.as_ref() {
92 if allowed.iter().all(|f| feature_ident.name.as_str() != f) {
93 sess.dcx().emit_err(FeatureNotAllowed {
94 span: feature_ident.span,
95 name: feature_ident.name,
96 });
97 continue;
98 }
99 }
100
101 if UNSTABLE_LANG_FEATURES.iter().find(|f| feature_ident.name == f.name).is_some() {
103 features.set_enabled_lang_feature(EnabledLangFeature {
104 gate_name: feature_ident.name,
105 attr_sp: feature_ident.span,
106 stable_since: None,
107 });
108 } else {
109 features.set_enabled_lib_feature(EnabledLibFeature {
112 gate_name: feature_ident.name,
113 attr_sp: feature_ident.span,
114 });
115 }
116
117 if features.internal(feature_ident.name) && !STDLIB_STABLE_CRATES.contains(&crate_name)
122 {
123 sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed);
124 }
125 }
126 }
127
128 features
129}
130
131pub fn pre_configure_attrs(sess: &Session, attrs: &[Attribute]) -> ast::AttrVec {
132 let strip_unconfigured = StripUnconfigured {
133 sess,
134 features: None,
135 config_tokens: false,
136 lint_node_id: ast::CRATE_NODE_ID,
137 };
138 attrs
139 .iter()
140 .flat_map(|attr| strip_unconfigured.process_cfg_attr(attr))
141 .take_while(|attr| {
142 !is_cfg(attr) || strip_unconfigured.cfg_true(attr, ShouldEmit::Nothing).as_bool()
143 })
144 .collect()
145}
146
147#[macro_export]
148macro_rules! configure {
149 ($this:ident, $node:ident) => {
150 match $this.configure($node) {
151 Some(node) => node,
152 None => return Default::default(),
153 }
154 };
155}
156
157impl<'a> StripUnconfigured<'a> {
158 pub fn configure<T: HasTokens>(&self, mut node: T) -> Option<T> {
159 self.process_cfg_attrs(&mut node);
160 self.in_cfg(node.attrs()).then(|| {
161 self.try_configure_tokens(&mut node);
162 node
163 })
164 }
165
166 fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
167 if self.config_tokens {
168 if let Some(Some(tokens)) = node.tokens_mut() {
169 let attr_stream = tokens.to_attr_token_stream();
170 *tokens = LazyAttrTokenStream::new_direct(self.configure_tokens(&attr_stream));
171 }
172 }
173 }
174
175 fn configure_tokens(&self, stream: &AttrTokenStream) -> AttrTokenStream {
180 fn can_skip(stream: &AttrTokenStream) -> bool {
181 stream.0.iter().all(|tree| match tree {
182 AttrTokenTree::AttrsTarget(_) => false,
183 AttrTokenTree::Token(..) => true,
184 AttrTokenTree::Delimited(.., inner) => can_skip(inner),
185 })
186 }
187
188 if can_skip(stream) {
189 return stream.clone();
190 }
191
192 let trees: Vec<_> = stream
193 .0
194 .iter()
195 .filter_map(|tree| match tree.clone() {
196 AttrTokenTree::AttrsTarget(mut target) => {
197 target.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
199
200 if self.in_cfg(&target.attrs) {
201 target.tokens = LazyAttrTokenStream::new_direct(
202 self.configure_tokens(&target.tokens.to_attr_token_stream()),
203 );
204 Some(AttrTokenTree::AttrsTarget(target))
205 } else {
206 None
209 }
210 }
211 AttrTokenTree::Delimited(sp, spacing, delim, mut inner) => {
212 inner = self.configure_tokens(&inner);
213 Some(AttrTokenTree::Delimited(sp, spacing, delim, inner))
214 }
215 AttrTokenTree::Token(Token { kind, .. }, _) if kind.is_delim() => {
216 {
::core::panicking::panic_fmt(format_args!("Should be `AttrTokenTree::Delimited`, not delim tokens: {0:?}",
tree));
};panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tree);
217 }
218 AttrTokenTree::Token(token, spacing) => Some(AttrTokenTree::Token(token, spacing)),
219 })
220 .collect();
221 AttrTokenStream::new(trees)
222 }
223
224 fn process_cfg_attrs<T: HasAttrs>(&self, node: &mut T) {
231 node.visit_attrs(|attrs| {
232 attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
233 });
234 }
235
236 fn process_cfg_attr(&self, attr: &Attribute) -> Vec<Attribute> {
237 if attr.has_name(sym::cfg_attr) {
238 self.expand_cfg_attr(attr, true)
239 } else {
240 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[attr.clone()]))vec![attr.clone()]
241 }
242 }
243
244 pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec<Attribute> {
252 let Some((cfg_predicate, expanded_attrs)) = rustc_attr_parsing::parse_cfg_attr(
253 cfg_attr,
254 self.sess,
255 self.features,
256 self.lint_node_id,
257 ) else {
258 let trace_attr = cfg_attr.clone().convert_normal_to_synthetic(
259 SyntheticAttr::CfgAttrTrace(CfgEntry::Bool(true, cfg_attr.span)),
260 );
261 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];
262 };
263
264 if expanded_attrs.is_empty() {
266 self.sess.psess.buffer_lint(
267 rustc_lint_defs::builtin::UNUSED_ATTRIBUTES,
268 cfg_attr.span,
269 ast::CRATE_NODE_ID,
270 crate::diagnostics::CfgAttrNoAttributes,
271 );
272 }
273
274 let cfg_eval = attr::eval_config_entry(self.sess, &cfg_predicate).as_bool();
275
276 let trace_attr = cfg_attr
279 .clone()
280 .convert_normal_to_synthetic(SyntheticAttr::CfgAttrTrace(cfg_predicate));
281
282 if !cfg_eval {
283 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];
284 }
285
286 if recursive {
287 let expanded_attrs = expanded_attrs
291 .into_iter()
292 .flat_map(|item| self.process_cfg_attr(&self.expand_cfg_attr_item(cfg_attr, item)));
293 iter::once(trace_attr).chain(expanded_attrs).collect()
294 } else {
295 let expanded_attrs =
296 expanded_attrs.into_iter().map(|item| self.expand_cfg_attr_item(cfg_attr, item));
297 iter::once(trace_attr).chain(expanded_attrs).collect()
298 }
299 }
300
301 fn expand_cfg_attr_item(
302 &self,
303 cfg_attr: &Attribute,
304 (attr_item, attr_item_span): (WithTokens<ast::AttrItem>, Span),
305 ) -> Attribute {
306 let mut orig_trees = cfg_attr.token_trees().into_iter();
310 let Some(TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _)) =
311 orig_trees.next()
312 else {
313 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
314 };
315
316 let mut trees = if cfg_attr.style == AttrStyle::Inner {
318 let Some(TokenTree::Token(bang_token @ Token { kind: TokenKind::Bang, .. }, _)) =
319 orig_trees.next()
320 else {
321 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
322 };
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::Joint),
AttrTokenTree::Token(bang_token, Spacing::JointHidden)]))vec![
324 AttrTokenTree::Token(pound_token, Spacing::Joint),
325 AttrTokenTree::Token(bang_token, Spacing::JointHidden),
326 ]
327 } else {
328 ::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)]
329 };
330
331 let Some(TokenTree::Delimited(delim_span, delim_spacing, Delimiter::Bracket, _)) =
333 orig_trees.next()
334 else {
335 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
336 };
337 trees.push(AttrTokenTree::Delimited(
338 delim_span,
339 delim_spacing,
340 Delimiter::Bracket,
341 attr_item
342 .tokens
343 .as_ref()
344 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing tokens for {0:?}",
attr_item.node));
}panic!("Missing tokens for {:?}", attr_item.node))
345 .to_attr_token_stream(),
346 ));
347
348 let attr_item_path_span = attr_item.node.path.span;
349 let attr_tokens = Some(LazyAttrTokenStream::new_direct(AttrTokenStream::new(trees)));
350 let attr = ast::attr::mk_attr_from_item(
351 &self.sess.psess.attr_id_generator,
352 attr_item.node,
353 attr_tokens,
354 cfg_attr.style,
355 attr_item_span,
356 );
357 if attr.has_name(sym::crate_type) {
358 self.sess.dcx().emit_err(CrateTypeInCfgAttr { span: attr_item_path_span });
359 }
360 if attr.has_name(sym::crate_name) {
361 self.sess.dcx().emit_err(CrateNameInCfgAttr { span: attr_item_path_span });
362 }
363 attr
364 }
365
366 fn in_cfg(&self, attrs: &[Attribute]) -> bool {
368 attrs.iter().all(|attr| {
369 !is_cfg(attr)
370 || self
371 .cfg_true(attr, ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed })
372 .as_bool()
373 })
374 }
375
376 pub(crate) fn cfg_true(&self, attr: &Attribute, emit_errors: ShouldEmit) -> EvalConfigResult {
377 let Some(cfg) = AttributeParser::parse_single(
378 self.sess,
379 attr,
380 attr.span,
381 self.lint_node_id,
382 Target::Crate,
384 self.features,
385 emit_errors,
386 parse_cfg,
387 &CFG_TEMPLATE,
388 AllowExprMetavar::Yes,
389 AttributeSafety::Normal,
390 ) else {
391 return EvalConfigResult::True;
393 };
394
395 eval_config_entry(self.sess, &cfg)
396 }
397
398 #[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(399u32),
::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))]
400 pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
401 if self.features.is_some_and(|features| !features.stmt_expr_attributes())
402 && !attr.span.allows_unstable(sym::stmt_expr_attributes)
403 {
404 let mut err = feature_err(
405 self.sess,
406 sym::stmt_expr_attributes,
407 attr.span,
408 msg!("attributes on expressions are experimental"),
409 );
410
411 if attr.is_doc_comment() {
412 err.help(if attr.style == AttrStyle::Outer {
413 msg!("`///` is used for outer documentation comments; for a plain comment, use `//`")
414 } else {
415 msg!("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`")
416 });
417 }
418
419 err.emit();
420 }
421 }
422
423 #[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(423u32),
::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))]
424 pub fn configure_expr(&self, expr: &mut ast::Expr, method_receiver: bool) {
425 if !method_receiver {
426 for attr in expr.attrs.iter() {
427 self.maybe_emit_expr_attr_err(attr);
428 }
429 }
430
431 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
439 self.sess.dcx().emit_err(RemoveExprNotSupported { span: attr.span });
440 }
441
442 self.process_cfg_attrs(expr);
443 self.try_configure_tokens(&mut *expr);
444 }
445}
446
447pub fn parse_cfg_old<'a>(meta_item: &'a MetaItem, sess: &Session) -> Option<&'a MetaItemInner> {
449 let span = meta_item.span;
450 match meta_item.meta_item_list() {
451 None => {
452 sess.dcx().emit_err(InvalidCfg::NotFollowedByParens { span });
453 None
454 }
455 Some([]) => {
456 sess.dcx().emit_err(InvalidCfg::NoPredicate { span });
457 None
458 }
459 Some([_, .., l]) => {
460 sess.dcx().emit_err(InvalidCfg::MultiplePredicates { span: l.span() });
461 None
462 }
463 Some([single]) => match single.meta_item_or_bool() {
464 Some(meta_item) => Some(meta_item),
465 None => {
466 sess.dcx().emit_err(InvalidCfg::PredicateLiteral { span: single.span() });
467 None
468 }
469 },
470 }
471}
472
473fn is_cfg(attr: &Attribute) -> bool {
474 attr.has_name(sym::cfg)
475}