Skip to content

Commit 20080dc

Browse files
authored
Rollup merge of #157571 - bjorn3:proc_macro_refactors6, r=petrochenkov
Remove ProcMacro enum from proc macro ABI Instead encode this information in the crate metadata. This helps shrink the proc-macro ABI to just the parts necessary for transmitting raw bytes to perform RPC on top of. r? @petrochenkov cc @cyrgani
2 parents 3905360 + 993bda7 commit 20080dc

22 files changed

Lines changed: 261 additions & 366 deletions

File tree

compiler/rustc_builtin_macros/src/proc_macro_harness.rs

Lines changed: 17 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,16 @@ use rustc_hir::attrs::AttributeKind;
1212
use rustc_session::Session;
1313
use rustc_span::hygiene::AstPass;
1414
use rustc_span::source_map::SourceMap;
15-
use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
15+
use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
1616
use smallvec::smallvec;
1717
use thin_vec::{ThinVec, thin_vec};
1818

1919
use crate::diagnostics;
2020

2121
struct ProcMacroDerive {
2222
id: NodeId,
23-
trait_name: Symbol,
2423
function_ident: Ident,
2524
span: Span,
26-
attrs: ThinVec<Symbol>,
2725
}
2826

2927
struct ProcMacroDef {
@@ -101,15 +99,12 @@ impl<'a> CollectProcMacros<'a> {
10199
function_ident: Ident,
102100
attr: &'a ast::Attribute,
103101
) {
104-
let Some(rustc_hir::Attribute::Parsed(AttributeKind::ProcMacroDerive {
105-
trait_name,
106-
helper_attrs,
107-
..
108-
})) = AttributeParser::parse_limited(
109-
self.session,
110-
slice::from_ref(attr),
111-
&[sym::proc_macro_derive],
112-
)
102+
let Some(rustc_hir::Attribute::Parsed(AttributeKind::ProcMacroDerive { .. })) =
103+
AttributeParser::parse_limited(
104+
self.session,
105+
slice::from_ref(attr),
106+
&[sym::proc_macro_derive],
107+
)
113108
else {
114109
return;
115110
};
@@ -118,9 +113,7 @@ impl<'a> CollectProcMacros<'a> {
118113
self.macros.push(ProcMacro::Derive(ProcMacroDerive {
119114
id: item.id,
120115
span: item.span,
121-
trait_name,
122116
function_ident,
123-
attrs: helper_attrs,
124117
}));
125118
} else {
126119
let msg = if !self.in_root {
@@ -291,10 +284,9 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> Box<ast::Item> {
291284

292285
let bridge = Ident::new(sym::bridge, span);
293286
let client = Ident::new(sym::client, span);
294-
let proc_macro_ty = Ident::new(sym::ProcMacro, span);
295-
let custom_derive = Ident::new(sym::custom_derive, span);
296-
let attr = Ident::new(sym::attr, span);
297-
let bang = Ident::new(sym::bang, span);
287+
let client_ty = Ident::new(sym::Client, span);
288+
let expand1 = Ident::new(sym::expand1, span);
289+
let expand2 = Ident::new(sym::expand2, span);
298290

299291
// We add NodeIds to 'resolver.proc_macros' in the order
300292
// that we generate expressions. The position of each NodeId
@@ -312,7 +304,7 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> Box<ast::Item> {
312304
let proc_macro_ty_method_path = |cx: &ExtCtxt<'_>, method| {
313305
cx.expr_path(cx.path(
314306
span.with_ctxt(harness_span.ctxt()),
315-
vec![proc_macro, bridge, client, proc_macro_ty, method],
307+
vec![proc_macro, bridge, client, client_ty, method],
316308
))
317309
};
318310
match m {
@@ -322,25 +314,15 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> Box<ast::Item> {
322314
// accepts it.
323315
cx.expr_call(
324316
harness_span,
325-
proc_macro_ty_method_path(cx, custom_derive),
326-
thin_vec![
327-
cx.expr_str(span, cd.trait_name),
328-
cx.expr_array_ref(
329-
span,
330-
cd.attrs
331-
.iter()
332-
.map(|&s| cx.expr_str(span, s))
333-
.collect::<ThinVec<_>>(),
334-
),
335-
local_path(cx, cd.function_ident),
336-
],
317+
proc_macro_ty_method_path(cx, expand1),
318+
thin_vec![local_path(cx, cd.function_ident)],
337319
)
338320
}
339321
ProcMacro::Attr(ca) | ProcMacro::Bang(ca) => {
340322
cx.resolver.declare_proc_macro(ca.id);
341323
let ident = match m {
342-
ProcMacro::Attr(_) => attr,
343-
ProcMacro::Bang(_) => bang,
324+
ProcMacro::Attr(_) => expand2,
325+
ProcMacro::Bang(_) => expand1,
344326
ProcMacro::Derive(_) => unreachable!(),
345327
};
346328

@@ -349,10 +331,7 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> Box<ast::Item> {
349331
cx.expr_call(
350332
harness_span,
351333
proc_macro_ty_method_path(cx, ident),
352-
thin_vec![
353-
cx.expr_str(span, ca.function_ident.name),
354-
local_path(cx, ca.function_ident),
355-
],
334+
thin_vec![local_path(cx, ca.function_ident)],
356335
)
357336
}
358337
}
@@ -367,7 +346,7 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> Box<ast::Item> {
367346
cx.ty(
368347
span,
369348
ast::TyKind::Slice(
370-
cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])),
349+
cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, client_ty])),
371350
),
372351
),
373352
None,

compiler/rustc_codegen_ssa/src/back/metadata.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ use super::apple;
3636
/// <dd>The metadata can be found in the `.rustc` section of the shared library.</dd>
3737
/// </dl>
3838
#[derive(Debug)]
39-
pub(crate) struct DefaultMetadataLoader;
39+
pub struct DefaultMetadataLoader;
4040

4141
static AIX_METADATA_SYMBOL_NAME: &'static str = "__aix_rust_metadata";
4242

compiler/rustc_expand/src/proc_macro.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ fn record_expand_proc_macro<'a>(
3131
}
3232

