Skip to content

Commit fa14810

Browse files
committed
Auto merge of #117731 - nnethercote:rustc_macros, r=Nilstrieb
`rustc_macros` cleanups Just some improvements I found while reading over this code. r? `@Nilstrieb`
2 parents 5526682 + dd6bab9 commit fa14810

File tree

9 files changed

+60
-93
lines changed

9 files changed

+60
-93
lines changed

compiler/rustc_macros/src/current_version.rs

+8-29
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,16 @@
11
use proc_macro::TokenStream;
22
use proc_macro2::Span;
33
use quote::quote;
4-
use syn::parse::{Parse, ParseStream};
5-
use syn::{parenthesized, parse_macro_input, LitStr, Token};
64

7-
pub struct Input {
8-
variable: LitStr,
9-
}
10-
11-
mod kw {
12-
syn::custom_keyword!(env);
13-
}
14-
15-
impl Parse for Input {
16-
// Input syntax is `env!("CFG_RELEASE")` to facilitate grepping.
17-
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
18-
let paren;
19-
input.parse::<kw::env>()?;
20-
input.parse::<Token![!]>()?;
21-
parenthesized!(paren in input);
22-
let variable: LitStr = paren.parse()?;
23-
Ok(Input { variable })
24-
}
25-
}
26-
27-
pub(crate) fn current_version(input: TokenStream) -> TokenStream {
28-
let input = parse_macro_input!(input as Input);
29-
30-
TokenStream::from(match RustcVersion::parse_env_var(&input.variable) {
5+
pub(crate) fn current_version(_input: TokenStream) -> TokenStream {
6+
let env_var = "CFG_RELEASE";
7+
TokenStream::from(match RustcVersion::parse_cfg_release(env_var) {
318
Ok(RustcVersion { major, minor, patch }) => quote!(
9+
// The produced literal has type `rustc_session::RustcVersion`.
3210
Self { major: #major, minor: #minor, patch: #patch }
3311
),
34-
Err(err) => syn::Error::new(Span::call_site(), err).into_compile_error(),
12+
Err(err) => syn::Error::new(Span::call_site(), format!("{env_var} env var: {err}"))
13+
.into_compile_error(),
3514
})
3615
}
3716

@@ -42,8 +21,8 @@ struct RustcVersion {
4221
}
4322

4423
impl RustcVersion {
45-
fn parse_env_var(env_var: &LitStr) -> Result<Self, Box<dyn std::error::Error>> {
46-
let value = proc_macro::tracked_env::var(env_var.value())?;
24+
fn parse_cfg_release(env_var: &str) -> Result<Self, Box<dyn std::error::Error>> {
25+
let value = proc_macro::tracked_env::var(env_var)?;
4726
Self::parse_str(&value)
4827
.ok_or_else(|| format!("failed to parse rustc version: {:?}", value).into())
4928
}

compiler/rustc_macros/src/diagnostics/diagnostic.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -229,8 +229,8 @@ fn generate_test(slug: &syn::Path, structure: &Structure<'_>) -> TokenStream {
229229
}
230230
}
231231
use std::sync::atomic::{AtomicUsize, Ordering};
232-
// We need to make sure that the same diagnostic slug can be used multiple times without causing an
233-
// error, so just have a global counter here.
232+
// We need to make sure that the same diagnostic slug can be used multiple times without
233+
// causing an error, so just have a global counter here.
234234
static COUNTER: AtomicUsize = AtomicUsize::new(0);
235235
let slug = slug.get_ident().unwrap();
236236
let ident = quote::format_ident!("verify_{slug}_{}", COUNTER.fetch_add(1, Ordering::Relaxed));

compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ pub(crate) struct DiagnosticDeriveVariantBuilder<'parent> {
5353
/// Slug is a mandatory part of the struct attribute as corresponds to the Fluent message that
5454
/// has the actual diagnostic message.
5555
pub slug: SpannedOption<Path>,
56+
5657
/// Error codes are a optional part of the struct attribute - this is only set to detect
5758
/// multiple specifications.
5859
pub code: SpannedOption<()>,
@@ -68,7 +69,7 @@ impl DiagnosticDeriveBuilder {
6869
/// Call `f` for the struct or for each variant of the enum, returning a `TokenStream` with the
6970
/// tokens from `f` wrapped in an `match` expression. Emits errors for use of derive on unions
7071
/// or attributes on the type itself when input is an enum.
71-
pub fn each_variant<'s, F>(&mut self, structure: &mut Structure<'s>, f: F) -> TokenStream
72+
pub(crate) fn each_variant<'s, F>(&mut self, structure: &mut Structure<'s>, f: F) -> TokenStream
7273
where
7374
F: for<'a, 'v> Fn(DiagnosticDeriveVariantBuilder<'a>, &VariantInfo<'v>) -> TokenStream,
7475
{
@@ -121,7 +122,7 @@ impl DiagnosticDeriveBuilder {
121122
impl<'a> DiagnosticDeriveVariantBuilder<'a> {
122123
/// Generates calls to `code` and similar functions based on the attributes on the type or
123124
/// variant.
124-
pub fn preamble(&mut self, variant: &VariantInfo<'_>) -> TokenStream {
125+
pub(crate) fn preamble(&mut self, variant: &VariantInfo<'_>) -> TokenStream {
125126
let ast = variant.ast();
126127
let attrs = &ast.attrs;
127128
let preamble = attrs.iter().map(|attr| {
@@ -135,7 +136,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
135136

136137
/// Generates calls to `span_label` and similar functions based on the attributes on fields or
137138
/// calls to `set_arg` when no attributes are present.
138-
pub fn body(&mut self, variant: &VariantInfo<'_>) -> TokenStream {
139+
pub(crate) fn body(&mut self, variant: &VariantInfo<'_>) -> TokenStream {
139140
let mut body = quote! {};
140141
// Generate `set_arg` calls first..
141142
for binding in variant.bindings().iter().filter(|bi| should_generate_set_arg(bi.ast())) {

compiler/rustc_macros/src/diagnostics/subdiagnostic.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
478478
}
479479
}
480480

481-
pub fn into_tokens(&mut self) -> Result<TokenStream, DiagnosticDeriveError> {
481+
pub(crate) fn into_tokens(&mut self) -> Result<TokenStream, DiagnosticDeriveError> {
482482
let kind_slugs = self.identify_kind()?;
483483
if kind_slugs.is_empty() {
484484
if self.is_enum {

compiler/rustc_macros/src/diagnostics/utils.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use synstructure::{BindingInfo, VariantInfo};
1717
use super::error::invalid_attr;
1818

1919
thread_local! {
20-
pub static CODE_IDENT_COUNT: RefCell<u32> = RefCell::new(0);
20+
pub(crate) static CODE_IDENT_COUNT: RefCell<u32> = RefCell::new(0);
2121
}
2222

2323
/// Returns an ident of the form `__code_N` where `N` is incremented once with every call.
@@ -208,7 +208,7 @@ impl<'ty> FieldInnerTy<'ty> {
208208
}
209209
}
210210

211-
pub fn span(&self) -> proc_macro2::Span {
211+
pub(crate) fn span(&self) -> proc_macro2::Span {
212212
match self {
213213
FieldInnerTy::Option(ty) | FieldInnerTy::Vec(ty) | FieldInnerTy::Plain(ty) => ty.span(),
214214
}
@@ -537,7 +537,7 @@ impl fmt::Display for SuggestionKind {
537537
}
538538

539539
impl SuggestionKind {
540-
pub fn to_suggestion_style(&self) -> TokenStream {
540+
pub(crate) fn to_suggestion_style(&self) -> TokenStream {
541541
match self {
542542
SuggestionKind::Normal => {
543543
quote! { rustc_errors::SuggestionStyle::ShowCode }

compiler/rustc_macros/src/hash_stable.rs

+35-44
Original file line numberDiff line numberDiff line change
@@ -38,33 +38,16 @@ fn parse_attributes(field: &syn::Field) -> Attributes {
3838
attrs
3939
}
4040

41-
pub fn hash_stable_generic_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream {
41+
pub(crate) fn hash_stable_generic_derive(
42+
mut s: synstructure::Structure<'_>,
43+
) -> proc_macro2::TokenStream {
4244
let generic: syn::GenericParam = parse_quote!(__CTX);
4345
s.add_bounds(synstructure::AddBounds::Generics);
4446
s.add_impl_generic(generic);
4547
s.add_where_predicate(parse_quote! { __CTX: crate::HashStableContext });
46-
let body = s.each(|bi| {
47-
let attrs = parse_attributes(bi.ast());
48-
if attrs.ignore {
49-
quote! {}
50-
} else if let Some(project) = attrs.project {
51-
quote! {
52-
(&#bi.#project).hash_stable(__hcx, __hasher);
53-
}
54-
} else {
55-
quote! {
56-
#bi.hash_stable(__hcx, __hasher);
57-
}
58-
}
59-
});
6048

61-
let discriminant = match s.ast().data {
62-
syn::Data::Enum(_) => quote! {
63-
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
64-
},
65-
syn::Data::Struct(_) => quote! {},
66-
syn::Data::Union(_) => panic!("cannot derive on union"),
67-
};
49+
let discriminant = hash_stable_discriminant(&mut s);
50+
let body = hash_stable_body(&mut s);
6851

6952
s.bound_impl(
7053
quote!(::rustc_data_structures::stable_hasher::HashStable<__CTX>),
@@ -81,32 +64,13 @@ pub fn hash_stable_generic_derive(mut s: synstructure::Structure<'_>) -> proc_ma
8164
)
8265
}
8366

84-
pub fn hash_stable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream {
67+
pub(crate) fn hash_stable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream {
8568
let generic: syn::GenericParam = parse_quote!('__ctx);
8669
s.add_bounds(synstructure::AddBounds::Generics);
8770
s.add_impl_generic(generic);
88-
let body = s.each(|bi| {
89-
let attrs = parse_attributes(bi.ast());
90-
if attrs.ignore {
91-
quote! {}
92-
} else if let Some(project) = attrs.project {
93-
quote! {
94-
(&#bi.#project).hash_stable(__hcx, __hasher);
95-
}
96-
} else {
97-
quote! {
98-
#bi.hash_stable(__hcx, __hasher);
99-
}
100-
}
101-
});
10271

103-
let discriminant = match s.ast().data {
104-
syn::Data::Enum(_) => quote! {
105-
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
106-
},
107-
syn::Data::Struct(_) => quote! {},
108-
syn::Data::Union(_) => panic!("cannot derive on union"),
109-
};
72+
let discriminant = hash_stable_discriminant(&mut s);
73+
let body = hash_stable_body(&mut s);
11074

11175
s.bound_impl(
11276
quote!(
@@ -126,3 +90,30 @@ pub fn hash_stable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::To
12690
},
12791
)
12892
}
93+
94+
fn hash_stable_discriminant(s: &mut synstructure::Structure<'_>) -> proc_macro2::TokenStream {
95+
match s.ast().data {
96+
syn::Data::Enum(_) => quote! {
97+
::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
98+
},
99+
syn::Data::Struct(_) => quote! {},
100+
syn::Data::Union(_) => panic!("cannot derive on union"),
101+
}
102+
}
103+
104+
fn hash_stable_body(s: &mut synstructure::Structure<'_>) -> proc_macro2::TokenStream {
105+
s.each(|bi| {
106+
let attrs = parse_attributes(bi.ast());
107+
if attrs.ignore {
108+
quote! {}
109+
} else if let Some(project) = attrs.project {
110+
quote! {
111+
(&#bi.#project).hash_stable(__hcx, __hasher);
112+
}
113+
} else {
114+
quote! {
115+
#bi.hash_stable(__hcx, __hasher);
116+
}
117+
}
118+
})
119+
}

compiler/rustc_macros/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ mod symbols;
2626
mod type_foldable;
2727
mod type_visitable;
2828

29+
// Reads the rust version (e.g. "1.75.0") from the CFG_RELEASE env var and
30+
// produces a `RustcVersion` literal containing that version (e.g.
31+
// `RustcVersion { major: 1, minor: 75, patch: 0 }`).
2932
#[proc_macro]
3033
pub fn current_rustc_version(input: TokenStream) -> TokenStream {
3134
current_version::current_version(input)

compiler/rustc_macros/src/symbols.rs

+3-10
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@
1919
//! ```bash
2020
//! cargo install cargo-expand # this is necessary only once
2121
//! cd compiler/rustc_span
22-
//! cargo expand > /tmp/rustc_span.rs # it's a big file
22+
//! # The specific version number in CFG_RELEASE doesn't matter.
23+
//! # The output is large.
24+
//! CFG_RELEASE="0.0.0" cargo +nightly expand > /tmp/rustc_span.rs
2325
//! ```
2426
2527
use proc_macro2::{Span, TokenStream};
@@ -318,13 +320,4 @@ fn symbols_with_errors(input: TokenStream) -> (TokenStream, Vec<syn::Error>) {
318320
};
319321

320322
(output, errors.list)
321-
322-
// To see the generated code, use the "cargo expand" command.
323-
// Do this once to install:
324-
// cargo install cargo-expand
325-
//
326-
// Then, cd to rustc_span and run:
327-
// cargo expand > /tmp/rustc_span_expanded.rs
328-
//
329-
// and read that file.
330323
}

compiler/rustc_session/src/version.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ pub struct RustcVersion {
99
}
1010

1111
impl RustcVersion {
12-
pub const CURRENT: Self = current_rustc_version!(env!("CFG_RELEASE"));
12+
pub const CURRENT: Self = current_rustc_version!();
1313
}
1414

1515
impl Display for RustcVersion {

0 commit comments

Comments
 (0)