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