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