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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! 客户端类型。

use super::*;

use std::marker::PhantomData;

macro_rules! define_handles {
    (
        'owned: $($oty:ident,)*
        'interned: $($ity:ident,)*
    ) => {
        #[repr(C)]
        #[allow(non_snake_case)]
        pub struct HandleCounters {
            $($oty: AtomicUsize,)*
            $($ity: AtomicUsize,)*
        }

        impl HandleCounters {
            // FIXME(eddyb) 使用对 `static COUNTERS` 的引用,而不是包装器 `fn` 指针,一旦 `const fn` 可以引用 `static`s。
            //
            extern "C" fn get() -> &'static Self {
                static COUNTERS: HandleCounters = HandleCounters {
                    $($oty: AtomicUsize::new(1),)*
                    $($ity: AtomicUsize::new(1),)*
                };
                &COUNTERS
            }
        }

        // FIXME(eddyb) 在 `server.rs` 中生成 `HandleStore` 的定义。
        #[allow(non_snake_case)]
        pub(super) struct HandleStore<S: server::Types> {
            $($oty: handle::OwnedStore<S::$oty>,)*
            $($ity: handle::InternedStore<S::$ity>,)*
        }

        impl<S: server::Types> HandleStore<S> {
            pub(super) fn new(handle_counters: &'static HandleCounters) -> Self {
                HandleStore {
                    $($oty: handle::OwnedStore::new(&handle_counters.$oty),)*
                    $($ity: handle::InternedStore::new(&handle_counters.$ity),)*
                }
            }
        }

        $(
            pub(crate) struct $oty {
                handle: handle::Handle,
                // 防止发送和同步实现。
                // `!Send`/`!Sync` 是执行此操作的常用方式,但这需要不稳定的特性。
                // rust-analyzer 使用此代码并避免了不稳定的特性。
                _marker: PhantomData<*mut ()>,
            }

            // 将 `Drop::drop` 转发到固有的 `drop` 方法。
            impl Drop for $oty {
                fn drop(&mut self) {
                    $oty {
                        handle: self.handle,
                        _marker: PhantomData,
                    }.drop();
                }
            }

            impl<S> Encode<S> for $oty {
                fn encode(self, w: &mut Writer, s: &mut S) {
                    let handle = self.handle;
                    mem::forget(self);
                    handle.encode(w, s);
                }
            }

            impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
                for Marked<S::$oty, $oty>
            {
                fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
                    s.$oty.take(handle::Handle::decode(r, &mut ()))
                }
            }

            impl<S> Encode<S> for &$oty {
                fn encode(self, w: &mut Writer, s: &mut S) {
                    self.handle.encode(w, s);
                }
            }

            impl<'s, S: server::Types> Decode<'_, 's, HandleStore<server::MarkedTypes<S>>>
                for &'s Marked<S::$oty, $oty>
            {
                fn decode(r: &mut Reader<'_>, s: &'s HandleStore<server::MarkedTypes<S>>) -> Self {
                    &s.$oty[handle::Handle::decode(r, &mut ())]
                }
            }

            impl<S> Encode<S> for &mut $oty {
                fn encode(self, w: &mut Writer, s: &mut S) {
                    self.handle.encode(w, s);
                }
            }

            impl<'s, S: server::Types> DecodeMut<'_, 's, HandleStore<server::MarkedTypes<S>>>
                for &'s mut Marked<S::$oty, $oty>
            {
                fn decode(
                    r: &mut Reader<'_>,
                    s: &'s mut HandleStore<server::MarkedTypes<S>>
                ) -> Self {
                    &mut s.$oty[handle::Handle::decode(r, &mut ())]
                }
            }

            impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
                for Marked<S::$oty, $oty>
            {
                fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
                    s.$oty.alloc(self).encode(w, s);
                }
            }

            impl<S> DecodeMut<'_, '_, S> for $oty {
                fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
                    $oty {
                        handle: handle::Handle::decode(r, s),
                        _marker: PhantomData,
                    }
                }
            }
        )*

        $(
            #[derive(Copy, Clone, PartialEq, Eq, Hash)]
            pub(crate) struct $ity {
                handle: handle::Handle,
                // 防止发送和同步实现。
                // `!Send`/`!Sync` 是执行此操作的常用方式,但这需要不稳定的特性。
                // rust-analyzer 使用此代码并避免了不稳定的特性。
                _marker: PhantomData<*mut ()>,
            }

            impl<S> Encode<S> for $ity {
                fn encode(self, w: &mut Writer, s: &mut S) {
                    self.handle.encode(w, s);
                }
            }

            impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>>
                for Marked<S::$ity, $ity>
            {
                fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self {
                    s.$ity.copy(handle::Handle::decode(r, &mut ()))
                }
            }

            impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>>
                for Marked<S::$ity, $ity>
            {
                fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) {
                    s.$ity.alloc(self).encode(w, s);
                }
            }

            impl<S> DecodeMut<'_, '_, S> for $ity {
                fn decode(r: &mut Reader<'_>, s: &mut S) -> Self {
                    $ity {
                        handle: handle::Handle::decode(r, s),
                        _marker: PhantomData,
                    }
                }
            }
        )*
    }
}
define_handles! {
    'owned:
    FreeFunctions,
    TokenStream,
    SourceFile,

    'interned:
    Span,
}

