windows-bindgen 0.66.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
#![doc = include_str!("../readme.md")]
#![expect(
    non_upper_case_globals,
    non_camel_case_types,
    dead_code,
    non_snake_case,
    clippy::enum_variant_names,
    clippy::upper_case_acronyms
)]

mod config;
mod derive;
mod derive_writer;
mod filter;
mod guid;
mod index;
mod io;
mod libraries;
mod param;
mod references;
mod signature;
mod tables;
mod tokens;
mod type_map;
mod type_name;
mod type_tree;
mod types;
mod value;
mod warnings;
mod winmd;

use config::*;
use derive::*;
use derive_writer::*;
use filter::*;
use guid::*;
use io::*;
pub use libraries::*;
use param::*;
use references::*;
use signature::*;
use std::cmp::Ordering;
use std::collections::*;
use std::fmt::Write;
use tables::*;
use tokens::*;
use type_map::*;
use type_name::*;
use type_tree::*;
use types::*;
use value::*;
pub use warnings::*;
use winmd::*;
mod method_names;
use method_names::*;

/// The conventional way of calling the `bindgen` function is as follows:
///
/// ```rust,no_run
/// let args = [
///     "--out",
///     "src/bindings.rs",
///     "--filter",
///     "GetTickCount",
/// ];
///
/// windows_bindgen::bindgen(args).unwrap();
/// ```
///
/// Here is a list of supported arguments.
///
/// | Argument | Description |
/// |----------|-------------|
/// | `--in` | .winmd files or directories to include. |
/// | `--out` | File name where the generated bindings will be saved. |
/// | `--filter` | APIs to include or exclude in the generated bindings. |
/// | `--rustfmt` | Overrides the default Rust formatting. |
/// | `--derive` | Extra traits for types to derive. |
/// | `--flat` | Avoids the default namespace-to-module conversion. |
/// | `--no-allow` | Avoids generating the default `allow` attribute. |
/// | `--no-comment` | Avoids generating the code generation comment. |
/// | `--no-deps` | Avoids dependencies on the various `windows-*` crates. |
/// | `--sys` | Generates raw or sys-style Rust bindings. |
/// | `--sys-fn-ptrs` | Additionally generates function pointers for sys-style Rust bindings. |
/// | `--sys-fn-extern` | Generates extern declarations rather than link macros for sys-style Rust bindings. |
/// | `--implement` | Includes implementation traits for WinRT interfaces. |
/// | `--link` | Overrides the default `windows-link` implementation for system calls. |
///
///
/// # `--out`
///
/// Exactly one `--out` argument is required and instructs the `bindgen` function where to write the bindings.
///
/// # `--filter`
///
/// At least one `--filter` is required and indicates what APIs to include in the generated bindings.
/// The following will, for example, also include the `Sleep` function:
///
/// ```rust
/// let args = [
///     "--out",
///     "src/bindings.rs",
///     "--filter",
///     "GetTickCount",
///     "Sleep",
/// ];
/// ```
///
/// The `--filter` argument can refer to the function or type name and nothing more. You can also refer
/// to the namespace that the API metadata uses to group functions and types:
///
/// ```rust
/// let args = [
///     "--out",
///     "src/bindings.rs",
///     "--filter",
///     "Windows.Foundation.Numerics",
///     "!Windows.Foundation.Numerics.Matrix3x2",
/// ];
/// ```
///
/// In this example, all types from the `Windows.Foundation.Numerics` namepace are included with the
/// exception of `Matrix3x2` which is excluded due to the `!` preamble.
///
/// # `--in`
///
/// `--in` can indicate a .winmd file or directory containing .winmd files. Alternatively, the special
/// "default" input can be used to include the particular .winmd files that ship with the `windows-bindgen`
/// crate. This may used to combine the default metadata with specific .winmd files.
///
/// ```rust
/// let args = [
///     "--in",
///     "default",
///     "Sample.winmd",
///     "--out",
///     "src/bindings.rs",
///     "--filter",
///     "Sample",
/// ];
/// ```
///
/// # `--flat`
///
/// By default, the bindings include a mapping of namespaces to modules. Consider this example again:
///
/// ```rust
/// let args = [
///     "--out",
///     "src/bindings.rs",
///     "--filter",
///     "GetTickCount",
///     "Sleep",
/// ];
/// ```
///
/// The resulting bindings might look something like this:
///
/// ```rust
/// pub mod Windows {
///     pub mod Win32 {
///         pub mod System {
///             pub mod SystemInformation {
///                 #[inline]
///                 pub unsafe fn GetTickCount() -> u32 {
///                     windows_link::link!("kernel32.dll" "system" fn GetTickCount() -> u32);
///                     unsafe { GetTickCount() }
///                 }
///             }
///             pub mod Threading {
///                 #[inline]
///                 pub unsafe fn Sleep(dwmilliseconds: u32) {
///                     windows_link::link!("kernel32.dll" "system" fn Sleep(dwmilliseconds : u32));
///                     unsafe { Sleep(dwmilliseconds) }
///                 }
///             }
///         }
///     }
/// }
/// ```
///
/// That's because the default metadata defines `GetTickCount` in the `Windows.Win32.System.SystemInformation`
/// namespace while `Sleep` is defined in the `Windows.Win32.System.Threading` namespace. Fortunately, it's
/// easy to turn that off by using the `--flat` argument:
///
/// ```rust
/// let args = [
///     "--out",
///     "src/bindings.rs",
///     "--flat",
///     "--filter",
///     "GetTickCount",
///     "Sleep",
/// ];
/// ```
///
/// The resulting bindings now look something like this:
///
/// ```rust
/// #[inline]
/// pub unsafe fn GetTickCount() -> u32 {
///     windows_link::link!("kernel32.dll" "system" fn GetTickCount() -> u32);
///     unsafe { GetTickCount() }
/// }
/// #[inline]
/// pub unsafe fn Sleep(dwmilliseconds: u32) {
///     windows_link::link!("kernel32.dll" "system" fn Sleep(dwmilliseconds : u32));
///     unsafe { Sleep(dwmilliseconds) }
/// }
/// ```
///
/// # `--no-allow`
///
/// The bindings also include an allow attribute that covers various common warnings inherent in
/// generated bindings.
///
/// ```rust
/// #![allow(
///     non_snake_case,
///     non_upper_case_globals,
///     non_camel_case_types,
///     dead_code,
///     clippy::all
/// )]
/// ```
///
/// You can prevent this from being generated if you prefer to manage this yourself with the `--no-allow`
/// argument.
///
/// # `--sys`
///
/// The `--sys` argument instruct the `bindgen` function to generate raw, sometimes called sys-style Rust
/// bindings.
///
/// ```rust
/// let args = [
///     "--out",
///     "src/bindings.rs",
///     "--flat",
///     "--sys",
///     "--filter",
///     "GetTickCount",
///     "Sleep",
/// ];
/// ```
///
/// The resulting bindings now look something like this:
///
/// ```rust
/// windows_link::link!("kernel32.dll" "system" fn GetTickCount() -> u32);
/// windows_link::link!("kernel32.dll" "system" fn Sleep(dwmilliseconds : u32));
/// ```
///
/// You'll notice that the bindings are simpler as there's no wrapper functions and other
/// conveniences. You just need to add a dependency on the tiny [windows-link](https://crates.io/crates/windows-link) crate and you're all set.
///
#[track_caller]
#[must_use]
pub fn bindgen<I, S>(args: I) -> Warnings
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let args = expand_args(args);
    let mut kind = ArgKind::None;
    let mut input = Vec::new();
    let mut include = Vec::new();
    let mut exclude = Vec::new();
    let mut references = Vec::new();
    let mut derive = Vec::new();

    let mut flat = false;
    let mut no_allow = false;
    let mut no_comment = false;
    let mut no_deps = false;
    let mut no_toml = false;
    let mut package = false;
    let mut implement = false;
    let mut specific_deps = false;
    let mut rustfmt = String::new();
    let mut output = String::new();
    let mut sys = false;
    let mut sys_fn_ptrs = false;
    let mut sys_fn_extern = false;
    let mut link = String::new();
    let mut index = false;

    for arg in &args {
        if arg.starts_with('-') {
            kind = ArgKind::None;
        }

        match kind {
            ArgKind::None => match arg.as_str() {
                "--in" => kind = ArgKind::Input,
                "--out" => kind = ArgKind::Output,
                "--filter" => kind = ArgKind::Filter,
                "--rustfmt" => kind = ArgKind::Rustfmt,
                "--reference" => kind = ArgKind::Reference,
                "--derive" => kind = ArgKind::Derive,
                "--flat" => flat = true,
                "--no-allow" => no_allow = true,
                "--no-comment" => no_comment = true,
                "--no-deps" => no_deps = true,
                "--no-toml" => no_toml = true,
                "--package" => package = true,
                "--sys" => sys = true,
                "--sys-fn-ptrs" => sys_fn_ptrs = true,
                "--sys-fn-extern" => sys_fn_extern = true,
                "--implement" => implement = true,
                "--specific-deps" => specific_deps = true,
                "--link" => kind = ArgKind::Link,
                "--index" => index = true,
                _ => panic!("invalid option `{arg}`"),
            },
            ArgKind::Output => {
                if output.is_empty() {
                    output = arg.to_string();
                } else {
                    panic!("exactly one `--out` is required");
                }
            }
            ArgKind::Input => input.push(arg.as_str()),
            ArgKind::Filter => {
                if let Some(rest) = arg.strip_prefix('!') {
                    exclude.push(rest);
                } else {
                    include.push(arg.as_str());
                }
            }
            ArgKind::Reference => {
                references.push(ReferenceStage::parse(arg));
            }
            ArgKind::Derive => {
                derive.push(arg.as_str());
            }
            ArgKind::Rustfmt => rustfmt = arg.to_string(),
            ArgKind::Link => link = arg.to_string(),
        }
    }

    if link.is_empty() {
        if sys || specific_deps {
            link = "windows_link".to_string();
        } else {
            link = "windows_core".to_string();
        }
    }

    if package && flat {
        panic!("cannot combine `--package` and `--flat`");
    }

    if input.is_empty() {
        input.push("default");
    };

    if output.is_empty() {
        panic!("exactly one `--out` is required");
    };

    // This isn't strictly necessary but avoids a common newbie pitfall where all metadata
    // would be generated when building a component for a specific API.
    if include.is_empty() {
        panic!("at least one `--filter` required");
    }

    let reader = Reader::new(expand_input(&input));

    if !sys && !no_deps {
        if reader.contains_key("Windows.Foundation") {
            references.insert(
                0,
                ReferenceStage::parse("windows_collections,flat,Windows.Foundation.Collections"),
            );
            references.insert(
                0,
                ReferenceStage::parse("windows_numerics,flat,Windows.Foundation.Numerics"),
            );
            references.insert(
                0,
                ReferenceStage::parse("windows_future,flat,Windows.Foundation.Async*"),
            );
            references.insert(
                0,
                ReferenceStage::parse("windows_future,flat,Windows.Foundation.IAsync*"),
            );
        }

        if reader.contains_key("Windows.Win32.Foundation") {
            if specific_deps {
                references.insert(
                    0,
                    ReferenceStage::parse(
                        "windows_result,flat,Windows.Win32.Foundation.WIN32_ERROR",
                    ),
                );
                references.insert(
                    0,
                    ReferenceStage::parse("windows_result,flat,Windows.Win32.Foundation.NTSTATUS"),
                );
                references.insert(
                    0,
                    ReferenceStage::parse(
                        "windows_result,flat,Windows.Win32.System.Rpc.RPC_STATUS",
                    ),
                );
            } else {
                references.insert(
                    0,
                    ReferenceStage::parse("windows_core,flat,Windows.Win32.Foundation.WIN32_ERROR"),
                );
                references.insert(
                    0,
                    ReferenceStage::parse("windows_core,flat,Windows.Win32.Foundation.NTSTATUS"),
                );
                references.insert(
                    0,
                    ReferenceStage::parse("windows_core,flat,Windows.Win32.System.Rpc.RPC_STATUS"),
                );
            }
        }
    }

    let filter = Filter::new(&reader, &include, &exclude);
    let references = References::new(&reader, references);
    let types = TypeMap::filter(&reader, &filter, &references);
    let derive = Derive::new(&reader, &types, &derive);
    let warnings = WarningBuilder::default();

    let config = Config {
        types: &types,
        flat,
        references: &references,
        derive: &derive,
        no_allow,
        no_comment,
        no_deps,
        no_toml,
        package,
        rustfmt: &rustfmt,
        output: &output,
        sys,
        sys_fn_ptrs,
        sys_fn_extern,
        implement,
        specific_deps,
        link: &link,
        warnings: &warnings,
        namespace: "",
    };

    let tree = TypeTree::new(&types);

    config.write(tree);

    if index {
        index::write(&types, &format!("{output}/features.json"));
    }

    warnings.build()
}

