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
use super::*;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct CppFn {
    pub namespace: &'static str,
    pub method: MethodDef,
}

impl Ord for CppFn {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.method.name(), self.method).cmp(&(other.method.name(), other.method))
    }
}

impl PartialOrd for CppFn {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl CppFn {
    pub fn type_name(&self) -> TypeName {
        TypeName(self.namespace, self.method.name())
    }

    pub fn write_name(&self, config: &Config) -> TokenStream {
        self.type_name().write(config, &[])
    }

    fn write_extern_signature(&self, config: &Config<'_>, underlying_types: bool) -> TokenStream {
        let signature = self.method.method_signature(&[], config.reader);

        let params = signature.params.iter().map(|param| {
            let name = param.write_ident();
            let ty = if underlying_types {
                param.underlying_type(config.reader).write_abi(config)
            } else {
                param.write_abi(config)
            };
            quote! { #name: #ty }
        });

        let return_sig = config.write_return_sig(self.method, &signature, underlying_types);

        let vararg = if signature.call_flags.contains(MethodCallAttributes::VARARG) {
            if signature.params.is_empty() {
                quote! { ... }
            } else {
                quote! { , ... }
            }
        } else {
            quote! {}
        };

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

    fn abi(&self, config: &Config<'_>) -> &'static str {
        self.variadic_abi(config)
            .unwrap_or_else(|| self.method.calling_convention())
    }

    fn variadic_abi(&self, config: &Config<'_>) -> Option<&'static str> {
        if !self
            .method
            .method_signature(&[], config.reader)
            .call_flags
            .contains(MethodCallAttributes::VARARG)
        {
            return None;
        }

        let flags = self.method.impl_map()?.flags();
        if flags.contains(windows_metadata::PInvokeAttributes::CallConvFastcall) {
            None
        } else if flags.contains(windows_metadata::PInvokeAttributes::CallConvCdecl) {
            Some("C")
        } else if flags.contains(windows_metadata::PInvokeAttributes::CallConvPlatformapi) {
            Some("system")
        } else {
            None
        }
    }

    fn reject_variadic(&self, config: &Config<'_>, reason: &str) -> TokenStream {
        assert!(
            !config
                .plan
                .selection
                .names_type(self.namespace, self.method.name()),
            "windows-bindgen: selected variadic function `{}.{}` {reason}",
            self.namespace,
            self.method.name()
        );
        quote! {}
    }

    pub fn write_fn_ptr(&self, config: &Config<'_>, underlying_types: bool) -> TokenStream {
        let ptr_name = self.method.name().to_string();
        let name = to_ident(&ptr_name);
        let abi = self.abi(config);
        let signature = self.write_extern_signature(config, underlying_types);

        quote! {
            pub type #name = unsafe extern #abi fn #signature;
        }
    }

    pub fn write_link(&self, config: &Config, underlying_types: bool) -> TokenStream {
        let library = if config.reader.legacy() {
            legacy::module_name(self.method)
        } else {
            self.method.module_name()
        };
        let symbol = self.method.import_name();
        let ordinal = windows_metadata::import_ordinal(symbol.unwrap_or(self.method.name()))
            .unwrap_or_else(|error| {
                panic!(
                    "windows-bindgen: function `{}.{}`: {error}",
                    self.namespace,
                    self.method.name()
                )
            });
        let name = to_ident(self.method.name());
        let abi = self.abi(config);
        let signature = self.write_extern_signature(config, underlying_types);
        let link = to_ident(config.link);

        if config.bindgen.extern_fns {
            quote! {
                unsafe extern #abi {
                    pub fn #name #signature;
                }
            }
        } else if let Some(ordinal) = ordinal {
            let ordinal = Literal::u16_unsuffixed(ordinal);
            quote! {
                #link::link!(#library #abi ordinal(#ordinal) fn #name #signature);
            }
        } else {
            quote! {
                #link::link!(#library #abi #symbol fn #name #signature);
            }
        }
    }

    pub fn write_cfg(&self, config: &Config) -> TokenStream {
        write_simple_cfg(self, config)
    }

    pub fn write(&self, config: &Config) -> TokenStream {
        let name = to_ident(self.method.name());
        let signature = self.method.method_signature(&[], config.reader);
        let variadic = signature.call_flags.contains(MethodCallAttributes::VARARG);

        // Legacy packages keep the fixed-parameter wrapper, which calls the variadic declaration
        // without variadic arguments.
        if variadic && config.bindgen.style == Style::Full && !config.reader.legacy() {
            return self.reject_variadic(
                config,
                "cannot be projected by full bindings; use default or `--sys` for its raw \
                 declaration",
            );
        }
        if variadic && self.variadic_abi(config).is_none() {
            return self.reject_variadic(
                config,
                "uses a calling convention that stable Rust cannot represent for C variadics",
            );
        }

        let link = self.write_link(config, false);
        let arches = write_arches(self.method);
        let cfg = self.write_cfg(config);
        let cfg = quote! { #arches #cfg };
        let window_long = self.write_window_long(config.reader);

        if config.bindgen.style.is_sys() || config.bindgen.style.is_minimal() {
            // `link!` already emits the function-pointer alias unless `--extern` bypasses it.
            let fn_ptr = if config.bindgen.extern_fns {
                let fn_ptr = self.write_fn_ptr(config, false);

                quote! {
                    #cfg
                    #fn_ptr
                }
            } else {
                quote! {}
            };

            return quote! {
                #fn_ptr
                #cfg
                #link
                #window_long
            };
        }

        let method = CppMethod::new(self.method, config.reader);
        let args = method.write_args(config);
        let params = method.write_params(config);
        let generics = method.write_generics();
        let abi_return_type = method.write_return(config);
        let result = config.write_core();
        let must_use = method.write_must_use(config.reader);

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

                quote! {
                    #cfg
                    #[inline]
                    pub unsafe fn #name<#generics T>(#params) -> #result Result<T> #where_clause {
                        #link
                        let mut result__ = core::ptr::null_mut();
                        unsafe { #name(#args).and_then(|| windows_core::imp::from_abi(result__)) }
                    }
                }
            }
            ReturnHint::QueryOptional(..) => {
                let where_clause = method.write_where(config, true);

                quote! {
                    #cfg
                    #[inline]
                    pub unsafe fn #name<#generics T>(#params result__: *mut Option<T>) -> #result Result<()> #where_clause {
                        #link
                        unsafe { #name(#args).ok() }
                    }
                }
            }
            ReturnHint::ResultValue => {
                let where_clause = method.write_where(config, false);
                let ty = 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! {
                    #cfg
                    #[inline]
                    pub unsafe fn #name<#generics>(#params) -> #result Result<#return_type> #where_clause {
                        #link
                        unsafe {
                            #init
                            #name(#args).#map
                        }
                    }
                }
            }
            ReturnHint::ReturnValue => {
                let where_clause = method.write_where(config, false);

                let return_type = method.signature.params[method.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! {
                        #cfg
                        #[inline]
                        pub unsafe fn #name<#generics>(#params) -> #result Result<#return_type> #where_clause {
                            #link
                            unsafe {
                                let mut result__ = core::mem::zeroed();
                                #name(#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 where_clause = method.write_where(config, false);
                    let return_type = return_type.write_name(config);

                    quote! {
                        #cfg
                        #[inline]
                        pub unsafe fn #name<#generics>(#params) -> #return_type #where_clause {
                            #link
                            unsafe {
                                let mut result__ = core::mem::zeroed();
                                #name(#args);
                                #map
                            }
                        }
                    }
                }
            }
            ReturnHint::ResultVoid => {
                let where_clause = method.write_where(config, false);

                quote! {
                    #cfg
                    #[inline]
                    pub unsafe fn #name<#generics>(#params) -> #result Result<()> #where_clause {
                        #link
                        unsafe { #name(#args).ok() }
                    }
                }
            }
            ReturnHint::ReturnStruct | ReturnHint::None
                if config.reader.legacy()
                    && legacy::handle_last_error(self.method, &signature, config.reader) =>
            {
                let where_clause = method.write_where(config, false);
                let return_type = signature.return_type.write_name(config);

                quote! {
                    #cfg
                    #[inline]
                    pub unsafe fn #name<#generics>(#params) -> #result Result<#return_type> #where_clause {
                        #link
                        let result__ = unsafe { #name(#args) };
                        (!result__.is_invalid()).then_some(result__).ok_or_else(windows_core::Error::from_thread)
                    }
                }
            }
            ReturnHint::ReturnStruct | ReturnHint::None => {
                let where_clause = method.write_where(config, false);

                quote! {
                    #cfg
                    #[inline]
                    pub unsafe fn #name<#generics>(#params) #abi_return_type #where_clause {
                        #link
                        unsafe { #name(#args) }
                    }
                }
            }
        };

        quote! {
            #must_use
            #wrapper
            #window_long
        }
    }

    /// Supplies the legacy x86 alias once, only when metadata lacks an x86 declaration.
    pub fn window_long_dependency(&self, reader: &Reader) -> Option<&'static str> {
        let dependency = match self.method.name() {
            "GetWindowLongPtrA" => "GetWindowLongA",
            "GetWindowLongPtrW" => "GetWindowLongW",
            "SetWindowLongPtrA" => "SetWindowLongA",
            "SetWindowLongPtrW" => "SetWindowLongW",
            _ => return None,
        };
        let mut declarations = reader
            .with_full_name(self.namespace, self.method.name())
            .filter_map(|ty| match ty {
                Type::CppFn(function) => Some(function),
                _ => None,
            });
        let first = declarations.next()?;
        if first != *self
            || std::iter::once(first).chain(declarations).any(|function| {
                let arches = function.method.arches();
                arches == 0 || arches & 1 != 0
            })
        {
            return None;
        }
        Some(dependency)
    }

    fn write_window_long(&self, reader: &Reader) -> TokenStream {
        let Some(dependency) = self.window_long_dependency(reader) else {
            return quote! {};
        };
        let dependency = to_ident(dependency);
        let name = to_ident(self.method.name());
        quote! {
            #[cfg(target_pointer_width = "32")]
            pub use #dependency as #name;
        }
    }
}

impl Dependencies for CppFn {
    fn combine(&self, dependencies: &mut TypeMap, reader: &Reader) {
        for ty in self.method.associated_enums(reader) {
            ty.combine(dependencies, reader);
        }
        self.method
            .method_signature(&[], reader)
            .combine(dependencies, reader);

        let dependency = self.window_long_dependency(reader);

        if let Some(dependency) = dependency {
            reader
                .unwrap_full_name(self.namespace, dependency)
                .combine(dependencies, reader);
        }
    }
}

impl Config<'_> {
    pub fn write_return_sig(
        &self,
        method: MethodDef,
        signature: &Signature,
        underlying_types: bool,
    ) -> TokenStream {
        match &signature.return_type {
            Type::Void => {
                if method.has_attribute("DoesNotReturnAttribute") {
                    quote! { -> ! }
                } else {
                    quote! {}
                }
            }
            ty => {
                let ty = if underlying_types {
                    ty.underlying_type(self.reader).write_default(self)
                } else {
                    ty.write_default(self)
                };

                quote! { -> #ty }
            }
        }
    }
}