// FIXME(eddyb) 通过对方法名称进行模式匹配来生成这些实现 -- 也可以使用 `fn drop` 的存在来区分上面的 `owned` 和 `interned`。
//
// 或者,可以在 with_api 中列出特殊的 "modes" 类型,而不是在此处和服务器 decl 中对方法进行模式匹配。
//
//

impl Clone for TokenStream {
    fn clone(&self) -> Self {
        self.clone()
    }
}

impl Clone for SourceFile {
    fn clone(&self) -> Self {
        self.clone()
    }
}

impl Span {
    pub(crate) fn def_site() -> Span {
        Bridge::with(|bridge| bridge.globals.def_site)
    }

    pub(crate) fn call_site() -> Span {
        Bridge::with(|bridge| bridge.globals.call_site)
    }

    pub(crate) fn mixed_site() -> Span {
        Bridge::with(|bridge| bridge.globals.mixed_site)
    }
}

impl fmt::Debug for Span {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.debug())
    }
}

pub(crate) use super::symbol::Symbol;

macro_rules! define_client_side {
    ($($name:ident {
        $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
    }),* $(,)?) => {
        $(impl $name {
            $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)? {
                Bridge::with(|bridge| {
                    let mut buf = bridge.cached_buffer.take();

                    buf.clear();
                    api_tags::Method::$name(api_tags::$name::$method).encode(&mut buf, &mut ());
                    reverse_encode!(buf; $($arg),*);

                    buf = bridge.dispatch.call(buf);

                    let r = Result::<_, PanicMessage>::decode(&mut &buf[..], &mut ());

                    bridge.cached_buffer = buf;

                    r.unwrap_or_else(|e| panic::resume_unwind(e.into()))
                })
            })*
        })*
    }
}
with_api!(self, self, define_client_side);

struct Bridge<'a> {
    /// 可重复使用的缓冲区 (仅 `clear`-ed,从不缩小),主要用于发出请求。
    ///
    cached_buffer: Buffer,

    /// 客户端用来发出请求的服务器端函数。
    dispatch: closure::Closure<'a, Buffer, Buffer>,

    /// 为这个宏扩展提供了全局变量。
    globals: ExpnGlobals<Span>,
}

impl<'a> !Send for Bridge<'a> {}
impl<'a> !Sync for Bridge<'a> {}

enum BridgeState<'a> {
    /// 当前没有服务器连接到该客户端。
    NotConnected,

    /// 服务器已连接并且可用于请求。
    Connected(Bridge<'a>),

    /// 专门获取对网桥的访问权限 (例如,在 `BridgeState::with` 期间)。
    ///
    InUse,
}

enum BridgeStateL {}

impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL {
    type Out = BridgeState<'a>;
}

