Skip to main content

proc_macro/bridge/
mod.rs

1//! Internal interface for communicating between a `proc_macro` client
2//! (a proc macro crate) and a `proc_macro` server (a compiler front-end).
3//!
4//! Serialization (with C ABI buffers) and unique integer handles are employed
5//! to allow safely interfacing between two copies of `proc_macro` built
6//! (from the same source) by different compilers with potentially mismatching
7//! Rust ABIs (e.g., stage0/bin/rustc vs stage1/bin/rustc during bootstrap).
8
9#![deny(unsafe_code)]
10
11use std::hash::Hash;
12use std::ops::{Bound, Range};
13use std::sync::Once;
14use std::{fmt, marker, mem, panic, thread};
15
16use crate::{Delimiter, Level};
17
18/// Higher-order macro describing the server RPC API, allowing automatic
19/// generation of type-safe Rust APIs, both client-side and server-side.
20///
21/// `with_api!(my_macro, MyTokenStream, MySpan, MySymbol)` expands to:
22/// ```rust,ignore (pseudo-code)
23/// my_macro! {
24///     fn ts_clone(stream: &MyTokenStream) -> MyTokenStream;
25///     fn span_debug(span: &MySpan) -> String;
26///     // ...
27/// }
28/// ```
29///
30/// The second (`TokenStream`), third (`Span`) and fourth (`Symbol`)
31/// argument serve to customize the argument/return types that need
32/// special handling, to enable several different representations of
33/// these types.
34macro_rules! with_api {
35    ($m:ident, $TokenStream: path, $Span: path, $Symbol: path) => {
36        $m! {
37            fn injected_env_var(var: &str) -> Option<String>;
38            fn track_env_var(var: &str, value: Option<&str>);
39            fn track_path(path: &str);
40            fn literal_from_str(s: &str) -> Result<Literal<$Span, $Symbol>, ()>;
41            fn emit_diagnostic(diagnostic: Diagnostic<$Span>);
42
43            fn ts_drop(stream: $TokenStream);
44            fn ts_clone(stream: &$TokenStream) -> $TokenStream;
45            fn ts_is_empty(stream: &$TokenStream) -> bool;
46            fn ts_expand_expr(stream: &$TokenStream) -> Result<$TokenStream, ()>;
47            fn ts_from_str(src: &str) -> $TokenStream;
48            fn ts_to_string(stream: &$TokenStream) -> String;
49            fn ts_from_token_tree(
50                tree: TokenTree<$TokenStream, $Span, $Symbol>,
51            ) -> $TokenStream;
52            fn ts_concat_trees(
53                base: Option<$TokenStream>,
54                trees: Vec<TokenTree<$TokenStream, $Span, $Symbol>>,
55            ) -> $TokenStream;
56            fn ts_concat_streams(
57                base: Option<$TokenStream>,
58                streams: Vec<$TokenStream>,
59            ) -> $TokenStream;
60            fn ts_into_trees(
61                stream: $TokenStream
62            ) -> Vec<TokenTree<$TokenStream, $Span, $Symbol>>;
63
64            fn span_debug(span: $Span) -> String;
65            fn span_parent(span: $Span) -> Option<$Span>;
66            fn span_source(span: $Span) -> $Span;
67            fn span_byte_range(span: $Span) -> Range<usize>;
68            fn span_start(span: $Span) -> $Span;
69            fn span_end(span: $Span) -> $Span;
70            fn span_line(span: $Span) -> usize;
71            fn span_column(span: $Span) -> usize;
72            fn span_file(span: $Span) -> String;
73            fn span_local_file(span: $Span) -> Option<String>;
74            fn span_join(span: $Span, other: $Span) -> Option<$Span>;
75            fn span_subspan(span: $Span, start: Bound<usize>, end: Bound<usize>) -> Option<$Span>;
76            fn span_resolved_at(span: $Span, at: $Span) -> $Span;
77            fn span_source_text(span: $Span) -> Option<String>;
78            fn span_save_span(span: $Span) -> usize;
79            fn span_recover_proc_macro_span(id: usize) -> $Span;
80
81            fn symbol_normalize_and_validate_ident(string: &str) -> Result<$Symbol, ()>;
82        }
83    };
84}
85
86pub(crate) struct Methods;
87
88#[allow(unsafe_code)]
89mod arena;
90#[allow(unsafe_code)]
91mod buffer;
92#[deny(unsafe_code)]
93pub mod client;
94#[allow(unsafe_code)]
95mod closure;
96#[forbid(unsafe_code)]
97mod fxhash;
98#[forbid(unsafe_code)]
99mod handle;
100#[macro_use]
101#[forbid(unsafe_code)]
102mod rpc;
103#[allow(unsafe_code)]
104mod selfless_reify;
105#[forbid(unsafe_code)]
106pub mod server;
107#[allow(unsafe_code)]
108mod symbol;
109
110use buffer::Buffer;
111pub use rpc::PanicMessage;
112use rpc::{Decode, Encode};
113
114/// Configuration for establishing an active connection between a server and a
115/// client.  The server creates the bridge config (`run_server` in `server.rs`),
116/// then passes it to the client through the function pointer in the `run` field
117/// of `client::Client`. The client constructs a local `Bridge` from the config
118/// in TLS during its execution (`Bridge::{enter, with}` in `client.rs`).
119#[repr(C)]
120pub struct BridgeConfig<'a> {
121    /// Buffer used to pass initial input to the client.
122    input: Buffer,
123
124    /// Server-side function that the client uses to make requests.
125    dispatch: closure::Closure<'a>,
126
127    /// If 'true', always invoke the default panic hook
128    force_show_panics: bool,
129}
130
131impl !Send for BridgeConfig<'_> {}
132impl !Sync for BridgeConfig<'_> {}
133
134macro_rules! declare_tags {
135    (
136        $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)*
137    ) => {
138        #[allow(non_camel_case_types)]
139        pub(super) enum ApiTags {
140            $($method),*
141        }
142        rpc_encode_decode!(enum ApiTags { $($method),* });
143    }
144}
145with_api!(declare_tags, __, __, __);
146
147/// Helper to wrap associated types to allow trait impl dispatch.
148/// That is, normally a pair of impls for `T::Foo` and `T::Bar`
149/// can overlap, but if the impls are, instead, on types like
150/// `Marked<T::Foo, Foo>` and `Marked<T::Bar, Bar>`, they can't.
151trait Mark {
152    type Unmarked;
153    fn mark(unmarked: Self::Unmarked) -> Self;
154    fn unmark(self) -> Self::Unmarked;
155}
156
157#[derive(Copy, Clone, PartialEq, Eq, Hash)]
158struct Marked<T, M> {
159    value: T,
160    _marker: marker::PhantomData<M>,
161}
162
163impl<T, M> Mark for Marked<T, M> {
164    type Unmarked = T;
165    fn mark(unmarked: Self::Unmarked) -> Self {
166        Marked { value: unmarked, _marker: marker::PhantomData }
167    }
168    fn unmark(self) -> Self::Unmarked {
169        self.value
170    }
171}
172impl<'a, T> Mark for &'a Marked<T, client::TokenStream> {
173    type Unmarked = &'a T;
174    fn mark(_: Self::Unmarked) -> Self {
175        unreachable!()
176    }
177    fn unmark(self) -> Self::Unmarked {
178        &self.value
179    }
180}
181
182impl<T: Mark> Mark for Vec<T> {
183    type Unmarked = Vec<T::Unmarked>;
184    fn mark(unmarked: Self::Unmarked) -> Self {
185        // Should be a no-op due to std's in-place collect optimizations.
186        unmarked.into_iter().map(T::mark).collect()
187    }
188    fn unmark(self) -> Self::Unmarked {
189        // Should be a no-op due to std's in-place collect optimizations.
190        self.into_iter().map(T::unmark).collect()
191    }
192}
193
194macro_rules! mark_noop {
195    ($($ty:ty),* $(,)?) => {
196        $(
197            impl Mark for $ty {
198                type Unmarked = Self;
199                fn mark(unmarked: Self::Unmarked) -> Self {
200                    unmarked
201                }
202                fn unmark(self) -> Self::Unmarked {
203                    self
204                }
205            }
206        )*
207    }
208}
209mark_noop! {
210    (),
211    bool,
212    &'_ str,
213    String,
214    u8,
215    usize,
216    Delimiter,
217    LitKind,
218    Level,
219    Bound<usize>,
220    Range<usize>,
221}
222
223rpc_encode_decode!(
224    enum Delimiter {
225        Parenthesis,
226        Brace,
227        Bracket,
228        None,
229    }
230);
231rpc_encode_decode!(
232    enum Level {
233        Error,
234        Warning,
235        Note,
236        Help,
237    }
238);
239
240#[derive(Copy, Clone, Eq, PartialEq, Debug)]
241pub enum LitKind {
242    Byte,
243    Char,
244    Integer,
245    Float,
246    Str,
247    StrRaw(u8),
248    ByteStr,
249    ByteStrRaw(u8),
250    CStr,
251    CStrRaw(u8),
252    // This should have an `ErrorGuaranteed`, except that type isn't available
253    // in this crate. (Imagine it is there.) Hence the `WithGuar` suffix. Must
254    // only be constructed in `LitKind::from_internal`, where an
255    // `ErrorGuaranteed` is available.
256    ErrWithGuar,
257}
258
259rpc_encode_decode!(
260    enum LitKind {
261        Byte,
262        Char,
263        Integer,
264        Float,
265        Str,
266        StrRaw(n),
267        ByteStr,
268        ByteStrRaw(n),
269        CStr,
270        CStrRaw(n),
271        ErrWithGuar,
272    }
273);
274
275macro_rules! mark_compound {
276    (struct $name:ident <$($T:ident),+> { $($field:ident),* $(,)? }) => {
277        impl<$($T: Mark),+> Mark for $name <$($T),+> {
278            type Unmarked = $name <$($T::Unmarked),+>;
279            fn mark(unmarked: Self::Unmarked) -> Self {
280                $name {
281                    $($field: Mark::mark(unmarked.$field)),*
282                }
283            }
284            fn unmark(self) -> Self::Unmarked {
285                $name {
286                    $($field: Mark::unmark(self.$field)),*
287                }
288            }
289        }
290    };
291    (enum $name:ident <$($T:ident),+> { $($variant:ident $(($field:ident))?),* $(,)? }) => {
292        impl<$($T: Mark),+> Mark for $name <$($T),+> {
293            type Unmarked = $name <$($T::Unmarked),+>;
294            fn mark(unmarked: Self::Unmarked) -> Self {
295                match unmarked {
296                    $($name::$variant $(($field))? => {
297                        $name::$variant $((Mark::mark($field)))?
298                    })*
299                }
300            }
301            fn unmark(self) -> Self::Unmarked {
302                match self {
303                    $($name::$variant $(($field))? => {
304                        $name::$variant $((Mark::unmark($field)))?
305                    })*
306                }
307            }
308        }
309    }
310}
311
312macro_rules! compound_traits {
313    ($($t:tt)*) => {
314        rpc_encode_decode!($($t)*);
315        mark_compound!($($t)*);
316    };
317}
318
319rpc_encode_decode!(
320    enum Bound<T> {
321        Included(x),
322        Excluded(x),
323        Unbounded,
324    }
325);
326
327compound_traits!(
328    enum Option<T> {
329        Some(t),
330        None,
331    }
332);
333
334compound_traits!(
335    enum Result<T, E> {
336        Ok(t),
337        Err(e),
338    }
339);
340
341#[derive(Copy, Clone)]
342pub struct DelimSpan<Span> {
343    pub open: Span,
344    pub close: Span,
345    pub entire: Span,
346}
347
348impl<Span: Copy> DelimSpan<Span> {
349    pub fn from_single(span: Span) -> Self {
350        DelimSpan { open: span, close: span, entire: span }
351    }
352}
353
354compound_traits!(struct DelimSpan<Span> { open, close, entire });
355
356#[derive(Clone)]
357pub struct Group<TokenStream, Span> {
358    pub delimiter: Delimiter,
359    pub stream: Option<TokenStream>,
360    pub span: DelimSpan<Span>,
361}
362
363compound_traits!(struct Group<TokenStream, Span> { delimiter, stream, span });
364
365#[derive(Clone)]
366pub struct Punct<Span> {
367    pub ch: u8,
368    pub joint: bool,
369    pub span: Span,
370}
371
372compound_traits!(struct Punct<Span> { ch, joint, span });
373
374#[derive(Copy, Clone, Eq, PartialEq)]
375pub struct Ident<Span, Symbol> {
376    pub sym: Symbol,
377    pub is_raw: bool,
378    pub span: Span,
379}
380
381compound_traits!(struct Ident<Span, Symbol> { sym, is_raw, span });
382
383#[derive(Clone, Eq, PartialEq)]
384pub struct Literal<Span, Symbol> {
385    pub kind: LitKind,
386    pub symbol: Symbol,
387    pub suffix: Option<Symbol>,
388    pub span: Span,
389}
390
391compound_traits!(struct Literal<Span, Symbol> { kind, symbol, suffix, span });
392
393#[derive(Clone)]
394pub enum TokenTree<TokenStream, Span, Symbol> {
395    Group(Group<TokenStream, Span>),
396    Punct(Punct<Span>),
397    Ident(Ident<Span, Symbol>),
398    Literal(Literal<Span, Symbol>),
399}
400
401compound_traits!(
402    enum TokenTree<TokenStream, Span, Symbol> {
403        Group(tt),
404        Punct(tt),
405        Ident(tt),
406        Literal(tt),
407    }
408);
409
410#[derive(Clone, Debug)]
411pub struct Diagnostic<Span> {
412    pub level: Level,
413    pub message: String,
414    pub spans: Vec<Span>,
415    pub children: Vec<Diagnostic<Span>>,
416}
417
418compound_traits!(
419    struct Diagnostic<Span> { level, message, spans, children }
420);
421
422/// Globals provided alongside the initial inputs for a macro expansion.
423/// Provides values such as spans which are used frequently to avoid RPC.
424#[derive(Clone)]
425pub struct ExpnGlobals<Span> {
426    pub def_site: Span,
427    pub call_site: Span,
428    pub mixed_site: Span,
429}
430
431compound_traits!(
432    struct ExpnGlobals<Span> { def_site, call_site, mixed_site }
433);
434
435rpc_encode_decode!(
436    struct Range<T> { start, end }
437);