3333
pub struct BangProcMacro {
34-
pub client: pm::bridge::client::Client<pm::TokenStream, pm::TokenStream>,
34+
pub client: pm::bridge::client::Client,
3535
}
3636

3737
impl base::BangProcMacro for BangProcMacro {
@@ -46,7 +46,7 @@ impl base::BangProcMacro for BangProcMacro {
4646
let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace;
4747
let strategy = exec_strategy(ecx.sess);
4848
let server = proc_macro_server::Rustc::new(ecx);
49-
self.client.run(&strategy, server, input, proc_macro_backtrace).map_err(|e| {
49+
self.client.run1(&strategy, server, input, proc_macro_backtrace).map_err(|e| {
5050
ecx.dcx().emit_err(errors::ProcMacroPanicked {
5151
span,
5252
message: e.into_string().map(|message| errors::ProcMacroPanickedHelp { message }),
@@ -56,7 +56,7 @@ impl base::BangProcMacro for BangProcMacro {
5656
}
5757

5858
pub struct AttrProcMacro {
59-
pub client: pm::bridge::client::Client<(pm::TokenStream, pm::TokenStream), pm::TokenStream>,
59+
pub client: pm::bridge::client::Client,
6060
}
6161

6262
impl base::AttrProcMacro for AttrProcMacro {
@@ -72,7 +72,7 @@ impl base::AttrProcMacro for AttrProcMacro {
7272
let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace;
7373
let strategy = exec_strategy(ecx.sess);
7474
let server = proc_macro_server::Rustc::new(ecx);
75-
self.client.run(&strategy, server, annotation, annotated, proc_macro_backtrace).map_err(
75+
self.client.run2(&strategy, server, annotation, annotated, proc_macro_backtrace).map_err(
7676
|e| {
7777
ecx.dcx().emit_err(errors::CustomAttributePanicked {
7878
span,
@@ -176,7 +176,7 @@ pub(super) fn provide_derive_macro_expansion<'tcx>(
176176
})
177177
}
178178

179-
type DeriveClient = pm::bridge::client::Client<pm::TokenStream, pm::TokenStream>;
179+
type DeriveClient = pm::bridge::client::Client;
180180

181181
fn expand_derive_macro(
182182
invoc_id: LocalExpnId,
@@ -196,7 +196,7 @@ fn expand_derive_macro(
196196
let strategy = exec_strategy(ecx.sess);
197197
let server = proc_macro_server::Rustc::new(ecx);
198198

199-
match client.run(&strategy, server, input, proc_macro_backtrace) {
199+
match client.run1(&strategy, server, input, proc_macro_backtrace) {
200200
Ok(stream) => Ok(stream),
201201
Err(e) => {
202202
let invoc_expn_data = invoc_id.expn_data();

compiler/rustc_metadata/src/creader.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use rustc_index::IndexVec;
2323
use rustc_middle::bug;
2424
use rustc_middle::ty::data_structures::IndexSet;
2525
use rustc_middle::ty::{TyCtxt, TyCtxtFeed};
26-
use rustc_proc_macro::bridge::client::ProcMacro;
26+
use rustc_proc_macro::bridge::client::Client as ProcMacroClient;
2727
use rustc_session::config::mitigation_coverage::DeniedPartialMitigationLevel;
2828
use rustc_session::config::{
2929
CrateType, ExtendedTargetModifierInfo, ExternLocation, Externs, OptionsTargetModifiers,
@@ -951,12 +951,13 @@ impl CStore {
951951
sess: &Session,
952952
path: &Path,
953953
stable_crate_id: StableCrateId,
954-
) -> Result<&'static [ProcMacro], CrateError> {
954+
) -> Result<&'static [ProcMacroClient], CrateError> {
955955
let sym_name = sess.generate_proc_macro_decls_symbol(stable_crate_id);
956956
debug!("trying to dlsym proc_macros {} for symbol `{}`", path.display(), sym_name);
957957

958958
unsafe {
959-
let result = load_symbol_from_dylib::<*const &[ProcMacro]>(path, &sym_name);
959+
// FIXME(bjorn3) this depends on the unstable slice memory layout
960+
let result = load_symbol_from_dylib::<*const &[ProcMacroClient]>(path, &sym_name);
960961
match result {
961962
Ok(result) => {
962963
debug!("loaded dlsym proc_macros {} for symbol `{}`", path.display(), sym_name);

compiler/rustc_metadata/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,4 @@ pub use native_libs::{
3131
NativeLibSearchFallback, find_native_static_library, try_find_native_dynamic_library,
3232
try_find_native_static_library, walk_native_lib_search_dirs,
3333
};
34-
pub use rmeta::{EncodedMetadata, METADATA_HEADER, encode_metadata, rendered_const};
34+
pub use rmeta::{EncodedMetadata, METADATA_HEADER, ProcMacroKind, encode_metadata, rendered_const};

compiler/rustc_metadata/src/locator.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ use tracing::{debug, info};
236236

237237
use crate::creader::{Library, MetadataLoader};
238238
use crate::errors;
239-
use crate::rmeta::{METADATA_HEADER, MetadataBlob, rustc_version};
239+
use crate::rmeta::{METADATA_HEADER, MetadataBlob, ProcMacroKind, rustc_version};
240240

241241
#[derive(Clone)]
242242
pub(crate) struct CrateLocator<'a> {
@@ -821,7 +821,7 @@ fn get_metadata_section<'p>(
821821
crate_name: Option<Symbol>,
822822
) -> Result<MetadataBlob, MetadataError<'p>> {
823823
if !filename.exists() {
824-
return Err(MetadataError::NotPresent(filename));
824+
return Err(MetadataError::NotPresent(filename.into()));
825825
}
826826
let raw_bytes = match flavor {
827827
CrateFlavor::Rlib => {
@@ -978,6 +978,20 @@ fn get_flavor_from_path(path: &Path) -> CrateFlavor {
978978
}
979979
}
980980

981+
/// A function to get information about all macros inside a proc-macro crate.
982+
///
983+
/// Used by rust-analyzer-proc-macro-srv.
984+
pub fn get_proc_macro_info<'p>(
985+
target: &Target,
986+
path: &'p Path,
987+
metadata_loader: &dyn MetadataLoader,
988+
cfg_version: &'static str,
989+
) -> Result<Vec<ProcMacroKind>, MetadataError<'p>> {
990+
let metadata =
991+
get_metadata_section(target, CrateFlavor::Dylib, path, metadata_loader, cfg_version, None)?;
992+
Ok(metadata.get_proc_macro_info())
993+
}
994+
981995
// ------------------------------------------ Error reporting -------------------------------------
982996

983997
#[derive(Clone, Debug)]
@@ -1024,9 +1038,10 @@ pub(crate) enum CrateError {
10241038
NotFound(Symbol),
10251039
}
10261040

1027-
enum MetadataError<'a> {
1041+
#[derive(Debug)]
1042+
pub enum MetadataError<'a> {
10281043
/// The file was missing.
1029-
NotPresent(&'a Path),
1044+
NotPresent(Cow<'a, Path>),
10301045
/// The file was present and invalid.
10311046
LoadFailure(String),
10321047
/// The file was present, but compiled with a different rustc version.

compiler/rustc_metadata/src/rmeta/decoder.rs

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
2626
use rustc_middle::ty::Visibility;
2727
use rustc_middle::ty::codec::TyDecoder;
2828
use rustc_middle::{bug, implement_ty_decoder};
29-
use rustc_proc_macro::bridge::client::ProcMacro;
29+
use rustc_proc_macro::bridge::client::Client as ProcMacroClient;
3030
use rustc_serialize::opaque::MemDecoder;
3131
use rustc_serialize::{Decodable, Decoder};
3232
use rustc_session::config::TargetModifier;
@@ -104,8 +104,8 @@ pub(crate) struct CrateMetadata {
104104
/// These can be introduced using either `#![rustc_coherence_is_core]`
105105
/// or `#[rustc_allow_incoherent_impl]`.
106106
incoherent_impls: FxIndexMap<SimplifiedType, LazyArray<DefIndex>>,
107-
/// Proc macro descriptions for this crate, if it's a proc macro crate.
108-
raw_proc_macros: Option<&'static [ProcMacro]>,
107+
/// Proc macro function pointers for this crate, if it's a proc macro crate.
108+
raw_proc_macros: Option<&'static [ProcMacroClient]>,
109109
/// Source maps for code from the crate.
110110
source_map_import_info: Lock<Vec<Option<ImportedSourceFile>>>,
111111
/// For every definition in this crate, maps its `DefPathHash` to its `DefIndex`.
@@ -930,6 +930,16 @@ impl MetadataBlob {
930930

931931
Ok(())
932932
}
933+
934+
pub(crate) fn get_proc_macro_info(&self) -> Vec<ProcMacroKind> {
935+
self.get_root()
936+
.proc_macro_data
937+
.unwrap()
938+
.macros
939+
.decode(self)
940+
.map(|(_id, kind)| kind.decode(self))
941+
.collect::<Vec<_>>()
942+
}
933943
}
934944

935945
impl CrateRoot {
@@ -976,19 +986,20 @@ impl CrateMetadata {
976986
bug!("missing `{descr}` for {:?}", self.local_def_id(id))
977987
}
978988

979-
fn raw_proc_macro(&self, tcx: TyCtxt<'_>, id: DefIndex) -> &ProcMacro {
989+
fn raw_proc_macro(&self, tcx: TyCtxt<'_>, id: DefIndex) -> (ProcMacroClient, ProcMacroKind) {
980990
// DefIndex's in root.proc_macro_data have a one-to-one correspondence
981991
// with items in 'raw_proc_macros'.
982-
let pos = self
992+
let (pos, (_id, kind)) = self
983993
.root
984994
.proc_macro_data
985995
.as_ref()
986996
.unwrap()
987997
.macros
988998
.decode((self, tcx))
989-
.position(|i| i == id)
999+
.enumerate()
1000+
.find(|(_pos, (i, _))| *i == id)
9901001
.unwrap();
991-
&self.raw_proc_macros.unwrap()[pos]
1002+
(self.raw_proc_macros.unwrap()[pos], kind.decode((self, tcx)))
9921003
}
9931004

9941005
fn opt_item_name(&self, item_index: DefIndex) -> Option<Symbol> {
@@ -1046,20 +1057,20 @@ impl CrateMetadata {
10461057
}
10471058

10481059
fn load_proc_macro<'tcx>(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> SyntaxExtension {
1049-
let (name, kind, helper_attrs) = match *self.raw_proc_macro(tcx, id) {
1050-
ProcMacro::CustomDerive { trait_name, attributes, client } => {
1060+
let (name, kind, helper_attrs) = match self.raw_proc_macro(tcx, id) {
1061+
(client, ProcMacroKind::CustomDerive { trait_name, attributes }) => {
10511062
let helper_attrs =
1052-
attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
1063+
attributes.into_iter().map(|attr| Symbol::intern(&attr)).collect();
10531064
(
10541065
trait_name,
10551066
SyntaxExtensionKind::Derive(Arc::new(DeriveProcMacro { client })),
10561067
helper_attrs,
10571068
)
10581069
}
1059-
ProcMacro::Attr { name, client } => {
1070+
(client, ProcMacroKind::Attr { name }) => {
10601071
(name, SyntaxExtensionKind::Attr(Arc::new(AttrProcMacro { client })), Vec::new())
10611072
}
1062-
ProcMacro::Bang { name, client } => {
1073+
(client, ProcMacroKind::Bang { name }) => {
10631074
(name, SyntaxExtensionKind::Bang(Arc::new(BangProcMacro { client })), Vec::new())
10641075
}
10651076
};
@@ -1072,7 +1083,7 @@ impl CrateMetadata {
10721083
self.get_span(tcx, id),
10731084
helper_attrs,
10741085
self.root.edition,
1075-
Symbol::intern(name),
1086+
Symbol::intern(&name),
10761087
&attrs,
10771088
false,
10781089
)
@@ -1269,7 +1280,7 @@ impl CrateMetadata {
12691280
// If we are loading as a proc macro, we want to return
12701281
// the view of this crate as a proc macro crate.
12711282
if id == CRATE_DEF_INDEX {
1272-
for child_index in data.macros.decode((self, tcx)) {
1283+
for (child_index, _) in data.macros.decode((self, tcx)) {
12731284
yield self.get_mod_child(tcx, child_index);
12741285
}
12751286
}
@@ -1872,7 +1883,7 @@ impl CrateMetadata {
18721883
tcx: TyCtxt<'_>,
18731884
blob: MetadataBlob,
18741885
root: CrateRoot,
1875-
raw_proc_macros: Option<&'static [ProcMacro]>,
1886+
raw_proc_macros: Option<&'static [ProcMacroClient]>,
18761887
cnum: CrateNum,
18771888
cnum_map: CrateNumMap,
18781889
dep_kind: CrateDepKind,
@@ -2022,7 +2033,7 @@ impl CrateMetadata {
20222033
) -> impl Iterator<Item = DefId> {
20232034
gen move {
20242035
for def_id in self.root.proc_macro_data.as_ref().into_iter().flat_map(move |data| {
2025-
data.macros.decode((self, tcx)).map(move |index| DefId { index, krate })
2036+
data.macros.decode((self, tcx)).map(move |(index, _)| DefId { index, krate })
20262037
}) {
20272038
yield def_id;
20282039
}

0 commit comments

Comments
 (0)