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