rustc_expand/
proc_macro.rs

1use rustc_ast::tokenstream::TokenStream;
2use rustc_errors::ErrorGuaranteed;
3use rustc_middle::ty::{self, TyCtxt};
4use rustc_parse::parser::{ForceCollect, Parser};
5use rustc_session::Session;
6use rustc_session::config::ProcMacroExecutionStrategy;
7use rustc_span::profiling::SpannedEventArgRecorder;
8use rustc_span::{LocalExpnId, Span};
9use {rustc_ast as ast, rustc_proc_macro as pm};
10
11use crate::base::{self, *};
12use crate::{errors, proc_macro_server};
13
14struct MessagePipe<T> {
15    tx: std::sync::mpsc::SyncSender<T>,
16    rx: std::sync::mpsc::Receiver<T>,
17}
18
19impl<T> pm::bridge::server::MessagePipe<T> for MessagePipe<T> {
20    fn new() -> (Self, Self) {
21        let (tx1, rx1) = std::sync::mpsc::sync_channel(1);
22        let (tx2, rx2) = std::sync::mpsc::sync_channel(1);
23        (MessagePipe { tx: tx1, rx: rx2 }, MessagePipe { tx: tx2, rx: rx1 })
24    }
25
26    fn send(&mut self, value: T) {
27        self.tx.send(value).unwrap();
28    }
29
30    fn recv(&mut self) -> Option<T> {
31        self.rx.recv().ok()
32    }
33}
34
35fn exec_strategy(sess: &Session) -> impl pm::bridge::server::ExecutionStrategy + 'static {
36    pm::bridge::server::MaybeCrossThread::<MessagePipe<_>>::new(
37        sess.opts.unstable_opts.proc_macro_execution_strategy
38            == ProcMacroExecutionStrategy::CrossThread,
39    )
40}
41
42pub struct BangProcMacro {
43    pub client: pm::bridge::client::Client<pm::TokenStream, pm::TokenStream>,
44}
45
46impl base::BangProcMacro for BangProcMacro {
47    fn expand(
48        &self,
49        ecx: &mut ExtCtxt<'_>,
50        span: Span,
51        input: TokenStream,
52    ) -> Result<TokenStream, ErrorGuaranteed> {
53        let _timer =
54            ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| {
55                recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span);
56            });
57
58        let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace;
59        let strategy = exec_strategy(ecx.sess);
60        let server = proc_macro_server::Rustc::new(ecx);
61        self.client.run(&strategy, server, input, proc_macro_backtrace).map_err(|e| {
62            ecx.dcx().emit_err(errors::ProcMacroPanicked {
63                span,
64                message: e
65                    .as_str()
66                    .map(|message| errors::ProcMacroPanickedHelp { message: message.into() }),
67            })
68        })
69    }
70}
71
72pub struct AttrProcMacro {
73    pub client: pm::bridge::client::Client<(pm::TokenStream, pm::TokenStream), pm::TokenStream>,
74}
75
76impl base::AttrProcMacro for AttrProcMacro {
77    fn expand(
78        &self,
79        ecx: &mut ExtCtxt<'_>,
80        span: Span,
81        annotation: TokenStream,
82        annotated: TokenStream,
83    ) -> Result<TokenStream, ErrorGuaranteed> {
84        let _timer =
85            ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| {
86                recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span);
87            });
88
89        let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace;
90        let strategy = exec_strategy(ecx.sess);
91        let server = proc_macro_server::Rustc::new(ecx);
92        self.client.run(&strategy, server, annotation, annotated, proc_macro_backtrace).map_err(
93            |e| {
94                ecx.dcx().emit_err(errors::CustomAttributePanicked {
95                    span,
96                    message: e.as_str().map(|message| errors::CustomAttributePanickedHelp {
97                        message: message.into(),
98                    }),
99                })
100            },
101        )
102    }
103}
104
105pub struct DeriveProcMacro {
106    pub client: DeriveClient,
107}
108
109impl MultiItemModifier for DeriveProcMacro {
110    fn expand(
111        &self,
112        ecx: &mut ExtCtxt<'_>,
113        span: Span,
114        _meta_item: &ast::MetaItem,
115        item: Annotatable,
116        _is_derive_const: bool,
117    ) -> ExpandResult<Vec<Annotatable>, Annotatable> {
118        let _timer = ecx.sess.prof.generic_activity_with_arg_recorder(
119            "expand_derive_proc_macro_outer",
120            |recorder| {
121                recorder.record_arg_with_span(ecx.sess.source_map(), ecx.expansion_descr(), span);
122            },
123        );
124
125        // We need special handling for statement items
126        // (e.g. `fn foo() { #[derive(Debug)] struct Bar; }`)
127        let is_stmt = #[allow(non_exhaustive_omitted_patterns)] match item {
    Annotatable::Stmt(..) => true,
    _ => false,
}matches!(item, Annotatable::Stmt(..));
128
129        // We used to have an alternative behaviour for crates that needed it.
130        // We had a lint for a long time, but now we just emit a hard error.
131        // Eventually we might remove the special case hard error check
132        // altogether. See #73345.
133        crate::base::ann_pretty_printing_compatibility_hack(&item, &ecx.sess.psess);
134        let input = item.to_tokens();
135
136        let invoc_id = ecx.current_expansion.id;
137
138        let res = if ecx.sess.opts.incremental.is_some()
139            && ecx.sess.opts.unstable_opts.cache_proc_macros
140        {
141            ty::tls::with(|tcx| {
142                let input = &*tcx.arena.alloc(input);
143                let key: (LocalExpnId, &TokenStream) = (invoc_id, input);
144
145                QueryDeriveExpandCtx::enter(ecx, self.client, move || {
146                    tcx.derive_macro_expansion(key).cloned()
147                })
148            })
149        } else {
150            expand_derive_macro(invoc_id, input, ecx, self.client)
151        };
152
153        let Ok(output) = res else {
154            // error will already have been emitted
155            return ExpandResult::Ready(::alloc::vec::Vec::new()vec![]);
156        };
157
158        let error_count_before = ecx.dcx().err_count();
159        let mut parser = Parser::new(&ecx.sess.psess, output, Some("proc-macro derive"));
160        let mut items = ::alloc::vec::Vec::new()vec![];
161
162        loop {
163            match parser.parse_item(ForceCollect::No) {
164                Ok(None) => break,
165                Ok(Some(item)) => {
166                    if is_stmt {
167                        items.push(Annotatable::Stmt(Box::new(ecx.stmt_item(span, item))));
168                    } else {
169                        items.push(Annotatable::Item(item));
170                    }
171                }
172                Err(err) => {
173                    err.emit();
174                    break;
175                }
176            }
177        }
178
179        // fail if there have been errors emitted
180        if ecx.dcx().err_count() > error_count_before {
181            ecx.dcx().emit_err(errors::ProcMacroDeriveTokens { span });
182        }
183
184        ExpandResult::Ready(items)
185    }
186}
187
188/// Provide a query for computing the output of a derive macro.
189pub(super) fn provide_derive_macro_expansion<'tcx>(
190    tcx: TyCtxt<'tcx>,
191    key: (LocalExpnId, &'tcx TokenStream),
192) -> Result<&'tcx TokenStream, ()> {
193    let (invoc_id, input) = key;
194
195    // Make sure that we invalidate the query when the crate defining the proc macro changes
196    let _ = tcx.crate_hash(invoc_id.expn_data().macro_def_id.unwrap().krate);
197
198    QueryDeriveExpandCtx::with(|ecx, client| {
199        expand_derive_macro(invoc_id, input.clone(), ecx, client).map(|ts| &*tcx.arena.alloc(ts))
200    })
201}
202
203type DeriveClient = pm::bridge::client::Client<pm::TokenStream, pm::TokenStream>;
204
205fn expand_derive_macro(
206    invoc_id: LocalExpnId,
207    input: TokenStream,
208    ecx: &mut ExtCtxt<'_>,
209    client: DeriveClient,
210) -> Result<TokenStream, ()> {
211    let _timer =
212        ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| {
213            let invoc_expn_data = invoc_id.expn_data();
214            let span = invoc_expn_data.call_site;
215            let event_arg = invoc_expn_data.kind.descr();
216            recorder.record_arg_with_span(ecx.sess.source_map(), event_arg.clone(), span);
217        });
218
219    let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace;
220    let strategy = exec_strategy(ecx.sess);
221    let server = proc_macro_server::Rustc::new(ecx);
222
223    match client.run(&strategy, server, input, proc_macro_backtrace) {
224        Ok(stream) => Ok(stream),
225        Err(e) => {
226            let invoc_expn_data = invoc_id.expn_data();
227            let span = invoc_expn_data.call_site;
228            ecx.dcx().emit_err({
229                errors::ProcMacroDerivePanicked {
230                    span,
231                    message: e.as_str().map(|message| errors::ProcMacroDerivePanickedHelp {
232                        message: message.into(),
233                    }),
234                }
235            });
236            Err(())
237        }
238    }
239}
240
241/// Stores the context necessary to expand a derive proc macro via a query.
242struct QueryDeriveExpandCtx {
243    /// Type-erased version of `&mut ExtCtxt`
244    expansion_ctx: *mut (),
245    client: DeriveClient,
246}
247
248impl QueryDeriveExpandCtx {
249    /// Store the extension context and the client into the thread local value.
250    /// It will be accessible via the `with` method while `f` is active.
251    fn enter<F, R>(ecx: &mut ExtCtxt<'_>, client: DeriveClient, f: F) -> R
252    where
253        F: FnOnce() -> R,
254    {
255        // We need erasure to get rid of the lifetime
256        let ctx = Self { expansion_ctx: ecx as *mut _ as *mut (), client };
257        DERIVE_EXPAND_CTX.set(&ctx, || f())
258    }
259
260    /// Accesses the thread local value of the derive expansion context.
261    /// Must be called while the `enter` function is active.
262    fn with<F, R>(f: F) -> R
263    where
264        F: for<'a, 'b> FnOnce(&'b mut ExtCtxt<'a>, DeriveClient) -> R,
265    {
266        DERIVE_EXPAND_CTX.with(|ctx| {
267            let ectx = {
268                let casted = ctx.expansion_ctx.cast::<ExtCtxt<'_>>();
269                // SAFETY: We can only get the value from `with` while the `enter` function
270                // is active (on the callstack), and that function's signature ensures that the
271                // lifetime is valid.
272                // If `with` is called at some other time, it will panic due to usage of
273                // `scoped_tls::with`.
274                unsafe { casted.as_mut().unwrap() }
275            };
276
277            f(ectx, ctx.client)
278        })
279    }
280}
281
282// When we invoke a query to expand a derive proc macro, we need to provide it with the expansion
283// context and derive Client. We do that using a thread-local.
284static DERIVE_EXPAND_CTX: ::scoped_tls::ScopedKey<QueryDeriveExpandCtx> =
    ::scoped_tls::ScopedKey {
        inner: {
            const FOO: ::std::thread::LocalKey<::std::cell::Cell<*const ()>> =
                {
                    const __RUST_STD_INTERNAL_INIT: ::std::cell::Cell<*const ()>
                        =
                        { ::std::cell::Cell::new(::std::ptr::null()) };
                    unsafe {
                        ::std::thread::LocalKey::new(const {
                                    if ::std::mem::needs_drop::<::std::cell::Cell<*const ()>>()
                                        {
                                        |_|
                                            {
                                                #[thread_local]
                                                static __RUST_STD_INTERNAL_VAL:
                                                    ::std::thread::local_impl::EagerStorage<::std::cell::Cell<*const ()>>
                                                    =
                                                    ::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                                __RUST_STD_INTERNAL_VAL.get()
                                            }
                                    } else {
                                        |_|
                                            {
                                                #[thread_local]
                                                static __RUST_STD_INTERNAL_VAL: ::std::cell::Cell<*const ()>
                                                    =
                                                    __RUST_STD_INTERNAL_INIT;
                                                &__RUST_STD_INTERNAL_VAL
                                            }
                                    }
                                })
                    }
                };
            &FOO
        },
        _marker: ::std::marker::PhantomData,
    };scoped_tls::scoped_thread_local!(static DERIVE_EXPAND_CTX: QueryDeriveExpandCtx);