]> git.lizzy.rs Git - rust.git/blob - crates/proc-macro-srv/src/abis/abi_1_64/proc_macro/bridge/mod.rs
Support the 1.64 nightly proc macro ABI
[rust.git] / crates / proc-macro-srv / src / abis / abi_1_64 / 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
11 pub use super::{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 is_empty($self: &$S::TokenStream) -> bool;
64                 fn expand_expr($self: &$S::TokenStream) -> Result<$S::TokenStream, ()>;
65                 fn from_str(src: &str) -> $S::TokenStream;
66                 fn to_string($self: &$S::TokenStream) -> String;
67                 fn from_token_tree(
68                     tree: TokenTree<$S::TokenStream, $S::Span, $S::Ident, $S::Literal>,
69                 ) -> $S::TokenStream;
70                 fn concat_trees(
71                     base: Option<$S::TokenStream>,
72                     trees: Vec<TokenTree<$S::TokenStream, $S::Span, $S::Ident, $S::Literal>>,
73                 ) -> $S::TokenStream;
74                 fn concat_streams(
75                     base: Option<$S::TokenStream>,
76                     streams: Vec<$S::TokenStream>,
77                 ) -> $S::TokenStream;
78                 fn into_trees(
79                     $self: $S::TokenStream
80                 ) -> Vec<TokenTree<$S::TokenStream, $S::Span, $S::Ident, $S::Literal>>;
81             },
82             Ident {
83                 fn new(string: &str, span: $S::Span, is_raw: bool) -> $S::Ident;
84                 fn span($self: $S::Ident) -> $S::Span;
85                 fn with_span($self: $S::Ident, span: $S::Span) -> $S::Ident;
86             },
87             Literal {
88                 fn drop($self: $S::Literal);
89                 fn clone($self: &$S::Literal) -> $S::Literal;
90                 fn from_str(s: &str) -> Result<$S::Literal, ()>;
91                 fn to_string($self: &$S::Literal) -> String;
92                 fn debug_kind($self: &$S::Literal) -> String;
93                 fn symbol($self: &$S::Literal) -> String;
94                 fn suffix($self: &$S::Literal) -> Option<String>;
95                 fn integer(n: &str) -> $S::Literal;
96                 fn typed_integer(n: &str, kind: &str) -> $S::Literal;
97                 fn float(n: &str) -> $S::Literal;
98                 fn f32(n: &str) -> $S::Literal;
99                 fn f64(n: &str) -> $S::Literal;
100                 fn string(string: &str) -> $S::Literal;
101                 fn character(ch: char) -> $S::Literal;
102                 fn byte_string(bytes: &[u8]) -> $S::Literal;
103                 fn span($self: &$S::Literal) -> $S::Span;
104                 fn set_span($self: &mut $S::Literal, span: $S::Span);
105                 fn subspan(
106                     $self: &$S::Literal,
107                     start: Bound<usize>,
108                     end: Bound<usize>,
109                 ) -> Option<$S::Span>;
110             },
111             SourceFile {
112                 fn drop($self: $S::SourceFile);
113                 fn clone($self: &$S::SourceFile) -> $S::SourceFile;
114                 fn eq($self: &$S::SourceFile, other: &$S::SourceFile) -> bool;
115                 fn path($self: &$S::SourceFile) -> String;
116                 fn is_real($self: &$S::SourceFile) -> bool;
117             },
118             MultiSpan {
119                 fn drop($self: $S::MultiSpan);
120                 fn new() -> $S::MultiSpan;
121                 fn push($self: &mut $S::MultiSpan, span: $S::Span);
122             },
123             Diagnostic {
124                 fn drop($self: $S::Diagnostic);
125                 fn new(level: Level, msg: &str, span: $S::MultiSpan) -> $S::Diagnostic;
126                 fn sub(
127                     $self: &mut $S::Diagnostic,
128                     level: Level,
129                     msg: &str,
130                     span: $S::MultiSpan,
131                 );
132                 fn emit($self: $S::Diagnostic);
133             },
134             Span {
135                 fn debug($self: $S::Span) -> String;
136                 fn source_file($self: $S::Span) -> $S::SourceFile;
137                 fn parent($self: $S::Span) -> Option<$S::Span>;
138                 fn source($self: $S::Span) -> $S::Span;
139                 fn start($self: $S::Span) -> LineColumn;
140                 fn end($self: $S::Span) -> LineColumn;
141                 fn before($self: $S::Span) -> $S::Span;
142                 fn after($self: $S::Span) -> $S::Span;
143                 fn join($self: $S::Span, other: $S::Span) -> Option<$S::Span>;
144                 fn resolved_at($self: $S::Span, at: $S::Span) -> $S::Span;
145                 fn source_text($self: $S::Span) -> Option<String>;
146                 fn save_span($self: $S::Span) -> usize;
147                 fn recover_proc_macro_span(id: usize) -> $S::Span;
148             },
149         }
150     };
151 }
152
153 // FIXME(eddyb) this calls `encode` for each argument, but in reverse,
154 // to match the ordering in `reverse_decode`.
155 macro_rules! reverse_encode {
156     ($writer:ident;) => {};
157     ($writer:ident; $first:ident $(, $rest:ident)*) => {
158         reverse_encode!($writer; $($rest),*);
159         $first.encode(&mut $writer, &mut ());
160     }
161 }
162
163 // FIXME(eddyb) this calls `decode` for each argument, but in reverse,
164 // to avoid borrow conflicts from borrows started by `&mut` arguments.
165 macro_rules! reverse_decode {
166     ($reader:ident, $s:ident;) => {};
167     ($reader:ident, $s:ident; $first:ident: $first_ty:ty $(, $rest:ident: $rest_ty:ty)*) => {
168         reverse_decode!($reader, $s; $($rest: $rest_ty),*);
169         let $first = <$first_ty>::decode(&mut $reader, $s);
170     }
171 }
172
173 #[allow(unsafe_code)]
174 mod buffer;
175 #[forbid(unsafe_code)]
176 pub mod client;
177 #[allow(unsafe_code)]
178 mod closure;
179 #[forbid(unsafe_code)]
180 mod handle;
181 #[macro_use]
182 #[forbid(unsafe_code)]
183 mod rpc;
184 #[allow(unsafe_code)]
185 mod scoped_cell;
186 #[allow(unsafe_code)]
187 mod selfless_reify;
188 #[forbid(unsafe_code)]
189 pub mod server;
190
191 use buffer::Buffer;
192 pub use rpc::PanicMessage;
193 use rpc::{Decode, DecodeMut, Encode, Reader, Writer};
194
195 /// Configuration for establishing an active connection between a server and a
196 /// client.  The server creates the bridge config (`run_server` in `server.rs`),
197 /// then passes it to the client through the function pointer in the `run` field
198 /// of `client::Client`. The client constructs a local `Bridge` from the config
199 /// in TLS during its execution (`Bridge::{enter, with}` in `client.rs`).
200 #[repr(C)]
201 pub struct BridgeConfig<'a> {
202     /// Buffer used to pass initial input to the client.
203     input: Buffer,
204
205     /// Server-side function that the client uses to make requests.
206     dispatch: closure::Closure<'a, Buffer, Buffer>,
207
208     /// If 'true', always invoke the default panic hook
209     force_show_panics: bool,
210
211     // Prevent Send and Sync impls. `!Send`/`!Sync` is the usual way of doing
212     // this, but that requires unstable features. rust-analyzer uses this code
213     // and avoids unstable features.
214     _marker: marker::PhantomData<*mut ()>,
215 }
216
217 #[forbid(unsafe_code)]
218 #[allow(non_camel_case_types)]
219 mod api_tags {
220     use super::rpc::{DecodeMut, Encode, Reader, Writer};
221
222     macro_rules! declare_tags {
223         ($($name:ident {
224             $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)*
225         }),* $(,)?) => {
226             $(
227                 pub(super) enum $name {
228                     $($method),*
229                 }
230                 rpc_encode_decode!(enum $name { $($method),* });
231             )*
232
233             pub(super) enum Method {
234                 $($name($name)),*
235             }
236             rpc_encode_decode!(enum Method { $($name(m)),* });
237         }
238     }
239     with_api!(self, self, declare_tags);
240 }
241
242 /// Helper to wrap associated types to allow trait impl dispatch.
243 /// That is, normally a pair of impls for `T::Foo` and `T::Bar`
244 /// can overlap, but if the impls are, instead, on types like
245 /// `Marked<T::Foo, Foo>` and `Marked<T::Bar, Bar>`, they can't.
246 trait Mark {
247     type Unmarked;
248     fn mark(unmarked: Self::Unmarked) -> Self;
249 }
250
251 /// Unwrap types wrapped by `Mark::mark` (see `Mark` for details).
252 trait Unmark {
253     type Unmarked;
254     fn unmark(self) -> Self::Unmarked;
255 }
256
257 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
258 struct Marked<T, M> {
259     value: T,
260     _marker: marker::PhantomData<M>,
261 }
262
263 impl<T, M> Mark for Marked<T, M> {
264     type Unmarked = T;
265     fn mark(unmarked: Self::Unmarked) -> Self {
266         Marked { value: unmarked, _marker: marker::PhantomData }
267     }
268 }
269 impl<T, M> Unmark for Marked<T, M> {
270     type Unmarked = T;
271     fn unmark(self) -> Self::Unmarked {
272         self.value
273     }
274 }
275 impl<'a, T, M> Unmark for &'a Marked<T, M> {
276     type Unmarked = &'a T;
277     fn unmark(self) -> Self::Unmarked {
278         &self.value
279     }
280 }
281 impl<'a, T, M> Unmark for &'a mut Marked<T, M> {
282     type Unmarked = &'a mut T;
283     fn unmark(self) -> Self::Unmarked {
284         &mut self.value
285     }
286 }
287
288 impl<T: Mark> Mark for Vec<T> {
289     type Unmarked = Vec<T::Unmarked>;
290     fn mark(unmarked: Self::Unmarked) -> Self {
291         // Should be a no-op due to std's in-place collect optimizations.
292         unmarked.into_iter().map(T::mark).collect()
293     }
294 }
295 impl<T: Unmark> Unmark for Vec<T> {
296     type Unmarked = Vec<T::Unmarked>;
297     fn unmark(self) -> Self::Unmarked {
298         // Should be a no-op due to std's in-place collect optimizations.
299         self.into_iter().map(T::unmark).collect()
300     }
301 }
302
303 macro_rules! mark_noop {
304     ($($ty:ty),* $(,)?) => {
305         $(
306             impl Mark for $ty {
307                 type Unmarked = Self;
308                 fn mark(unmarked: Self::Unmarked) -> Self {
309                     unmarked
310                 }
311             }
312             impl Unmark for $ty {
313                 type Unmarked = Self;
314                 fn unmark(self) -> Self::Unmarked {
315                     self
316                 }
317             }
318         )*
319     }
320 }
321 mark_noop! {
322     (),
323     bool,
324     char,
325     &'_ [u8],
326     &'_ str,
327     String,
328     u8,
329     usize,
330     Delimiter,
331     Level,
332     LineColumn,
333     Spacing,
334 }
335
336 rpc_encode_decode!(
337     enum Delimiter {
338         Parenthesis,
339         Brace,
340         Bracket,
341         None,
342     }
343 );
344 rpc_encode_decode!(
345     enum Level {
346         Error,
347         Warning,
348         Note,
349         Help,
350     }
351 );
352 rpc_encode_decode!(struct LineColumn { line, column });
353 rpc_encode_decode!(
354     enum Spacing {
355         Alone,
356         Joint,
357     }
358 );
359
360 macro_rules! mark_compound {
361     (struct $name:ident <$($T:ident),+> { $($field:ident),* $(,)? }) => {
362         impl<$($T: Mark),+> Mark for $name <$($T),+> {
363             type Unmarked = $name <$($T::Unmarked),+>;
364             fn mark(unmarked: Self::Unmarked) -> Self {
365                 $name {
366                     $($field: Mark::mark(unmarked.$field)),*
367                 }
368             }
369         }
370         impl<$($T: Unmark),+> Unmark for $name <$($T),+> {
371             type Unmarked = $name <$($T::Unmarked),+>;
372             fn unmark(self) -> Self::Unmarked {
373                 $name {
374                     $($field: Unmark::unmark(self.$field)),*
375                 }
376             }
377         }
378     };
379     (enum $name:ident <$($T:ident),+> { $($variant:ident $(($field:ident))?),* $(,)? }) => {
380         impl<$($T: Mark),+> Mark for $name <$($T),+> {
381             type Unmarked = $name <$($T::Unmarked),+>;
382             fn mark(unmarked: Self::Unmarked) -> Self {
383                 match unmarked {
384                     $($name::$variant $(($field))? => {
385                         $name::$variant $((Mark::mark($field)))?
386                     })*
387                 }
388             }
389         }
390         impl<$($T: Unmark),+> Unmark for $name <$($T),+> {
391             type Unmarked = $name <$($T::Unmarked),+>;
392             fn unmark(self) -> Self::Unmarked {
393                 match self {
394                     $($name::$variant $(($field))? => {
395                         $name::$variant $((Unmark::unmark($field)))?
396                     })*
397                 }
398             }
399         }
400     }
401 }
402
403 macro_rules! compound_traits {
404     ($($t:tt)*) => {
405         rpc_encode_decode!($($t)*);
406         mark_compound!($($t)*);
407     };
408 }
409
410 compound_traits!(
411     enum Bound<T> {
412         Included(x),
413         Excluded(x),
414         Unbounded,
415     }
416 );
417
418 compound_traits!(
419     enum Option<T> {
420         Some(t),
421         None,
422     }
423 );
424
425 compound_traits!(
426     enum Result<T, E> {
427         Ok(t),
428         Err(e),
429     }
430 );
431
432 #[derive(Copy, Clone)]
433 pub struct DelimSpan<Span> {
434     pub open: Span,
435     pub close: Span,
436     pub entire: Span,
437 }
438
439 impl<Span: Copy> DelimSpan<Span> {
440     pub fn from_single(span: Span) -> Self {
441         DelimSpan { open: span, close: span, entire: span }
442     }
443 }
444
445 compound_traits!(struct DelimSpan<Span> { open, close, entire });
446
447 #[derive(Clone)]
448 pub struct Group<TokenStream, Span> {
449     pub delimiter: Delimiter,
450     pub stream: Option<TokenStream>,
451     pub span: DelimSpan<Span>,
452 }
453
454 compound_traits!(struct Group<TokenStream, Span> { delimiter, stream, span });
455
456 #[derive(Clone)]
457 pub struct Punct<Span> {
458     pub ch: u8,
459     pub joint: bool,
460     pub span: Span,
461 }
462
463 compound_traits!(struct Punct<Span> { ch, joint, span });
464
465 #[derive(Clone)]
466 pub enum TokenTree<TokenStream, Span, Ident, Literal> {
467     Group(Group<TokenStream, Span>),
468     Punct(Punct<Span>),
469     Ident(Ident),
470     Literal(Literal),
471 }
472
473 compound_traits!(
474     enum TokenTree<TokenStream, Span, Ident, Literal> {
475         Group(tt),
476         Punct(tt),
477         Ident(tt),
478         Literal(tt),
479     }
480 );
481
482 /// Globals provided alongside the initial inputs for a macro expansion.
483 /// Provides values such as spans which are used frequently to avoid RPC.
484 #[derive(Clone)]
485 pub struct ExpnGlobals<Span> {
486     pub def_site: Span,
487     pub call_site: Span,
488     pub mixed_site: Span,
489 }
490
491 compound_traits!(
492     struct ExpnGlobals<Span> { def_site, call_site, mixed_site }
493 );