Skip to main content

windows_bindgen/
cli.rs

1use super::*;
2
3/// Generates bindings using command-line-style arguments.
4///
5/// ```rust,no_run
6/// let args = [
7///     "--out",
8///     "src/bindings.rs",
9///     "--filter",
10///     "GetTickCount",
11/// ];
12///
13/// windows_bindgen::bindgen(args);
14/// ```
15///
16/// Supported arguments:
17///
18/// - `--in`: Metadata files or directories.
19/// - `--out`: Generated Rust file.
20/// - `--filter`: Included or excluded APIs.
21/// - `--rustfmt`: Comma-separated `rustfmt --config` options, such as `max_width=120`.
22/// - `--derive`: Extra derives as `Type=Trait,OtherTrait`, for example `SYSTEMTIME=Debug`.
23/// - `--modules`: Nests items in one module per namespace.
24/// - `--package`: Generates a package with one file per namespace.
25/// - `--sys`: Generates raw bindings that depend only on `windows-link`.
26/// - `--extern`: Uses extern declarations in any style; the caller supplies import libraries.
27/// - `--full`: Adds class wrappers, inherited forwarders, handle wrappers, and implementation traits
28///   for interfaces not marked `ExclusiveTo`.
29/// - `--implement`: Implementation traits for dotted interface names or namespace prefixes.
30///   Without names, includes every native and WinRT interface in scope.
31///   See [`Bindgen::implement`] for restrictions on member filters with named selectors.
32/// - `--compose`: Selects WinRT class composition targets.
33/// - `--dead-code`: Emits `pub(crate)` items for dead-code analysis.
34/// - `--etc`: Reads arguments from command files.
35/// - `--filter-file`: Reads filters from text files.
36///
37/// # `--out`
38///
39/// Defaults to `bindings.rs` in the runtime `OUT_DIR` directory. An explicit path is required when
40/// `OUT_DIR` is unset or empty, and always with `--package`. Bindgen does not emit Cargo
41/// dependency-tracking directives.
42///
43/// # `--filter`
44///
45/// Uses the same syntax as [`Bindgen::filter`], including groups and exclusions:
46///
47/// ```text
48/// --filter GetTickCount HWND
49///
50/// --filter Windows.Win32.GetTickCount
51///
52/// --filter Windows::Win32::{GetTickCount, GetTickCount64}
53///
54/// --filter Windows.Foundation
55/// ```
56///
57/// See [`Bindgen::filter`] for name resolution, member selection, dependencies, and rule precedence.
58///
59/// # `--filter-file` and `--etc`
60///
61/// Use a filter file for longer filter lists:
62///
63/// ```text
64/// --filter-file path/to/filter.txt
65/// ```
66///
67/// Filter and command files separate arguments with whitespace. Filter expressions keep `{...}`
68/// groups together across lines and allow trailing commas:
69///
70/// ```text
71/// ID2D1RenderTarget::{
72///     BeginDraw,
73///     EndDraw,
74///     Clear, // Reset the surface
75/// }
76/// ```
77///
78/// Lines beginning with `//` after optional whitespace are comments. Inline comments start with
79/// a separate `//` token, followed by whitespace or the end of the line. This leaves UNC paths
80/// such as `--in //server/share/input.winmd` intact. In command files, grouping applies only to
81/// `--filter` arguments; braces in paths are literal.
82///
83/// The in-repo crates use this convention; see the filter `.txt` files in
84/// `crates/tools/bindings/src`.
85///
86#[track_caller]
87pub fn bindgen<I, S>(args: I)
88where
89    I: IntoIterator<Item = S>,
90    S: AsRef<str>,
91{
92    let args = expand_args(args);
93    let mut builder = Bindgen::new();
94    let mut kind = ArgKind::None;
95    let mut has_output = false;
96    let mut output_required = false;
97    let mut implement = None::<Vec<String>>;
98    let mut compose = None::<Vec<String>>;
99
100    for arg in args {
101        if arg.starts_with('-') {
102            assert!(!output_required, "`--out` requires a path");
103            kind = ArgKind::None;
104        }
105
106        match kind {
107            ArgKind::None => match arg.as_str() {
108                "--in" => kind = ArgKind::Input,
109                "--out" => {
110                    kind = ArgKind::Output;
111                    output_required = true;
112                }
113                "--filter" => kind = ArgKind::Filter,
114                "--filter-file" => kind = ArgKind::FilterFile,
115                "--rustfmt" => kind = ArgKind::Rustfmt,
116                "--derive" => kind = ArgKind::Derive,
117                "--modules" => {
118                    builder.modules();
119                }
120                "--package" => {
121                    builder.package();
122                }
123                "--sys" => {
124                    builder.sys();
125                }
126                "--full" => {
127                    builder.full();
128                }
129                "--dead-code" => {
130                    builder.dead_code();
131                }
132                "--extern" => {
133                    builder.extern_fns();
134                }
135                "--implement" => {
136                    implement.get_or_insert_with(Vec::new);
137                    kind = ArgKind::Implement;
138                }
139                "--compose" => {
140                    compose.get_or_insert_with(Vec::new);
141                    kind = ArgKind::Compose;
142                }
143                _ => panic!("invalid option `{arg}`"),
144            },
145            ArgKind::Output => {
146                assert!(!has_output, "exactly one `--out` is required");
147                builder.output(arg);
148                has_output = true;
149                output_required = false;
150            }
151            ArgKind::Input => {
152                if arg == "default" {
153                    builder.input_default();
154                } else {
155                    builder.input(arg);
156                }
157            }
158            ArgKind::Filter => {
159                builder.filter(&arg);
160            }
161            ArgKind::FilterFile => {
162                builder.filter_file(&arg);
163            }
164            ArgKind::Derive => {
165                builder.derive(&arg);
166            }
167            ArgKind::Implement => {
168                implement.as_mut().unwrap().push(arg.clone());
169            }
170            ArgKind::Compose => {
171                compose.as_mut().unwrap().push(arg.clone());
172            }
173            ArgKind::Rustfmt => {
174                builder.rustfmt(&arg);
175            }
176        }
177    }
178
179    assert!(!output_required, "`--out` requires a path");
180
181    if let Some(implement) = implement {
182        if implement.is_empty() {
183            builder.implement_all();
184        } else {
185            builder.implements(implement);
186        }
187    }
188    if let Some(compose) = compose {
189        assert!(!compose.is_empty(), "`--compose` requires a class name");
190        builder.composes(compose);
191    }
192
193    builder.write();
194}
195
196enum ArgKind {
197    None,
198    Input,
199    Output,
200    Filter,
201    FilterFile,
202    Rustfmt,
203    Derive,
204    Implement,
205    Compose,
206}
207
208#[track_caller]
209fn expand_args<I, S>(args: I) -> Vec<String>
210where
211    I: IntoIterator<Item = S>,
212    S: AsRef<str>,
213{
214    #[track_caller]
215    fn expand<I, S>(result: &mut Vec<String>, filter_args: &mut bool, args: I)
216    where
217        I: IntoIterator<Item = S>,
218        S: AsRef<str>,
219    {
220        let mut command_files = false;
221
222        for arg in args.into_iter().map(|arg| arg.as_ref().to_string()) {
223            if arg.starts_with('-') {
224                command_files = false;
225            }
226
227            if command_files {
228                let tokens = read_tokens(arg, *filter_args);
229                expand(result, filter_args, tokens);
230            } else if arg == "--etc" {
231                command_files = true;
232            } else {
233                if arg.starts_with('-') {
234                    *filter_args = arg == "--filter";
235                }
236                result.push(arg);
237            }
238        }
239    }
240
241    let mut result = Vec::new();
242    expand(&mut result, &mut false, args);
243    result
244}
245
246#[track_caller]
247pub(super) fn read_tokens(input: impl AsRef<Path>, mut filter_args: bool) -> Vec<String> {
248    let input = input.as_ref();
249    let mut result = Vec::new();
250    let mut current = String::new();
251    let mut brace_depth = 0u32;
252    let mut group_line = 0;
253
254    for (index, line) in read_file_lines(input).iter().enumerate() {
255        if line.trim_start().starts_with("//") {
256            continue;
257        }
258        let line_number = index + 1;
259        let mut chars = line.chars().peekable();
260
261        while let Some(ch) = chars.next() {
262            if ch == '/'
263                && chars.peek() == Some(&'/')
264                && (current.is_empty() || current.ends_with(char::is_whitespace))
265                && chars.clone().nth(1).is_none_or(char::is_whitespace)
266            {
267                break;
268            }
269            if filter_args && ch == '{' {
270                if brace_depth == 0 {
271                    group_line = line_number;
272                }
273                brace_depth += 1;
274                current.push(ch);
275            } else if filter_args && ch == '}' {
276                assert!(
277                    brace_depth > 0,
278                    "{}:{line_number}: unbalanced `}}`",
279                    input.display()
280                );
281                brace_depth -= 1;
282                current.push(ch);
283            } else if ch.is_whitespace() && brace_depth == 0 {
284                if !current.is_empty() {
285                    if current.starts_with('-') {
286                        filter_args = current == "--filter";
287                    }
288                    result.push(std::mem::take(&mut current));
289                }
290            } else {
291                current.push(ch);
292            }
293        }
294        if brace_depth > 0 {
295            current.push('\n');
296        } else if !current.is_empty() {
297            if current.starts_with('-') {
298                filter_args = current == "--filter";
299            }
300            result.push(std::mem::take(&mut current));
301        }
302    }
303
304    assert!(
305        brace_depth == 0,
306        "{}:{group_line}: unbalanced `{{`",
307        input.display()
308    );
309    result
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    #[test]
317    fn command_file_paths_and_comments() {
318        let path = std::env::temp_dir().join(format!(
319            "windows-bindgen-command-tokens-{}.txt",
320            std::process::id()
321        ));
322        std::fs::write(
323            &path,
324            r"--in C:\metadata\input.winmd relative//input.winmd \\server\share\input.winmd
325--out generated/{bindings}.rs // output }
326--filter Type::{Method} --in metadata/input{.winmd // literal brace
327",
328        )
329        .unwrap();
330        let tokens = read_tokens(&path, false);
331        std::fs::remove_file(&path).unwrap();
332        assert_eq!(
333            tokens,
334            [
335                "--in",
336                r"C:\metadata\input.winmd",
337                "relative//input.winmd",
338                r"\\server\share\input.winmd",
339                "--out",
340                "generated/{bindings}.rs",
341                "--filter",
342                "Type::{Method}",
343                "--in",
344                "metadata/input{.winmd",
345            ]
346        );
347    }
348
349    #[test]
350    fn command_file_unc_paths_are_not_comments() {
351        let path = std::env::temp_dir().join(format!(
352            "windows-bindgen-command-unc-{}.txt",
353            std::process::id()
354        ));
355        std::fs::write(
356            &path,
357            "//Whole-line comment\n\
358             --in //server/share/input.winmd // metadata\n\
359             --out //server/share/output.rs // generated output\n\
360             --filter-file //server/share/filters.txt //\n\
361             --etc //server/share/commands.txt // nested commands\n\
362             --filter Type::{} //\tfilter\n",
363        )
364        .unwrap();
365        let tokens = read_tokens(&path, false);
366        std::fs::remove_file(&path).unwrap();
367        assert_eq!(
368            tokens,
369            [
370                "--in",
371                "//server/share/input.winmd",
372                "--out",
373                "//server/share/output.rs",
374                "--filter-file",
375                "//server/share/filters.txt",
376                "--etc",
377                "//server/share/commands.txt",
378                "--filter",
379                "Type::{}",
380            ]
381        );
382    }
383
384    #[test]
385    fn command_files_inherit_argument_kind() {
386        let directory = std::env::temp_dir().join(format!(
387            "windows-bindgen-command-context-{}",
388            std::process::id()
389        ));
390        std::fs::create_dir_all(&directory).unwrap();
391        let selector = directory.join("selector.txt");
392        let arguments = directory.join("arguments.txt");
393        let outer = directory.join("outer.txt");
394        std::fs::write(
395            &outer,
396            format!("--etc {} {}", selector.display(), arguments.display()),
397        )
398        .unwrap();
399
400        for (option, value) in [
401            ("--filter", "Test::{\n    CONSTANT,\n}"),
402            ("--out", "generated/bindings}.rs"),
403            ("--in", "metadata/input{.winmd"),
404        ] {
405            std::fs::write(&selector, option).unwrap();
406            std::fs::write(&arguments, value).unwrap();
407            for args in [
408                vec![option, "--etc", arguments.to_str().unwrap()],
409                vec![
410                    "--etc",
411                    selector.to_str().unwrap(),
412                    arguments.to_str().unwrap(),
413                ],
414                vec!["--etc", outer.to_str().unwrap()],
415            ] {
416                assert_eq!(expand_args(args), [option, value]);
417            }
418        }
419
420        for path in [selector, arguments, outer] {
421            std::fs::remove_file(path).unwrap();
422        }
423        std::fs::remove_dir(directory).unwrap();
424    }
425}