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