thread_local! {
    static BRIDGE_STATE: scoped_cell::ScopedCell<BridgeStateL> =
        scoped_cell::ScopedCell::new(BridgeState::NotConnected);
}

impl BridgeState<'_> {
    /// 独占控制线程本地的 `BridgeState`,并将其可变地传递给 `f`。
    /// `f` 退出后,甚至 panic 都将恢复状态,包括 `f` 对它的修改。
    ///
    ///
    /// 注意,在运行 `f` 时,线程本地状态为 `BridgeState::InUse`。
    ///
    ///
    fn with<R>(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R {
        BRIDGE_STATE.with(|state| {
            state.replace(BridgeState::InUse, |mut state| {
                // FIXME(#52812) 当 `RefMutL` 不存在时,直接将 `f` 传递给 `replace`
                f(&mut *state)
            })
        })
    }
}

impl Bridge<'_> {
    fn with<R>(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R {
        BridgeState::with(|state| match state {
            BridgeState::NotConnected => {
                panic!("procedural macro API is used outside of a procedural macro");
            }
            BridgeState::InUse => {
                panic!("procedural macro API is used while it's already in use");
            }
            BridgeState::Connected(bridge) => f(bridge),
        })
    }
}

pub(crate) fn is_available() -> bool {
    BridgeState::with(|state| match state {
        BridgeState::Connected(_) | BridgeState::InUse => true,
        BridgeState::NotConnected => false,
    })
}

/// 客户端 RPC 入口点,它可能使用与服务器使用的 `proc_macro` 不同的 `proc_macro`,但可以兼容地调用。
///
/// 注意,(phantom) `I` ("input") 和 `O` ("output") 类型参数用入口点的 RPC "interface" 装饰 `Client<I, O>`,但本身不参与 ABI,根本只方便类型检查。
///
/// E.g.
/// `Client<TokenStream, TokenStream>` 是常用的 proc 宏接口,用于 `#[proc_macro] fn foo(input: TokenStream) -> TokenStream`,表示 RPC 输入输出会序列化 token 流,强制使用 take/return `S::TokenStream`,server-side 的 API。
///
///
///
///
///
#[repr(C)]
pub struct Client<I, O> {
    // FIXME(eddyb) 使用对 `static COUNTERS` 的引用,而不是包装器 `fn` 指针,一旦 `const fn` 可以引用 `static`s。
    //
    pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters,

