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