-
Notifications
You must be signed in to change notification settings - Fork 13.3k
/
Copy pathproc_macro.rs
197 lines (173 loc) · 7.12 KB
/
proc_macro.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
use rustc_ast as ast;
use rustc_ast::ptr::P;
use rustc_ast::tokenstream::TokenStream;
use rustc_errors::ErrorGuaranteed;
use rustc_middle::ty;
use rustc_parse::parser::{ForceCollect, Parser};
use rustc_session::Session;
use rustc_session::config::ProcMacroExecutionStrategy;
use rustc_span::Span;
use rustc_span::profiling::SpannedEventArgRecorder;
use crate::base::{self, *};
use crate::{errors, proc_macro_server};
struct MessagePipe<T> {
tx: std::sync::mpsc::SyncSender<T>,
rx: std::sync::mpsc::Receiver<T>,
}
impl<T> pm::bridge::server::MessagePipe<T> for MessagePipe<T> {
fn new() -> (Self, Self) {
let (tx1, rx1) = std::sync::mpsc::sync_channel(1);
let (tx2, rx2) = std::sync::mpsc::sync_channel(1);
(MessagePipe { tx: tx1, rx: rx2 }, MessagePipe { tx: tx2, rx: rx1 })
}
fn send(&mut self, value: T) {
self.tx.send(value).unwrap();
}
fn recv(&mut self) -> Option<T> {
self.rx.recv().ok()
}
}
pub fn exec_strategy(sess: &Session) -> impl pm::bridge::server::ExecutionStrategy + 'static {
pm::bridge::server::MaybeCrossThread::<MessagePipe<_>>::new(
sess.opts.unstable_opts.proc_macro_execution_strategy
== ProcMacroExecutionStrategy::CrossThread,
)
}
pub struct BangProcMacro {
pub client: pm::bridge::client::Client<pm::TokenStream, pm::TokenStream>,
}
impl base::BangProcMacro for BangProcMacro {
fn expand(
&self,
ecx: &mut ExtCtxt<'_>,
span: Span,
input: TokenStream,
) -> Result<TokenStream, ErrorGuaranteed> {
let _timer =
ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| {
recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span);
});
let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace;
let strategy = exec_strategy(ecx.sess);
let server = proc_macro_server::Rustc::new(ecx);
self.client.run(&strategy, server, input, proc_macro_backtrace).map_err(|e| {
ecx.dcx().emit_err(errors::ProcMacroPanicked {
span,
message: e
.as_str()
.map(|message| errors::ProcMacroPanickedHelp { message: message.into() }),
})
})
}
}
pub struct AttrProcMacro {
pub client: pm::bridge::client::Client<(pm::TokenStream, pm::TokenStream), pm::TokenStream>,
}
impl base::AttrProcMacro for AttrProcMacro {
fn expand(
&self,
ecx: &mut ExtCtxt<'_>,
span: Span,
annotation: TokenStream,
annotated: TokenStream,
) -> Result<TokenStream, ErrorGuaranteed> {
let _timer =
ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| {
recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span);
});
let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace;
let strategy = exec_strategy(ecx.sess);
let server = proc_macro_server::Rustc::new(ecx);
self.client.run(&strategy, server, annotation, annotated, proc_macro_backtrace).map_err(
|e| {
ecx.dcx().emit_err(errors::CustomAttributePanicked {
span,
message: e.as_str().map(|message| errors::CustomAttributePanickedHelp {
message: message.into(),
}),
})
},
)
}
}
pub struct DeriveProcMacro {
pub client: pm::bridge::client::Client<pm::TokenStream, pm::TokenStream>,
}
impl MultiItemModifier for DeriveProcMacro {
fn expand(
&self,
ecx: &mut ExtCtxt<'_>,
span: Span,
_meta_item: &ast::MetaItem,
item: Annotatable,
_is_derive_const: bool,
) -> ExpandResult<Vec<Annotatable>, Annotatable> {
let _timer = ecx.sess.prof.generic_activity_with_arg_recorder(
"expand_derive_proc_macro_outer",
|recorder| {
recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span);
},
);
// We need special handling for statement items
// (e.g. `fn foo() { #[derive(Debug)] struct Bar; }`)
let is_stmt = matches!(item, Annotatable::Stmt(..));
// We used to have an alternative behaviour for crates that needed it.
// We had a lint for a long time, but now we just emit a hard error.
// Eventually we might remove the special case hard error check
// altogether. See #73345.
crate::base::ann_pretty_printing_compatibility_hack(&item, &ecx.sess.psess);
let input = item.to_tokens();
let res = ty::tls::with(|tcx| {
// FIXME(pr-time): without flattened some (weird) tests fail, but no idea if it's correct/enough
let input = tcx.arena.alloc(input.flattened()) as &TokenStream;
let invoc_id = ecx.current_expansion.id;
let invoc_expn_data = invoc_id.expn_data();
// FIXME(pr-time): Just using the crate hash to notice when the proc-macro code has
// changed. How to *correctly* depend on exactly the macro definition?
// I.e., depending on the crate hash is just a HACK, and ideally the dependency would be
// more narrow.
let macro_def_id = invoc_expn_data.macro_def_id.unwrap();
let proc_macro_crate_hash = tcx.crate_hash(macro_def_id.krate);
assert_eq!(invoc_expn_data.call_site, span);
let key = (invoc_id, proc_macro_crate_hash, input);
// FIXME(pr-time): Is this the correct way to check for incremental compilation (as
// well)?
if tcx.sess.opts.incremental.is_some() && tcx.sess.opts.unstable_opts.cache_proc_macros
{
crate::derive_macro_expansion::enter_context((ecx, self.client), move || {
tcx.derive_macro_expansion(key).cloned()
})
} else {
crate::derive_macro_expansion::provide_derive_macro_expansion(tcx, key).cloned()
}
});
let Ok(output) = res else {
// error will already have been emitted
return ExpandResult::Ready(vec![]);
};
let error_count_before = ecx.dcx().err_count();
let mut parser = Parser::new(&ecx.sess.psess, output, Some("proc-macro derive"));
let mut items = vec![];
loop {
match parser.parse_item(ForceCollect::No) {
Ok(None) => break,
Ok(Some(item)) => {
if is_stmt {
items.push(Annotatable::Stmt(P(ecx.stmt_item(span, item))));
} else {
items.push(Annotatable::Item(item));
}
}
Err(err) => {
err.emit();
break;
}
}
}
// fail if there have been errors emitted
if ecx.dcx().err_count() > error_count_before {
ecx.dcx().emit_err(errors::ProcMacroDeriveTokens { span });
}
ExpandResult::Ready(items)
}
}