enum ArgKind {
    None,
    Input,
    Output,
    Filter,
    Rustfmt,
    Reference,
    Derive,
    Link,
}

#[track_caller]
fn expand_args<I, S>(args: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    // This function is needed to avoid a recursion limit in the Rust compiler.
    #[track_caller]
    fn from_string(result: &mut Vec<String>, value: &str) {
        expand_args(result, value.split_whitespace().map(|arg| arg.to_string()))
    }

    #[track_caller]
    fn expand_args<I, S>(result: &mut Vec<String>, args: I)
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut expand = false;

        for arg in args.into_iter().map(|arg| arg.as_ref().to_string()) {
            if arg.starts_with('-') {
                expand = false;
            }
            if expand {
                for args in io::read_file_lines(&arg) {
                    if !args.starts_with("//") {
                        from_string(result, &args);
                    }
                }
            } else if arg == "--etc" {
                expand = true;
            } else {
                result.push(arg);
            }
        }
    }

    let mut result = vec![];
    expand_args(&mut result, args);
    result
}

#[track_caller]
fn expand_input(input: &[&str]) -> Vec<File> {
    #[track_caller]
    fn expand_input(result: &mut Vec<String>, input: &str) {
        let path = std::path::Path::new(input);

        if path.is_dir() {
            let prev_len = result.len();

            for path in path
                .read_dir()
                .unwrap_or_else(|_| panic!("failed to read directory `{input}`"))
                .flatten()
                .map(|entry| entry.path())
            {
                if path.is_file()
                    && path
                        .extension()
                        .is_some_and(|extension| extension.eq_ignore_ascii_case("winmd"))
                {
                    result.push(path.to_string_lossy().to_string());
                }
            }

            if result.len() == prev_len {
                panic!("failed to find .winmd files in directory `{input}`");
            }
        } else {
            result.push(input.to_string());
        }
    }

    let mut paths = vec![];
    let mut use_default = false;

    for input in input {
        if *input == "default" {
            use_default = true;
        } else {
            expand_input(&mut paths, input);
        }
    }

    let mut input = vec![];

    if use_default {
        input = [
            std::include_bytes!("../default/Windows.winmd").to_vec(),
            std::include_bytes!("../default/Windows.Win32.winmd").to_vec(),
            std::include_bytes!("../default/Windows.Wdk.winmd").to_vec(),
        ]
        .into_iter()
        .map(|bytes| File::new(bytes).unwrap())
        .collect();
    }

    for path in &paths {
        let Ok(bytes) = std::fs::read(path) else {
            panic!("failed to read binary file `{path}`");
        };

        let Some(file) = File::new(bytes) else {
            panic!("failed to read .winmd format `{path}`");
        };

        input.push(file);
    }

    input
}

fn namespace_starts_with(namespace: &str, starts_with: &str) -> bool {
    namespace.starts_with(starts_with)
        && (namespace.len() == starts_with.len()
            || namespace.as_bytes().get(starts_with.len()) == Some(&b'.'))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_starts_with() {
        assert!(namespace_starts_with(
            "Windows.Win32.Graphics.Direct3D11on12",
            "Windows.Win32.Graphics.Direct3D11on12"
        ));
        assert!(namespace_starts_with(
            "Windows.Win32.Graphics.Direct3D11on12",
            "Windows.Win32.Graphics"
        ));
        assert!(!namespace_starts_with(
            "Windows.Win32.Graphics.Direct3D11on12",
            "Windows.Win32.Graphics.Direct3D11"
        ));
        assert!(!namespace_starts_with(
            "Windows.Win32.Graphics.Direct3D",
            "Windows.Win32.Graphics.Direct3D11"
        ));
    }
}