windows_bindgen/
lib.rs

1#![doc = include_str!("../readme.md")]
2#![expect(
3    non_upper_case_globals,
4    non_camel_case_types,
5    dead_code,
6    non_snake_case,
7    clippy::enum_variant_names,
8    clippy::upper_case_acronyms
9)]
10
11mod config;
12mod derive;
13mod derive_writer;
14mod filter;
15mod guid;
16mod index;
17mod io;
18mod libraries;
19mod param;
20mod references;
21mod signature;
22mod tables;
23mod tokens;
24mod type_map;
25mod type_name;
26mod type_tree;
27mod types;
28mod value;
29mod warnings;
30mod winmd;
31
32use config::*;
33use derive::*;
34use derive_writer::*;
35use filter::*;
36use guid::*;
37use io::*;
38pub use libraries::*;
39use param::*;
40use references::*;
41use signature::*;
42use std::cmp::Ordering;
43use std::collections::*;
44use std::fmt::Write;
45use tables::*;
46use tokens::*;
47use type_map::*;
48use type_name::*;
49use type_tree::*;
50use types::*;
51use value::*;
52pub use warnings::*;
53use winmd::*;
54mod method_names;
55use method_names::*;
56
57/// The conventional way of calling the `bindgen` function is as follows:
58///
59/// ```rust,no_run
60/// let args = [
61///     "--out",
62///     "src/bindings.rs",
63///     "--filter",
64///     "GetTickCount",
65/// ];
66///
67/// windows_bindgen::bindgen(args).unwrap();
68/// ```
69///
70/// Here is a list of supported arguments.
71///
72/// | Argument | Description |
73/// |----------|-------------|
74/// | `--in` | .winmd files or directories to include. |
75/// | `--out` | File name where the generated bindings will be saved. |
76/// | `--filter` | APIs to include or exclude in the generated bindings. |
77/// | `--rustfmt` | Overrides the default Rust formatting. |
78/// | `--derive` | Extra traits for types to derive. |
79/// | `--flat` | Avoids the default namespace-to-module conversion. |
80/// | `--no-allow` | Avoids generating the default `allow` attribute. |
81/// | `--no-comment` | Avoids generating the code generation comment. |
82/// | `--no-deps` | Avoids dependencies on the various `windows-*` crates. |
83/// | `--sys` | Generates raw or sys-style Rust bindings. |
84/// | `--implement` | Includes implementation traits for WinRT interfaces. |
85/// | `--link` | Overrides the default `windows-link` implementation for system calls. |
86///
87///
88/// # `--out`
89///
90/// Exactly one `--out` argument is required and instructs the `bindgen` function where to write the bindings.
91///
92/// # `--filter`
93///
94/// At least one `--filter` is required and indicates what APIs to include in the generated bindings.
95/// The following will, for example, also include the `Sleep` function:
96///
97/// ```rust
98/// let args = [
99///     "--out",
100///     "src/bindings.rs",
101///     "--filter",
102///     "GetTickCount",
103///     "Sleep",
104/// ];
105/// ```
106///
107/// The `--filter` argument can refer to the function or type name and nothing more. You can also refer
108/// to the namespace that the API metadata uses to group functions and types:
109///
110/// ```rust
111/// let args = [
112///     "--out",
113///     "src/bindings.rs",
114///     "--filter",
115///     "Windows.Foundation.Numerics",
116///     "!Windows.Foundation.Numerics.Matrix3x2",
117/// ];
118/// ```
119///
120/// In this example, all types from the `Windows.Foundation.Numerics` namepace are included with the
121/// exception of `Matrix3x2` which is excluded due to the `!` preamble.
122///
123/// # `--in`
124///
125/// `--in` can indicate a .winmd file or directory containing .winmd files. Alternatively, the special
126/// "default" input can be used to include the particular .winmd files that ship with the `windows-bindgen`
127/// crate. This may used to combine the default metadata with specific .winmd files.
128///
129/// ```rust
130/// let args = [
131///     "--in",
132///     "default",
133///     "Sample.winmd",
134///     "--out",
135///     "src/bindings.rs",
136///     "--filter",
137///     "Sample",
138/// ];
139/// ```
140///
141/// # `--flat`
142///
143/// By default, the bindings include a mapping of namespaces to modules. Consider this example again:
144///
145/// ```rust
146/// let args = [
147///     "--out",
148///     "src/bindings.rs",
149///     "--filter",
150///     "GetTickCount",
151///     "Sleep",
152/// ];
153/// ```
154///
155/// The resulting bindings might look something like this:
156///
157/// ```rust
158/// pub mod Windows {
159///     pub mod Win32 {
160///         pub mod System {
161///             pub mod SystemInformation {
162///                 #[inline]
163///                 pub unsafe fn GetTickCount() -> u32 {
164///                     windows_link::link!("kernel32.dll" "system" fn GetTickCount() -> u32);
165///                     unsafe { GetTickCount() }
166///                 }
167///             }
168///             pub mod Threading {
169///                 #[inline]
170///                 pub unsafe fn Sleep(dwmilliseconds: u32) {
171///                     windows_link::link!("kernel32.dll" "system" fn Sleep(dwmilliseconds : u32));
172///                     unsafe { Sleep(dwmilliseconds) }
173///                 }
174///             }
175///         }
176///     }
177/// }
178/// ```
179///
180/// That's because the default metadata defines `GetTickCount` in the `Windows.Win32.System.SystemInformation`
181/// namespace while `Sleep` is defined in the `Windows.Win32.System.Threading` namespace. Fortunately, it's
182/// easy to turn that off by using the `--flat` argument:
183///
184/// ```rust
185/// let args = [
186///     "--out",
187///     "src/bindings.rs",
188///     "--flat",
189///     "--filter",
190///     "GetTickCount",
191///     "Sleep",
192/// ];
193/// ```
194///
195/// The resulting bindings now look something like this:
196///
197/// ```rust
198/// #[inline]
199/// pub unsafe fn GetTickCount() -> u32 {
200///     windows_link::link!("kernel32.dll" "system" fn GetTickCount() -> u32);
201///     unsafe { GetTickCount() }
202/// }
203/// #[inline]
204/// pub unsafe fn Sleep(dwmilliseconds: u32) {
205///     windows_link::link!("kernel32.dll" "system" fn Sleep(dwmilliseconds : u32));
206///     unsafe { Sleep(dwmilliseconds) }
207/// }
208/// ```
209///
210/// # `--no-allow`
211///
212/// The bindings also include an allow attribute that covers various common warnings inherent in
213/// generated bindings.
214///
215/// ```rust
216/// #![allow(
217///     non_snake_case,
218///     non_upper_case_globals,
219///     non_camel_case_types,
220///     dead_code,
221///     clippy::all
222/// )]
223/// ```
224///
225/// You can prevent this from being generated if you prefer to manage this yourself with the `--no-allow`
226/// argument.
227///
228/// # `--sys`
229///
230/// The `--sys` argument instruct the `bindgen` function to generate raw, sometimes called sys-style Rust
231/// bindings.
232///
233/// ```rust
234/// let args = [
235///     "--out",
236///     "src/bindings.rs",
237///     "--flat",
238///     "--sys",
239///     "--filter",
240///     "GetTickCount",
241///     "Sleep",
242/// ];
243/// ```
244///
245/// The resulting bindings now look something like this:
246///
247/// ```rust
248/// windows_link::link!("kernel32.dll" "system" fn GetTickCount() -> u32);
249/// windows_link::link!("kernel32.dll" "system" fn Sleep(dwmilliseconds : u32));
250/// ```
251///
252/// You'll notice that the bindings are simpler as there's no wrapper functions and other
253/// 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.
254///
255#[track_caller]
256#[must_use]
257pub fn bindgen<I, S>(args: I) -> Warnings
258where
259    I: IntoIterator<Item = S>,
260    S: AsRef<str>,
261{
262    let args = expand_args(args);
263    let mut kind = ArgKind::None;
264    let mut input = Vec::new();
265    let mut include = Vec::new();
266    let mut exclude = Vec::new();
267    let mut references = Vec::new();
268    let mut derive = Vec::new();
269
270    let mut flat = false;
271    let mut no_allow = false;
272    let mut no_comment = false;
273    let mut no_deps = false;
274    let mut no_toml = false;
275    let mut package = false;
276    let mut implement = false;
277    let mut rustfmt = String::new();
278    let mut output = String::new();
279    let mut sys = false;
280    let mut link = "windows_link".to_string();
281    let mut index = false;
282
283    for arg in &args {
284        if arg.starts_with('-') {
285            kind = ArgKind::None;
286        }
287
288        match kind {
289            ArgKind::None => match arg.as_str() {
290                "--in" => kind = ArgKind::Input,
291                "--out" => kind = ArgKind::Output,
292                "--filter" => kind = ArgKind::Filter,
293                "--rustfmt" => kind = ArgKind::Rustfmt,
294                "--reference" => kind = ArgKind::Reference,
295                "--derive" => kind = ArgKind::Derive,
296                "--flat" => flat = true,
297                "--no-allow" => no_allow = true,
298                "--no-comment" => no_comment = true,
299                "--no-deps" => no_deps = true,
300                "--no-toml" => no_toml = true,
301                "--package" => package = true,
302                "--sys" => sys = true,
303                "--implement" => implement = true,
304                "--link" => kind = ArgKind::Link,
305                "--index" => index = true,
306                _ => panic!("invalid option `{arg}`"),
307            },
308            ArgKind::Output => {
309                if output.is_empty() {
310                    output = arg.to_string();
311                } else {
312                    panic!("exactly one `--out` is required");
313                }
314            }
315            ArgKind::Input => input.push(arg.as_str()),
316            ArgKind::Filter => {
317                if let Some(rest) = arg.strip_prefix('!') {
318                    exclude.push(rest);
319                } else {
320                    include.push(arg.as_str());
321                }
322            }
323            ArgKind::Reference => {
324                references.push(ReferenceStage::parse(arg));
325            }
326            ArgKind::Derive => {
327                derive.push(arg.as_str());
328            }
329            ArgKind::Rustfmt => rustfmt = arg.to_string(),
330            ArgKind::Link => link = arg.to_string(),
331        }
332    }
333
334    if package && flat {
335        panic!("cannot combine `--package` and `--flat`");
336    }
337
338    if input.is_empty() {
339        input.push("default");
340    };
341
342    if output.is_empty() {
343        panic!("exactly one `--out` is required");
344    };
345
346    if !sys && !no_deps {
347        references.insert(
348            0,
349            ReferenceStage::parse("windows_collections,flat,Windows.Foundation.Collections"),
350        );
351        references.insert(
352            0,
353            ReferenceStage::parse("windows_numerics,flat,Windows.Foundation.Numerics"),
354        );
355        references.insert(
356            0,
357            ReferenceStage::parse("windows_future,flat,Windows.Foundation.Async*"),
358        );
359        references.insert(
360            0,
361            ReferenceStage::parse("windows_future,flat,Windows.Foundation.IAsync*"),
362        );
363    }
364
365    // This isn't strictly necessary but avoids a common newbie pitfall where all metadata
366    // would be generated when building a component for a specific API.
367    if include.is_empty() {
368        panic!("at least one `--filter` required");
369    }
370
371    let reader = Reader::new(expand_input(&input));
372    let filter = Filter::new(&reader, &include, &exclude);
373    let references = References::new(&reader, references);
374    let types = TypeMap::filter(&reader, &filter, &references);
375    let derive = Derive::new(&reader, &types, &derive);
376    let warnings = WarningBuilder::default();
377
378    let config = Config {
379        types: &types,
380        flat,
381        references: &references,
382        derive: &derive,
383        no_allow,
384        no_comment,
385        no_deps,
386        no_toml,
387        package,
388        rustfmt: &rustfmt,
389        output: &output,
390        sys,
391        implement,
392        link: &link,
393        warnings: &warnings,
394        namespace: "",
395    };
396
397    let tree = TypeTree::new(&types);
398
399    config.write(tree);
400
401    if index {
402        index::write(&types, &format!("{output}/features.json"));
403    }
404
405    warnings.build()
406}
407
408enum ArgKind {
409    None,
410    Input,
411    Output,
412    Filter,
413    Rustfmt,
414    Reference,
415    Derive,
416    Link,
417}
418
419#[track_caller]
420fn expand_args<I, S>(args: I) -> Vec<String>
421where
422    I: IntoIterator<Item = S>,
423    S: AsRef<str>,
424{
425    // This function is needed to avoid a recursion limit in the Rust compiler.
426    #[track_caller]
427    fn from_string(result: &mut Vec<String>, value: &str) {
428        expand_args(result, value.split_whitespace().map(|arg| arg.to_string()))
429    }
430
431    #[track_caller]
432    fn expand_args<I, S>(result: &mut Vec<String>, args: I)
433    where
434        I: IntoIterator<Item = S>,
435        S: AsRef<str>,
436    {
437        let mut expand = false;
438
439        for arg in args.into_iter().map(|arg| arg.as_ref().to_string()) {
440            if arg.starts_with('-') {
441                expand = false;
442            }
443            if expand {
444                for args in io::read_file_lines(&arg) {
445                    if !args.starts_with("//") {
446                        from_string(result, &args);
447                    }
448                }
449            } else if arg == "--etc" {
450                expand = true;
451            } else {
452                result.push(arg);
453            }
454        }
455    }
456
457    let mut result = vec![];
458    expand_args(&mut result, args);
459    result
460}
461
462#[track_caller]
463fn expand_input(input: &[&str]) -> Vec<File> {
464    #[track_caller]
465    fn expand_input(result: &mut Vec<String>, input: &str) {
466        let path = std::path::Path::new(input);
467
468        if path.is_dir() {
469            let prev_len = result.len();
470
471            for path in path
472                .read_dir()
473                .unwrap_or_else(|_| panic!("failed to read directory `{input}`"))
474                .flatten()
475                .map(|entry| entry.path())
476            {
477                if path.is_file()
478                    && path
479                        .extension()
480                        .is_some_and(|extension| extension.eq_ignore_ascii_case("winmd"))
481                {
482                    result.push(path.to_string_lossy().to_string());
483                }
484            }
485
486            if result.len() == prev_len {
487                panic!("failed to find .winmd files in directory `{input}`");
488            }
489        } else {
490            result.push(input.to_string());
491        }
492    }
493
494    let mut paths = vec![];
495    let mut use_default = false;
496
497    for input in input {
498        if *input == "default" {
499            use_default = true;
500        } else {
501            expand_input(&mut paths, input);
502        }
503    }
504
505    let mut input = vec![];
506
507    if use_default {
508        input = [
509            std::include_bytes!("../default/Windows.winmd").to_vec(),
510            std::include_bytes!("../default/Windows.Win32.winmd").to_vec(),
511            std::include_bytes!("../default/Windows.Wdk.winmd").to_vec(),
512        ]
513        .into_iter()
514        .map(|bytes| File::new(bytes).unwrap())
515        .collect();
516    }
517
518    for path in &paths {
519        let Ok(bytes) = std::fs::read(path) else {
520            panic!("failed to read binary file `{path}`");
521        };
522
523        let Some(file) = File::new(bytes) else {
524            panic!("failed to read .winmd format `{path}`");
525        };
526
527        input.push(file);
528    }
529
530    input
531}
532
533fn namespace_starts_with(namespace: &str, starts_with: &str) -> bool {
534    namespace.starts_with(starts_with)
535        && (namespace.len() == starts_with.len()
536            || namespace.as_bytes().get(starts_with.len()) == Some(&b'.'))
537}
538
539#[cfg(test)]
540mod tests {
541    use super::*;
542
543    #[test]
544    fn test_starts_with() {
545        assert!(namespace_starts_with(
546            "Windows.Win32.Graphics.Direct3D11on12",
547            "Windows.Win32.Graphics.Direct3D11on12"
548        ));
549        assert!(namespace_starts_with(
550            "Windows.Win32.Graphics.Direct3D11on12",
551            "Windows.Win32.Graphics"
552        ));
553        assert!(!namespace_starts_with(
554            "Windows.Win32.Graphics.Direct3D11on12",
555            "Windows.Win32.Graphics.Direct3D11"
556        ));
557        assert!(!namespace_starts_with(
558            "Windows.Win32.Graphics.Direct3D",
559            "Windows.Win32.Graphics.Direct3D11"
560        ));
561    }
562}