1use anyhow::{bail, Result};
16use proc_macro2::Span;
17use proc_macro2::TokenStream;
18use quote::TokenStreamExt;
19use quote::{quote, ToTokens};
20use syn::parse_quote;
21use syn::FnArg;
22use syn::GenericArgument;
23use syn::ImplItemFn;
24use syn::ItemImpl;
25use syn::Pat;
26use syn::PathArguments;
27use syn::ReceiverKind;
28use syn::Type;
29
30#[proc_macro_attribute]
31pub fn php_async_impl(
32 _: proc_macro::TokenStream,
33 input: proc_macro::TokenStream,
34) -> proc_macro::TokenStream {
35 expand(input.into()).into()
36}
37
38fn expand(input: TokenStream) -> TokenStream {
39 match syn::parse2::<ItemImpl>(input) {
40 Ok(input) => parser(input)
41 .unwrap_or_else(|e| syn::Error::new(Span::call_site(), e).to_compile_error()),
42 Err(e) => e.to_compile_error(),
43 }
44}
45
46fn parser(input: ItemImpl) -> Result<TokenStream> {
47 let ItemImpl { self_ty, items, .. } = input;
48
49 if input.trait_.is_some() {
50 bail!("This macro cannot be used on trait implementations.");
51 }
52
53 let tokens = items
54 .into_iter()
55 .map(|item| {
56 Ok(match item {
57 syn::ImplItem::Fn(method) => handle_method(method)?,
58 item => item.to_token_stream(),
59 })
60 })
61 .collect::<Result<Vec<_>>>()?;
62
63 let output = quote! {
64 #[::ext_php_rs::php_impl]
65 impl #self_ty {
66 #(#tokens)*
67 }
68 };
69
70 Ok(output)
71}
72
73fn handle_method(input: ImplItemFn) -> Result<TokenStream> {
74 let mut receiver = false;
75 let mut receiver_mutable = false;
76 let mut hack_tokens = quote! {};
77 for arg in input.sig.inputs.iter() {
78 match arg {
79 FnArg::Receiver(r) => {
80 receiver = true;
81 match &r.kind {
83 ReceiverKind::Reference(_, _, mutability) => {
84 receiver_mutable = mutability.is_some();
85 }
86 _ if input.sig.asyncness.is_some() => {
87 bail!("Async methods must take &self or &mut self.")
88 }
89 _ => {}
90 }
91 }
92 FnArg::Typed(ty) => {
93 let mut this = false;
94 for attr in ty.attrs.iter() {
95 if attr.path().to_token_stream().to_string() == "this" {
96 this = true;
97 }
98 }
99
100 if !this {
101 let param = match &*ty.pat {
102 Pat::Ident(pat) => &pat.ident,
103 _ => bail!("Invalid parameter type."),
104 };
105
106 let mut ty_inner = &*ty.ty;
107 let mut is_option = false;
108
109 if let Type::Path(t) = ty_inner {
110 if t.path.segments[0].ident == "Option" {
111 if let PathArguments::AngleBracketed(t) = &t.path.segments[0].arguments
112 {
113 if let GenericArgument::Type(t) = &t.args[0] {
114 ty_inner = t;
115 is_option = true;
116 }
117 }
118 }
119 }
120 let mut is_str = false;
121 if let Type::Reference(t) = ty_inner {
122 if t.mutability.is_none() {
123 if let Type::Path(t) = &*t.elem {
124 is_str = t.path.is_ident("str");
125 }
126 }
127 hack_tokens.append_all(if is_str {
128 if is_option {
129 quote! { let #param = #param.and_then(|__temp| Some(unsafe { ::core::mem::transmute::<&str, &'static str>(__temp) })); }
130 } else {
131 quote! { let #param = unsafe { ::core::mem::transmute::<&str, &'static str>(#param) }; }
132 }
133 } else {
134 if is_option {
135 quote! { let #param = #param.and_then(|__temp| Some(unsafe { ::php_tokio::borrow_unchecked::borrow_unchecked(__temp) })); }
136 } else {
137 quote! { let #param = unsafe { ::php_tokio::borrow_unchecked::borrow_unchecked(#param) }; }
138 }
139 });
140 }
141 }
142 }
143 }
144 }
145
146 let mut input = input.clone();
147 if input.sig.asyncness.is_some() {
148 input.sig.asyncness = None;
149 let stmts = input.block;
150 let this = if receiver {
151 if receiver_mutable {
152 quote! { let this = unsafe { std::mem::transmute::<&mut Self, &'static mut Self>(self) }; }
153 } else {
154 quote! { let this = unsafe { std::mem::transmute::<&Self, &'static Self>(self) }; }
155 }
156 } else {
157 quote! {}
158 };
159 input.block = parse_quote! {{
160 #this
161 #hack_tokens
162
163 ::php_tokio::EventLoop::suspend_on(async move #stmts)
164 }};
165 }
166
167 let result = quote! {
168 #input
169 };
170 Ok(result)
171}
172
173#[cfg(test)]
174mod tests {
175 use super::expand;
176 use proc_macro2::TokenStream;
177 use quote::quote;
178
179 #[track_caller]
180 fn assert_expands(input: TokenStream, expected: TokenStream) {
181 assert_eq!(expand(input).to_string(), expected.to_string());
182 }
183
184 #[test]
185 fn async_methods_suspend_on_their_body() {
186 assert_expands(
187 quote! {
188 impl Native {
189 const C: u8 = 1;
190 pub fn sync(a: &str) -> u8 { 1 }
191 pub async fn plain(ms: u64, n: Option<u64>, v: Vec<u8>) -> u64 { ms }
192 }
193 },
194 quote! {
195 #[::ext_php_rs::php_impl]
196 impl Native {
197 const C: u8 = 1;
198 pub fn sync(a: &str) -> u8 { 1 }
199 pub fn plain(ms: u64, n: Option<u64>, v: Vec<u8>) -> u64 {
200 ::php_tokio::EventLoop::suspend_on(async move { ms })
201 }
202 }
203 },
204 );
205 }
206
207 #[test]
208 fn receivers_are_borrowed_for_the_suspension() {
209 assert_expands(
210 quote! {
211 impl Native {
212 async fn shared(&self) {}
213 async fn exclusive(&mut self) {}
214 }
215 },
216 quote! {
217 #[::ext_php_rs::php_impl]
218 impl Native {
219 fn shared(&self) {
220 let this = unsafe { std::mem::transmute::<&Self, &'static Self>(self) };
221 ::php_tokio::EventLoop::suspend_on(async move {})
222 }
223 fn exclusive(&mut self) {
224 let this = unsafe { std::mem::transmute::<&mut Self, &'static mut Self>(self) };
225 ::php_tokio::EventLoop::suspend_on(async move {})
226 }
227 }
228 },
229 );
230 }
231
232 #[test]
233 fn references_are_borrowed_for_the_suspension() {
234 assert_expands(
235 quote! {
236 impl Native {
237 async fn args(
238 s: &str,
239 os: Option<&str>,
240 b: &[u8],
241 ob: Option<&[u8]>,
242 m: &mut str,
243 r: &&str,
244 #[this] t: &Native,
245 #[allow(unused)] u: &str,
246 o: Option,
247 l: Option<'a>,
248 ) {}
249 }
250 },
251 quote! {
252 #[::ext_php_rs::php_impl]
253 impl Native {
254 fn args(
255 s: &str,
256 os: Option<&str>,
257 b: &[u8],
258 ob: Option<&[u8]>,
259 m: &mut str,
260 r: & &str,
261 #[this] t: &Native,
262 #[allow(unused)] u: &str,
263 o: Option,
264 l: Option<'a>,
265 ) {
266 let s = unsafe { ::core::mem::transmute::<&str, &'static str>(s) };
267 let os = os.and_then(|__temp| Some(unsafe { ::core::mem::transmute::<&str, &'static str>(__temp) }));
268 let b = unsafe { ::php_tokio::borrow_unchecked::borrow_unchecked(b) };
269 let ob = ob.and_then(|__temp| Some(unsafe { ::php_tokio::borrow_unchecked::borrow_unchecked(__temp) }));
270 let m = unsafe { ::php_tokio::borrow_unchecked::borrow_unchecked(m) };
271 let r = unsafe { ::php_tokio::borrow_unchecked::borrow_unchecked(r) };
272 let u = unsafe { ::core::mem::transmute::<&str, &'static str>(u) };
273 ::php_tokio::EventLoop::suspend_on(async move {})
274 }
275 }
276 },
277 );
278 }
279
280 #[test]
281 fn errors_become_compile_errors() {
282 let error = |message: &str| quote! { ::core::compile_error! { #message } }.to_string();
283 assert_eq!(
284 expand(quote! { impl Trait for Native {} }).to_string(),
285 error("This macro cannot be used on trait implementations.")
286 );
287 assert_eq!(
288 expand(quote! { impl Native { async fn f((a, b): (u8, u8)) {} } }).to_string(),
289 error("Invalid parameter type.")
290 );
291 for receiver in [quote! { self }, quote! { self: Box<Self> }] {
292 assert_eq!(
293 expand(quote! { impl Native { async fn f(#receiver) {} } }).to_string(),
294 error("Async methods must take &self or &mut self.")
295 );
296 assert_eq!(
298 expand(quote! { impl Native { fn f(#receiver) {} } }).to_string(),
299 quote! { #[::ext_php_rs::php_impl] impl Native { fn f(#receiver) {} } }.to_string()
300 );
301 }
302 assert_eq!(
303 expand(quote! { fn f() {} }).to_string(),
304 error("expected `impl`")
305 );
306 }
307}