1 | use proc_macro2::{Ident, Span, TokenStream}; |
2 | |
3 | use quote::{format_ident, quote}; |
4 | |
5 | use crate::{ |
6 | protocol::{Interface, Protocol, Type}, |
7 | util::{description_to_doc_attr, dotted_to_relname, is_keyword, snake_to_camel, to_doc_attr}, |
8 | Side, |
9 | }; |
10 | |
11 | pub fn generate_client_objects(protocol: &Protocol) -> TokenStream { |
12 | protocol.interfaces.iter().map(generate_objects_for).collect() |
13 | } |
14 | |
15 | fn generate_objects_for(interface: &Interface) -> TokenStream { |
16 | let mod_name = Ident::new(&interface.name, Span::call_site()); |
17 | let mod_doc = interface.description.as_ref().map(description_to_doc_attr); |
18 | let iface_name = Ident::new(&snake_to_camel(&interface.name), Span::call_site()); |
19 | let iface_const_name = format_ident!(" {}_INTERFACE" , interface.name.to_ascii_uppercase()); |
20 | |
21 | let enums = crate::common::generate_enums_for(interface); |
22 | let sinces = crate::common::gen_msg_constants(&interface.requests, &interface.events); |
23 | |
24 | let requests = crate::common::gen_message_enum( |
25 | &format_ident!("Request" ), |
26 | Side::Client, |
27 | false, |
28 | &interface.requests, |
29 | ); |
30 | let events = crate::common::gen_message_enum( |
31 | &format_ident!("Event" ), |
32 | Side::Client, |
33 | true, |
34 | &interface.events, |
35 | ); |
36 | |
37 | let parse_body = crate::common::gen_parse_body(interface, Side::Client); |
38 | let write_body = crate::common::gen_write_body(interface, Side::Client); |
39 | let methods = gen_methods(interface); |
40 | |
41 | let event_ref = if interface.events.is_empty() { |
42 | "This interface has no events." |
43 | } else { |
44 | "See also the [Event] enum for this interface." |
45 | }; |
46 | let docs = match &interface.description { |
47 | Some((short, long)) => format!(" {}\n\n{}\n\n{}" , short, long, event_ref), |
48 | None => format!(" {}\n\n{}" , interface.name, event_ref), |
49 | }; |
50 | let doc_attr = to_doc_attr(&docs); |
51 | |
52 | quote! { |
53 | #mod_doc |
54 | pub mod #mod_name { |
55 | use std::sync::Arc; |
56 | use std::os::unix::io::OwnedFd; |
57 | |
58 | use super::wayland_client::{ |
59 | backend::{ |
60 | Backend, WeakBackend, smallvec, ObjectData, ObjectId, InvalidId, |
61 | protocol::{WEnum, Argument, Message, Interface, same_interface} |
62 | }, |
63 | QueueProxyData, Proxy, Connection, Dispatch, QueueHandle, DispatchError, Weak, |
64 | }; |
65 | |
66 | #enums |
67 | #sinces |
68 | #requests |
69 | #events |
70 | |
71 | #doc_attr |
72 | #[derive(Debug, Clone)] |
73 | pub struct #iface_name { |
74 | id: ObjectId, |
75 | version: u32, |
76 | data: Option<Arc<dyn ObjectData>>, |
77 | backend: WeakBackend, |
78 | } |
79 | |
80 | impl std::cmp::PartialEq for #iface_name { |
81 | fn eq(&self, other: &#iface_name) -> bool { |
82 | self.id == other.id |
83 | } |
84 | } |
85 | |
86 | impl std::cmp::Eq for #iface_name {} |
87 | |
88 | impl PartialEq<Weak<#iface_name>> for #iface_name { |
89 | fn eq(&self, other: &Weak<#iface_name>) -> bool { |
90 | self.id == other.id() |
91 | } |
92 | } |
93 | |
94 | impl std::borrow::Borrow<ObjectId> for #iface_name { |
95 | fn borrow(&self) -> &ObjectId { |
96 | &self.id |
97 | } |
98 | } |
99 | |
100 | impl std::hash::Hash for #iface_name { |
101 | fn hash<H: std::hash::Hasher>(&self, state: &mut H) { |
102 | self.id.hash(state) |
103 | } |
104 | } |
105 | |
106 | impl super::wayland_client::Proxy for #iface_name { |
107 | type Request<'request> = Request<'request>; |
108 | type Event = Event; |
109 | |
110 | #[inline] |
111 | fn interface() -> &'static Interface{ |
112 | &super::#iface_const_name |
113 | } |
114 | |
115 | #[inline] |
116 | fn id(&self) -> ObjectId { |
117 | self.id.clone() |
118 | } |
119 | |
120 | #[inline] |
121 | fn version(&self) -> u32 { |
122 | self.version |
123 | } |
124 | |
125 | #[inline] |
126 | fn data<U: Send + Sync + 'static>(&self) -> Option<&U> { |
127 | self.data.as_ref().and_then(|arc| arc.data_as_any().downcast_ref::<U>()) |
128 | } |
129 | |
130 | fn object_data(&self) -> Option<&Arc<dyn ObjectData>> { |
131 | self.data.as_ref() |
132 | } |
133 | |
134 | fn backend(&self) -> &WeakBackend { |
135 | &self.backend |
136 | } |
137 | |
138 | fn send_request(&self, req: Self::Request<'_>) -> Result<(), InvalidId> { |
139 | let conn = Connection::from_backend(self.backend.upgrade().ok_or(InvalidId)?); |
140 | let id = conn.send_request(self, req, None)?; |
141 | debug_assert!(id.is_null()); |
142 | Ok(()) |
143 | } |
144 | |
145 | fn send_constructor<I: Proxy>(&self, req: Self::Request<'_>, data: Arc<dyn ObjectData>) -> Result<I, InvalidId> { |
146 | let conn = Connection::from_backend(self.backend.upgrade().ok_or(InvalidId)?); |
147 | let id = conn.send_request(self, req, Some(data))?; |
148 | Proxy::from_id(&conn, id) |
149 | } |
150 | |
151 | #[inline] |
152 | fn from_id(conn: &Connection, id: ObjectId) -> Result<Self, InvalidId> { |
153 | if !same_interface(id.interface(), Self::interface()) && !id.is_null() { |
154 | return Err(InvalidId); |
155 | } |
156 | let version = conn.object_info(id.clone()).map(|info| info.version).unwrap_or(0); |
157 | let data = conn.get_object_data(id.clone()).ok(); |
158 | let backend = conn.backend().downgrade(); |
159 | Ok(#iface_name { id, data, version, backend }) |
160 | } |
161 | |
162 | #[inline] |
163 | fn inert(backend: WeakBackend) -> Self { |
164 | #iface_name { id: ObjectId::null(), data: None, version: 0, backend } |
165 | } |
166 | |
167 | fn parse_event(conn: &Connection, msg: Message<ObjectId, OwnedFd>) -> Result<(Self, Self::Event), DispatchError> { |
168 | #parse_body |
169 | } |
170 | |
171 | fn write_request<'a>(&self, conn: &Connection, msg: Self::Request<'a>) -> Result<(Message<ObjectId, std::os::unix::io::BorrowedFd<'a>>, Option<(&'static Interface, u32)>), InvalidId> { |
172 | #write_body |
173 | } |
174 | } |
175 | |
176 | impl #iface_name { |
177 | #methods |
178 | } |
179 | } |
180 | } |
181 | } |
182 | |
183 | fn gen_methods(interface: &Interface) -> TokenStream { |
184 | interface.requests.iter().map(|request| { |
185 | let created_interface = request.args.iter().find(|arg| arg.typ == Type::NewId).map(|arg| &arg.interface); |
186 | |
187 | let method_name = format_ident!(" {}{}" , if is_keyword(&request.name) { "_" } else { "" }, request.name); |
188 | let enum_variant = Ident::new(&snake_to_camel(&request.name), Span::call_site()); |
189 | |
190 | let fn_args = request.args.iter().flat_map(|arg| { |
191 | if arg.typ == Type::NewId { |
192 | if arg.interface.is_none() { |
193 | // the new_id argument of a bind-like method |
194 | // it shoudl expand as a (interface, type) tuple, but the type is already handled by |
195 | // the prototype type parameter, so just put a version here |
196 | return Some(quote! { version: u32 }); |
197 | } else { |
198 | // this is a regular new_id, skip it |
199 | return None; |
200 | } |
201 | } |
202 | |
203 | let arg_name = format_ident!(" {}{}" , if is_keyword(&arg.name) { "_" } else { "" }, arg.name); |
204 | |
205 | let arg_type = if let Some(ref enu) = arg.enum_ { |
206 | let enum_type = dotted_to_relname(enu); |
207 | quote! { #enum_type } |
208 | } else { |
209 | match arg.typ { |
210 | Type::Uint => quote! { u32 }, |
211 | Type::Int => quote! { i32 }, |
212 | Type::Fixed => quote! { f64 }, |
213 | Type::String => if arg.allow_null { quote!{ Option<String> } } else { quote!{ String } }, |
214 | Type::Array => if arg.allow_null { quote!{ Option<Vec<u8>> } } else { quote!{ Vec<u8> } }, |
215 | Type::Fd => quote! { ::std::os::unix::io::BorrowedFd<'_> }, |
216 | Type::Object => { |
217 | let iface = arg.interface.as_ref().unwrap(); |
218 | let iface_mod = Ident::new(iface, Span::call_site()); |
219 | let iface_type = |
220 | Ident::new(&snake_to_camel(iface), Span::call_site()); |
221 | if arg.allow_null { quote! { Option<&super::#iface_mod::#iface_type> } } else { quote! { &super::#iface_mod::#iface_type } } |
222 | }, |
223 | Type::NewId => unreachable!(), |
224 | Type::Destructor => panic!("An argument cannot have type \"destructor \"." ), |
225 | } |
226 | }; |
227 | |
228 | Some(quote! { |
229 | #arg_name: #arg_type |
230 | }) |
231 | }); |
232 | |
233 | let enum_args = request.args.iter().flat_map(|arg| { |
234 | let arg_name = format_ident!(" {}{}" , if is_keyword(&arg.name) { "_" } else { "" }, arg.name); |
235 | if arg.enum_.is_some() { |
236 | Some(quote! { #arg_name: WEnum::Value(#arg_name) }) |
237 | } else if arg.typ == Type::NewId { |
238 | if arg.interface.is_none() { |
239 | Some(quote! { #arg_name: (I::interface(), version) }) |
240 | } else { |
241 | None |
242 | } |
243 | } else if arg.typ == Type::Object { |
244 | if arg.allow_null { |
245 | Some(quote! { #arg_name: #arg_name.cloned() }) |
246 | } else { |
247 | Some(quote! { #arg_name: #arg_name.clone() }) |
248 | } |
249 | } else { |
250 | Some(quote! { #arg_name }) |
251 | } |
252 | }); |
253 | |
254 | let doc_attr = request |
255 | .description |
256 | .as_ref() |
257 | .map(description_to_doc_attr); |
258 | |
259 | match created_interface { |
260 | Some(Some(ref created_interface)) => { |
261 | // a regular creating request |
262 | let created_iface_mod = Ident::new(created_interface, Span::call_site()); |
263 | let created_iface_type = Ident::new(&snake_to_camel(created_interface), Span::call_site()); |
264 | quote! { |
265 | #doc_attr |
266 | #[allow(clippy::too_many_arguments)] |
267 | pub fn #method_name<U: Send + Sync + 'static, D: Dispatch<super::#created_iface_mod::#created_iface_type, U> + 'static>(&self, #(#fn_args,)* qh: &QueueHandle<D>, udata: U) -> super::#created_iface_mod::#created_iface_type { |
268 | self.send_constructor( |
269 | Request::#enum_variant { |
270 | #(#enum_args),* |
271 | }, |
272 | qh.make_data::<super::#created_iface_mod::#created_iface_type, U>(udata), |
273 | ).unwrap_or_else(|_| Proxy::inert(self.backend.clone())) |
274 | } |
275 | } |
276 | }, |
277 | Some(None) => { |
278 | // a bind-like request |
279 | quote! { |
280 | #doc_attr |
281 | #[allow(clippy::too_many_arguments)] |
282 | pub fn #method_name<I: Proxy + 'static, U: Send + Sync + 'static, D: Dispatch<I, U> + 'static>(&self, #(#fn_args,)* qh: &QueueHandle<D>, udata: U) -> I { |
283 | self.send_constructor( |
284 | Request::#enum_variant { |
285 | #(#enum_args),* |
286 | }, |
287 | qh.make_data::<I, U>(udata), |
288 | ).unwrap_or_else(|_| Proxy::inert(self.backend.clone())) |
289 | } |
290 | } |
291 | }, |
292 | None => { |
293 | // a non-creating request |
294 | quote! { |
295 | #doc_attr |
296 | #[allow(clippy::too_many_arguments)] |
297 | pub fn #method_name(&self, #(#fn_args),*) { |
298 | let backend = match self.backend.upgrade() { |
299 | Some(b) => b, |
300 | None => return, |
301 | }; |
302 | let conn = Connection::from_backend(backend); |
303 | let _ = conn.send_request( |
304 | self, |
305 | Request::#enum_variant { |
306 | #(#enum_args),* |
307 | }, |
308 | None |
309 | ); |
310 | } |
311 | } |
312 | } |
313 | } |
314 | }).collect() |
315 | } |
316 | |
317 | #[cfg (test)] |
318 | mod tests { |
319 | #[test ] |
320 | fn client_gen() { |
321 | let protocol_file = |
322 | std::fs::File::open("./tests/scanner_assets/test-protocol.xml" ).unwrap(); |
323 | let protocol_parsed = crate::parse::parse(protocol_file); |
324 | let generated: String = super::generate_client_objects(&protocol_parsed).to_string(); |
325 | let generated = crate::format_rust_code(&generated); |
326 | |
327 | let reference = |
328 | std::fs::read_to_string("./tests/scanner_assets/test-client-code.rs" ).unwrap(); |
329 | let reference = crate::format_rust_code(&reference); |
330 | |
331 | if reference != generated { |
332 | let diff = similar::TextDiff::from_lines(&reference, &generated); |
333 | print!(" {}" , diff.unified_diff().context_radius(10).header("reference" , "generated" )); |
334 | panic!("Generated does not match reference!" ) |
335 | } |
336 | } |
337 | } |
338 | |