windows-bindgen 0.101.0

Code generator for Windows metadata
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
use super::*;

#[derive(Clone, Debug)]
pub struct CppMethod {
    pub def: MethodDef,
    pub signature: Signature,
    pub dependencies: TypeMap,
    pub return_hint: ReturnHint,
    pub param_hints: Vec<ParamHint>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum ReturnHint {
    None,
    Query(usize, usize),
    QueryOptional(usize, usize),
    ResultValue,
    /// Legacy only: `HRESULT`, or `BOOL` with `SetLastError`, projected as `Result<()>`.
    ResultVoid,
    ReturnStruct,
    ReturnValue,
}

#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ParamHint {
    None,
    ArrayRaw,
    /// Legacy only: a pointer to a fixed number of elements.
    ArrayFixed(usize),
    /// Legacy only: a pointer whose element count is the indicated parameter.
    ArrayRelativeLen(usize),
    /// Legacy only: a byte pointer whose size is the indicated parameter.
    ArrayRelativeByteLen(usize),
    /// Legacy only: the length of the indicated slice parameter.
    ArrayRelativePtr(usize),
    /// Legacy only: an integer parameter exposed as its associated enum.
    AssociatedEnum,
    IntoParam,
    Optional,
    ValueType,
    Blittable,
    Bool,
}

impl ParamHint {
    fn is_slice(self) -> bool {
        matches!(
            self,
            Self::ArrayFixed(_) | Self::ArrayRelativeLen(_) | Self::ArrayRelativeByteLen(_)
        )
    }
}

impl CppMethod {
    pub fn new(def: MethodDef, reader: &Reader) -> Self {
        let signature = def.method_signature(&[], reader);
        let mut dependencies = signature.dependencies(reader);
        for ty in def.associated_enums(reader) {
            ty.combine(&mut dependencies, reader);
        }
        let mut param_hints = if reader.legacy() {
            legacy::array_hints(&signature)
        } else {
            vec![ParamHint::None; signature.params.len()]
        };

        for (position, hint) in param_hints.iter_mut().enumerate() {
            if *hint != ParamHint::None {
                continue;
            }
            let param = &signature.params[position];
            if param.associated_enum.is_some() {
                *hint = ParamHint::AssociatedEnum;
                continue;
            }
            let ty = param.projection_type(reader);
            // COM values still use borrowed references, not raw-buffer ownership.
            if (param.has_buffer_attributes() || param.has_unresolved_contracts())
                && !ty.is_interface()
            {
                *hint = ParamHint::ArrayRaw;
                continue;
            }
            if !param.has_direction() {
                if ty.is_pointer() || ty.is_primitive(reader) {
                    *hint = ParamHint::ValueType;
                }
                continue;
            }

            if param.is_convertible_with_reader(reader) {
                *hint = ParamHint::IntoParam;
            } else if ty.is_copyable(reader) && param.is_optional_or_reserved() {
                *hint = ParamHint::Optional;
            } else if param.is_input_only() && ty == Type::BOOL {
                *hint = ParamHint::Bool;
            } else if ty.is_primitive(reader)
                && (!ty.is_pointer() || ty.deref().is_copyable(reader))
            {
                *hint = ParamHint::ValueType;
            } else if ty.is_copyable(reader) {
                *hint = ParamHint::Blittable;
            }
        }

        let is_retval = signature.is_retval(reader);
        let mut return_hint = ReturnHint::None;

        if reader.legacy() {
            return_hint = legacy::return_hint(def, &signature, is_retval, reader);
        } else {
            match signature.return_type.projection_type(reader) {
                Type::Void if is_retval => return_hint = ReturnHint::ReturnValue,
                Type::HRESULT => {
                    if is_retval {
                        return_hint = ReturnHint::ResultValue;
                    }

                    if signature.params.len() >= 2
                        && let Some((guid, object)) =
                            signature_param_is_query(&signature.params, reader)
                    {
                        if signature.params[object].is_optional_or_reserved() {
                            return_hint = ReturnHint::QueryOptional(object, guid);
                        } else {
                            return_hint = ReturnHint::Query(object, guid);
                        }
                    }
                }
                Type::GUID => return_hint = ReturnHint::ReturnStruct,
                Type::CppStruct(ty) if !ty.is_handle(reader) => {
                    return_hint = ReturnHint::ReturnStruct;
                }
                _ => {}
            }
        }

        Self {
            def,
            signature,
            dependencies,
            param_hints,
            return_hint,
        }
    }

