]> git.lizzy.rs Git - rust.git/blob - crates/proc_macro_srv/src/abis/abi_1_55/proc_macro/bridge/mod.rs
Merge #11184
[rust.git] / crates / proc_macro_srv / src / abis / abi_1_55 / proc_macro / bridge / mod.rs
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
16 pub use super::{Delimiter, Level, LineColumn, Spacing};
17 use std::fmt;
18 use std::hash::Hash;
19 use std::marker;
20 use std::mem;
21 use std::ops::Bound;
22 use std::panic;
23 use std::sync::atomic::AtomicUsize;
24 use std::sync::Once;
25 use 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`.
57 macro_rules! with_api {
58     ($S:ident, $self:ident, $m:ident) => {
59         $m! {
60             FreeFunctions {
61                 fn drop($self: $S::FreeFunctions);
62                 fn track_env_var(var: &str, value: Option<&str>);
63             },
64             TokenStream {
65                 fn drop($self: $S::TokenStream);
66                 fn clone($self: &$S::TokenStream) -> $S::TokenStream;
67                 fn new() -> $S::TokenStream;
68                 fn is_empty($self: &$S::TokenStream) -> bool;
69                 fn from_str(src: &str) -> $S::TokenStream;
70                 fn to_string($self: &$S::TokenStream) -> String;
71                 fn from_token_tree(
72                     tree: TokenTree<$S::Group, $S::Punct, $S::Ident, $S::Literal>,
73                 ) -> $S::TokenStream;
74                 fn into_iter($self: $S::TokenStream) -> $S::TokenStreamIter;
75             },
76             TokenStreamBuilder {
77                 fn drop($self: $S::TokenStreamBuilder);
78                 fn new() -> $S::TokenStreamBuilder;
79                 fn push($self: &mut $S::TokenStreamBuilder, stream: $S::TokenStream);
80                 fn build($self: $S::TokenStreamBuilder) -> $S::TokenStream;
81             },
82             TokenStreamIter {
83                 fn drop($self: $S::TokenStreamIter);
84                 fn clone($self: &$S::TokenStreamIter) -> $S::TokenStreamIter;
85                 fn next(
86                     $self: &mut $S::TokenStreamIter,
87                 ) -> Option<TokenTree<$S::Group, $S::Punct, $S::Ident, $S::Literal>>;
88             },
89             Group {
90                 fn drop($self: $S::Group);
91                 fn clone($self: &$S::Group) -> $S::Group;
92                 fn new(delimiter: Delimiter, stream: $S::TokenStream) -> $S::Group;
93                 fn delimiter($self: &$S::Group) -> Delimiter;
94                 fn stream($self: &$S::Group) -> $S::TokenStream;
95                 fn span($self: &$S::Group) -> $S::Span;
96                 fn span_open($self: &$S::Group) -> $S::Span;
97                 fn span_close($self: &$S::Group) -> $S::Span;
98                 fn set_span($self: &mut $S::Group, span: $S::Span);
99             },
100             Punct {
101                 fn new(ch: char, spacing: Spacing) -> $S::Punct;
102                 fn as_char($self: $S::Punct) -> char;
103                 fn spacing($self: $S::Punct) -> Spacing;
104                 fn span($self: $S::Punct) -> $S::Span;
105                 fn with_span($self: $S::Punct, span: $S::Span) -> $S::Punct;
106             },
107             Ident {
108                 fn new(string: &str, span: $S::Span, is_raw: bool) -> $S::Ident;
109                 fn span($self: $S::Ident) -> $S::Span;
110                 fn with_span($self: $S::Ident, span: $S::Span) -> $S::Ident;
111             },
112             Literal {
113                 fn drop($self: $S::Literal);
114                 fn clone($self: &$S::Literal) -> $S::Literal;
115                 fn from_str(s: &str) -> Result<$S::Literal, ()>;
116                 fn debug_kind($self: &$S::Literal) -> String;
117                 fn symbol($self: &$S::Literal) -> String;
118                 fn suffix($self: &$S::Literal) -> Option<String>;
119                 fn integer(n: &str) -> $S::Literal;
120                 fn typed_integer(n: &str, kind: &str) -> $S::Literal;
121                 fn float(n: &str) -> $S::Literal;
122                 fn f32(n: &str) -> $S::Literal;
123                 fn f64(n: &str) -> $S::Literal;
124                 fn string(string: &str) -> $S::Literal;
125                 fn character(ch: char) -> $S::Literal;
126                 fn byte_string(bytes: &[u8]) -> $S::Literal;
127                 fn span($self: &$S::Literal) -> $S::Span;
128                 fn set_span($self: &mut $S::Literal, span: $S::Span);
129                 fn subspan(
130                     $self: &$S::Literal,
131                     start: Bound<usize>,
132                     end: Bound<usize>,
133                 ) -> Option<$S::Span>;
134             },
135             SourceFile {
136                 fn drop($self: $S::SourceFile);
137                 fn clone($self: &$S::SourceFile) -> $S::SourceFile;
138                 fn eq($self: &$S::SourceFile, other: &$S::SourceFile) -> bool;
139                 fn path($self: &$S::SourceFile) -> String;
140                 fn is_real($self: &$S::SourceFile) -> bool;
141             },
142             MultiSpan {
143                 fn drop($self: $S::MultiSpan);
144                 fn new() -> $S::MultiSpan;
145                 fn push($self: &mut $S::MultiSpan, span: $S::Span);
146             },
147             Diagnostic {
148                 fn drop($self: $S::Diagnostic);
149                 fn new(level: Level, msg: &str, span: $S::MultiSpan) -> $S::Diagnostic;
150                 fn sub(
151                     $self: &mut $S::Diagnostic,
152                     level: Level,
153                     msg: &str,
154                     span: $S::MultiSpan,
155                 );
156                 fn emit($self: $S::Diagnostic);
157             },
158             Span {
159                 fn debug($self: $S::Span) -> String;
160                 fn def_site() -> $S::Span;
161                 fn call_site() -> $S::Span;
162                 fn mixed_site() -> $S::Span;
163                 fn source_file($self: $S::Span) -> $S::SourceFile;
164                 fn parent($self: $S::Span) -> Option<$S::Span>;
165                 fn source($self: $S::Span) -> $S::Span;
166                 fn start($self: $S::Span) -> LineColumn;
167                 fn end($self: $S::Span) -> LineColumn;
168                 fn join($self: $S::Span, other: $S::Span) -> Option<$S::Span>;
169                 fn resolved_at($self: $S::Span, at: $S::Span) -> $S::Span;
170                 fn source_text($self: $S::Span) -> Option<String>;
171             },
172         }
173     };
174 }
175
176 // FIXME(eddyb) this calls `encode` for each argument, but in reverse,
177 // to avoid borrow conflicts from borrows started by `&mut` arguments.
178 macro_rules! reverse_encode {
179     ($writer:ident;) => {};
180     ($writer:ident; $first:ident $(, $rest:ident)*) => {
181         reverse_encode!($writer; $($rest),*);
182         $first.encode(&mut $writer, &mut ());
183     }
184 }
185
186 // FIXME(eddyb) this calls `decode` for each argument, but in reverse,
187 // to avoid borrow conflicts from borrows started by `&mut` arguments.
188 macro_rules! reverse_decode {
189     ($reader:ident, $s:ident;) => {};
190     ($reader:ident, $s:ident; $first:ident: $first_ty:ty $(, $rest:ident: $rest_ty:ty)*) => {
191         reverse_decode!($reader, $s; $($rest: $rest_ty),*);
192         let $first = <$first_ty>::decode(&mut $reader, $s);
193     }
194 }
195
196 #[allow(unsafe_code)]
197 mod buffer;
198 #[forbid(unsafe_code)]
199 pub mod client;
200 #[allow(unsafe_code)]
201 mod closure;
202 #[forbid(unsafe_code)]
203 mod handle;
204 #[macro_use]
205 #[forbid(unsafe_code)]
206 mod rpc;
207 #[allow(unsafe_code)]
208 mod scoped_cell;
209 #[forbid(unsafe_code)]
210 pub mod server;
211
212 use buffer::Buffer;
213 pub use rpc::PanicMessage;
214 use rpc::{Decode, DecodeMut, Encode, Reader, Writer};
215
216 /// An active connection between a server and a client.
217 /// The server creates the bridge (`Bridge::run_server` in `server.rs`),
218 /// then passes it to the client through the function pointer in the `run`
219 /// field of `client::Client`. The client holds its copy of the `Bridge`
220 /// in TLS during its execution (`Bridge::{enter, with}` in `client.rs`).
221 #[repr(C)]
222 pub struct Bridge<'a> {
223     /// Reusable buffer (only `clear`-ed, never shrunk), primarily
224     /// used for making requests, but also for passing input to client.
225     cached_buffer: Buffer<u8>,
226
227     /// Server-side function that the client uses to make requests.
228     dispatch: closure::Closure<'a, Buffer<u8>, Buffer<u8>>,
229
230     /// If 'true', always invoke the default panic hook
231     force_show_panics: bool,
232 }
233
234 // impl<'a> !Sync for Bridge<'a> {}
235 // impl<'a> !Send for Bridge<'a> {}
236
237 #[forbid(unsafe_code)]
238 #[allow(non_camel_case_types)]
239 mod api_tags {
240     use super::rpc::{DecodeMut, Encode, Reader, Writer};
241
242     macro_rules! declare_tags {
243         ($($name:ident {
244             $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)*
245         }),* $(,)?) => {
246             $(
247                 pub(super) enum $name {
248                     $($method),*
249                 }
250                 rpc_encode_decode!(enum $name { $($method),* });
251             )*
252
253
254             pub(super) enum Method {
255                 $($name($name)),*
256             }
257             rpc_encode_decode!(enum Method { $($name(m)),* });
258         }
259     }
260     with_api!(self, self, declare_tags);
261 }
262
263 /// Helper to wrap associated types to allow trait impl dispatch.
264 /// That is, normally a pair of impls for `T::Foo` and `T::Bar`
265 /// can overlap, but if the impls are, instead, on types like
266 /// `Marked<T::Foo, Foo>` and `Marked<T::Bar, Bar>`, they can't.
267 trait Mark {
268     type Unmarked;
269     fn mark(unmarked: Self::Unmarked) -> Self;
270 }
271
272 /// Unwrap types wrapped by `cov_mark::mark` (see `Mark` for details).
273 trait Unmark {
274     type Unmarked;
275     fn unmark(self) -> Self::Unmarked;
276 }
277
278 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
279 struct Marked<T, M> {
280     value: T,
281     _marker: marker::PhantomData<M>,
282 }
283
284 impl<T, M> Mark for Marked<T, M> {
285     type Unmarked = T;
286     fn mark(unmarked: Self::Unmarked) -> Self {
287         Marked { value: unmarked, _marker: marker::PhantomData }
288     }
289 }
290 impl<T, M> Unmark for Marked<T, M> {
291     type Unmarked = T;
292     fn unmark(self) -> Self::Unmarked {
293         self.value
294     }
295 }
296 impl<'a, T, M> Unmark for &'a Marked<T, M> {
297     type Unmarked = &'a T;
298     fn unmark(self) -> Self::Unmarked {
299         &self.value
300     }
301 }
302 impl<'a, T, M> Unmark for &'a mut Marked<T, M> {
303     type Unmarked = &'a mut T;
304     fn unmark(self) -> Self::Unmarked {
305         &mut self.value
306     }
307 }
308
309 impl<T: Mark> Mark for Option<T> {
310     type Unmarked = Option<T::Unmarked>;
311     fn mark(unmarked: Self::Unmarked) -> Self {
312         unmarked.map(T::mark)
313     }
314 }
315 impl<T: Unmark> Unmark for Option<T> {
316     type Unmarked = Option<T::Unmarked>;
317     fn unmark(self) -> Self::Unmarked {
318         self.map(T::unmark)
319     }
320 }
321 impl<T: Mark, E: Mark> Mark for Result<T, E> {
322     type Unmarked = Result<T::Unmarked, E::Unmarked>;
323     fn mark(unmarked: Self::Unmarked) -> Self {
324         unmarked.map(T::mark).map_err(E::mark)
325     }
326 }
327 impl<T: Unmark, E: Unmark> Unmark for Result<T, E> {
328     type Unmarked = Result<T::Unmarked, E::Unmarked>;
329     fn unmark(self) -> Self::Unmarked {
330         self.map(T::unmark).map_err(E::unmark)
331     }
332 }
333
334 macro_rules! mark_noop {
335     ($($ty:ty),* $(,)?) => {
336         $(
337             impl Mark for $ty {
338                 type Unmarked = Self;
339                 fn mark(unmarked: Self::Unmarked) -> Self {
340                     unmarked
341                 }
342             }
343             impl Unmark for $ty {
344                 type Unmarked = Self;
345                 fn unmark(self) -> Self::Unmarked {
346                     self
347                 }
348             }
349         )*
350     }
351 }
352 mark_noop! {
353     (),
354     bool,
355     char,
356     &'_ [u8],
357     &'_ str,
358     String,
359     Delimiter,
360     Level,
361     LineColumn,
362     Spacing,
363     Bound<usize>,
364 }
365
366 rpc_encode_decode!(
367     enum Delimiter {
368         Parenthesis,
369         Brace,
370         Bracket,
371         None,
372     }
373 );
374 rpc_encode_decode!(
375     enum Level {
376         Error,
377         Warning,
378         Note,
379         Help,
380     }
381 );
382 rpc_encode_decode!(struct LineColumn { line, column });
383 rpc_encode_decode!(
384     enum Spacing {
385         Alone,
386         Joint,
387     }
388 );
389
390 #[derive(Clone)]
391 pub enum TokenTree<G, P, I, L> {
392     Group(G),
393     Punct(P),
394     Ident(I),
395     Literal(L),
396 }
397
398 impl<G: Mark, P: Mark, I: Mark, L: Mark> Mark for TokenTree<G, P, I, L> {
399     type Unmarked = TokenTree<G::Unmarked, P::Unmarked, I::Unmarked, L::Unmarked>;
400     fn mark(unmarked: Self::Unmarked) -> Self {
401         match unmarked {
402             TokenTree::Group(tt) => TokenTree::Group(G::mark(tt)),
403             TokenTree::Punct(tt) => TokenTree::Punct(P::mark(tt)),
404             TokenTree::Ident(tt) => TokenTree::Ident(I::mark(tt)),
405             TokenTree::Literal(tt) => TokenTree::Literal(L::mark(tt)),
406         }
407     }
408 }
409 impl<G: Unmark, P: Unmark, I: Unmark, L: Unmark> Unmark for TokenTree<G, P, I, L> {
410     type Unmarked = TokenTree<G::Unmarked, P::Unmarked, I::Unmarked, L::Unmarked>;
411     fn unmark(self) -> Self::Unmarked {
412         match self {
413             TokenTree::Group(tt) => TokenTree::Group(tt.unmark()),
414             TokenTree::Punct(tt) => TokenTree::Punct(tt.unmark()),
415             TokenTree::Ident(tt) => TokenTree::Ident(tt.unmark()),
416             TokenTree::Literal(tt) => TokenTree::Literal(tt.unmark()),
417         }
418     }
419 }
420
421 rpc_encode_decode!(
422     enum TokenTree<G, P, I, L> {
423         Group(tt),
424         Punct(tt),
425         Ident(tt),
426         Literal(tt),
427     }
428 );