    pub(super) run: extern "C" fn(BridgeConfig<'_>) -> Buffer,

    pub(super) _marker: PhantomData<fn(I) -> O>,
}

impl<I, O> Copy for Client<I, O> {}
impl<I, O> Clone for Client<I, O> {
    fn clone(&self) -> Self {
        *self
    }
}

fn maybe_install_panic_hook(force_show_panics: bool) {
    // 隐藏 `proc_macro` 扩展中的默认 panic 输出。
    // NB. 服务器不能这样做,因为它可能使用不同的 std。
    static HIDE_PANICS_DURING_EXPANSION: Once = Once::new();
    HIDE_PANICS_DURING_EXPANSION.call_once(|| {
        let prev = panic::take_hook();
        panic::set_hook(Box::new(move |info| {
            let show = BridgeState::with(|state| match state {
                BridgeState::NotConnected => true,
                BridgeState::Connected(_) | BridgeState::InUse => force_show_panics,
            });
            if show {
                prev(info)
            }
        }));
    });
}

/// 客户端帮助程序,用于处理客户端 panics,进入网桥,反序列化输入和序列化输出。
///
// FIXME(eddyb) 可以用这个代替 `Bridge::enter` 吗?
fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>(
    config: BridgeConfig<'_>,
    f: impl FnOnce(A) -> R,
) -> Buffer {
    let BridgeConfig { input: mut buf, dispatch, force_show_panics, .. } = config;

    panic::catch_unwind(panic::AssertUnwindSafe(|| {
        maybe_install_panic_hook(force_show_panics);

        // 在解码输入之前确保符号存储为空。
        Symbol::invalidate_all();

        let reader = &mut &buf[..];
        let (globals, input) = <(ExpnGlobals<Span>, A)>::decode(reader, &mut ());

        // 将我们用于输入的缓冲区放回 `Bridge` 中用于请求。
        let new_state =
            BridgeState::Connected(Bridge { cached_buffer: buf.take(), dispatch, globals });

        BRIDGE_STATE.with(|state| {
            state.set(new_state, || {
                let output = f(input);

                // 取出 `cached_buffer` 作为输出值。
                buf = Bridge::with(|bridge| bridge.cached_buffer.take());

                // HACK(eddyb) 将成功值的编码 (`Ok(output)`) 与 panic 的编码 (`Err(e: PanicMessage)`) 分开,以避免句柄 `bridge.enter(|| ...)` 在作用域之外,并捕获在编码成功时可能发生的 panics。
                //
                // 请注意,在此之后 panics 应该是不可能的,但这是防御性地尝试避免任何意外的 panicking 到达 `extern "C"` (应该是 `abort`,但目前可能不会,因此这也可能会阻止 UB)。
                //
                //
                //
                //
                //
                //
                buf.clear();
                Ok::<_, ()>(output).encode(&mut buf, &mut ());
            })
        })
    }))
    .map_err(PanicMessage::from)
    .unwrap_or_else(|e| {
        buf.clear();
        Err::<(), _>(e).encode(&mut buf, &mut ());
    });

    // 现在响应已被序列化,使内部注册的所有符号无效。
    //
    Symbol::invalidate_all();
    buf
}

impl Client<crate::TokenStream, crate::TokenStream> {
    pub const fn expand1(f: impl Fn(crate::TokenStream) -> crate::TokenStream + Copy) -> Self {
        Client {
            get_handle_counters: HandleCounters::get,
            run: super::selfless_reify::reify_to_extern_c_fn_hrt_bridge(move |bridge| {
                run_client(bridge, |input| f(crate::TokenStream(Some(input))).0)
            }),
            _marker: PhantomData,
        }
    }
}

impl Client<(crate::TokenStream, crate::TokenStream), crate::TokenStream> {
    pub const fn expand2(
        f: impl Fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream + Copy,
    ) -> Self {
        Client {
            get_handle_counters: HandleCounters::get,
            run: super::selfless_reify::reify_to_extern_c_fn_hrt_bridge(move |bridge| {
                run_client(bridge, |(input, input2)| {
                    f(crate::TokenStream(Some(input)), crate::TokenStream(Some(input2))).0
                })
            }),
            _marker: PhantomData,
        }
    }
}

#[repr(C)]
#[derive(Copy, Clone)]
pub enum ProcMacro {
    CustomDerive {
        trait_name: &'static str,
        attributes: &'static [&'static str],
        client: Client<crate::TokenStream, crate::TokenStream>,
    },

    Attr {
        name: &'static str,
        client: Client<(crate::TokenStream, crate::TokenStream), crate::TokenStream>,
    },

    Bang {
        name: &'static str,
        client: Client<crate::TokenStream, crate::TokenStream>,
    },
}

impl ProcMacro {
    pub fn name(&self) -> &'static str {
        match self {
            ProcMacro::CustomDerive { trait_name, .. } => trait_name,
            ProcMacro::Attr { name, .. } => name,
            ProcMacro::Bang { name, .. } => name,
        }
    }

    pub const fn custom_derive(
        trait_name: &'static str,
        attributes: &'static [&'static str],
        expand: impl Fn(crate::TokenStream) -> crate::TokenStream + Copy,
    ) -> Self {
        ProcMacro::CustomDerive { trait_name, attributes, client: Client::expand1(expand) }
    }

    pub const fn attr(
        name: &'static str,
        expand: impl Fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream + Copy,
    ) -> Self {
        ProcMacro::Attr { name, client: Client::expand2(expand) }
    }

    pub const fn bang(
        name: &'static str,
        expand: impl Fn(crate::TokenStream) -> crate::TokenStream + Copy,
    ) -> Self {
        ProcMacro::Bang { name, client: Client::expand1(expand) }
    }
}