1use std::iter;
4
5use rustc_ast::token::{Delimiter, Token, TokenKind};
6use rustc_ast::tokenstream::{
7 AttrTokenStream, AttrTokenTree, LazyAttrTokenStream, Spacing, TokenTree,
8};
9use rustc_ast::{
10 self as ast, AttrItemKind, AttrKind, AttrStyle, Attribute, EarlyParsedAttribute, HasAttrs,
11 HasTokens, MetaItem, MetaItemInner, NodeId, NormalAttr,
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::parse::feature_err;
31use rustc_span::{STDLIB_STABLE_CRATES, Span, Symbol, sym};
32use tracing::instrument;
33
34use crate::errors::{
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
146pub(crate) fn attr_into_trace(mut attr: Attribute, trace_name: Symbol) -> Attribute {
147 match &mut attr.kind {
148 AttrKind::Normal(normal) => {
149 let NormalAttr { item, tokens } = &mut **normal;
150 item.path.segments[0].ident.name = trace_name;
151 *tokens = Some(LazyAttrTokenStream::new_direct(AttrTokenStream::default()));
153 }
154 AttrKind::DocComment(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
155 }
156 attr
157}
158
159#[macro_export]
160macro_rules! configure {
161 ($this:ident, $node:ident) => {
162 match $this.configure($node) {
163 Some(node) => node,
164 None => return Default::default(),
165 }
166 };
167}
168
169impl<'a> StripUnconfigured<'a> {
170 pub fn configure<T: HasAttrs + HasTokens>(&self, mut node: T) -> Option<T> {
171 self.process_cfg_attrs(&mut node);
172 self.in_cfg(node.attrs()).then(|| {
173 self.try_configure_tokens(&mut node);
174 node
175 })
176 }
177
178 fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
179 if self.config_tokens {
180 if let Some(Some(tokens)) = node.tokens_mut() {
181 let attr_stream = tokens.to_attr_token_stream();
182 *tokens = LazyAttrTokenStream::new_direct(self.configure_tokens(&attr_stream));
183 }
184 }
185 }
186
187 fn configure_tokens(&self, stream: &AttrTokenStream) -> AttrTokenStream {
192 fn can_skip(stream: &AttrTokenStream) -> bool {
193 stream.0.iter().all(|tree| match tree {
194 AttrTokenTree::AttrsTarget(_) => false,
195 AttrTokenTree::Token(..) => true,
196 AttrTokenTree::Delimited(.., inner) => can_skip(inner),
197 })
198 }
199
200 if can_skip(stream) {
201 return stream.clone();
202 }
203
204 let trees: Vec<_> = stream
205 .0
206 .iter()
207 .filter_map(|tree| match tree.clone() {
208 AttrTokenTree::AttrsTarget(mut target) => {
209 target.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
211
212 if self.in_cfg(&target.attrs) {
213 target.tokens = LazyAttrTokenStream::new_direct(
214 self.configure_tokens(&target.tokens.to_attr_token_stream()),
215 );
216 Some(AttrTokenTree::AttrsTarget(target))
217 } else {
218 None
221 }
222 }
223 AttrTokenTree::Delimited(sp, spacing, delim, mut inner) => {
224 inner = self.configure_tokens(&inner);
225 Some(AttrTokenTree::Delimited(sp, spacing, delim, inner))
226 }
227 AttrTokenTree::Token(Token { kind, .. }, _) if kind.is_delim() => {
228 {
::core::panicking::panic_fmt(format_args!("Should be `AttrTokenTree::Delimited`, not delim tokens: {0:?}",
tree));
};panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tree);
229 }
230 AttrTokenTree::Token(token, spacing) => Some(AttrTokenTree::Token(token, spacing)),
231 })
232 .collect();
233 AttrTokenStream::new(trees)
234 }
235
236 fn process_cfg_attrs<T: HasAttrs>(&self, node: &mut T) {
243 node.visit_attrs(|attrs| {
244 attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
245 });
246 }
247
248 fn process_cfg_attr(&self, attr: &Attribute) -> Vec<Attribute> {
249 if attr.has_name(sym::cfg_attr) {
250 self.expand_cfg_attr(attr, true)
251 } else {
252 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[attr.clone()]))vec![attr.clone()]
253 }
254 }
255
256 pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec<Attribute> {
264 let mut trace_attr = cfg_attr.clone();
267 trace_attr.replace_args(AttrItemKind::Parsed(EarlyParsedAttribute::CfgAttrTrace));
268 let trace_attr = attr_into_trace(trace_attr, sym::cfg_attr_trace);
269
270 let Some((cfg_predicate, expanded_attrs)) = rustc_attr_parsing::parse_cfg_attr(
271 cfg_attr,
272 self.sess,
273 self.features,
274 self.lint_node_id,
275 ) else {
276 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];
277 };
278
279 if expanded_attrs.is_empty() {
281 self.sess.psess.buffer_lint(
282 rustc_lint_defs::builtin::UNUSED_ATTRIBUTES,
283 cfg_attr.span,
284 ast::CRATE_NODE_ID,
285 crate::errors::CfgAttrNoAttributes,
286 );
287 }
288
289 if !attr::eval_config_entry(self.sess, &cfg_predicate).as_bool() {
290 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];
291 }
292
293 if recursive {
294 let expanded_attrs = expanded_attrs
298 .into_iter()
299 .flat_map(|item| self.process_cfg_attr(&self.expand_cfg_attr_item(cfg_attr, item)));
300 iter::once(trace_attr).chain(expanded_attrs).collect()
301 } else {
302 let expanded_attrs =
303 expanded_attrs.into_iter().map(|item| self.expand_cfg_attr_item(cfg_attr, item));
304 iter::once(trace_attr).chain(expanded_attrs).collect()
305 }
306 }
307
308 fn expand_cfg_attr_item(
309 &self,
310 cfg_attr: &Attribute,
311 (item, item_span): (ast::AttrItem, Span),
312 ) -> Attribute {
313 let mut orig_trees = cfg_attr.token_trees().into_iter();
317 let Some(TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _)) =
318 orig_trees.next()
319 else {
320 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
321 };
322
323 let mut trees = if cfg_attr.style == AttrStyle::Inner {
325 let Some(TokenTree::Token(bang_token @ Token { kind: TokenKind::Bang, .. }, _)) =
326 orig_trees.next()
327 else {
328 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
329 };
330 ::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![
331 AttrTokenTree::Token(pound_token, Spacing::Joint),
332 AttrTokenTree::Token(bang_token, Spacing::JointHidden),
333 ]
334 } else {
335 ::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)]
336 };
337
338 let Some(TokenTree::Delimited(delim_span, delim_spacing, Delimiter::Bracket, _)) =
340 orig_trees.next()
341 else {
342 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
343 };
344 trees.push(AttrTokenTree::Delimited(
345 delim_span,
346 delim_spacing,
347 Delimiter::Bracket,
348 item.tokens
349 .as_ref()
350 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing tokens for {0:?}",
item));
}panic!("Missing tokens for {item:?}"))
351 .to_attr_token_stream(),
352 ));
353
354 let tokens = Some(LazyAttrTokenStream::new_direct(AttrTokenStream::new(trees)));
355 let attr = ast::attr::mk_attr_from_item(
356 &self.sess.psess.attr_id_generator,
357 item,
358 tokens,
359 cfg_attr.style,
360 item_span,
361 );
362 if attr.has_name(sym::crate_type) {
363 self.sess.dcx().emit_err(CrateTypeInCfgAttr { span: attr.span });
364 }
365 if attr.has_name(sym::crate_name) {
366 self.sess.dcx().emit_err(CrateNameInCfgAttr { span: attr.span });
367 }
368 attr
369 }
370
371 fn in_cfg(&self, attrs: &[Attribute]) -> bool {
373 attrs.iter().all(|attr| {
374 !is_cfg(attr)
375 || self
376 .cfg_true(attr, ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed })
377 .as_bool()
378 })
379 }
380
381 pub(crate) fn cfg_true(&self, attr: &Attribute, emit_errors: ShouldEmit) -> EvalConfigResult {
382 let Some(cfg) = AttributeParser::parse_single(
383 self.sess,
384 attr,
385 attr.span,
386 self.lint_node_id,
387 Target::Crate,
389 self.features,
390 emit_errors,
391 parse_cfg,
392 &CFG_TEMPLATE,
393 AllowExprMetavar::Yes,
394 AttributeSafety::Normal,
395 ) else {
396 return EvalConfigResult::True;
398 };
399
400 eval_config_entry(self.sess, &cfg)
401 }
402
403 #[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(404u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::config"),
::tracing_core::field::FieldSet::new(&["attr"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&attr)
as &dyn 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))]
405 pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
406 if self.features.is_some_and(|features| !features.stmt_expr_attributes())
407 && !attr.span.allows_unstable(sym::stmt_expr_attributes)
408 {
409 let mut err = feature_err(
410 self.sess,
411 sym::stmt_expr_attributes,
412 attr.span,
413 msg!("attributes on expressions are experimental"),
414 );
415
416 if attr.is_doc_comment() {
417 err.help(if attr.style == AttrStyle::Outer {
418 msg!("`///` is used for outer documentation comments; for a plain comment, use `//`")
419 } else {
420 msg!("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`")
421 });
422 }
423
424 err.emit();
425 }
426 }
427
428 #[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(428u32),
::tracing_core::__macro_support::Option::Some("rustc_expand::config"),
::tracing_core::field::FieldSet::new(&["expr",
"method_receiver"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&method_receiver as
&dyn 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))]
429 pub fn configure_expr(&self, expr: &mut ast::Expr, method_receiver: bool) {
430 if !method_receiver {
431 for attr in expr.attrs.iter() {
432 self.maybe_emit_expr_attr_err(attr);
433 }
434 }
435
436 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
444 self.sess.dcx().emit_err(RemoveExprNotSupported { span: attr.span });
445 }
446
447 self.process_cfg_attrs(expr);
448 self.try_configure_tokens(&mut *expr);
449 }
450}
451
452pub fn parse_cfg_old<'a>(meta_item: &'a MetaItem, sess: &Session) -> Option<&'a MetaItemInner> {
454 let span = meta_item.span;
455 match meta_item.meta_item_list() {
456 None => {
457 sess.dcx().emit_err(InvalidCfg::NotFollowedByParens { span });
458 None
459 }
460 Some([]) => {
461 sess.dcx().emit_err(InvalidCfg::NoPredicate { span });
462 None
463 }
464 Some([_, .., l]) => {
465 sess.dcx().emit_err(InvalidCfg::MultiplePredicates { span: l.span() });
466 None
467 }
468 Some([single]) => match single.meta_item_or_bool() {
469 Some(meta_item) => Some(meta_item),
470 None => {
471 sess.dcx().emit_err(InvalidCfg::PredicateLiteral { span: single.span() });
472 None
473 }
474 },
475 }
476}
477
478fn is_cfg(attr: &Attribute) -> bool {
479 attr.has_name(sym::cfg)
480}