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