aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_proc_macro_srv/src/proc_macro/bridge
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_proc_macro_srv/src/proc_macro/bridge')
-rw-r--r--crates/ra_proc_macro_srv/src/proc_macro/bridge/buffer.rs149
-rw-r--r--crates/ra_proc_macro_srv/src/proc_macro/bridge/client.rs478
-rw-r--r--crates/ra_proc_macro_srv/src/proc_macro/bridge/closure.rs30
-rw-r--r--crates/ra_proc_macro_srv/src/proc_macro/bridge/handle.rs73
-rw-r--r--crates/ra_proc_macro_srv/src/proc_macro/bridge/mod.rs408
-rw-r--r--crates/ra_proc_macro_srv/src/proc_macro/bridge/rpc.rs311
-rw-r--r--crates/ra_proc_macro_srv/src/proc_macro/bridge/scoped_cell.rs84
-rw-r--r--crates/ra_proc_macro_srv/src/proc_macro/bridge/server.rs323
8 files changed, 0 insertions, 1856 deletions
diff --git a/crates/ra_proc_macro_srv/src/proc_macro/bridge/buffer.rs b/crates/ra_proc_macro_srv/src/proc_macro/bridge/buffer.rs
deleted file mode 100644
index dae6ff1d1..000000000
--- a/crates/ra_proc_macro_srv/src/proc_macro/bridge/buffer.rs
+++ /dev/null
@@ -1,149 +0,0 @@
1//! lib-proc-macro Buffer management for same-process client<->server communication.
2//!
3//! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/buffer.rs
4//! augmented with removing unstable features
5
6use std::io::{self, Write};
7use std::mem;
8use std::ops::{Deref, DerefMut};
9use std::slice;
10
11#[repr(C)]
12struct Slice<'a, T> {
13 data: &'a [T; 0],
14 len: usize,
15}
16
17unsafe impl<'a, T: Sync> Sync for Slice<'a, T> {}
18unsafe impl<'a, T: Sync> Send for Slice<'a, T> {}
19
20impl<'a, T> Copy for Slice<'a, T> {}
21impl<'a, T> Clone for Slice<'a, T> {
22 fn clone(&self) -> Self {
23 *self
24 }
25}
26
27impl<'a, T> From<&'a [T]> for Slice<'a, T> {
28 fn from(xs: &'a [T]) -> Self {
29 Slice { data: unsafe { &*(xs.as_ptr() as *const [T; 0]) }, len: xs.len() }
30 }
31}
32
33impl<'a, T> Deref for Slice<'a, T> {
34 type Target = [T];
35 fn deref(&self) -> &[T] {
36 unsafe { slice::from_raw_parts(self.data.as_ptr(), self.len) }
37 }
38}
39
40#[repr(C)]
41pub struct Buffer<T: Copy> {
42 data: *mut T,
43 len: usize,
44 capacity: usize,
45 extend_from_slice: extern "C" fn(Buffer<T>, Slice<'_, T>) -> Buffer<T>,
46 drop: extern "C" fn(Buffer<T>),
47}
48
49unsafe impl<T: Copy + Sync> Sync for Buffer<T> {}
50unsafe impl<T: Copy + Send> Send for Buffer<T> {}
51
52impl<T: Copy> Default for Buffer<T> {
53 fn default() -> Self {
54 Self::from(vec![])
55 }
56}
57
58impl<T: Copy> Deref for Buffer<T> {
59 type Target = [T];
60 fn deref(&self) -> &[T] {
61 unsafe { slice::from_raw_parts(self.data as *const T, self.len) }
62 }
63}
64
65impl<T: Copy> DerefMut for Buffer<T> {
66 fn deref_mut(&mut self) -> &mut [T] {
67 unsafe { slice::from_raw_parts_mut(self.data, self.len) }
68 }
69}
70
71impl<T: Copy> Buffer<T> {
72 pub(super) fn new() -> Self {
73 Self::default()
74 }
75
76 pub(super) fn clear(&mut self) {
77 self.len = 0;
78 }
79
80 pub(super) fn take(&mut self) -> Self {
81 mem::take(self)
82 }
83
84 pub(super) fn extend_from_slice(&mut self, xs: &[T]) {
85 // Fast path to avoid going through an FFI call.
86 if let Some(final_len) = self.len.checked_add(xs.len()) {
87 if final_len <= self.capacity {
88 let dst = unsafe { slice::from_raw_parts_mut(self.data, self.capacity) };
89 dst[self.len..][..xs.len()].copy_from_slice(xs);
90 self.len = final_len;
91 return;
92 }
93 }
94 let b = self.take();
95 *self = (b.extend_from_slice)(b, Slice::from(xs));
96 }
97}
98
99impl Write for Buffer<u8> {
100 fn write(&mut self, xs: &[u8]) -> io::Result<usize> {
101 self.extend_from_slice(xs);
102 Ok(xs.len())
103 }
104
105 fn write_all(&mut self, xs: &[u8]) -> io::Result<()> {
106 self.extend_from_slice(xs);
107 Ok(())
108 }
109
110 fn flush(&mut self) -> io::Result<()> {
111 Ok(())
112 }
113}
114
115impl<T: Copy> Drop for Buffer<T> {
116 fn drop(&mut self) {
117 let b = self.take();
118 (b.drop)(b);
119 }
120}
121
122impl<T: Copy> From<Vec<T>> for Buffer<T> {
123 fn from(mut v: Vec<T>) -> Self {
124 let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity());
125 mem::forget(v);
126
127 // This utility function is nested in here because it can *only*
128 // be safely called on `Buffer`s created by *this* `proc_macro`.
129 fn to_vec<T: Copy>(b: Buffer<T>) -> Vec<T> {
130 unsafe {
131 let Buffer { data, len, capacity, .. } = b;
132 mem::forget(b);
133 Vec::from_raw_parts(data, len, capacity)
134 }
135 }
136
137 extern "C" fn extend_from_slice<T: Copy>(b: Buffer<T>, xs: Slice<'_, T>) -> Buffer<T> {
138 let mut v = to_vec(b);
139 v.extend_from_slice(&xs);
140 Buffer::from(v)
141 }
142
143 extern "C" fn drop<T: Copy>(b: Buffer<T>) {
144 mem::drop(to_vec(b));
145 }
146
147 Buffer { data, len, capacity, extend_from_slice, drop }
148 }
149}
diff --git a/crates/ra_proc_macro_srv/src/proc_macro/bridge/client.rs b/crates/ra_proc_macro_srv/src/proc_macro/bridge/client.rs
deleted file mode 100644
index cb4b3bdb0..000000000
--- a/crates/ra_proc_macro_srv/src/proc_macro/bridge/client.rs
+++ /dev/null
@@ -1,478 +0,0 @@
1//! lib-proc-macro Client-side types.
2//!
3//! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/client.rs
4//! augmented with removing unstable features
5
6use super::*;
7
8macro_rules! define_handles {
9 (
10 'owned: $($oty:ident,)*
11 'interned: $($ity:ident,)*
12 ) => {
13 #[repr(C)]
14 #[allow(non_snake_case)]
15 pub struct HandleCounters {
16 $($oty: AtomicUsize,)*
17 $($ity: AtomicUsize,)*
18 }
19
20 impl HandleCounters {
21 // FIXME(eddyb) use a reference to the `static COUNTERS`, instead of
22 // a wrapper `fn` pointer, once `const fn` can reference `static`s.
23 extern "C" fn get() -> &'static Self {
24 static COUNTERS: HandleCounters = HandleCounters {
25 $($oty: AtomicUsize::new(1),)*
26 $($ity: AtomicUsize::new(1),)*
27 };
28 &COUNTERS
29 }
30 }
31
32 // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
33 #[repr(C)]
34 #[allow(non_snake_case)]
35 pub(super) struct HandleStore<S: server::Types> {
36 $($oty: handle::OwnedStore<S::$oty>,)*
37 $($ity: handle::InternedStore<S::$ity>,)*
38 }
39
40 impl<S: server::Types> HandleStore<S> {
41 pub(super) fn new(handle_counters: &'static HandleCounters) -> Self {
42 HandleStore {
43 $($oty: handle::OwnedStore::new(&handle_counters.$oty),)*
44 $($ity: handle::InternedStore::new(&handle_counters.$ity),)*
45 }
46 }
47 }
48
49 $(
50 #[repr(C)]
51 pub struct $oty(pub(crate) handle::Handle);
52 // impl !Send for $oty {}
53 // impl !Sync for $oty {}
54
55 // Forward `Drop::drop` to the inherent `drop` method.
56 impl Drop for $oty {
57 fn drop(&mut self) {
58 $oty(self.0).drop();
59 }
60 }
61
62 impl<S> Encode<S> for $oty {
63 fn encode(self, w: &mut Writer, s: &mut S) {
64 let handle = self.0;
65 mem::forget(self);
66 handle.encode(w, s);
67 }
68 }
69
70 impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
71 for Marked<S::$oty, $oty>
72 {
73 fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
74 s.$oty.take(handle::Handle::decode(r, &mut ()))
75 }
76 }
77
78 impl<S> Encode<S> for &$oty {
79 fn encode(self, w: &mut Writer, s: &mut S) {
80 self.0.encode(w, s);
81 }
82 }
83
84 impl<'s, S: server::Types,> Decode<'_, 's, HandleStore<server::MarkedTypes<S>>>
85 for &'s Marked<S::$oty, $oty>
86 {
87 fn decode(r: &mut Reader<'_>, s: &'s HandleStore<server::MarkedTypes<S>>) -> Self {
88 &s.$oty[handle::Handle::decode(r, &mut ())]
89 }
90 }
91
92 impl<S> Encode<S> for &mut $oty {
93 fn encode(self, w: &mut Writer, s: &mut S) {
94 self.0.encode(w, s);
95 }
96 }
97
98 impl<'s, S: server::Types> DecodeMut<'_, 's, HandleStore<server::MarkedTypes<S>>>
99 for &'s mut Marked<S::$oty, $oty>
100 {
101 fn decode(
102 r: &mut Reader<'_>,
103 s: &'s mut HandleStore<server::MarkedTypes<S>>
104 ) -> Self {
105 &mut s.$oty[handle::Handle::decode(r, &mut ())]
106 }
107 }
108
109 impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
110 for Marked<S::$oty, $oty>
111 {
112 fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
113 s.$oty.alloc(self).encode(w, s);
114 }
115 }
116
117 impl<S> DecodeMut<'_, '_, S> for $oty {
118 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
119 $oty(handle::Handle::decode(r, s))
120 }
121 }
122 )*
123
124 $(
125 #[repr(C)]
126 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
127 pub(crate) struct $ity(handle::Handle);
128 // impl !Send for $ity {}
129 // impl !Sync for $ity {}
130
131 impl<S> Encode<S> for $ity {
132 fn encode(self, w: &mut Writer, s: &mut S) {
133 self.0.encode(w, s);
134 }
135 }
136
137 impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
138 for Marked<S::$ity, $ity>
139 {
140 fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
141 s.$ity.copy(handle::Handle::decode(r, &mut ()))
142 }
143 }
144
145 impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
146 for Marked<S::$ity, $ity>
147 {
148 fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
149 s.$ity.alloc(self).encode(w, s);
150 }
151 }
152
153 impl<S> DecodeMut<'_, '_, S> for $ity {
154 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
155 $ity(handle::Handle::decode(r, s))
156 }
157 }
158 )*
159 }
160}
161define_handles! {
162 'owned:
163 TokenStream,
164 TokenStreamBuilder,
165 TokenStreamIter,
166 Group,
167 Literal,
168 SourceFile,
169 MultiSpan,
170 Diagnostic,
171
172 'interned:
173 Punct,
174 Ident,
175 Span,
176}
177
178// FIXME(eddyb) generate these impls by pattern-matching on the
179// names of methods - also could use the presence of `fn drop`
180// to distinguish between 'owned and 'interned, above.
181// Alternatively, special 'modes" could be listed of types in with_api
182// instead of pattern matching on methods, here and in server decl.
183
184impl Clone for TokenStream {
185 fn clone(&self) -> Self {
186 self.clone()
187 }
188}
189
190impl Clone for TokenStreamIter {
191 fn clone(&self) -> Self {
192 self.clone()
193 }
194}
195
196impl Clone for Group {
197 fn clone(&self) -> Self {
198 self.clone()
199 }
200}
201
202impl Clone for Literal {
203 fn clone(&self) -> Self {
204 self.clone()
205 }
206}
207
208impl fmt::Debug for Literal {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 f.debug_struct("Literal")
211 // format the kind without quotes, as in `kind: Float`
212 // .field("kind", &format_args!("{}", &self.debug_kind()))
213 .field("symbol", &self.symbol())
214 // format `Some("...")` on one line even in {:#?} mode
215 // .field("suffix", &format_args!("{:?}", &self.suffix()))
216 .field("span", &self.span())
217 .finish()
218 }
219}
220
221impl Clone for SourceFile {
222 fn clone(&self) -> Self {
223 self.clone()
224 }
225}
226
227impl fmt::Debug for Span {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 f.write_str(&self.debug())
230 }
231}
232
233macro_rules! define_client_side {
234 ($($name:ident {
235 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)*
236 }),* $(,)?) => {
237 $(impl $name {
238 #[allow(unused)]
239 $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* {
240 panic!("hello");
241 // Bridge::with(|bridge| {
242 // let mut b = bridge.cached_buffer.take();
243
244 // b.clear();
245 // api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ());
246 // reverse_encode!(b; $($arg),*);
247
248 // b = bridge.dispatch.call(b);
249
250 // let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ());
251
252 // bridge.cached_buffer = b;
253
254 // r.unwrap_or_else(|e| panic::resume_unwind(e.into()))
255 // })
256 })*
257 })*
258 }
259}
260with_api!(self, self, define_client_side);
261
262enum BridgeState<'a> {
263 /// No server is currently connected to this client.
264 NotConnected,
265
266 /// A server is connected and available for requests.
267 Connected(Bridge<'a>),
268
269 /// Access to the bridge is being exclusively acquired
270 /// (e.g., during `BridgeState::with`).
271 InUse,
272}
273
274enum BridgeStateL {}
275
276impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL {
277 type Out = BridgeState<'a>;
278}
279
280thread_local! {
281 static BRIDGE_STATE: scoped_cell::ScopedCell<BridgeStateL> =
282 scoped_cell::ScopedCell::new(BridgeState::NotConnected);
283}
284
285impl BridgeState<'_> {
286 /// Take exclusive control of the thread-local
287 /// `BridgeState`, and pass it to `f`, mutably.
288 /// The state will be restored after `f` exits, even
289 /// by panic, including modifications made to it by `f`.
290 ///
291 /// N.B., while `f` is running, the thread-local state
292 /// is `BridgeState::InUse`.
293 fn with<R>(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R {
294 BRIDGE_STATE.with(|state| {
295 state.replace(BridgeState::InUse, |mut state| {
296 // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone
297 f(&mut *state)
298 })
299 })
300 }
301}
302
303impl Bridge<'_> {
304 fn enter<R>(self, f: impl FnOnce() -> R) -> R {
305 // Hide the default panic output within `proc_macro` expansions.
306 // NB. the server can't do this because it may use a different libstd.
307 static HIDE_PANICS_DURING_EXPANSION: Once = Once::new();
308 HIDE_PANICS_DURING_EXPANSION.call_once(|| {
309 let prev = panic::take_hook();
310 panic::set_hook(Box::new(move |info| {
311 let hide = BridgeState::with(|state| match state {
312 BridgeState::NotConnected => false,
313 BridgeState::Connected(_) | BridgeState::InUse => true,
314 });
315 if !hide {
316 prev(info)
317 }
318 }));
319 });
320
321 BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f))
322 }
323
324 fn with<R>(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R {
325 BridgeState::with(|state| match state {
326 BridgeState::NotConnected => {
327 panic!("procedural macro API is used outside of a procedural macro");
328 }
329 BridgeState::InUse => {
330 panic!("procedural macro API is used while it's already in use");
331 }
332 BridgeState::Connected(bridge) => f(bridge),
333 })
334 }
335}
336
337/// A client-side "global object" (usually a function pointer),
338/// which may be using a different `proc_macro` from the one
339/// used by the server, but can be interacted with compatibly.
340///
341/// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer).
342/// The call ABI of function pointers used for `F` doesn't
343/// need to match between server and client, since it's only
344/// passed between them and (eventually) called by the client.
345#[repr(C)]
346#[derive(Copy, Clone)]
347pub struct Client<F> {
348 // FIXME(eddyb) use a reference to the `static COUNTERS`, instead of
349 // a wrapper `fn` pointer, once `const fn` can reference `static`s.
350 pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters,
351 pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer<u8>,
352 pub(super) f: F,
353}
354
355/// Client-side helper for handling client panics, entering the bridge,
356/// deserializing input and serializing output.
357// FIXME(eddyb) maybe replace `Bridge::enter` with this?
358fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>(
359 mut bridge: Bridge<'_>,
360 f: impl FnOnce(A) -> R,
361) -> Buffer<u8> {
362 // The initial `cached_buffer` contains the input.
363 let mut b = bridge.cached_buffer.take();
364
365 panic::catch_unwind(panic::AssertUnwindSafe(|| {
366 bridge.enter(|| {
367 let reader = &mut &b[..];
368 let input = A::decode(reader, &mut ());
369
370 // Put the `cached_buffer` back in the `Bridge`, for requests.
371 Bridge::with(|bridge| bridge.cached_buffer = b.take());
372
373 let output = f(input);
374
375 // Take the `cached_buffer` back out, for the output value.
376 b = Bridge::with(|bridge| bridge.cached_buffer.take());
377
378 // HACK(eddyb) Separate encoding a success value (`Ok(output)`)
379 // from encoding a panic (`Err(e: PanicMessage)`) to avoid
380 // having handles outside the `bridge.enter(|| ...)` scope, and
381 // to catch panics that could happen while encoding the success.
382 //
383 // Note that panics should be impossible beyond this point, but
384 // this is defensively trying to avoid any accidental panicking
385 // reaching the `extern "C"` (which should `abort` but may not
386 // at the moment, so this is also potentially preventing UB).
387 b.clear();
388 Ok::<_, ()>(output).encode(&mut b, &mut ());
389 })
390 }))
391 .map_err(PanicMessage::from)
392 .unwrap_or_else(|e| {
393 b.clear();
394 Err::<(), _>(e).encode(&mut b, &mut ());
395 });
396 b
397}
398
399impl Client<fn(crate::TokenStream) -> crate::TokenStream> {
400 pub fn expand1(f: fn(crate::TokenStream) -> crate::TokenStream) -> Self {
401 extern "C" fn run(
402 bridge: Bridge<'_>,
403 f: impl FnOnce(crate::TokenStream) -> crate::TokenStream,
404 ) -> Buffer<u8> {
405 run_client(bridge, |input| f(crate::TokenStream(input)).0)
406 }
407 Client { get_handle_counters: HandleCounters::get, run, f }
408 }
409}
410
411impl Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
412 pub fn expand2(f: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream) -> Self {
413 extern "C" fn run(
414 bridge: Bridge<'_>,
415 f: impl FnOnce(crate::TokenStream, crate::TokenStream) -> crate::TokenStream,
416 ) -> Buffer<u8> {
417 run_client(bridge, |(input, input2)| {
418 f(crate::TokenStream(input), crate::TokenStream(input2)).0
419 })
420 }
421 Client { get_handle_counters: HandleCounters::get, run, f }
422 }
423}
424
425#[repr(C)]
426#[derive(Copy, Clone)]
427pub enum ProcMacro {
428 CustomDerive {
429 trait_name: &'static str,
430 attributes: &'static [&'static str],
431 client: Client<fn(crate::TokenStream) -> crate::TokenStream>,
432 },
433
434 Attr {
435 name: &'static str,
436 client: Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream>,
437 },
438
439 Bang {
440 name: &'static str,
441 client: Client<fn(crate::TokenStream) -> crate::TokenStream>,
442 },
443}
444
445impl std::fmt::Debug for ProcMacro {
446 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447 write!(f, "ProcMacro {{ name: {} }}", self.name())
448 }
449}
450
451impl ProcMacro {
452 pub fn name(&self) -> &'static str {
453 match self {
454 ProcMacro::CustomDerive { trait_name, .. } => trait_name,
455 ProcMacro::Attr { name, .. } => name,
456 ProcMacro::Bang { name, .. } => name,
457 }
458 }
459
460 pub fn custom_derive(
461 trait_name: &'static str,
462 attributes: &'static [&'static str],
463 expand: fn(crate::TokenStream) -> crate::TokenStream,
464 ) -> Self {
465 ProcMacro::CustomDerive { trait_name, attributes, client: Client::expand1(expand) }
466 }
467
468 pub fn attr(
469 name: &'static str,
470 expand: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream,
471 ) -> Self {
472 ProcMacro::Attr { name, client: Client::expand2(expand) }
473 }
474
475 pub fn bang(name: &'static str, expand: fn(crate::TokenStream) -> crate::TokenStream) -> Self {
476 ProcMacro::Bang { name, client: Client::expand1(expand) }
477 }
478}
diff --git a/crates/ra_proc_macro_srv/src/proc_macro/bridge/closure.rs b/crates/ra_proc_macro_srv/src/proc_macro/bridge/closure.rs
deleted file mode 100644
index 273a97715..000000000
--- a/crates/ra_proc_macro_srv/src/proc_macro/bridge/closure.rs
+++ /dev/null
@@ -1,30 +0,0 @@
1//! lib-proc-macro Closure type (equivalent to `&mut dyn FnMut(A) -> R`) that's `repr(C)`.
2//!
3//! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/closure.rs#
4//! augmented with removing unstable features
5
6#[repr(C)]
7pub struct Closure<'a, A, R> {
8 call: unsafe extern "C" fn(&mut Env, A) -> R,
9 env: &'a mut Env,
10}
11
12struct Env;
13
14// impl<'a, A, R> !Sync for Closure<'a, A, R> {}
15// impl<'a, A, R> !Send for Closure<'a, A, R> {}
16
17impl<'a, A, R, F: FnMut(A) -> R> From<&'a mut F> for Closure<'a, A, R> {
18 fn from(f: &'a mut F) -> Self {
19 unsafe extern "C" fn call<A, R, F: FnMut(A) -> R>(env: &mut Env, arg: A) -> R {
20 (*(env as *mut _ as *mut F))(arg)
21 }
22 Closure { call: call::<A, R, F>, env: unsafe { &mut *(f as *mut _ as *mut Env) } }
23 }
24}
25
26impl<'a, A, R> Closure<'a, A, R> {
27 pub fn call(&mut self, arg: A) -> R {
28 unsafe { (self.call)(self.env, arg) }
29 }
30}
diff --git a/crates/ra_proc_macro_srv/src/proc_macro/bridge/handle.rs b/crates/ra_proc_macro_srv/src/proc_macro/bridge/handle.rs
deleted file mode 100644
index a2f77b5ac..000000000
--- a/crates/ra_proc_macro_srv/src/proc_macro/bridge/handle.rs
+++ /dev/null
@@ -1,73 +0,0 @@
1//! lib-proc-macro Server-side handles and storage for per-handle data.
2//!
3//! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/handle.rs
4//! augmented with removing unstable features
5
6use std::collections::{BTreeMap, HashMap};
7use std::hash::Hash;
8use std::num::NonZeroU32;
9use std::ops::{Index, IndexMut};
10use std::sync::atomic::{AtomicUsize, Ordering};
11
12pub(super) type Handle = NonZeroU32;
13
14pub(super) struct OwnedStore<T: 'static> {
15 counter: &'static AtomicUsize,
16 data: BTreeMap<Handle, T>,
17}
18
19impl<T> OwnedStore<T> {
20 pub(super) fn new(counter: &'static AtomicUsize) -> Self {
21 // Ensure the handle counter isn't 0, which would panic later,
22 // when `NonZeroU32::new` (aka `Handle::new`) is called in `alloc`.
23 assert_ne!(counter.load(Ordering::SeqCst), 0);
24
25 OwnedStore { counter, data: BTreeMap::new() }
26 }
27}
28
29impl<T> OwnedStore<T> {
30 pub(super) fn alloc(&mut self, x: T) -> Handle {
31 let counter = self.counter.fetch_add(1, Ordering::SeqCst);
32 let handle = Handle::new(counter as u32).expect("`proc_macro` handle counter overflowed");
33 assert!(self.data.insert(handle, x).is_none());
34 handle
35 }
36
37 pub(super) fn take(&mut self, h: Handle) -> T {
38 self.data.remove(&h).expect("use-after-free in `proc_macro` handle")
39 }
40}
41
42impl<T> Index<Handle> for OwnedStore<T> {
43 type Output = T;
44 fn index(&self, h: Handle) -> &T {
45 self.data.get(&h).expect("use-after-free in `proc_macro` handle")
46 }
47}
48
49impl<T> IndexMut<Handle> for OwnedStore<T> {
50 fn index_mut(&mut self, h: Handle) -> &mut T {
51 self.data.get_mut(&h).expect("use-after-free in `proc_macro` handle")
52 }
53}
54
55pub(super) struct InternedStore<T: 'static> {
56 owned: OwnedStore<T>,
57 interner: HashMap<T, Handle>,
58}
59
60impl<T: Copy + Eq + Hash> InternedStore<T> {
61 pub(super) fn new(counter: &'static AtomicUsize) -> Self {
62 InternedStore { owned: OwnedStore::new(counter), interner: HashMap::new() }
63 }
64
65 pub(super) fn alloc(&mut self, x: T) -> Handle {
66 let owned = &mut self.owned;
67 *self.interner.entry(x).or_insert_with(|| owned.alloc(x))
68 }
69
70 pub(super) fn copy(&mut self, h: Handle) -> T {
71 self.owned[h]
72 }
73}
diff --git a/crates/ra_proc_macro_srv/src/proc_macro/bridge/mod.rs b/crates/ra_proc_macro_srv/src/proc_macro/bridge/mod.rs
deleted file mode 100644
index aeb05aad4..000000000
--- a/crates/ra_proc_macro_srv/src/proc_macro/bridge/mod.rs
+++ /dev/null
@@ -1,408 +0,0 @@
1//! lib-proc-macro Internal interface for communicating between a `proc_macro` client
2//!
3//! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/mod.rs
4//! augmented with removing unstable features
5//!
6//! Internal interface for communicating between a `proc_macro` client
7//! (a proc macro crate) and a `proc_macro` server (a compiler front-end).
8//!
9//! Serialization (with C ABI buffers) and unique integer handles are employed
10//! to allow safely interfacing between two copies of `proc_macro` built
11//! (from the same source) by different compilers with potentially mismatching
12//! Rust ABIs (e.g., stage0/bin/rustc vs stage1/bin/rustc during bootstrap).
13
14#![deny(unsafe_code)]
15
16pub use crate::proc_macro::{Delimiter, Level, LineColumn, Spacing};
17use std::fmt;
18use std::hash::Hash;
19use std::marker;
20use std::mem;
21use std::ops::Bound;
22use std::panic;
23use std::sync::atomic::AtomicUsize;
24use std::sync::Once;
25use std::thread;
26
27/// Higher-order macro describing the server RPC API, allowing automatic
28/// generation of type-safe Rust APIs, both client-side and server-side.
29///
30/// `with_api!(MySelf, my_self, my_macro)` expands to:
31/// ```rust,ignore (pseudo-code)
32/// my_macro! {
33/// // ...
34/// Literal {
35/// // ...
36/// fn character(ch: char) -> MySelf::Literal;
37/// // ...
38/// fn span(my_self: &MySelf::Literal) -> MySelf::Span;
39/// fn set_span(my_self: &mut MySelf::Literal, span: MySelf::Span);
40/// },
41/// // ...
42/// }
43/// ```
44///
45/// The first two arguments serve to customize the arguments names
46/// and argument/return types, to enable several different usecases:
47///
48/// If `my_self` is just `self`, then each `fn` signature can be used
49/// as-is for a method. If it's anything else (`self_` in practice),
50/// then the signatures don't have a special `self` argument, and
51/// can, therefore, have a different one introduced.
52///
53/// If `MySelf` is just `Self`, then the types are only valid inside
54/// a trait or a trait impl, where the trait has associated types
55/// for each of the API types. If non-associated types are desired,
56/// a module name (`self` in practice) can be used instead of `Self`.
57macro_rules! with_api {
58 ($S:ident, $self:ident, $m:ident) => {
59 $m! {
60 TokenStream {
61 fn drop($self: $S::TokenStream);
62 fn clone($self: &$S::TokenStream) -> $S::TokenStream;
63 fn new() -> $S::TokenStream;
64 fn is_empty($self: &$S::TokenStream) -> bool;
65 fn from_str(src: &str) -> $S::TokenStream;
66 fn to_string($self: &$S::TokenStream) -> String;
67 fn from_token_tree(
68 tree: TokenTree<$S::Group, $S::Punct, $S::Ident, $S::Literal>,
69 ) -> $S::TokenStream;
70 fn into_iter($self: $S::TokenStream) -> $S::TokenStreamIter;
71 },
72 TokenStreamBuilder {
73 fn drop($self: $S::TokenStreamBuilder);
74 fn new() -> $S::TokenStreamBuilder;
75 fn push($self: &mut $S::TokenStreamBuilder, stream: $S::TokenStream);
76 fn build($self: $S::TokenStreamBuilder) -> $S::TokenStream;
77 },
78 TokenStreamIter {
79 fn drop($self: $S::TokenStreamIter);
80 fn clone($self: &$S::TokenStreamIter) -> $S::TokenStreamIter;
81 fn next(
82 $self: &mut $S::TokenStreamIter,
83 ) -> Option<TokenTree<$S::Group, $S::Punct, $S::Ident, $S::Literal>>;
84 },
85 Group {
86 fn drop($self: $S::Group);
87 fn clone($self: &$S::Group) -> $S::Group;
88 fn new(delimiter: Delimiter, stream: $S::TokenStream) -> $S::Group;
89 fn delimiter($self: &$S::Group) -> Delimiter;
90 fn stream($self: &$S::Group) -> $S::TokenStream;
91 fn span($self: &$S::Group) -> $S::Span;
92 fn span_open($self: &$S::Group) -> $S::Span;
93 fn span_close($self: &$S::Group) -> $S::Span;
94 fn set_span($self: &mut $S::Group, span: $S::Span);
95 },
96 Punct {
97 fn new(ch: char, spacing: Spacing) -> $S::Punct;
98 fn as_char($self: $S::Punct) -> char;
99 fn spacing($self: $S::Punct) -> Spacing;
100 fn span($self: $S::Punct) -> $S::Span;
101 fn with_span($self: $S::Punct, span: $S::Span) -> $S::Punct;
102 },
103 Ident {
104 fn new(string: &str, span: $S::Span, is_raw: bool) -> $S::Ident;
105 fn span($self: $S::Ident) -> $S::Span;
106 fn with_span($self: $S::Ident, span: $S::Span) -> $S::Ident;
107 },
108 Literal {
109 fn drop($self: $S::Literal);
110 fn clone($self: &$S::Literal) -> $S::Literal;
111 fn debug_kind($self: &$S::Literal) -> String;
112 fn symbol($self: &$S::Literal) -> String;
113 fn suffix($self: &$S::Literal) -> Option<String>;
114 fn integer(n: &str) -> $S::Literal;
115 fn typed_integer(n: &str, kind: &str) -> $S::Literal;
116 fn float(n: &str) -> $S::Literal;
117 fn f32(n: &str) -> $S::Literal;
118 fn f64(n: &str) -> $S::Literal;
119 fn string(string: &str) -> $S::Literal;
120 fn character(ch: char) -> $S::Literal;
121 fn byte_string(bytes: &[u8]) -> $S::Literal;
122 fn span($self: &$S::Literal) -> $S::Span;
123 fn set_span($self: &mut $S::Literal, span: $S::Span);
124 fn subspan(
125 $self: &$S::Literal,
126 start: Bound<usize>,
127 end: Bound<usize>,
128 ) -> Option<$S::Span>;
129 },
130 SourceFile {
131 fn drop($self: $S::SourceFile);
132 fn clone($self: &$S::SourceFile) -> $S::SourceFile;
133 fn eq($self: &$S::SourceFile, other: &$S::SourceFile) -> bool;
134 fn path($self: &$S::SourceFile) -> String;
135 fn is_real($self: &$S::SourceFile) -> bool;
136 },
137 MultiSpan {
138 fn drop($self: $S::MultiSpan);
139 fn new() -> $S::MultiSpan;
140 fn push($self: &mut $S::MultiSpan, span: $S::Span);
141 },
142 Diagnostic {
143 fn drop($self: $S::Diagnostic);
144 fn new(level: Level, msg: &str, span: $S::MultiSpan) -> $S::Diagnostic;
145 fn sub(
146 $self: &mut $S::Diagnostic,
147 level: Level,
148 msg: &str,
149 span: $S::MultiSpan,
150 );
151 fn emit($self: $S::Diagnostic);
152 },
153 Span {
154 fn debug($self: $S::Span) -> String;
155 fn def_site() -> $S::Span;
156 fn call_site() -> $S::Span;
157 fn mixed_site() -> $S::Span;
158 fn source_file($self: $S::Span) -> $S::SourceFile;
159 fn parent($self: $S::Span) -> Option<$S::Span>;
160 fn source($self: $S::Span) -> $S::Span;
161 fn start($self: $S::Span) -> LineColumn;
162 fn end($self: $S::Span) -> LineColumn;
163 fn join($self: $S::Span, other: $S::Span) -> Option<$S::Span>;
164 fn resolved_at($self: $S::Span, at: $S::Span) -> $S::Span;
165 fn source_text($self: $S::Span) -> Option<String>;
166 },
167 }
168 };
169}
170
171// FIXME(eddyb) this calls `encode` for each argument, but in reverse,
172// to avoid borrow conflicts from borrows started by `&mut` arguments.
173macro_rules! reverse_encode {
174 ($writer:ident;) => {};
175 ($writer:ident; $first:ident $(, $rest:ident)*) => {
176 reverse_encode!($writer; $($rest),*);
177 $first.encode(&mut $writer, &mut ());
178 }
179}
180
181// FIXME(eddyb) this calls `decode` for each argument, but in reverse,
182// to avoid borrow conflicts from borrows started by `&mut` arguments.
183macro_rules! reverse_decode {
184 ($reader:ident, $s:ident;) => {};
185 ($reader:ident, $s:ident; $first:ident: $first_ty:ty $(, $rest:ident: $rest_ty:ty)*) => {
186 reverse_decode!($reader, $s; $($rest: $rest_ty),*);
187 let $first = <$first_ty>::decode(&mut $reader, $s);
188 }
189}
190
191#[allow(unsafe_code)]
192mod buffer;
193#[forbid(unsafe_code)]
194pub mod client;
195#[allow(unsafe_code)]
196mod closure;
197#[forbid(unsafe_code)]
198mod handle;
199#[macro_use]
200#[forbid(unsafe_code)]
201mod rpc;
202#[allow(unsafe_code)]
203mod scoped_cell;
204#[forbid(unsafe_code)]
205pub mod server;
206
207use buffer::Buffer;
208pub use rpc::PanicMessage;
209use rpc::{Decode, DecodeMut, Encode, Reader, Writer};
210
211/// An active connection between a server and a client.
212/// The server creates the bridge (`Bridge::run_server` in `server.rs`),
213/// then passes it to the client through the function pointer in the `run`
214/// field of `client::Client`. The client holds its copy of the `Bridge`
215/// in TLS during its execution (`Bridge::{enter, with}` in `client.rs`).
216#[repr(C)]
217pub struct Bridge<'a> {
218 /// Reusable buffer (only `clear`-ed, never shrunk), primarily
219 /// used for making requests, but also for passing input to client.
220 cached_buffer: Buffer<u8>,
221
222 /// Server-side function that the client uses to make requests.
223 dispatch: closure::Closure<'a, Buffer<u8>, Buffer<u8>>,
224}
225
226// impl<'a> !Sync for Bridge<'a> {}
227// impl<'a> !Send for Bridge<'a> {}
228
229#[forbid(unsafe_code)]
230#[allow(non_camel_case_types)]
231mod api_tags {
232 use super::rpc::{DecodeMut, Encode, Reader, Writer};
233
234 macro_rules! declare_tags {
235 ($($name:ident {
236 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)*
237 }),* $(,)?) => {
238 $(
239 pub(super) enum $name {
240 $($method),*
241 }
242 rpc_encode_decode!(enum $name { $($method),* });
243 )*
244
245
246 pub(super) enum Method {
247 $($name($name)),*
248 }
249 rpc_encode_decode!(enum Method { $($name(m)),* });
250 }
251 }
252 with_api!(self, self, declare_tags);
253}
254
255/// Helper to wrap associated types to allow trait impl dispatch.
256/// That is, normally a pair of impls for `T::Foo` and `T::Bar`
257/// can overlap, but if the impls are, instead, on types like
258/// `Marked<T::Foo, Foo>` and `Marked<T::Bar, Bar>`, they can't.
259trait Mark {
260 type Unmarked;
261 fn mark(unmarked: Self::Unmarked) -> Self;
262}
263
264/// Unwrap types wrapped by `Mark::mark` (see `Mark` for details).
265trait Unmark {
266 type Unmarked;
267 fn unmark(self) -> Self::Unmarked;
268}
269
270#[derive(Copy, Clone, PartialEq, Eq, Hash)]
271struct Marked<T, M> {
272 value: T,
273 _marker: marker::PhantomData<M>,
274}
275
276impl<T, M> Mark for Marked<T, M> {
277 type Unmarked = T;
278 fn mark(unmarked: Self::Unmarked) -> Self {
279 Marked { value: unmarked, _marker: marker::PhantomData }
280 }
281}
282impl<T, M> Unmark for Marked<T, M> {
283 type Unmarked = T;
284 fn unmark(self) -> Self::Unmarked {
285 self.value
286 }
287}
288impl<'a, T, M> Unmark for &'a Marked<T, M> {
289 type Unmarked = &'a T;
290 fn unmark(self) -> Self::Unmarked {
291 &self.value
292 }
293}
294impl<'a, T, M> Unmark for &'a mut Marked<T, M> {
295 type Unmarked = &'a mut T;
296 fn unmark(self) -> Self::Unmarked {
297 &mut self.value
298 }
299}
300
301impl<T: Mark> Mark for Option<T> {
302 type Unmarked = Option<T::Unmarked>;
303 fn mark(unmarked: Self::Unmarked) -> Self {
304 unmarked.map(T::mark)
305 }
306}
307impl<T: Unmark> Unmark for Option<T> {
308 type Unmarked = Option<T::Unmarked>;
309 fn unmark(self) -> Self::Unmarked {
310 self.map(T::unmark)
311 }
312}
313
314macro_rules! mark_noop {
315 ($($ty:ty),* $(,)?) => {
316 $(
317 impl Mark for $ty {
318 type Unmarked = Self;
319 fn mark(unmarked: Self::Unmarked) -> Self {
320 unmarked
321 }
322 }
323 impl Unmark for $ty {
324 type Unmarked = Self;
325 fn unmark(self) -> Self::Unmarked {
326 self
327 }
328 }
329 )*
330 }
331}
332mark_noop! {
333 (),
334 bool,
335 char,
336 &'_ [u8],
337 &'_ str,
338 String,
339 Delimiter,
340 Level,
341 LineColumn,
342 Spacing,
343 Bound<usize>,
344}
345
346rpc_encode_decode!(
347 enum Delimiter {
348 Parenthesis,
349 Brace,
350 Bracket,
351 None,
352 }
353);
354rpc_encode_decode!(
355 enum Level {
356 Error,
357 Warning,
358 Note,
359 Help,
360 }
361);
362rpc_encode_decode!(struct LineColumn { line, column });
363rpc_encode_decode!(
364 enum Spacing {
365 Alone,
366 Joint,
367 }
368);
369
370#[derive(Clone)]
371pub enum TokenTree<G, P, I, L> {
372 Group(G),
373 Punct(P),
374 Ident(I),
375 Literal(L),
376}
377
378impl<G: Mark, P: Mark, I: Mark, L: Mark> Mark for TokenTree<G, P, I, L> {
379 type Unmarked = TokenTree<G::Unmarked, P::Unmarked, I::Unmarked, L::Unmarked>;
380 fn mark(unmarked: Self::Unmarked) -> Self {
381 match unmarked {
382 TokenTree::Group(tt) => TokenTree::Group(G::mark(tt)),
383 TokenTree::Punct(tt) => TokenTree::Punct(P::mark(tt)),
384 TokenTree::Ident(tt) => TokenTree::Ident(I::mark(tt)),
385 TokenTree::Literal(tt) => TokenTree::Literal(L::mark(tt)),
386 }
387 }
388}
389impl<G: Unmark, P: Unmark, I: Unmark, L: Unmark> Unmark for TokenTree<G, P, I, L> {
390 type Unmarked = TokenTree<G::Unmarked, P::Unmarked, I::Unmarked, L::Unmarked>;
391 fn unmark(self) -> Self::Unmarked {
392 match self {
393 TokenTree::Group(tt) => TokenTree::Group(tt.unmark()),
394 TokenTree::Punct(tt) => TokenTree::Punct(tt.unmark()),
395 TokenTree::Ident(tt) => TokenTree::Ident(tt.unmark()),
396 TokenTree::Literal(tt) => TokenTree::Literal(tt.unmark()),
397 }
398 }
399}
400
401rpc_encode_decode!(
402 enum TokenTree<G, P, I, L> {
403 Group(tt),
404 Punct(tt),
405 Ident(tt),
406 Literal(tt),
407 }
408);
diff --git a/crates/ra_proc_macro_srv/src/proc_macro/bridge/rpc.rs b/crates/ra_proc_macro_srv/src/proc_macro/bridge/rpc.rs
deleted file mode 100644
index 3528d5c99..000000000
--- a/crates/ra_proc_macro_srv/src/proc_macro/bridge/rpc.rs
+++ /dev/null
@@ -1,311 +0,0 @@
1//! lib-proc-macro Serialization for client-server communication.
2//!
3//! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/rpc.rs
4//! augmented with removing unstable features
5//!
6//! Serialization for client-server communication.
7
8use std::any::Any;
9use std::char;
10use std::io::Write;
11use std::num::NonZeroU32;
12use std::ops::Bound;
13use std::str;
14
15pub(super) type Writer = super::buffer::Buffer<u8>;
16
17pub(super) trait Encode<S>: Sized {
18 fn encode(self, w: &mut Writer, s: &mut S);
19}
20
21pub(super) type Reader<'a> = &'a [u8];
22
23pub(super) trait Decode<'a, 's, S>: Sized {
24 fn decode(r: &mut Reader<'a>, s: &'s S) -> Self;
25}
26
27pub(super) trait DecodeMut<'a, 's, S>: Sized {
28 fn decode(r: &mut Reader<'a>, s: &'s mut S) -> Self;
29}
30
31macro_rules! rpc_encode_decode {
32 (le $ty:ty) => {
33 impl<S> Encode<S> for $ty {
34 fn encode(self, w: &mut Writer, _: &mut S) {
35 w.write_all(&self.to_le_bytes()).unwrap();
36 }
37 }
38
39 impl<S> DecodeMut<'_, '_, S> for $ty {
40 fn decode(r: &mut Reader<'_>, _: &mut S) -> Self {
41 const N: usize = ::std::mem::size_of::<$ty>();
42
43 let mut bytes = [0; N];
44 bytes.copy_from_slice(&r[..N]);
45 *r = &r[N..];
46
47 Self::from_le_bytes(bytes)
48 }
49 }
50 };
51 (struct $name:ident { $($field:ident),* $(,)? }) => {
52 impl<S> Encode<S> for $name {
53 fn encode(self, w: &mut Writer, s: &mut S) {
54 $(self.$field.encode(w, s);)*
55 }
56 }
57
58 impl<S> DecodeMut<'_, '_, S> for $name {
59 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
60 $name {
61 $($field: DecodeMut::decode(r, s)),*
62 }
63 }
64 }
65 };
66 (enum $name:ident $(<$($T:ident),+>)? { $($variant:ident $(($field:ident))*),* $(,)? }) => {
67 impl<S, $($($T: Encode<S>),+)?> Encode<S> for $name $(<$($T),+>)? {
68 fn encode(self, w: &mut Writer, s: &mut S) {
69 // HACK(eddyb): `Tag` enum duplicated between the
70 // two impls as there's no other place to stash it.
71 #[allow(non_upper_case_globals)]
72 mod tag {
73 #[repr(u8)] enum Tag { $($variant),* }
74
75 $(pub const $variant: u8 = Tag::$variant as u8;)*
76 }
77
78 match self {
79 $($name::$variant $(($field))* => {
80 tag::$variant.encode(w, s);
81 $($field.encode(w, s);)*
82 })*
83 }
84 }
85 }
86
87 impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S>
88 for $name $(<$($T),+>)?
89 {
90 fn decode(r: &mut Reader<'a>, s: &mut S) -> Self {
91 // HACK(eddyb): `Tag` enum duplicated between the
92 // two impls as there's no other place to stash it.
93 #[allow(non_upper_case_globals)]
94 mod tag {
95 #[repr(u8)] enum Tag { $($variant),* }
96
97 $(pub const $variant: u8 = Tag::$variant as u8;)*
98 }
99
100 match u8::decode(r, s) {
101 $(tag::$variant => {
102 $(let $field = DecodeMut::decode(r, s);)*
103 $name::$variant $(($field))*
104 })*
105 _ => unreachable!(),
106 }
107 }
108 }
109 }
110}
111
112impl<S> Encode<S> for () {
113 fn encode(self, _: &mut Writer, _: &mut S) {}
114}
115
116impl<S> DecodeMut<'_, '_, S> for () {
117 fn decode(_: &mut Reader<'_>, _: &mut S) -> Self {}
118}
119
120impl<S> Encode<S> for u8 {
121 fn encode(self, w: &mut Writer, _: &mut S) {
122 w.write_all(&[self]).unwrap();
123 }
124}
125
126impl<S> DecodeMut<'_, '_, S> for u8 {
127 fn decode(r: &mut Reader<'_>, _: &mut S) -> Self {
128 let x = r[0];
129 *r = &r[1..];
130 x
131 }
132}
133
134rpc_encode_decode!(le u32);
135rpc_encode_decode!(le usize);
136
137impl<S> Encode<S> for bool {
138 fn encode(self, w: &mut Writer, s: &mut S) {
139 (self as u8).encode(w, s);
140 }
141}
142
143impl<S> DecodeMut<'_, '_, S> for bool {
144 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
145 match u8::decode(r, s) {
146 0 => false,
147 1 => true,
148 _ => unreachable!(),
149 }
150 }
151}
152
153impl<S> Encode<S> for char {
154 fn encode(self, w: &mut Writer, s: &mut S) {
155 (self as u32).encode(w, s);
156 }
157}
158
159impl<S> DecodeMut<'_, '_, S> for char {
160 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
161 char::from_u32(u32::decode(r, s)).unwrap()
162 }
163}
164
165impl<S> Encode<S> for NonZeroU32 {
166 fn encode(self, w: &mut Writer, s: &mut S) {
167 self.get().encode(w, s);
168 }
169}
170
171impl<S> DecodeMut<'_, '_, S> for NonZeroU32 {
172 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
173 Self::new(u32::decode(r, s)).unwrap()
174 }
175}
176
177impl<S, A: Encode<S>, B: Encode<S>> Encode<S> for (A, B) {
178 fn encode(self, w: &mut Writer, s: &mut S) {
179 self.0.encode(w, s);
180 self.1.encode(w, s);
181 }
182}
183
184impl<'a, S, A: for<'s> DecodeMut<'a, 's, S>, B: for<'s> DecodeMut<'a, 's, S>> DecodeMut<'a, '_, S>
185 for (A, B)
186{
187 fn decode(r: &mut Reader<'a>, s: &mut S) -> Self {
188 (DecodeMut::decode(r, s), DecodeMut::decode(r, s))
189 }
190}
191
192rpc_encode_decode!(
193 enum Bound<T> {
194 Included(x),
195 Excluded(x),
196 Unbounded,
197 }
198);
199
200rpc_encode_decode!(
201 enum Option<T> {
202 None,
203 Some(x),
204 }
205);
206
207rpc_encode_decode!(
208 enum Result<T, E> {
209 Ok(x),
210 Err(e),
211 }
212);
213
214impl<S> Encode<S> for &[u8] {
215 fn encode(self, w: &mut Writer, s: &mut S) {
216 self.len().encode(w, s);
217 w.write_all(self).unwrap();
218 }
219}
220
221impl<'a, S> DecodeMut<'a, '_, S> for &'a [u8] {
222 fn decode(r: &mut Reader<'a>, s: &mut S) -> Self {
223 let len = usize::decode(r, s);
224 let xs = &r[..len];
225 *r = &r[len..];
226 xs
227 }
228}
229
230impl<S> Encode<S> for &str {
231 fn encode(self, w: &mut Writer, s: &mut S) {
232 self.as_bytes().encode(w, s);
233 }
234}
235
236impl<'a, S> DecodeMut<'a, '_, S> for &'a str {
237 fn decode(r: &mut Reader<'a>, s: &mut S) -> Self {
238 str::from_utf8(<&[u8]>::decode(r, s)).unwrap()
239 }
240}
241
242impl<S> Encode<S> for String {
243 fn encode(self, w: &mut Writer, s: &mut S) {
244 self[..].encode(w, s);
245 }
246}
247
248impl<S> DecodeMut<'_, '_, S> for String {
249 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
250 <&str>::decode(r, s).to_string()
251 }
252}
253
254/// Simplied version of panic payloads, ignoring
255/// types other than `&'static str` and `String`.
256#[derive(Debug)]
257pub enum PanicMessage {
258 StaticStr(&'static str),
259 String(String),
260 Unknown,
261}
262
263impl From<Box<dyn Any + Send>> for PanicMessage {
264 fn from(payload: Box<dyn Any + Send + 'static>) -> Self {
265 if let Some(s) = payload.downcast_ref::<&'static str>() {
266 return PanicMessage::StaticStr(s);
267 }
268 if let Ok(s) = payload.downcast::<String>() {
269 return PanicMessage::String(*s);
270 }
271 PanicMessage::Unknown
272 }
273}
274
275impl Into<Box<dyn Any + Send>> for PanicMessage {
276 fn into(self) -> Box<dyn Any + Send> {
277 match self {
278 PanicMessage::StaticStr(s) => Box::new(s),
279 PanicMessage::String(s) => Box::new(s),
280 PanicMessage::Unknown => {
281 struct UnknownPanicMessage;
282 Box::new(UnknownPanicMessage)
283 }
284 }
285 }
286}
287
288impl PanicMessage {
289 pub fn as_str(&self) -> Option<&str> {
290 match self {
291 PanicMessage::StaticStr(s) => Some(s),
292 PanicMessage::String(s) => Some(s),
293 PanicMessage::Unknown => None,
294 }
295 }
296}
297
298impl<S> Encode<S> for PanicMessage {
299 fn encode(self, w: &mut Writer, s: &mut S) {
300 self.as_str().encode(w, s);
301 }
302}
303
304impl<S> DecodeMut<'_, '_, S> for PanicMessage {
305 fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
306 match Option::<String>::decode(r, s) {
307 Some(s) => PanicMessage::String(s),
308 None => PanicMessage::Unknown,
309 }
310 }
311}
diff --git a/crates/ra_proc_macro_srv/src/proc_macro/bridge/scoped_cell.rs b/crates/ra_proc_macro_srv/src/proc_macro/bridge/scoped_cell.rs
deleted file mode 100644
index 6ef7ea43c..000000000
--- a/crates/ra_proc_macro_srv/src/proc_macro/bridge/scoped_cell.rs
+++ /dev/null
@@ -1,84 +0,0 @@
1//! lib-proc-macro `Cell` variant for (scoped) existential lifetimes.
2//!
3//! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/scoped_cell.rs#L1
4//! augmented with removing unstable features
5
6use std::cell::Cell;
7use std::mem;
8use std::ops::{Deref, DerefMut};
9
10/// Type lambda application, with a lifetime.
11#[allow(unused_lifetimes)]
12pub trait ApplyL<'a> {
13 type Out;
14}
15
16/// Type lambda taking a lifetime, i.e., `Lifetime -> Type`.
17pub trait LambdaL: for<'a> ApplyL<'a> {}
18
19impl<T: for<'a> ApplyL<'a>> LambdaL for T {}
20
21// HACK(eddyb) work around projection limitations with a newtype
22// FIXME(#52812) replace with `&'a mut <T as ApplyL<'b>>::Out`
23pub struct RefMutL<'a, 'b, T: LambdaL>(&'a mut <T as ApplyL<'b>>::Out);
24
25impl<'a, 'b, T: LambdaL> Deref for RefMutL<'a, 'b, T> {
26 type Target = <T as ApplyL<'b>>::Out;
27 fn deref(&self) -> &Self::Target {
28 self.0
29 }
30}
31
32impl<'a, 'b, T: LambdaL> DerefMut for RefMutL<'a, 'b, T> {
33 fn deref_mut(&mut self) -> &mut Self::Target {
34 self.0
35 }
36}
37
38pub struct ScopedCell<T: LambdaL>(Cell<<T as ApplyL<'static>>::Out>);
39
40impl<T: LambdaL> ScopedCell<T> {
41 pub fn new(value: <T as ApplyL<'static>>::Out) -> Self {
42 ScopedCell(Cell::new(value))
43 }
44
45 /// Sets the value in `self` to `replacement` while
46 /// running `f`, which gets the old value, mutably.
47 /// The old value will be restored after `f` exits, even
48 /// by panic, including modifications made to it by `f`.
49 pub fn replace<'a, R>(
50 &self,
51 replacement: <T as ApplyL<'a>>::Out,
52 f: impl for<'b, 'c> FnOnce(RefMutL<'b, 'c, T>) -> R,
53 ) -> R {
54 /// Wrapper that ensures that the cell always gets filled
55 /// (with the original state, optionally changed by `f`),
56 /// even if `f` had panicked.
57 struct PutBackOnDrop<'a, T: LambdaL> {
58 cell: &'a ScopedCell<T>,
59 value: Option<<T as ApplyL<'static>>::Out>,
60 }
61
62 impl<'a, T: LambdaL> Drop for PutBackOnDrop<'a, T> {
63 fn drop(&mut self) {
64 self.cell.0.set(self.value.take().unwrap());
65 }
66 }
67
68 let mut put_back_on_drop = PutBackOnDrop {
69 cell: self,
70 value: Some(self.0.replace(unsafe {
71 let erased = mem::transmute_copy(&replacement);
72 mem::forget(replacement);
73 erased
74 })),
75 };
76
77 f(RefMutL(put_back_on_drop.value.as_mut().unwrap()))
78 }
79
80 /// Sets the value in `self` to `value` while running `f`.
81 pub fn set<R>(&self, value: <T as ApplyL<'_>>::Out, f: impl FnOnce() -> R) -> R {
82 self.replace(value, |_| f())
83 }
84}
diff --git a/crates/ra_proc_macro_srv/src/proc_macro/bridge/server.rs b/crates/ra_proc_macro_srv/src/proc_macro/bridge/server.rs
deleted file mode 100644
index 45d41ac02..000000000
--- a/crates/ra_proc_macro_srv/src/proc_macro/bridge/server.rs
+++ /dev/null
@@ -1,323 +0,0 @@
1//! lib-proc-macro server-side traits
2//!
3//! Copy from https://github.com/rust-lang/rust/blob/6050e523bae6de61de4e060facc43dc512adaccd/src/libproc_macro/bridge/server.rs
4//! augmented with removing unstable features
5
6use super::*;
7
8// FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
9use super::client::HandleStore;
10
11/// Declare an associated item of one of the traits below, optionally
12/// adjusting it (i.e., adding bounds to types and default bodies to methods).
13macro_rules! associated_item {
14 (type TokenStream) =>
15 (type TokenStream: 'static + Clone;);
16 (type TokenStreamBuilder) =>
17 (type TokenStreamBuilder: 'static;);
18 (type TokenStreamIter) =>
19 (type TokenStreamIter: 'static + Clone;);
20 (type Group) =>
21 (type Group: 'static + Clone;);
22 (type Punct) =>
23 (type Punct: 'static + Copy + Eq + Hash;);
24 (type Ident) =>
25 (type Ident: 'static + Copy + Eq + Hash;);
26 (type Literal) =>
27 (type Literal: 'static + Clone;);
28 (type SourceFile) =>
29 (type SourceFile: 'static + Clone;);
30 (type MultiSpan) =>
31 (type MultiSpan: 'static;);
32 (type Diagnostic) =>
33 (type Diagnostic: 'static;);
34 (type Span) =>
35 (type Span: 'static + Copy + Eq + Hash;);
36 (fn drop(&mut self, $arg:ident: $arg_ty:ty)) =>
37 (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) });
38 (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) =>
39 (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() });
40 ($($item:tt)*) => ($($item)*;)
41}
42
43macro_rules! declare_server_traits {
44 ($($name:ident {
45 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
46 }),* $(,)?) => {
47 pub trait Types {
48 $(associated_item!(type $name);)*
49 }
50
51 $(pub trait $name: Types {
52 $(associated_item!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
53 })*
54
55 pub trait Server: Types $(+ $name)* {}
56 impl<S: Types $(+ $name)*> Server for S {}
57 }
58}
59with_api!(Self, self_, declare_server_traits);
60
61pub(super) struct MarkedTypes<S: Types>(S);
62
63macro_rules! define_mark_types_impls {
64 ($($name:ident {
65 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
66 }),* $(,)?) => {
67 impl<S: Types> Types for MarkedTypes<S> {
68 $(type $name = Marked<S::$name, client::$name>;)*
69 }
70
71 $(impl<S: $name> $name for MarkedTypes<S> {
72 $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? {
73 <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*))
74 })*
75 })*
76 }
77}
78with_api!(Self, self_, define_mark_types_impls);
79
80struct Dispatcher<S: Types> {
81 handle_store: HandleStore<S>,
82 server: S,
83}
84
85macro_rules! define_dispatcher_impl {
86 ($($name:ident {
87 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
88 }),* $(,)?) => {
89 // FIXME(eddyb) `pub` only for `ExecutionStrategy` below.
90 pub trait DispatcherTrait {
91 // HACK(eddyb) these are here to allow `Self::$name` to work below.
92 $(type $name;)*
93 fn dispatch(&mut self, b: Buffer<u8>) -> Buffer<u8>;
94 }
95
96 impl<S: Server> DispatcherTrait for Dispatcher<MarkedTypes<S>> {
97 $(type $name = <MarkedTypes<S> as Types>::$name;)*
98 fn dispatch(&mut self, mut b: Buffer<u8>) -> Buffer<u8> {
99 let Dispatcher { handle_store, server } = self;
100
101 let mut reader = &b[..];
102 match api_tags::Method::decode(&mut reader, &mut ()) {
103 $(api_tags::Method::$name(m) => match m {
104 $(api_tags::$name::$method => {
105 let mut call_method = || {
106 reverse_decode!(reader, handle_store; $($arg: $arg_ty),*);
107 $name::$method(server, $($arg),*)
108 };
109 // HACK(eddyb) don't use `panic::catch_unwind` in a panic.
110 // If client and server happen to use the same `libstd`,
111 // `catch_unwind` asserts that the panic counter was 0,
112 // even when the closure passed to it didn't panic.
113 let r = if thread::panicking() {
114 Ok(call_method())
115 } else {
116 panic::catch_unwind(panic::AssertUnwindSafe(call_method))
117 .map_err(PanicMessage::from)
118 };
119
120 b.clear();
121 r.encode(&mut b, handle_store);
122 })*
123 }),*
124 }
125 b
126 }
127 }
128 }
129}
130with_api!(Self, self_, define_dispatcher_impl);
131
132pub trait ExecutionStrategy {
133 fn run_bridge_and_client<D: Copy + Send + 'static>(
134 &self,
135 dispatcher: &mut impl DispatcherTrait,
136 input: Buffer<u8>,
137 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
138 client_data: D,
139 ) -> Buffer<u8>;
140}
141
142pub struct SameThread;
143
144impl ExecutionStrategy for SameThread {
145 fn run_bridge_and_client<D: Copy + Send + 'static>(
146 &self,
147 dispatcher: &mut impl DispatcherTrait,
148 input: Buffer<u8>,
149 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
150 client_data: D,
151 ) -> Buffer<u8> {
152 let mut dispatch = |b| dispatcher.dispatch(b);
153
154 run_client(Bridge { cached_buffer: input, dispatch: (&mut dispatch).into() }, client_data)
155 }
156}
157
158// NOTE(eddyb) Two implementations are provided, the second one is a bit
159// faster but neither is anywhere near as fast as same-thread execution.
160
161pub struct CrossThread1;
162
163impl ExecutionStrategy for CrossThread1 {
164 fn run_bridge_and_client<D: Copy + Send + 'static>(
165 &self,
166 dispatcher: &mut impl DispatcherTrait,
167 input: Buffer<u8>,
168 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
169 client_data: D,
170 ) -> Buffer<u8> {
171 use std::sync::mpsc::channel;
172
173 let (req_tx, req_rx) = channel();
174 let (res_tx, res_rx) = channel();
175
176 let join_handle = thread::spawn(move || {
177 let mut dispatch = |b| {
178 req_tx.send(b).unwrap();
179 res_rx.recv().unwrap()
180 };
181
182 run_client(
183 Bridge { cached_buffer: input, dispatch: (&mut dispatch).into() },
184 client_data,
185 )
186 });
187
188 for b in req_rx {
189 res_tx.send(dispatcher.dispatch(b)).unwrap();
190 }
191
192 join_handle.join().unwrap()
193 }
194}
195
196pub struct CrossThread2;
197
198impl ExecutionStrategy for CrossThread2 {
199 fn run_bridge_and_client<D: Copy + Send + 'static>(
200 &self,
201 dispatcher: &mut impl DispatcherTrait,
202 input: Buffer<u8>,
203 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
204 client_data: D,
205 ) -> Buffer<u8> {
206 use std::sync::{Arc, Mutex};
207
208 enum State<T> {
209 Req(T),
210 Res(T),
211 }
212
213 let mut state = Arc::new(Mutex::new(State::Res(Buffer::new())));
214
215 let server_thread = thread::current();
216 let state2 = state.clone();
217 let join_handle = thread::spawn(move || {
218 let mut dispatch = |b| {
219 *state2.lock().unwrap() = State::Req(b);
220 server_thread.unpark();
221 loop {
222 thread::park();
223 if let State::Res(b) = &mut *state2.lock().unwrap() {
224 break b.take();
225 }
226 }
227 };
228
229 let r = run_client(
230 Bridge { cached_buffer: input, dispatch: (&mut dispatch).into() },
231 client_data,
232 );
233
234 // Wake up the server so it can exit the dispatch loop.
235 drop(state2);
236 server_thread.unpark();
237
238 r
239 });
240
241 // Check whether `state2` was dropped, to know when to stop.
242 while Arc::get_mut(&mut state).is_none() {
243 thread::park();
244 let mut b = match &mut *state.lock().unwrap() {
245 State::Req(b) => b.take(),
246 _ => continue,
247 };
248 b = dispatcher.dispatch(b.take());
249 *state.lock().unwrap() = State::Res(b);
250 join_handle.thread().unpark();
251 }
252
253 join_handle.join().unwrap()
254 }
255}
256
257fn run_server<
258 S: Server,
259 I: Encode<HandleStore<MarkedTypes<S>>>,
260 O: for<'a, 's> DecodeMut<'a, 's, HandleStore<MarkedTypes<S>>>,
261 D: Copy + Send + 'static,
262>(
263 strategy: &impl ExecutionStrategy,
264 handle_counters: &'static client::HandleCounters,
265 server: S,
266 input: I,
267 run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
268 client_data: D,
269) -> Result<O, PanicMessage> {
270 let mut dispatcher =
271 Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) };
272
273 let mut b = Buffer::new();
274 input.encode(&mut b, &mut dispatcher.handle_store);
275
276 b = strategy.run_bridge_and_client(&mut dispatcher, b, run_client, client_data);
277
278 Result::decode(&mut &b[..], &mut dispatcher.handle_store)
279}
280
281impl client::Client<fn(crate::TokenStream) -> crate::TokenStream> {
282 pub fn run<S: Server>(
283 &self,
284 strategy: &impl ExecutionStrategy,
285 server: S,
286 input: S::TokenStream,
287 ) -> Result<S::TokenStream, PanicMessage> {
288 let client::Client { get_handle_counters, run, f } = *self;
289 run_server(
290 strategy,
291 get_handle_counters(),
292 server,
293 <MarkedTypes<S> as Types>::TokenStream::mark(input),
294 run,
295 f,
296 )
297 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
298 }
299}
300
301impl client::Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
302 pub fn run<S: Server>(
303 &self,
304 strategy: &impl ExecutionStrategy,
305 server: S,
306 input: S::TokenStream,
307 input2: S::TokenStream,
308 ) -> Result<S::TokenStream, PanicMessage> {
309 let client::Client { get_handle_counters, run, f } = *self;
310 run_server(
311 strategy,
312 get_handle_counters(),
313 server,
314 (
315 <MarkedTypes<S> as Types>::TokenStream::mark(input),
316 <MarkedTypes<S> as Types>::TokenStream::mark(input2),
317 ),
318 run,
319 f,
320 )
321 .map(<MarkedTypes<S> as Types>::TokenStream::unmark)
322 }
323}