1use std::iter;
4
5use rustc_ast::attr::data_structures::CfgEntry;
6use rustc_ast::token::{Delimiter, Token, TokenKind};
7use rustc_ast::tokenstream::{LazyTokenStream, Spacing, TokenStream, TokenTree, WithTokens};
8use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, NodeId, SyntheticAttr};
9use rustc_attr_ir::target::{AstTarget, Target};
10use rustc_attr_ir::{self as attrs, AttributeKind};
11use rustc_attr_parsing::parser::AllowExprMetavar;
12use rustc_attr_parsing::{
13 self as attr, AttributeParser, AttributeSafety, CFG_TEMPLATE, EvalConfigResult, ShouldEmit,
14 eval_config_entry, parse_cfg,
15};
16use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
17use rustc_errors::msg;
18use rustc_feature::{
19 ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature, Features, REMOVED_LANG_FEATURES,
20 UNSTABLE_LANG_FEATURES,
21};
22use rustc_lint_defs::builtin::UNUSED_ATTRIBUTES;
23use rustc_parse::parser::Recovery;
24use rustc_session::Session;
25use rustc_session::diagnostics::feature_err;
26use rustc_span::{STDLIB_STABLE_CRATES, Span, Symbol, sym};
27use tracing::instrument;
28
29use crate::diagnostics::{
30 CfgNotSupportedInPosition, CrateNameInCfgAttr, CrateTypeInCfgAttr, FeatureNotAllowed,
31 FeatureRemoved, FeatureRemovedReason,
32};
33
34pub struct StripUnconfigured<'a> {
36 pub sess: &'a Session,
37 pub features: Option<&'a Features>,
38 pub config_tokens: bool,
42 pub lint_node_id: NodeId,
43}
44
45pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) -> Features {
46 let mut features = Features::default();
47
48 if let Some(attrs::Attribute::Parsed(AttributeKind::Feature(feature_idents, _))) =
49 AttributeParser::parse_limited_sym(sess, krate_attrs, &[sym::feature])
50 {
51 for feature_ident in feature_idents {
52 if let Some(f) =
54 REMOVED_LANG_FEATURES.iter().find(|f| feature_ident.name == f.feature.name)
55 {
56 let pull_note = if let Some(pull) = f.pull {
57 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("; see <https://github.com/rust-lang/rust/pull/{0}> for more information",
pull))
})format!(
58 "; see <https://github.com/rust-lang/rust/pull/{pull}> for more information",
59 )
60 } else {
61 "".to_owned()
62 };
63 sess.dcx().emit_err(FeatureRemoved {
64 span: feature_ident.span,
65 reason: f.reason.map(|reason| FeatureRemovedReason { reason }),
66 removed_rustc_version: f.feature.since,
67 pull_note,
68 });
69 continue;
70 }
71
72 if let Some(f) = ACCEPTED_LANG_FEATURES.iter().find(|f| feature_ident.name == f.name) {
74 features.set_enabled_lang_feature(EnabledLangFeature {
75 gate_name: feature_ident.name,
76 attr_sp: feature_ident.span,
77 stable_since: Some(Symbol::intern(f.since)),
78 });
79 continue;
80 }
81
82 if let Some(allowed) = sess.opts.unstable_opts.allow_features.as_ref() {
86 if allowed.iter().all(|f| feature_ident.name.as_str() != f) {
87 sess.dcx().emit_err(FeatureNotAllowed {
88 span: feature_ident.span,
89 name: feature_ident.name,
90 });
91 continue;
92 }
93 }
94
95 if UNSTABLE_LANG_FEATURES.iter().find(|f| feature_ident.name == f.name).is_some() {
97 features.set_enabled_lang_feature(EnabledLangFeature {
98 gate_name: feature_ident.name,
99 attr_sp: feature_ident.span,
100 stable_since: None,
101 });
102 } else {
103 features.set_enabled_lib_feature(EnabledLibFeature {
106 gate_name: feature_ident.name,
107 attr_sp: feature_ident.span,
108 });
109 }
110
111 if features.internal(feature_ident.name) && !STDLIB_STABLE_CRATES.contains(&crate_name)
116 {
117 sess.using_internal_features.store(true, std::sync::atomic::Ordering::Relaxed);
118 }
119 }
120 }
121
122 features
123}
124
125pub fn pre_configure_attrs(sess: &Session, attrs: &[Attribute]) -> ast::AttrVec {
126 let strip_unconfigured = StripUnconfigured {
127 sess,
128 features: None,
129 config_tokens: false,
130 lint_node_id: ast::CRATE_NODE_ID,
131 };
132 attrs
133 .iter()
134 .flat_map(|attr| strip_unconfigured.process_cfg_attr(attr))
135 .take_while(|attr| {
136 !is_cfg(attr) || strip_unconfigured.cfg_true(attr, ShouldEmit::Nothing).as_bool()
137 })
138 .collect()
139}
140
141#[macro_export]
142macro_rules! configure {
143 ($this:ident, $node:ident) => {
144 match $this.configure($node) {
145 Some(node) => node,
146 None => return Default::default(),
147 }
148 };
149}
150
151impl<'a> StripUnconfigured<'a> {
152 pub fn configure<T: HasTokens>(&self, mut node: T) -> Option<T> {
153 self.process_cfg_attrs(&mut node);
154 self.in_cfg(node.attrs()).then(|| {
155 self.try_configure_tokens(&mut node);
156 node
157 })
158 }
159
160 fn try_configure_tokens<T: HasTokens>(&self, node: &mut T) {
161 if self.config_tokens {
162 if let Some(Some(tokens)) = node.tokens_mut() {
163 let stream = tokens.to_configured_token_stream(&mut |target| {
164 target.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
166 self.in_cfg(&target.attrs)
169 });
170 *tokens = LazyTokenStream::new_direct(stream);
171 }
172 }
173 }
174
175 fn process_cfg_attrs<T: HasAttrs>(&self, node: &mut T) {
182 node.visit_attrs(|attrs| {
183 attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
184 });
185 }
186
187 fn process_cfg_attr(&self, attr: &Attribute) -> Vec<Attribute> {
188 if attr.has_name(sym::cfg_attr) {
189 self.expand_cfg_attr(attr, true)
190 } else {
191 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[attr.clone()]))vec![attr.clone()]
192 }
193 }
194
195 pub(crate) fn expand_cfg_attr(&self, cfg_attr: &Attribute, recursive: bool) -> Vec<Attribute> {
203 let Some((cfg_predicate, expanded_attrs)) = rustc_attr_parsing::parse_cfg_attr(
204 cfg_attr,
205 self.sess,
206 self.features,
207 self.lint_node_id,
208 ) else {
209 let trace_attr = cfg_attr.clone().convert_normal_to_synthetic(
210 SyntheticAttr::CfgAttrTrace(CfgEntry::Bool(true, cfg_attr.span)),
211 );
212 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];
213 };
214
215 if expanded_attrs.is_empty() {
217 self.sess.psess.buffer_lint(
218 UNUSED_ATTRIBUTES,
219 cfg_attr.span,
220 ast::CRATE_NODE_ID,
221 crate::diagnostics::CfgAttrNoAttributes,
222 );
223 }
224
225 let cfg_eval = attr::eval_config_entry(self.sess, &cfg_predicate).as_bool();
226
227 let trace_attr = cfg_attr
230 .clone()
231 .convert_normal_to_synthetic(SyntheticAttr::CfgAttrTrace(cfg_predicate));
232
233 if !cfg_eval {
234 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];
235 }
236
237 if recursive {
238 let expanded_attrs = expanded_attrs
242 .into_iter()
243 .flat_map(|item| self.process_cfg_attr(&self.expand_cfg_attr_item(cfg_attr, item)));
244 iter::once(trace_attr).chain(expanded_attrs).collect()
245 } else {
246 let expanded_attrs =
247 expanded_attrs.into_iter().map(|item| self.expand_cfg_attr_item(cfg_attr, item));
248 iter::once(trace_attr).chain(expanded_attrs).collect()
249 }
250 }
251
252 fn expand_cfg_attr_item(
253 &self,
254 cfg_attr: &Attribute,
255 (attr_item, attr_item_span): (WithTokens<ast::AttrItem>, Span),
256 ) -> Attribute {
257 let mut orig_trees = ::alloc::vec::Vec::new()vec![];
261 cfg_attr.append_token_trees_to(&mut orig_trees);
262 let mut orig_trees = orig_trees.into_iter();
263 let Some(TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _)) =
264 orig_trees.next()
265 else {
266 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
267 };
268
269 let mut trees = if cfg_attr.style == AttrStyle::Inner {
271 let Some(TokenTree::Token(bang_token @ Token { kind: TokenKind::Bang, .. }, _)) =
272 orig_trees.next()
273 else {
274 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
275 };
276 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[TokenTree::Token(pound_token, Spacing::Joint),
TokenTree::Token(bang_token, Spacing::JointHidden)]))vec![
277 TokenTree::Token(pound_token, Spacing::Joint),
278 TokenTree::Token(bang_token, Spacing::JointHidden),
279 ]
280 } else {
281 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[TokenTree::Token(pound_token, Spacing::JointHidden)]))vec![TokenTree::Token(pound_token, Spacing::JointHidden)]
282 };
283
284 let Some(TokenTree::Delimited(delim_span, delim_spacing, Delimiter::Bracket, _)) =
286 orig_trees.next()
287 else {
288 {
::core::panicking::panic_fmt(format_args!("Bad tokens for attribute {0:?}",
cfg_attr));
};panic!("Bad tokens for attribute {cfg_attr:?}");
289 };
290 trees.push(TokenTree::Delimited(
291 delim_span,
292 delim_spacing,
293 Delimiter::Bracket,
294 attr_item
295 .tokens
296 .as_ref()
297 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing tokens for {0:?}",
attr_item.node));
}panic!("Missing tokens for {:?}", attr_item.node))
298 .to_token_stream(),
299 ));
300
301 let attr_item_path_span = attr_item.node.path.span;
302 let attr_tokens = Some(LazyTokenStream::new_direct(TokenStream::new(trees)));
303 let attr = ast::attr::mk_attr_from_item(
304 &self.sess.psess.attr_id_generator,
305 attr_item.node,
306 attr_tokens,
307 cfg_attr.style,
308 attr_item_span,
309 );
310 if attr.has_name(sym::crate_type) {
311 self.sess.dcx().emit_err(CrateTypeInCfgAttr { span: attr_item_path_span });
312 }
313 if attr.has_name(sym::crate_name) {
314 self.sess.dcx().emit_err(CrateNameInCfgAttr { span: attr_item_path_span });
315 }
316 attr
317 }
318
319 fn in_cfg(&self, attrs: &[Attribute]) -> bool {
321 attrs.iter().all(|attr| {
322 !is_cfg(attr)
323 || self
324 .cfg_true(attr, ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed })
325 .as_bool()
326 })
327 }
328
329 pub(crate) fn cfg_true(&self, attr: &Attribute, emit_errors: ShouldEmit) -> EvalConfigResult {
330 let Some(cfg) = AttributeParser::parse_single(
331 self.sess,
332 attr,
333 attr.span,
334 self.lint_node_id,
335 AstTarget::None(Target::Crate),
337 self.features,
338 emit_errors,
339 parse_cfg,
340 &CFG_TEMPLATE,
341 AllowExprMetavar::Yes,
342 AttributeSafety::Normal,
343 ) else {
344 return EvalConfigResult::True;
346 };
347
348 eval_config_entry(self.sess, &cfg)
349 }
350
351 {}
#[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("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_expand/src/config.rs"),
::tracing_core::__macro_support::Option::Some(352u32),
::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))]
353 pub(crate) fn maybe_emit_expr_attr_err(&self, attr: &Attribute) {
354 if self.features.is_some_and(|features| !features.stmt_expr_attributes())
355 && !attr.span.allows_unstable(sym::stmt_expr_attributes)
356 {
357 let mut err = feature_err(
358 self.sess,
359 sym::stmt_expr_attributes,
360 attr.span,
361 msg!("attributes on expressions are experimental"),
362 );
363
364 if attr.is_doc_comment() {
365 err.help(if attr.style == AttrStyle::Outer {
366 msg!("`///` is used for outer documentation comments; for a plain comment, use `//`")
367 } else {
368 msg!("`//!` is used for inner documentation comments; for a plain comment, use `//` by removing the `!` or inserting a space in between them: `// !`")
369 });
370 }
371
372 err.emit();
373 }
374 }
375
376 {}
#[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("/rustc-dev/bbcdfd90a3f81ca2a5f6d69b943a6ff0d8582102/compiler/rustc_expand/src/config.rs"),
::tracing_core::__macro_support::Option::Some(376u32),
::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(CfgNotSupportedInPosition {
span: attr.span,
});
}
self.process_cfg_attrs(expr);
self.try_configure_tokens(&mut *expr);
}
}
}#[instrument(level = "trace", skip(self))]
377 pub fn configure_expr(&self, expr: &mut ast::Expr, method_receiver: bool) {
378 if !method_receiver {
379 for attr in expr.attrs.iter() {
380 self.maybe_emit_expr_attr_err(attr);
381 }
382 }
383
384 if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) {
392 self.sess.dcx().emit_err(CfgNotSupportedInPosition { span: attr.span });
393 }
394
395 self.process_cfg_attrs(expr);
396 self.try_configure_tokens(&mut *expr);
397 }
398}
399
400fn is_cfg(attr: &Attribute) -> bool {
401 attr.has_name(sym::cfg)
402}