winrt_macros 0.7.2

Macros for the winrt crate
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
extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::parse::{self, Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::{parse_macro_input, Error, Ident, Token, UseTree};

use winrt_gen::{
    dependencies, NamespaceTypes, TypeLimit, TypeLimits, TypeReader, TypeStage, WinmdFile,
};

use std::convert::{TryFrom, TryInto};
use std::{collections::BTreeSet, path::PathBuf};

/// A macro for generating WinRT modules into the current module.
///
/// This macro can be used to import WinRT APIs from OS dependencies as well
/// as NuGet packages. Use the `import` macro to directly include the generated code
/// into any module.
///
/// # Usage
/// To use, first specify which dependencies you are relying on. This can be both
/// `os` for depending on WinRT metadata shipped with Windows or `nuget: My.Package`
/// for NuGet packages.
///
/// ## NuGet
/// NuGet dependencies are expected in a well defined place. The `winmd` metadata files
/// should be in the cargo workspace's `target` directory in a subdirectory `nuget\My.Package`
/// where `My.Package` is the name of the NuGet package.
///
/// Any DLLs needed for the NuGet package to work should be next to work must be next to the final
/// executable.
///
/// Instead of handling this yourself, you can use the [`cargo winrt`](https://github.com/microsoft/winrt-rs/tree/master/crates/cargo-winrt)
/// helper subcommand.
///
/// ## Types
/// After specifying the dependencies, you must then specify which types you want to use. These
/// follow the same convention as Rust `use` paths. Types know which other types they depend on so
/// `import` will generate any other WinRT types needed for the specified type to work.
///
/// # Example
/// The following `import!` depends on both `os` metadata (i.e., metadata shipped on Windows 10), as well
/// as a 3rd-party NuGet dependency. It then generates all types inside of the `microsoft::ai::machine_learning`
/// namespace.
///
/// ```rust,ignore
/// import!(
///     dependencies
///         os
///         nuget: Microsoft.AI.MachineLearning
///     types
///         microsoft::ai::machine_learning::*
/// );
/// ```
#[proc_macro]
pub fn import(stream: TokenStream) -> TokenStream {
    let import = parse_macro_input!(stream as ImportMacro);
    import.to_tokens()
}

/// A macro for generating WinRT modules to a .rs file at build time.
///
/// This macro can be used to import WinRT APIs from OS dependencies as well
/// as NuGet packages. It is only intended for use from a crate's build.rs script.
///
/// The macro generates a single `build` function which can be used in build scripts
/// to generate the WinRT bindings. After using the `build` macro, call the
/// generated `build` function somewhere in the build.rs script's main function.
///
/// # Usage
/// To use, first specify which dependencies you are relying on. This can be both
/// `os` for depending on WinRT metadata shipped with Windows or `nuget: My.Package`
/// for NuGet packages.
///
/// ## NuGet
/// NuGet dependencies are expected in a well defined place. The `winmd` metadata files
/// should be in the cargo workspace's `target` directory in a subdirectory `nuget\My.Package`
/// where `My.Package` is the name of the NuGet package.
///
/// Any DLLs needed for the NuGet package to work should be next to work must be next to the final
/// executable.
///
/// Instead of handling this yourself, you can use the [`cargo winrt`](https://github.com/microsoft/winrt-rs/tree/master/crates/cargo-winrt)
/// helper subcommand.
///
/// ## Types
/// After specifying the dependencies, you must then specify which types you want to use. These
/// follow the same convention as Rust `use` paths. Types know which other types they depend on so
/// `import` will generate any other WinRT types needed for the specified type to work.
///
/// # Example
/// The following `build!` depends on both `os` metadata (i.e., metadata shipped on Windows 10), as well
/// as a 3rd-party NuGet dependency. It then generates all types inside of the `microsoft::ai::machine_learning`
/// namespace.
///
/// ```rust,ignore
/// build!(
///     dependencies
///         os
///         nuget: Microsoft.AI.MachineLearning
///     types
///         microsoft::ai::machine_learning::*
/// );
/// ```
#[proc_macro]
pub fn build(stream: TokenStream) -> TokenStream {
    let import = parse_macro_input!(stream as ImportMacro);
    let winmd_paths = import.winmd_paths().iter().map(|p| p.display().to_string());

    let change_if = quote! {
        #(println!("cargo:rerun-if-changed={}", #winmd_paths);)*
    };

    let tokens = import.to_tokens();
    let tokens = tokens.to_string();

    let tokens = quote! {
        fn build() {
            use ::std::io::Write;
            let mut path = ::std::path::PathBuf::from(
                ::std::env::var("OUT_DIR").expect("No `OUT_DIR` env variable set"),
            );

            path.push("winrt.rs");
            let mut file = ::std::fs::File::create(&path).expect("Failed to create winrt.rs");

            let mut cmd = ::std::process::Command::new("rustfmt");
            cmd.arg("--emit").arg("stdout");
            cmd.stdin(::std::process::Stdio::piped());
            cmd.stdout(::std::process::Stdio::piped());
            {
                let child = cmd.spawn().unwrap();
                let mut stdin = child.stdin.unwrap();
                let stdout = child.stdout.unwrap();

                let t = ::std::thread::spawn(move || {
                    let mut s = stdout;
                    ::std::io::copy(&mut s, &mut file).unwrap();
                });

                #change_if

                writeln!(&mut stdin, "{}", #tokens).unwrap();
                // drop stdin to close that end of the pipe
                ::std::mem::drop(stdin);

                t.join().unwrap();
            }

            let status = cmd.status().unwrap();
            assert!(status.success(), "Could not successfully build");
        }
    };
    tokens.into()
}

/// A parsed `import!` macro
struct ImportMacro {
    dependencies: Dependencies,
    types: TypesDeclarations,
}

impl ImportMacro {
    fn winmd_paths(&self) -> &BTreeSet<PathBuf> {
        &self.dependencies.0
    }

    fn to_tokens(self) -> TokenStream {
        let dependencies = self
            .dependencies
            .0
            .iter()
            .map(|p| WinmdFile::new(p))
            .collect();

        let reader = &TypeReader::new(dependencies);
        let mut limits = TypeLimits::new(reader);

        for limit in self.types.0 {
            let types = limit.types;
            let syntax = limit.syntax;
            if let Err(e) = limits.insert(types).map_err(|ns| {
                syn::Error::new_spanned(syntax, format!("'{}' is not a known namespace", ns))
            }) {
                return e.to_compile_error().into();
            };
        }

        let stage = TypeStage::from_limits(reader, &limits);
        let tree = stage.into_tree();

        tree.to_tokens()
            .collect::<proc_macro2::TokenStream>()
            .into()
    }
}

impl Parse for ImportMacro {
    fn parse(input: ParseStream) -> parse::Result<Self> {
        let _ = input.parse::<keywords::dependencies>()?;
        let dependencies: Dependencies = input.parse()?;
        let _ = input.parse::<keywords::types>()?;
        let types: TypesDeclarations = input.parse()?;

        Ok(ImportMacro {
            dependencies,
            types,
        })
    }
}

/// keywords used in the `import!` macro
mod keywords {
    syn::custom_keyword!(os);
    syn::custom_keyword!(nuget);
    syn::custom_keyword!(dependencies);
    syn::custom_keyword!(types);
}

/// A parsed `dependencies` section of the `import!` macro
#[derive(Debug)]
struct Dependencies(BTreeSet<PathBuf>);

impl Parse for Dependencies {
    fn parse(input: ParseStream) -> parse::Result<Self> {
        enum Keyword {
            Os,
            Nuget,
        }
        let mut dependencies = BTreeSet::new();
        while let Some((keyword, keyword_span)) = {
            if let Some(k) = input.parse::<Option<keywords::os>>()? {
                Some((Keyword::Os, k.span()))
            } else if let Some(k) = input.parse::<Option<keywords::nuget>>()? {
                Some((Keyword::Nuget, k.span()))
            } else {
                None
            }
        } {
            match keyword {
                Keyword::Os => {
                    let path = dependencies::system_metadata_root().ok_or_else(|| {
                        syn::Error::new(keyword_span, "'windir' environment variable is not set. Perhaps you're trying to use operating system dependencies on a non-Windows OS?")
                    })?;

                    dependencies::expand_paths(&path, &mut dependencies, false).map_err(|_| {
                        syn::Error::new(
                            keyword_span,
                            format!("system metadata cannot be found at '{}'", path.display()),
                        )
                    })?;
                }
                Keyword::Nuget => {
                    input.parse::<Token![:]>()?;

                    let package = Punctuated::<Ident, Token![.]>::parse_separated_nonempty(input)?;

                    let name = package
                        .iter()
                        .map(|ident| ident.to_string())
                        .collect::<Vec<String>>()
                        .join(".");
                    let nuget_path =
                        std::fs::read_dir(dependencies::nuget_root()).map_err(|e| {
                            syn::Error::new_spanned(
                                &package,
                                format!("could not read nuget directory: {}", e),
                            )
                        })?;

                    let mut dependency_path_iter = nuget_path
                        .into_iter()
                        .filter_map(|entry| entry.ok())
                        .filter(|entry| {
                            if let Some(entry) = entry.file_name().to_str().map(str::to_owned) {
                                entry.starts_with(&name)
                            } else {
                                false
                            }
                        })
                        .map(|entry| entry.path());

                    let path = dependency_path_iter.next().ok_or_else(|| {
                        syn::Error::new_spanned(
                            &package,
                            format!(
                                "could not find folder for dependency '{}' in target\nuget folder",
                                name
                            ),
                        )
                    })?;
                    // Check for multiple versions
                    if dependency_path_iter.next().is_some() {
                        return Err(syn::Error::new_spanned(
                            &package,
                            format!("multiple nuget package versions found for '{}'", name),
                        ));
                    }

                    dependencies::expand_paths(path, &mut dependencies, true).map_err(|e| {
                        syn::Error::new_spanned(
                            package,
                            format!("could not read dependency: {}", e),
                        )
                    })?;
                }
            }
        }
        Ok(Dependencies(dependencies))
    }
}

/// A parsed `types` section of the `import!` macro
struct TypesDeclarations(BTreeSet<TypesDeclaration>);

struct TypesDeclaration {
    types: NamespaceTypes,
    syntax: syn::UseTree,
}
impl std::cmp::PartialOrd for TypesDeclaration {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl std::cmp::Ord for TypesDeclaration {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.types.cmp(&other.types)
    }
}
impl PartialEq for TypesDeclaration {
    fn eq(&self, other: &Self) -> bool {
        self.types == other.types
    }
}
impl Eq for TypesDeclaration {}

impl TryFrom<syn::UseTree> for TypesDeclaration {
    type Error = syn::Error;
    fn try_from(tree: UseTree) -> Result<Self, Self::Error> {
        Ok(Self {
            types: use_tree_to_namespace_types(&tree)?,
            syntax: tree,
        })
    }
}

impl Parse for TypesDeclarations {
    fn parse(input: ParseStream) -> parse::Result<Self> {
        let mut limits = BTreeSet::new();
        loop {
            if input.is_empty() {
                break;
            }

            let use_tree: syn::UseTree = input.parse()?;
            let limit: TypesDeclaration = use_tree.try_into()?;

            limits.insert(limit);
        }
        Ok(Self(limits))
    }
}

// Snake <-> camel casing is lossy so we go for character but not case conversion
// and deal with casing once we have an index of namespaces to compare against.
fn namespace_literal_to_rough_namespace(namespace: &str) -> String {
    let mut result = String::with_capacity(namespace.len());
    for c in namespace.chars() {
        if c != '"' && c != '_' {
            result.extend(c.to_lowercase());
        }
    }
    result
}

fn use_tree_to_namespace_types(use_tree: &syn::UseTree) -> parse::Result<NamespaceTypes> {
    fn recurse(tree: &UseTree, current: &mut String) -> parse::Result<NamespaceTypes> {
        fn check_for_module_instead_of_type(name: &str, span: Span) -> parse::Result<()> {
            let error = Err(Error::new(
                span,
                "Expected `*` or type name, but found what appears to be a module",
            ));
            if name.to_lowercase() == name {
                return error;
            }
            Ok(())
        }

        match tree {
            UseTree::Path(p) => {
                if !current.is_empty() {
                    current.push('.');
                }

                current.push_str(&p.ident.to_string());

                recurse(&*p.tree, current)
            }
            UseTree::Glob(_) => {
                let namespace = namespace_literal_to_rough_namespace(&current.clone());
                Ok(NamespaceTypes {
                    namespace,
                    limit: TypeLimit::All,
                })
            }
            UseTree::Group(g) => {
                let namespace = namespace_literal_to_rough_namespace(&current.clone());

                let mut types = Vec::with_capacity(g.items.len());
                for tree in &g.items {
                    match tree {
                        UseTree::Name(n) => {
                            let name = n.ident.to_string();
                            check_for_module_instead_of_type(&name, n.span())?;
                            types.push(name);
                        }
                        UseTree::Rename(_) => {
                            return Err(Error::new(tree.span(), "Renaming syntax is not supported"))
                        }
                        _ => return Err(Error::new(tree.span(), "Nested paths not allowed")),
                    }
                }
                Ok(NamespaceTypes {
                    namespace,
                    limit: TypeLimit::Some(types),
                })
            }
            UseTree::Name(n) => {
                let namespace = namespace_literal_to_rough_namespace(&current.clone());
                let name = n.ident.to_string();
                check_for_module_instead_of_type(&name, n.span())?;
                Ok(NamespaceTypes {
                    namespace,
                    limit: TypeLimit::Some(vec![name]),
                })
            }
            UseTree::Rename(r) => {
                return Err(Error::new(r.span(), "Renaming syntax is not supported"))
            }
        }
    }

    recurse(use_tree, &mut String::new())
}