1 //! Internal interface for communicating between a `proc_macro` client
2 //! (a proc macro crate) and a `proc_macro` server (a compiler front-end).
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).
11 use crate::{Delimiter, Level, LineColumn, Spacing};
18 use std::sync::atomic::AtomicUsize;
22 /// Higher-order macro describing the server RPC API, allowing automatic
23 /// generation of type-safe Rust APIs, both client-side and server-side.
25 /// `with_api!(MySelf, my_self, my_macro)` expands to:
26 /// ```rust,ignore (pseudo-code)
31 /// fn character(ch: char) -> MySelf::Literal;
33 /// fn span(my_self: &MySelf::Literal) -> MySelf::Span;
34 /// fn set_span(my_self: &mut MySelf::Literal, span: MySelf::Span);
40 /// The first two arguments serve to customize the arguments names
41 /// and argument/return types, to enable several different usecases:
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.
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) => {
56 fn drop($self: $S::FreeFunctions);
57 fn track_env_var(var: &str, value: Option<&str>);
58 fn track_path(path: &str);
59 fn literal_from_str(s: &str) -> Result<Literal<$S::Span, $S::Symbol>, ()>;
60 fn emit_diagnostic(diagnostic: Diagnostic<$S::Span>);
63 fn drop($self: $S::TokenStream);
64 fn clone($self: &$S::TokenStream) -> $S::TokenStream;
65 fn is_empty($self: &$S::TokenStream) -> bool;
66 fn expand_expr($self: &$S::TokenStream) -> Result<$S::TokenStream, ()>;
67 fn from_str(src: &str) -> $S::TokenStream;
68 fn to_string($self: &$S::TokenStream) -> String;
70 tree: TokenTree<$S::TokenStream, $S::Span, $S::Symbol>,
73 base: Option<$S::TokenStream>,
74 trees: Vec<TokenTree<$S::TokenStream, $S::Span, $S::Symbol>>,
77 base: Option<$S::TokenStream>,
78 streams: Vec<$S::TokenStream>,
81 $self: $S::TokenStream
82 ) -> Vec<TokenTree<$S::TokenStream, $S::Span, $S::Symbol>>;
85 fn drop($self: $S::SourceFile);
86 fn clone($self: &$S::SourceFile) -> $S::SourceFile;
87 fn eq($self: &$S::SourceFile, other: &$S::SourceFile) -> bool;
88 fn path($self: &$S::SourceFile) -> String;
89 fn is_real($self: &$S::SourceFile) -> bool;
92 fn debug($self: $S::Span) -> String;
93 fn source_file($self: $S::Span) -> $S::SourceFile;
94 fn parent($self: $S::Span) -> Option<$S::Span>;
95 fn source($self: $S::Span) -> $S::Span;
96 fn start($self: $S::Span) -> LineColumn;
97 fn end($self: $S::Span) -> LineColumn;
98 fn before($self: $S::Span) -> $S::Span;
99 fn after($self: $S::Span) -> $S::Span;
100 fn join($self: $S::Span, other: $S::Span) -> Option<$S::Span>;
101 fn subspan($self: $S::Span, start: Bound<usize>, end: Bound<usize>) -> Option<$S::Span>;
102 fn resolved_at($self: $S::Span, at: $S::Span) -> $S::Span;
103 fn source_text($self: $S::Span) -> Option<String>;
104 fn save_span($self: $S::Span) -> usize;
105 fn recover_proc_macro_span(id: usize) -> $S::Span;
108 fn normalize_and_validate_ident(string: &str) -> Result<$S::Symbol, ()>;
114 // FIXME(eddyb) this calls `encode` for each argument, but in reverse,
115 // to match the ordering in `reverse_decode`.
116 macro_rules! reverse_encode {
117 ($writer:ident;) => {};
118 ($writer:ident; $first:ident $(, $rest:ident)*) => {
119 reverse_encode!($writer; $($rest),*);
120 $first.encode(&mut $writer, &mut ());
124 // FIXME(eddyb) this calls `decode` for each argument, but in reverse,
125 // to avoid borrow conflicts from borrows started by `&mut` arguments.
126 macro_rules! reverse_decode {
127 ($reader:ident, $s:ident;) => {};
128 ($reader:ident, $s:ident; $first:ident: $first_ty:ty $(, $rest:ident: $rest_ty:ty)*) => {
129 reverse_decode!($reader, $s; $($rest: $rest_ty),*);
130 let $first = <$first_ty>::decode(&mut $reader, $s);
134 #[allow(unsafe_code)]
136 #[allow(unsafe_code)]
138 #[forbid(unsafe_code)]
140 #[allow(unsafe_code)]
142 #[forbid(unsafe_code)]
144 #[forbid(unsafe_code)]
147 #[forbid(unsafe_code)]
149 #[allow(unsafe_code)]
151 #[allow(unsafe_code)]
153 #[forbid(unsafe_code)]
155 #[allow(unsafe_code)]
159 pub use rpc::PanicMessage;
160 use rpc::{Decode, DecodeMut, Encode, Reader, Writer};
162 /// Configuration for establishing an active connection between a server and a
163 /// client. The server creates the bridge config (`run_server` in `server.rs`),
164 /// then passes it to the client through the function pointer in the `run` field
165 /// of `client::Client`. The client constructs a local `Bridge` from the config
166 /// in TLS during its execution (`Bridge::{enter, with}` in `client.rs`).
168 pub struct BridgeConfig<'a> {
169 /// Buffer used to pass initial input to the client.
172 /// Server-side function that the client uses to make requests.
173 dispatch: closure::Closure<'a, Buffer, Buffer>,
175 /// If 'true', always invoke the default panic hook
176 force_show_panics: bool,
178 // Prevent Send and Sync impls. `!Send`/`!Sync` is the usual way of doing
179 // this, but that requires unstable features. rust-analyzer uses this code
180 // and avoids unstable features.
181 _marker: marker::PhantomData<*mut ()>,
184 #[forbid(unsafe_code)]
185 #[allow(non_camel_case_types)]
187 use super::rpc::{DecodeMut, Encode, Reader, Writer};
189 macro_rules! declare_tags {
191 $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)*
194 pub(super) enum $name {
197 rpc_encode_decode!(enum $name { $($method),* });
200 pub(super) enum Method {
203 rpc_encode_decode!(enum Method { $($name(m)),* });
206 with_api!(self, self, declare_tags);
209 /// Helper to wrap associated types to allow trait impl dispatch.
210 /// That is, normally a pair of impls for `T::Foo` and `T::Bar`
211 /// can overlap, but if the impls are, instead, on types like
212 /// `Marked<T::Foo, Foo>` and `Marked<T::Bar, Bar>`, they can't.
215 fn mark(unmarked: Self::Unmarked) -> Self;
218 /// Unwrap types wrapped by `Mark::mark` (see `Mark` for details).
221 fn unmark(self) -> Self::Unmarked;
224 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
225 struct Marked<T, M> {
227 _marker: marker::PhantomData<M>,
230 impl<T, M> Mark for Marked<T, M> {
232 fn mark(unmarked: Self::Unmarked) -> Self {
233 Marked { value: unmarked, _marker: marker::PhantomData }
236 impl<T, M> Unmark for Marked<T, M> {
238 fn unmark(self) -> Self::Unmarked {
242 impl<'a, T, M> Unmark for &'a Marked<T, M> {
243 type Unmarked = &'a T;
244 fn unmark(self) -> Self::Unmarked {
248 impl<'a, T, M> Unmark for &'a mut Marked<T, M> {
249 type Unmarked = &'a mut T;
250 fn unmark(self) -> Self::Unmarked {
255 impl<T: Mark> Mark for Vec<T> {
256 type Unmarked = Vec<T::Unmarked>;
257 fn mark(unmarked: Self::Unmarked) -> Self {
258 // Should be a no-op due to std's in-place collect optimizations.
259 unmarked.into_iter().map(T::mark).collect()
262 impl<T: Unmark> Unmark for Vec<T> {
263 type Unmarked = Vec<T::Unmarked>;
264 fn unmark(self) -> Self::Unmarked {
265 // Should be a no-op due to std's in-place collect optimizations.
266 self.into_iter().map(T::unmark).collect()
270 macro_rules! mark_noop {
271 ($($ty:ty),* $(,)?) => {
274 type Unmarked = Self;
275 fn mark(unmarked: Self::Unmarked) -> Self {
279 impl Unmark for $ty {
280 type Unmarked = Self;
281 fn unmark(self) -> Self::Unmarked {
320 rpc_encode_decode!(struct LineColumn { line, column });
328 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
355 macro_rules! mark_compound {
356 (struct $name:ident <$($T:ident),+> { $($field:ident),* $(,)? }) => {
357 impl<$($T: Mark),+> Mark for $name <$($T),+> {
358 type Unmarked = $name <$($T::Unmarked),+>;
359 fn mark(unmarked: Self::Unmarked) -> Self {
361 $($field: Mark::mark(unmarked.$field)),*
366 impl<$($T: Unmark),+> Unmark for $name <$($T),+> {
367 type Unmarked = $name <$($T::Unmarked),+>;
368 fn unmark(self) -> Self::Unmarked {
370 $($field: Unmark::unmark(self.$field)),*
375 (enum $name:ident <$($T:ident),+> { $($variant:ident $(($field:ident))?),* $(,)? }) => {
376 impl<$($T: Mark),+> Mark for $name <$($T),+> {
377 type Unmarked = $name <$($T::Unmarked),+>;
378 fn mark(unmarked: Self::Unmarked) -> Self {
380 $($name::$variant $(($field))? => {
381 $name::$variant $((Mark::mark($field)))?
387 impl<$($T: Unmark),+> Unmark for $name <$($T),+> {
388 type Unmarked = $name <$($T::Unmarked),+>;
389 fn unmark(self) -> Self::Unmarked {
391 $($name::$variant $(($field))? => {
392 $name::$variant $((Unmark::unmark($field)))?
400 macro_rules! compound_traits {
402 rpc_encode_decode!($($t)*);
403 mark_compound!($($t)*);
429 #[derive(Copy, Clone)]
430 pub struct DelimSpan<Span> {
436 impl<Span: Copy> DelimSpan<Span> {
437 pub fn from_single(span: Span) -> Self {
438 DelimSpan { open: span, close: span, entire: span }
442 compound_traits!(struct DelimSpan<Span> { open, close, entire });
445 pub struct Group<TokenStream, Span> {
446 pub delimiter: Delimiter,
447 pub stream: Option<TokenStream>,
448 pub span: DelimSpan<Span>,
451 compound_traits!(struct Group<TokenStream, Span> { delimiter, stream, span });
454 pub struct Punct<Span> {
460 compound_traits!(struct Punct<Span> { ch, joint, span });
462 #[derive(Copy, Clone, Eq, PartialEq)]
463 pub struct Ident<Span, Symbol> {
469 compound_traits!(struct Ident<Span, Symbol> { sym, is_raw, span });
471 #[derive(Clone, Eq, PartialEq)]
472 pub struct Literal<Span, Symbol> {
475 pub suffix: Option<Symbol>,
479 compound_traits!(struct Literal<Sp, Sy> { kind, symbol, suffix, span });
482 pub enum TokenTree<TokenStream, Span, Symbol> {
483 Group(Group<TokenStream, Span>),
485 Ident(Ident<Span, Symbol>),
486 Literal(Literal<Span, Symbol>),
490 enum TokenTree<TokenStream, Span, Symbol> {
498 #[derive(Clone, Debug)]
499 pub struct Diagnostic<Span> {
502 pub spans: Vec<Span>,
503 pub children: Vec<Diagnostic<Span>>,
507 struct Diagnostic<Span> { level, message, spans, children }
510 /// Globals provided alongside the initial inputs for a macro expansion.
511 /// Provides values such as spans which are used frequently to avoid RPC.
513 pub struct ExpnGlobals<Span> {
516 pub mixed_site: Span,
520 struct ExpnGlobals<Span> { def_site, call_site, mixed_site }