Skip to main content

rustc_expand/
proc_macro.rs

1use rustc_ast::tokenstream::TokenStream;
2use rustc_errors::ErrorGuaranteed;
3use rustc_middle::ty::{self, TyCtxt};
4use rustc_parse::parser::{AllowConstBlockItems, 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(
164                ForceCollect::No,
165                if is_stmt { AllowConstBlockItems::No } else { AllowConstBlockItems::Yes },
166            ) {
167                Ok(None) => break,
168                Ok(Some(item)) => {
169                    if is_stmt {
170                        items.push(Annotatable::Stmt(Box::new(ecx.stmt_item(span, item))));
171                    } else {
172                        items.push(Annotatable::Item(item));
173                    }
174                }
175                Err(err) => {
176                    err.emit();
177                    break;
178                }
179            }
180        }
181
182        // fail if there have been errors emitted
183        if ecx.dcx().err_count() > error_count_before {
184            ecx.dcx().emit_err(errors::ProcMacroDeriveTokens { span });
185        }
186
187        ExpandResult::Ready(items)
188    }
189}
190
191/// Provide a query for computing the output of a derive macro.
192pub(super) fn provide_derive_macro_expansion<'tcx>(
193    tcx: TyCtxt<'tcx>,
194    key: (LocalExpnId, &'tcx TokenStream),
195) -> Result<&'tcx TokenStream, ()> {
196    let (invoc_id, input) = key;
197
198    // Make sure that we invalidate the query when the crate defining the proc macro changes
199    let _ = tcx.crate_hash(invoc_id.expn_data().macro_def_id.unwrap().krate);
200
201    QueryDeriveExpandCtx::with(|ecx, client| {
202        expand_derive_macro(invoc_id, input.clone(), ecx, client).map(|ts| &*tcx.arena.alloc(ts))
203    })
204}
205
206type DeriveClient = pm::bridge::client::Client<pm::TokenStream, pm::TokenStream>;
207
208fn expand_derive_macro(
209    invoc_id: LocalExpnId,
210    input: TokenStream,
211    ecx: &mut ExtCtxt<'_>,
212    client: DeriveClient,
213) -> Result<TokenStream, ()> {
214    let _timer =
215        ecx.sess.prof.generic_activity_with_arg_recorder("expand_proc_macro", |recorder| {
216            let invoc_expn_data = invoc_id.expn_data();
217            let span = invoc_expn_data.call_site;
218            let event_arg = invoc_expn_data.kind.descr();
219            recorder.record_arg_with_span(ecx.sess.source_map(), event_arg.clone(), span);
220        });
221
222    let proc_macro_backtrace = ecx.ecfg.proc_macro_backtrace;
223    let strategy = exec_strategy(ecx.sess);
224    let server = proc_macro_server::Rustc::new(ecx);
225
226    match client.run(&strategy, server, input, proc_macro_backtrace) {
227        Ok(stream) => Ok(stream),
228        Err(e) => {
229            let invoc_expn_data = invoc_id.expn_data();
230            let span = invoc_expn_data.call_site;
231            ecx.dcx().emit_err({
232                errors::ProcMacroDerivePanicked {
233                    span,
234                    message: e.as_str().map(|message| errors::ProcMacroDerivePanickedHelp {
235                        message: message.into(),
236                    }),
237                }
238            });
239            Err(())
240        }
241    }
242}
243
244/// Stores the context necessary to expand a derive proc macro via a query.
245struct QueryDeriveExpandCtx {
246    /// Type-erased version of `&mut ExtCtxt`
247    expansion_ctx: *mut (),
248    client: DeriveClient,
249}
250
251impl QueryDeriveExpandCtx {
252    /// Store the extension context and the client into the thread local value.
253    /// It will be accessible via the `with` method while `f` is active.
254    fn enter<F, R>(ecx: &mut ExtCtxt<'_>, client: DeriveClient, f: F) -> R
255    where
256        F: FnOnce() -> R,
257    {
258        // We need erasure to get rid of the lifetime
259        let ctx = Self { expansion_ctx: ecx as *mut _ as *mut (), client };
260        DERIVE_EXPAND_CTX.set(&ctx, || f())
261    }
262
263    /// Accesses the thread local value of the derive expansion context.
264    /// Must be called while the `enter` function is active.
265    fn with<F, R>(f: F) -> R
266    where
267        F: for<'a, 'b> FnOnce(&'b mut ExtCtxt<'a>, DeriveClient) -> R,
268    {
269        DERIVE_EXPAND_CTX.with(|ctx| {
270            let ectx = {
271                let casted = ctx.expansion_ctx.cast::<ExtCtxt<'_>>();
272                // SAFETY: We can only get the value from `with` while the `enter` function
273                // is active (on the callstack), and that function's signature ensures that the
274                // lifetime is valid.
275                // If `with` is called at some other time, it will panic due to usage of
276                // `scoped_tls::with`.
277                unsafe { casted.as_mut().unwrap() }
278            };
279
280            f(ectx, ctx.client)
281        })
282    }
283}
284
285// When we invoke a query to expand a derive proc macro, we need to provide it with the expansion
286// context and derive Client. We do that using a thread-local.
287static 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);