    pub fn write_cfg(&self, config: &Config, parent: &Cfg, not: bool) -> TokenStream {
        write_method_cfg(&self.dependencies, config, parent, not)
    }

    /// Projects `MustUseAttribute` unless the wrapper already returns `()` or a `#[must_use]` type.
    pub fn write_must_use(&self, reader: &Reader) -> TokenStream {
        if !self.def.attributes().any(|attribute| {
            attribute.namespace() == "Windows.Win32.Metadata"
                && attribute.name() == "MustUseAttribute"
        }) {
            return quote! {};
        }
        let is_must_use_type = |ty: Type| {
            matches!(
                ty,
                Type::BOOL | Type::HRESULT | Type::NTSTATUS | Type::RPC_STATUS
            )
        };
        let projected_must_use = match self.return_hint {
            ReturnHint::Query(..)
            | ReturnHint::QueryOptional(..)
            | ReturnHint::ResultValue
            | ReturnHint::ResultVoid => true,
            ReturnHint::ReturnValue => {
                let param = self.signature.params.last().unwrap();
                let ty = param.projection_pointee(reader).projection_type(reader);
                ty.is_interface_with_reader(reader) || is_must_use_type(ty)
            }
            ReturnHint::ReturnStruct | ReturnHint::None => {
                let ty = self.signature.return_type.projection_type(reader);
                ty == Type::Void || is_must_use_type(ty)
            }
        };
        if projected_must_use {
            quote! {}
        } else {
            quote! { #[must_use] }
        }
    }

    pub fn write_generics(&self) -> TokenStream {
        let mut tokens = quote! {};

        for (position, hint) in self.param_hints.iter().enumerate() {
            if *hint == ParamHint::IntoParam {
                let name: TokenStream = format!("P{position},").parse().unwrap();
                tokens.combine(name);
            }
        }

        tokens
    }

    pub fn write_where(&self, config: &Config, query: bool) -> TokenStream {
        let mut tokens = quote! {};

        for (position, param) in self.signature.params.iter().enumerate() {
            if self.param_hints[position] == ParamHint::IntoParam {
                let name: TokenStream = format!("P{position}").parse().unwrap();
                let into = param.write_name(config);
                tokens.combine(quote! { #name: windows_core::Param<#into>, });
            }
        }

        if query {
            tokens.combine(quote! { T: windows_core::Interface });
        }

        if tokens.is_empty() {
            tokens
        } else {
            quote! { where #tokens }
        }
    }

    pub fn write(
        &self,
        config: &Config,
        method_names: &mut MethodNames,
        vname: &TokenStream,
    ) -> TokenStream {
        let name = method_names.add(self.def);

        let args = self.write_args(config);
        let params = self.write_params(config);
        let generics = self.write_generics();
        let abi_return_type = self.write_return(config);
        let result = config.write_core();

        let vis = config.item_vis();
        let must_use = self.write_must_use(config.reader);

        let wrapper = match self.return_hint {
            ReturnHint::Query(..) => {
                let where_clause = self.write_where(config, true);

                quote! {
                    #vis unsafe fn #name<#generics T>(&self, #params) -> #result Result<T> #where_clause {
                        let mut result__ = core::ptr::null_mut();
                        unsafe { (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self),#args).and_then(|| windows_core::imp::from_abi(result__)) }
                    }
                }
            }
            ReturnHint::QueryOptional(..) => {
                let where_clause = self.write_where(config, true);

                quote! {
                    #vis unsafe fn #name<#generics T>(&self, #params result__: *mut Option<T>) -> #result Result<()> #where_clause {
                        unsafe { (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self),#args).ok() }
                    }
                }
            }
            ReturnHint::ResultValue => {
                let where_clause = self.write_where(config, false);

                let ty = self
                    .signature
                    .params
                    .last()
                    .unwrap()
                    .projection_pointee(config.reader);
                let map = ty
                    .projection_type(config.reader)
                    .write_result_map(config.reader);
                let init = ty.projection_type(config.reader).write_result_init(config);
                let return_type = ty.write_name(config);

                quote! {
                    #vis unsafe fn #name<#generics>(&self, #params) -> #result Result<#return_type> #where_clause {
                        unsafe {
                            #init
                            (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self),#args).#map
                        }
                    }
                }
            }
            ReturnHint::ResultVoid => {
                let where_clause = self.write_where(config, false);

                quote! {
                    #vis unsafe fn #name<#generics>(&self, #params) -> #result Result<()> #where_clause {
                        unsafe { (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self),#args).ok() }
                    }
                }
            }
            ReturnHint::ReturnValue => {
                let where_clause = self.write_where(config, false);

                let return_type = self.signature.params[self.signature.params.len() - 1]
                    .projection_pointee(config.reader);
                let projection_type = return_type.projection_type(config.reader);

                if projection_type.is_interface_with_reader(config.reader) {
                    let return_type = return_type.write_name(config);

                    quote! {
                        #vis unsafe fn #name<#generics>(&self, #params) -> #result Result<#return_type> #where_clause {
                            unsafe {
                                let mut result__ = core::mem::zeroed();
                                (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self), #args);
                                windows_core::imp::from_abi(result__)
                            }
                        }
                    }
                } else {
                    let map = if projection_type.is_copyable(config.reader) {
                        quote! { result__ }
                    } else {
                        quote! { core::mem::transmute(result__) }
                    };

                    let return_type = return_type.write_name(config);
                    let where_clause = self.write_where(config, false);

                    quote! {
                        #vis unsafe fn #name<#generics>(&self, #params) -> #return_type #where_clause {
                            unsafe {
                                let mut result__ = core::mem::zeroed();
                                (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self), #args);
                                #map
                            }
                        }
                    }
                }
            }
            ReturnHint::ReturnStruct => {
                let return_type = self.signature.return_type.write_name(config);
                let where_clause = self.write_where(config, false);

                quote! {
                    #vis unsafe fn #name<#generics>(&self, #params) -> #return_type #where_clause {
                        unsafe {
                            let mut result__ = core::mem::zeroed();
                            (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self), &mut result__, #args);
                            result__
                        }
                    }
                }
            }
            ReturnHint::None => {
                let where_clause = self.write_where(config, false);

                if matches!(self.signature.return_type, Type::Void) {
                    quote! {
                        #vis unsafe fn #name<#generics>(&self, #params) #abi_return_type #where_clause {
                            unsafe { (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self), #args); }
                        }
                    }
                } else {
                    quote! {
                        #vis unsafe fn #name<#generics>(&self, #params) #abi_return_type #where_clause {
                            unsafe { (windows_core::Interface::vtable(self).#vname)(windows_core::Interface::as_raw(self), #args) }
                        }
                    }
                }
            }
        };

        quote! {
            #must_use
            #wrapper
        }
    }

    pub fn write_upcall(
        &self,
        parent_impl: &TokenStream,
        name: &TokenStream,
        config: &Config,
    ) -> TokenStream {
        let reader = config.reader;
        match self.return_hint {
            ReturnHint::ResultValue => {
                let invoke_args = self.signature.params[..self.signature.params.len() - 1]
                    .iter()
                    .map(|p| write_invoke_arg(p, config));

                let last_param = &self.signature.params[self.signature.params.len() - 1];
                let result = last_param.write_ident();
                let result = if matches!(last_param.projection_type(reader), Type::PtrConst(..)) {
                    let target = last_param
                        .projection_pointee(reader)
                        .write_abi_pointee(config);
                    quote! { (#result as *mut #target) }
                } else {
                    result
                };

                // For copyable types the Rust and ABI types are identical, so
                // the transmute would be from a type to itself and tripping
                // `clippy::useless_transmute`.
                let write_result = if last_param
                    .projection_pointee(reader)
                    .projection_type(reader)
                    .is_copyable(reader)
                {
                    quote! { #result.write(ok__); }
                } else {
                    let ty = last_param.projection_pointee(reader).write_name(config);
                    quote! { #result.cast::<#ty>().write(ok__); }
                };
                quote! {
                    match #parent_impl::#name(this, #(#invoke_args,)*) {
                        Ok(ok__) => {
                            // use `ptr::write` since the result could be uninitialized
                            #write_result
                            windows_core::HRESULT(0)
                        }
                        Err(err) => {
                            #result.write_bytes(0, 1);
                            err.into()
                        }
                    }
                }
            }
            ReturnHint::Query(..) | ReturnHint::QueryOptional(..) | ReturnHint::ResultVoid => {
                let invoke_args = self
                    .signature
                    .params
                    .iter()
                    .map(|p| write_invoke_arg(p, config));

                quote! {
                    #parent_impl::#name(this, #(#invoke_args,)*).into()
                }
            }
            ReturnHint::ReturnStruct => {
                let invoke_args = self
                    .signature
                    .params
                    .iter()
                    .map(|p| write_invoke_arg(p, config));

                quote! {
                    *result__ = #parent_impl::#name(this, #(#invoke_args,)*);
                }
            }
            _ => {
                let invoke_args = self
                    .signature
                    .params
                    .iter()
                    .map(|p| write_invoke_arg(p, config));

                if matches!(self.signature.return_type, Type::Void) {
                    quote! {
                        #parent_impl::#name(this, #(#invoke_args,)*);
                    }
                } else {
                    quote! {
                        #parent_impl::#name(this, #(#invoke_args,)*)
                    }
                }
            }
        }
    }

    pub fn write_impl_signature(&self, config: &Config) -> TokenStream {
        let mut params = quote! {};

        if self.return_hint == ReturnHint::ResultValue {
            for (position, param) in self.signature.params[..self.signature.params.len() - 1]
                .iter()
                .enumerate()
            {
                params.combine(write_produce_type(
                    config,
                    param,
                    self.param_hints[position],
                ));
            }
        } else {
            for (position, param) in self.signature.params.iter().enumerate() {
                params.combine(write_produce_type(
                    config,
                    param,
                    self.param_hints[position],
                ));
            }
        }

        let result = config.write_core();

        let return_type = match self.return_hint {
            ReturnHint::Query(..) | ReturnHint::QueryOptional(..) | ReturnHint::ResultVoid => {
                quote! { -> #result Result<()> }
            }
            ReturnHint::ResultValue => {
                let return_type = self
                    .signature
                    .params
                    .last()
                    .unwrap()
                    .projection_pointee(config.reader)
                    .write_name(config);

                quote! { -> #result Result<#return_type> }
            }
            _ => self.write_return(config),
        };

        quote! { (&self, #params) #return_type }
    }

    pub fn write_abi(&self, config: &Config, named_params: bool) -> TokenStream {
        let mut params: Vec<_> = self
            .signature
            .params
            .iter()
            .map(|param| {
                let ty = param.write_abi(config);

                if named_params {
                    let name = param.write_ident();
                    quote! { #name: #ty }
                } else {
                    ty
                }
            })
            .collect();

        let mut return_sig = quote! {};

        match self.return_hint {
            ReturnHint::ReturnStruct => {
                let return_type = self.signature.return_type.write_abi(config);

                if named_params {
                    params.insert(0, quote! { result__: *mut #return_type });
                } else {
                    params.insert(0, quote! { *mut #return_type });
                }
            }
            _ => {
                return_sig = config.write_return_sig(self.def, &self.signature, false);
            }
        }

        let this = if named_params {
            quote! { this: *mut core::ffi::c_void }
        } else {
            quote! { *mut core::ffi::c_void }
        };

        quote! { (#this, #(#params),*) #return_sig }
    }

    pub fn write_params(&self, config: &Config) -> TokenStream {
        let mut tokens = quote! {};

        for (position, param) in self.signature.params.iter().enumerate() {
            match self.return_hint {
                ReturnHint::Query(object, guid) | ReturnHint::QueryOptional(object, guid)
                    if (object == position || guid == position) =>
                {
                    continue;
                }
                ReturnHint::ReturnValue | ReturnHint::ResultValue
                    if self.signature.params.len() - 1 == position =>
                {
                    continue;
                }
                _ => {}
            }

            let name = param.write_ident();

            match self.param_hints[position] {
                ParamHint::ArrayFixed(_)
                | ParamHint::ArrayRelativeLen(_)
                | ParamHint::ArrayRelativeByteLen(_) => {
                    let ty = match self.param_hints[position] {
                        ParamHint::ArrayRelativeByteLen(_) => quote! { u8 },
                        _ => param.deref().write_default(config),
                    };
                    let ty = if let ParamHint::ArrayFixed(fixed) = self.param_hints[position] {
                        let len = Literal::usize_unsuffixed(fixed);
                        quote! { [#ty; #len] }
                    } else {
                        quote! { [#ty] }
                    };
                    let ty = if param.is_input_only() {
                        quote! { &#ty }
                    } else {
                        quote! { &mut #ty }
                    };
                    if param.is_optional_or_reserved() {
                        let name = if param.is_input_only() {
                            name
                        } else {
                            quote! { mut #name }
                        };
                        tokens.combine(&quote! { #name: Option<#ty>, });
                    } else {
                        tokens.combine(&quote! { #name: #ty, });
                    }
                }
                ParamHint::ArrayRelativePtr(_) => {}
                ParamHint::AssociatedEnum => {
                    let kind = param.associated_enum.as_ref().unwrap().write_name(config);
                    tokens.combine(&quote! { #name: #kind, });
                }
                ParamHint::ArrayRaw => {
                    let kind = param.write_default(config);
                    if param.is_optional_or_reserved() {
                        tokens.combine(&quote! { #name: Option<#kind>, });
                    } else {
                        tokens.combine(&quote! { #name: #kind, });
                    }
                }
                ParamHint::IntoParam => {
                    let kind: TokenStream = format!("P{position}").parse().unwrap();
                    tokens.combine(&quote! { #name: #kind, });
                }
                ParamHint::Optional => {
                    if matches!(param.ty, Type::CppDelegate(..) | Type::FnPtr(_)) {
                        let kind = param.write_name(config);
                        tokens.combine(&quote! { #name: #kind, });
                    } else {
                        let kind = param.write_name(config);
                        tokens.combine(&quote! { #name: Option<#kind>, });
                    }
                }
                ParamHint::Bool => {
                    tokens.combine(&quote! { #name: bool, });
                }
                ParamHint::ValueType | ParamHint::Blittable => {
                    let kind = param.write_default(config);
                    tokens.combine(&quote! { #name: #kind, });
                }
                ParamHint::None => {
                    let kind = param.write_default(config);
                    tokens.combine(&quote! { #name: &#kind, });
                }
            }
        }

        tokens
    }

    pub fn write_args(&self, config: &Config) -> TokenStream {
        let mut tokens = quote! {};

        for (position, param) in self.signature.params.iter().enumerate() {
            let new = match self.return_hint {
                ReturnHint::Query(object, _) if object == position => {
                    quote! { &mut result__, }
                }
                ReturnHint::ReturnValue | ReturnHint::ResultValue
                    if self.signature.params.len() - 1 == position =>
                {
                    // A native pointer typedef spells an interface slot as `*mut Option<T>`, while
                    // the result reads the raw interface pointer.
                    if matches!(&param.ty, Type::CppStruct(ty) if ty.is_native_typedef(config.reader))
                        && param
                            .projection_pointee(config.reader)
                            .projection_type(config.reader)
                            .is_interface_with_reader(config.reader)
                    {
                        quote! { core::ptr::from_mut::<*mut core::ffi::c_void>(&mut result__).cast(), }
                    } else if self.return_hint == ReturnHint::ResultValue {
                        let arg = param
                            .projection_pointee(config.reader)
                            .projection_type(config.reader)
                            .write_result_arg(config.reader);
                        quote! { #arg, }
                    } else {
                        quote! { &mut result__, }
                    }
                }
                ReturnHint::QueryOptional(object, _) if object == position => {
                    quote! { result__ as *mut _ as *mut _, }
                }
                ReturnHint::Query(_, guid) | ReturnHint::QueryOptional(_, guid)
                    if guid == position =>
                {
                    quote! { &T::IID, }
                }
                _ => {
                    let name = param.write_ident();
                    match self.param_hints[position] {
                        ParamHint::ArrayFixed(_)
                        | ParamHint::ArrayRelativeLen(_)
                        | ParamHint::ArrayRelativeByteLen(_) => {
                            let optional = param.is_optional_or_reserved();
                            let map = match (param.is_input_only(), optional) {
                                (true, false) => quote! { #name.as_ptr() },
                                (false, false) => quote! { #name.as_mut_ptr() },
                                (true, true) => {
                                    quote! { #name.as_deref().map_or(core::ptr::null(), |slice| slice.as_ptr()) }
                                }
                                (false, true) => {
                                    quote! { #name.as_deref_mut().map_or(core::ptr::null_mut(), |slice| slice.as_mut_ptr()) }
                                }
                            };
                            quote! { core::mem::transmute(#map), }
                        }
                        ParamHint::ArrayRelativePtr(relative) => {
                            let relative_param = &self.signature.params[relative];
                            let name = relative_param.write_ident();
                            if relative_param.is_optional_or_reserved() {
                                quote! { #name.as_deref().map_or(0, |slice| slice.len().try_into().unwrap()), }
                            } else {
                                quote! { #name.len().try_into().unwrap(), }
                            }
                        }
                        ParamHint::AssociatedEnum => {
                            quote! { #name.0 as _, }
                        }
                        ParamHint::ArrayRaw => {
                            if param.is_optional_or_reserved() {
                                quote! { #name.unwrap_or(core::mem::zeroed()) as _, }
                            } else if param
                                .projection_type(config.reader)
                                .is_primitive(config.reader)
                                && param
                                    .projection_type(config.reader)
                                    .deref()
                                    .is_copyable(config.reader)
                            {
                                if param.is_input_only() {
                                    quote! { #name, }
                                } else {
                                    quote! { #name as _, }
                                }
                            } else if param.write_default(config).to_string()
                                == param.write_abi(config).to_string()
                            {
                                quote! { #name, }
                            } else if param.projection_type(config.reader).is_pointer() {
                                quote! { #name as _, }
                            } else {
                                quote! { core::mem::transmute(#name), }
                            }
                        }
                        ParamHint::IntoParam => {
                            quote! { #name.param().abi(), }
                        }
                        ParamHint::Optional => {
                            if matches!(param.ty, Type::CppDelegate(..) | Type::FnPtr(_)) {
                                quote! { #name, }
                            } else {
                                quote! { #name.unwrap_or(core::mem::zeroed()) as _, }
                            }
                        }
                        ParamHint::Bool => {
                            quote! { #name.into(), }
                        }
                        ParamHint::ValueType => {
                            if param.is_input_only()
                                || (!param.has_direction()
                                    && !param.projection_type(config.reader).is_pointer())
                            {
                                quote! { #name, }
                            } else {
                                quote! { #name as _, }
                            }
                        }
                        ParamHint::Blittable => {
                            // A blittable (copyable) param's Rust type usually matches
                            // its ABI type, making the transmute redundant. It is only
                            // needed when the two differ (e.g. a generic's `AbiType`).
                            if param.write_default(config).to_string()
                                == param.write_abi(config).to_string()
                            {
                                quote! { #name, }
                            } else if param.projection_type(config.reader).is_pointer() {
                                quote! { #name as _, }
                            } else {
                                quote! { core::mem::transmute(#name), }
                            }
                        }
                        ParamHint::None => {
                            quote! { core::mem::transmute_copy(#name), }
                        }
                    }
                }
            };
            tokens.combine(&new);
        }

        tokens
    }

    pub fn write_return(&self, config: &Config) -> TokenStream {
        match &self.signature.return_type {
            Type::Void if self.def.has_attribute("DoesNotReturnAttribute") => quote! {  -> ! },
            Type::Void => quote! {},
            ty => {
                let ty = ty.write_default(config);
                quote! { -> #ty }
            }
        }
    }
}

fn write_produce_type(config: &Config, param: &Param, hint: ParamHint) -> TokenStream {
    let name = param.write_ident();
    let kind = param.write_default(config);

    let ty = param.projection_type(config.reader);

    if let Some(associated_enum) = &param.associated_enum {
        let associated_enum = associated_enum.write_name(config);
        return quote! { #name: &#associated_enum, };
    }

    if ty.is_interface_with_reader(config.reader) {
        let type_name = param.write_name(config);
        quote! { #name: windows_core::Ref<#type_name>, }
    } else if param.has_direction()
        && !param.is_input_only()
        && ty.deref().is_interface_with_reader(config.reader)
        && hint != ParamHint::ArrayRaw
        && !hint.is_slice()
    {
        let type_name = param.projection_pointee(config.reader).write_name(config);
        quote! { #name: windows_core::OutRef<#type_name>, }
    } else if param.is_input_only() {
        if ty.is_primitive(config.reader) {
            quote! { #name: #kind, }
        } else {
            quote! { #name: &#kind, }
        }
    } else {
        quote! { #name: #kind, }
    }
}

fn write_invoke_arg(param: &Param, config: &Config) -> TokenStream {
    let reader = config.reader;
    let name = param.write_ident();

    if let Some(associated_enum) = &param.associated_enum {
        let associated_enum = associated_enum.write_name(config);
        return quote! { &#associated_enum(#name as _) };
    }

    let ty = param.projection_type(reader);

    if ty.is_interface_with_reader(reader) {
        quote! { core::mem::transmute_copy(&#name) }
    } else if param.is_input_only() && !ty.is_primitive(reader) {
        quote! { &*(&raw const #name).cast() }
    } else {
        quote! { core::mem::transmute_copy(&#name) }
    }
}

pub fn signature_param_is_query(params: &[Param], reader: &Reader) -> Option<(usize, usize)> {
    if let Some(guid) = params.iter().rposition(|param| {
        param.projection_type(reader) == Type::PtrConst(Box::new(Type::GUID), 1)
            && param.is_input_only()
            && !param.has_buffer_attributes()
            && !param.has_unresolved_contracts()
    }) && let Some(object) = params.iter().rposition(|param| {
        let ty = param.projection_type(reader);
        matches!(ty, Type::PtrMut(..))
            && ty.deref() == Type::PtrMut(Box::new(Type::Void), 1)
            && param.is_metadata_output_only()
            && param.has_attribute("ComOutPtrAttribute")
            && !param.has_buffer_attributes()
            && !param.has_unresolved_contracts()
    }) {
        return Some((guid, object));
    }

    None
}