Debian Codegraph @

third_party/rust/windows-implement/src/lib.rs

raw
1 /*!
2 Learn more about Rust for Windows here: <https://github.com/microsoft/windows-rs>
3 */
4
5 use quote::{quote, ToTokens};
6
7 /// Implements one or more COM interfaces.
8 ///
9 /// # Example
10 ///
11 /// Here is a [more complete tutorial](https://kennykerr.ca/rust-getting-started/how-to-implement-com-interface.html).
12 ///
13 /// ```rust,ignore
14 /// #[interface("094d70d6-5202-44b8-abb8-43860da5aca2")]
15 /// unsafe trait IValue: IUnknown {
16 /// fn GetValue(&self, value: *mut i32) -> HRESULT;
17 /// }
18 ///
19 /// #[implement(IValue)]
20 /// struct Value(i32);
21 ///
22 /// impl IValue_Impl for Value {
23 /// unsafe fn GetValue(&self, value: *mut i32) -> HRESULT {
24 /// *value = self.0;
25 /// HRESULT(0)
26 /// }
27 /// }
28 ///
29 /// fn main() {
30 /// let rust_instance = Value(123);
31 /// let com_object: IValue = rust_instance.into();
32 /// // You can now call interface methods on com_object.
33 /// }
34 /// ```
35 #[proc_macro_attribute]
36 pub fn implement(
37 attributes: proc_macro::TokenStream,
38 original_type: proc_macro::TokenStream,
39 ) -> proc_macro::TokenStream {
40 let attributes = syn::parse_macro_input!(attributes as ImplementAttributes);
41 let interfaces_len = proc_macro2::Literal::usize_unsuffixed(attributes.implement.len());
42
43 let identity_type = if let Some(first) = attributes.implement.first() {
44 first.to_ident()
45 } else {
46 quote! { ::windows_core::IInspectable }
47 };
48
49 let original_type2 = original_type.clone();
50 let original_type2 = syn::parse_macro_input!(original_type2 as syn::ItemStruct);
51 let vis = &original_type2.vis;
52 let original_ident = &original_type2.ident;
53 let mut constraints = quote! {};
54
55 if let Some(where_clause) = &original_type2.generics.where_clause {
56 where_clause.predicates.to_tokens(&mut constraints);
57 }
58
59 let generics = if original_type2.generics.lt_token.is_some() {
60 let mut params = quote! {};
61 original_type2.generics.params.to_tokens(&mut params);
62 quote! { <#params> }
63 } else {
64 quote! { <> }
65 };
66
67 let impl_ident = quote::format_ident!("{}_Impl", original_ident);
68 let vtbl_idents = attributes
69 .implement
70 .iter()
71 .map(|implement| implement.to_vtbl_ident());
72 let vtbl_idents2 = vtbl_idents.clone();
73
74 let vtable_news = attributes
75 .implement
76 .iter()
77 .enumerate()
78 .map(|(enumerate, implement)| {
79 let vtbl_ident = implement.to_vtbl_ident();
80 let offset = proc_macro2::Literal::isize_unsuffixed(-1 - enumerate as isize);
81 quote! { #vtbl_ident::new::<Self, #offset>() }
82 });
83
84 let offset = attributes
85 .implement
86 .iter()
87 .enumerate()
88 .map(|(offset, _)| proc_macro2::Literal::usize_unsuffixed(offset));
89
90 let queries = attributes
91 .implement
92 .iter()
93 .enumerate()
94 .map(|(count, implement)| {
95 let vtbl_ident = implement.to_vtbl_ident();
96 let offset = proc_macro2::Literal::usize_unsuffixed(count);
97 quote! {
98 else if #vtbl_ident::matches(iid) {
99 &self.vtables.#offset as *const _ as *mut _
100 }
101 }
102 });
103
104 // Dynamic casting requires that the object not contain non-static lifetimes.
105 let enable_dyn_casting = original_type2.generics.lifetimes().count() == 0;
106 let dynamic_cast_query = if enable_dyn_casting {
107 quote! {
108 else if *iid == ::windows_core::DYNAMIC_CAST_IID {
109 // DYNAMIC_CAST_IID is special. We _do not_ increase the reference count for this pseudo-interface.
110 // Also, instead of returning an interface pointer, we simply write the `&dyn Any` directly to the
111 // 'interface' pointer. Since the size of `&dyn Any` is 2 pointers, not one, the caller must be
112 // prepared for this. This is not a normal QueryInterface call.
113 //
114 // See the `Interface::cast_to_any` method, which is the only caller that should use DYNAMIC_CAST_ID.
115 (interface as *mut *const dyn core::any::Any).write(self as &dyn ::core::any::Any as *const dyn ::core::any::Any);
116 return ::windows_core::HRESULT(0);
117 }
118 }
119 } else {
120 quote!()
121 };
122
123 // The distance from the beginning of the generated type to the 'this' field, in units of pointers (not bytes).
124 let offset_of_this_in_pointers = 1 + attributes.implement.len();
125 let offset_of_this_in_pointers_token =
126 proc_macro2::Literal::usize_unsuffixed(offset_of_this_in_pointers);
127
128 let trust_level = proc_macro2::Literal::usize_unsuffixed(attributes.trust_level);
129
130 let conversions = attributes.implement.iter().enumerate().map(|(enumerate, implement)| {
131 let interface_ident = implement.to_ident();
132 let offset = proc_macro2::Literal::usize_unsuffixed(enumerate);
133 quote! {
134 impl #generics ::core::convert::From<#original_ident::#generics> for #interface_ident where #constraints {
135 #[inline(always)]
136 fn from(this: #original_ident::#generics) -> Self {
137 let com_object = ::windows_core::ComObject::new(this);
138 com_object.into_interface()
139 }
140 }
141
142 impl #generics ::windows_core::ComObjectInterface<#interface_ident> for #impl_ident::#generics where #constraints {
143 #[inline(always)]
144 fn as_interface_ref(&self) -> ::windows_core::InterfaceRef<'_, #interface_ident> {
145 unsafe {
146 let interface_ptr = &self.vtables.#offset;
147 ::core::mem::transmute(interface_ptr)
148 }
149 }
150 }
151
152 impl #generics ::windows_core::AsImpl<#original_ident::#generics> for #interface_ident where #constraints {
153 // SAFETY: the offset is guranteed to be in bounds, and the implementation struct
154 // is guaranteed to live at least as long as `self`.
155 #[inline(always)]
156 unsafe fn as_impl_ptr(&self) -> ::core::ptr::NonNull<#original_ident::#generics> {
157 let this = ::windows_core::Interface::as_raw(self);
158 // Subtract away the vtable offset plus 1, for the `identity` field, to get
159 // to the impl struct which contains that original implementation type.
160 let this = (this as *mut *mut ::core::ffi::c_void).sub(1 + #offset) as *mut #impl_ident::#generics;
161 ::core::ptr::NonNull::new_unchecked(::core::ptr::addr_of!((*this).this) as *const #original_ident::#generics as *mut #original_ident::#generics)
162 }
163 }
164 }
165 });
166
167 let tokens = quote! {
168 #[repr(C)]
169 #[allow(non_camel_case_types)]
170 #vis struct #impl_ident #generics where #constraints {
171 identity: &'static ::windows_core::IInspectable_Vtbl,
172 vtables: (#(&'static #vtbl_idents,)*),
173 this: #original_ident::#generics,
174 count: ::windows_core::imp::WeakRefCount,
175 }
176
177 impl #generics #impl_ident::#generics where #constraints {
178 const VTABLES: (#(#vtbl_idents2,)*) = (#(#vtable_news,)*);
179 const IDENTITY: ::windows_core::IInspectable_Vtbl = ::windows_core::IInspectable_Vtbl::new::<Self, #identity_type, 0>();
180 }
181
182 impl #generics ::windows_core::ComObjectInner for #original_ident::#generics where #constraints {
183 type Outer = #impl_ident::#generics;
184
185 // IMPORTANT! This function handles assembling the "boxed" type of a COM object.
186 // It immediately moves the box into a heap allocation (box) and returns only a ComObject
187 // reference that points to it. We intentionally _do not_ expose any owned instances of
188 // Foo_Impl to safe Rust code, because doing so would allow unsound behavior in safe Rust
189 // code, due to the adjustments of the reference count that Foo_Impl permits.
190 //
191 // This is why this function returns ComObject<Self> instead of returning #impl_ident.
192
193 fn into_object(self) -> ::windows_core::ComObject<Self> {
194 let boxed = ::windows_core::imp::Box::new(#impl_ident::#generics {
195 identity: &#impl_ident::#generics::IDENTITY,
196 vtables: (#(&#impl_ident::#generics::VTABLES.#offset,)*),
197 this: self,
198 count: ::windows_core::imp::WeakRefCount::new(),
199 });
200 unsafe {
201 let ptr = ::windows_core::imp::Box::into_raw(boxed);
202 ::windows_core::ComObject::from_raw(
203 ::core::ptr::NonNull::new_unchecked(ptr)
204 )
205 }
206 }
207 }
208
209 impl #generics ::windows_core::IUnknownImpl for #impl_ident::#generics where #constraints {
210 type Impl = #original_ident::#generics;
211
212 #[inline(always)]
213 fn get_impl(&self) -> &Self::Impl {
214 &self.this
215 }
216
217 #[inline(always)]
218 fn get_impl_mut(&mut self) -> &mut Self::Impl {
219 &mut self.this
220 }
221
222 #[inline(always)]
223 fn is_reference_count_one(&self) -> bool {
224 self.count.is_one()
225 }
226
227 #[inline(always)]
228 fn into_inner(self) -> Self::Impl {
229 self.this
230 }
231
232 unsafe fn QueryInterface(&self, iid: *const ::windows_core::GUID, interface: *mut *mut ::core::ffi::c_void) -> ::windows_core::HRESULT {
233 if iid.is_null() || interface.is_null() {
234 return ::windows_core::imp::E_POINTER;
235 }
236
237 let iid = &*iid;
238
239 let interface_ptr: *mut ::core::ffi::c_void = if iid == &<::windows_core::IUnknown as ::windows_core::Interface>::IID
240 || iid == &<::windows_core::IInspectable as ::windows_core::Interface>::IID
241 || iid == &<::windows_core::imp::IAgileObject as ::windows_core::Interface>::IID {
242 &self.identity as *const _ as *mut _
243 }
244 #(#queries)*
245 #dynamic_cast_query
246 else {
247 ::core::ptr::null_mut()
248 };
249
250 if !interface_ptr.is_null() {
251 *interface = interface_ptr;
252 self.count.add_ref();
253 return ::windows_core::HRESULT(0);
254 }
255
256 let interface_ptr = self.count.query(iid, &self.identity as *const _ as *mut _);
257 *interface = interface_ptr;
258
259 if interface_ptr.is_null() {
260 ::windows_core::imp::E_NOINTERFACE
261 } else {
262 ::windows_core::HRESULT(0)
263 }
264 }
265
266 #[inline(always)]
267 fn AddRef(&self) -> u32 {
268 self.count.add_ref()
269 }
270
271 #[inline(always)]
272 unsafe fn Release(self_: *mut Self) -> u32 {
273 let remaining = (*self_).count.release();
274 if remaining == 0 {
275 _ = ::windows_core::imp::Box::from_raw(self_);
276 }
277 remaining
278 }
279
280 unsafe fn GetTrustLevel(&self, value: *mut i32) -> ::windows_core::HRESULT {
281 if value.is_null() {
282 return ::windows_core::imp::E_POINTER;
283 }
284 *value = #trust_level;
285 ::windows_core::HRESULT(0)
286 }
287
288 unsafe fn from_inner_ref(inner: &Self::Impl) -> &Self {
289 &*((inner as *const Self::Impl as *const *const ::core::ffi::c_void)
290 .sub(#offset_of_this_in_pointers_token) as *const Self)
291 }
292
293 fn to_object(&self) -> ::windows_core::ComObject<Self::Impl> {
294 self.count.add_ref();
295 unsafe {
296 ::windows_core::ComObject::from_raw(
297 ::core::ptr::NonNull::new_unchecked(self as *const Self as *mut Self)
298 )
299 }
300 }
301
302 const INNER_OFFSET_IN_POINTERS: usize = #offset_of_this_in_pointers_token;
303 }
304
305 impl #generics #original_ident::#generics where #constraints {
306 /// Try casting as the provided interface
307 ///
308 /// # Safety
309 ///
310 /// This function can only be safely called if `self` has been heap allocated and pinned using
311 /// the mechanisms provided by `implement` macro.
312 #[inline(always)]
313 unsafe fn cast<I: ::windows_core::Interface>(&self) -> ::windows_core::Result<I> {
314 let boxed = (self as *const _ as *const *mut ::core::ffi::c_void).sub(1 + #interfaces_len) as *mut #impl_ident::#generics;
315 let mut result = ::core::ptr::null_mut();
316 _ = <#impl_ident::#generics as ::windows_core::IUnknownImpl>::QueryInterface(&*boxed, &I::IID, &mut result);
317 ::windows_core::Type::from_abi(result)
318 }
319 }
320
321 impl #generics ::core::convert::From<#original_ident::#generics> for ::windows_core::IUnknown where #constraints {
322 #[inline(always)]
323 fn from(this: #original_ident::#generics) -> Self {
324 let com_object = ::windows_core::ComObject::new(this);
325 com_object.into_interface()
326 }
327 }
328
329 impl #generics ::core::convert::From<#original_ident::#generics> for ::windows_core::IInspectable where #constraints {
330 #[inline(always)]
331 fn from(this: #original_ident::#generics) -> Self {
332 let com_object = ::windows_core::ComObject::new(this);
333 com_object.into_interface()
334 }
335 }
336
337 impl #generics ::windows_core::ComObjectInterface<::windows_core::IUnknown> for #impl_ident::#generics where #constraints {
338 #[inline(always)]
339 fn as_interface_ref(&self) -> ::windows_core::InterfaceRef<'_, ::windows_core::IUnknown> {
340 unsafe {
341 let interface_ptr = &self.identity;
342 ::core::mem::transmute(interface_ptr)
343 }
344 }
345 }
346
347 impl #generics ::windows_core::ComObjectInterface<::windows_core::IInspectable> for #impl_ident::#generics where #constraints {
348 #[inline(always)]
349 fn as_interface_ref(&self) -> ::windows_core::InterfaceRef<'_, ::windows_core::IInspectable> {
350 unsafe {
351 let interface_ptr = &self.identity;
352 ::core::mem::transmute(interface_ptr)
353 }
354 }
355 }
356
357 impl #generics ::windows_core::AsImpl<#original_ident::#generics> for ::windows_core::IUnknown where #constraints {
358 // SAFETY: the offset is guranteed to be in bounds, and the implementation struct
359 // is guaranteed to live at least as long as `self`.
360 #[inline(always)]
361 unsafe fn as_impl_ptr(&self) -> ::core::ptr::NonNull<#original_ident::#generics> {
362 let this = ::windows_core::Interface::as_raw(self);
363 // Subtract away the vtable offset plus 1, for the `identity` field, to get
364 // to the impl struct which contains that original implementation type.
365 let this = (this as *mut *mut ::core::ffi::c_void).sub(1) as *mut #impl_ident::#generics;
366 ::core::ptr::NonNull::new_unchecked(::core::ptr::addr_of!((*this).this) as *const #original_ident::#generics as *mut #original_ident::#generics)
367 }
368 }
369
370 impl #generics ::core::ops::Deref for #impl_ident::#generics where #constraints {
371 type Target = #original_ident::#generics;
372
373 #[inline(always)]
374 fn deref(&self) -> &Self::Target {
375 &self.this
376 }
377 }
378
379 // We intentionally do not provide a DerefMut impl, due to paranoia around soundness.
380
381 #(#conversions)*
382 };
383
384 let mut tokens: proc_macro::TokenStream = tokens.into();
385 tokens.extend(core::iter::once(original_type));
386 tokens
387 }
388
389 #[derive(Default)]
390 struct ImplementType {
391 type_name: String,
392 generics: Vec<ImplementType>,
393 }
394
395 impl ImplementType {
396 fn to_ident(&self) -> proc_macro2::TokenStream {
397 let type_name = syn::parse_str::<proc_macro2::TokenStream>(&self.type_name)
398 .expect("Invalid token stream");
399 let generics = self.generics.iter().map(|g| g.to_ident());
400 quote! { #type_name<#(#generics,)*> }
401 }
402 fn to_vtbl_ident(&self) -> proc_macro2::TokenStream {
403 let ident = self.to_ident();
404 quote! {
405 <#ident as ::windows_core::Interface>::Vtable
406 }
407 }
408 }
409
410 #[derive(Default)]
411 struct ImplementAttributes {
412 pub implement: Vec<ImplementType>,
413 pub trust_level: usize,
414 }
415
416 impl syn::parse::Parse for ImplementAttributes {
417 fn parse(cursor: syn::parse::ParseStream<'_>) -> syn::parse::Result<Self> {
418 let mut input = Self::default();
419
420 while !cursor.is_empty() {
421 input.parse_implement(cursor)?;
422 }
423
424 Ok(input)
425 }
426 }
427
428 impl ImplementAttributes {
429 fn parse_implement(&mut self, cursor: syn::parse::ParseStream<'_>) -> syn::parse::Result<()> {
430 let tree = cursor.parse::<UseTree2>()?;
431 self.walk_implement(&tree, &mut String::new())?;
432
433 if !cursor.is_empty() {
434 cursor.parse::<syn::Token![,]>()?;
435 }
436
437 Ok(())
438 }
439
440 fn walk_implement(
441 &mut self,
442 tree: &UseTree2,
443 namespace: &mut String,
444 ) -> syn::parse::Result<()> {
445 match tree {
446 UseTree2::Path(input) => {
447 if !namespace.is_empty() {
448 namespace.push_str("::");
449 }
450
451 namespace.push_str(&input.ident.to_string());
452 self.walk_implement(&input.tree, namespace)?;
453 }
454 UseTree2::Name(_) => {
455 self.implement.push(tree.to_element_type(namespace)?);
456 }
457 UseTree2::Group(input) => {
458 for tree in &input.items {
459 self.walk_implement(tree, namespace)?;
460 }
461 }
462 UseTree2::TrustLevel(input) => self.trust_level = *input,
463 }
464
465 Ok(())
466 }
467 }
468
469 enum UseTree2 {
470 Path(UsePath2),
471 Name(UseName2),
472 Group(UseGroup2),
473 TrustLevel(usize),
474 }
475
476 impl UseTree2 {
477 fn to_element_type(&self, namespace: &mut String) -> syn::parse::Result<ImplementType> {
478 match self {
479 UseTree2::Path(input) => {
480 if !namespace.is_empty() {
481 namespace.push_str("::");
482 }
483
484 namespace.push_str(&input.ident.to_string());
485 input.tree.to_element_type(namespace)
486 }
487 UseTree2::Name(input) => {
488 let mut type_name = input.ident.to_string();
489
490 if !namespace.is_empty() {
491 type_name = format!("{namespace}::{type_name}");
492 }
493
494 let mut generics = vec![];
495
496 for g in &input.generics {
497 generics.push(g.to_element_type(&mut String::new())?);
498 }
499
500 Ok(ImplementType {
501 type_name,
502 generics,
503 })
504 }
505 UseTree2::Group(input) => Err(syn::parse::Error::new(
506 input.brace_token.span.join(),
507 "Syntax not supported",
508 )),
509 _ => unimplemented!(),
510 }
511 }
512 }
513
514 struct UsePath2 {
515 pub ident: syn::Ident,
516 pub tree: Box<UseTree2>,
517 }
518
519 struct UseName2 {
520 pub ident: syn::Ident,
521 pub generics: Vec<UseTree2>,
522 }
523
524 struct UseGroup2 {
525 pub brace_token: syn::token::Brace,
526 pub items: syn::punctuated::Punctuated<UseTree2, syn::Token![,]>,
527 }
528
529 impl syn::parse::Parse for UseTree2 {
530 fn parse(input: syn::parse::ParseStream<'_>) -> syn::parse::Result<UseTree2> {
531 let lookahead = input.lookahead1();
532 if lookahead.peek(syn::Ident) {
533 use syn::ext::IdentExt;
534 let ident = input.call(syn::Ident::parse_any)?;
535 if input.peek(syn::Token![::]) {
536 input.parse::<syn::Token![::]>()?;
537 Ok(UseTree2::Path(UsePath2 {
538 ident,
539 tree: Box::new(input.parse()?),
540 }))
541 } else if input.peek(syn::Token![=]) {
542 if ident != "TrustLevel" {
543 return Err(syn::parse::Error::new(
544 ident.span(),
545 "Unrecognized key-value pair",
546 ));
547 }
548 input.parse::<syn::Token![=]>()?;
549 let span = input.span();
550 let value = input.call(syn::Ident::parse_any)?;
551 match value.to_string().as_str() {
552 "Partial" => Ok(UseTree2::TrustLevel(1)),
553 "Full" => Ok(UseTree2::TrustLevel(2)),
554 _ => Err(syn::parse::Error::new(
555 span,
556 "`TrustLevel` must be `Partial` or `Full`",
557 )),
558 }
559 } else {
560 let generics = if input.peek(syn::Token![<]) {
561 input.parse::<syn::Token![<]>()?;
562 let mut generics = Vec::new();
563 loop {
564 generics.push(input.parse::<UseTree2>()?);
565
566 if input.parse::<syn::Token![,]>().is_err() {
567 break;
568 }
569 }
570 input.parse::<syn::Token![>]>()?;
571 generics
572 } else {
573 Vec::new()
574 };
575
576 Ok(UseTree2::Name(UseName2 { ident, generics }))
577 }
578 } else if lookahead.peek(syn::token::Brace) {
579 let content;
580 let brace_token = syn::braced!(content in input);
581 let items = content.parse_terminated(UseTree2::parse, syn::Token![,])?;
582
583 Ok(UseTree2::Group(UseGroup2 { brace_token, items }))
584 } else {
585 Err(lookahead.error())
586 }
587 }
588 }