[go: up one dir, main page]

windows_gen 0.14.1

Code generation for the windows crate
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
use super::*;

// TODO: need to split win32 and winrt structs as their signatures are different and win32 structs also include unions and they are
// radically different.

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct Struct(pub tables::TypeDef);

impl Struct {
    pub fn gen(&self, gen: &Gen) -> TokenStream {
        self.gen_struct(self.0.name(), gen)
    }

    fn gen_struct(&self, struct_name: &str, gen: &Gen) -> TokenStream {
        if let Some(replacement) = self.gen_replacement() {
            return replacement;
        }

        let name = to_ident(struct_name);

        if let Some(guid) = Guid::from_attributes(self.0.attributes()) {
            let guid = guid.gen();

            return quote! {
                pub const #name: ::windows::Guid = ::windows::Guid::from_values(#guid);
            };
        }

        let fields: Vec<(tables::Field, Signature, Ident)> = self
            .0
            .fields()
            .filter_map(move |f| {
                if f.flags().literal() {
                    None
                } else {
                    let signature = f.signature();
                    let name = f.name();
                    Some((f, signature, to_ident(name)))
                }
            })
            .collect();

        if fields.is_empty() {
            return quote! {
                #[repr(C)]
                #[derive(::std::clone::Clone, ::std::default::Default, ::std::fmt::Debug, ::std::cmp::PartialEq, ::std::cmp::Eq, ::std::marker::Copy)]
                pub struct #name(pub u8);
            };
        }

        let is_winrt = self.0.is_winrt();
        let is_handle = self.0.is_handle();
        let is_union = self.0.flags().explicit();
        let layout = self.0.class_layout();
        let is_packed = self.0.is_packed();

        let repr = if let Some(layout) = &layout {
            let packing = Literal::u32_unsuffixed(layout.packing_size());
            quote! { #[repr(C, packed(#packing))] }
        } else if is_handle {
            quote! { #[repr(transparent)] }
        } else {
            quote! { #[repr(C)] }
        };

        // TODO: add test for Windows.Win32.Security.TRUSTEE_A
        let has_union = fields
            .iter()
            .any(|(_, signature, _)| signature.is_explicit());

        // TODO: workaround for getting windows-docs building
        let has_complex_array = fields
            .iter()
            .any(|(_, signature, _)| match &signature.kind {
                ElementType::Array((signature, _)) => {
                    !signature.is_blittable() || signature.kind.is_nullable()
                }
                _ => false,
            });

        let runtime_type = if is_winrt {
            let signature = Literal::byte_string(&self.0.type_signature().as_bytes());

            quote! {
                unsafe impl ::windows::RuntimeType for #name {
                    type DefaultType = Self;
                    const SIGNATURE: ::windows::ConstBuffer = ::windows::ConstBuffer::from_slice(#signature);
                }
            }
        } else {
            quote! {}
        };

        let clone_or_copy = if self.0.is_blittable() {
            quote! {
                #[derive(::std::clone::Clone, ::std::marker::Copy)]
            }
        } else if is_union || has_union || is_packed {
            quote! {}
        } else {
            quote! {
                #[derive(::std::clone::Clone)]
            }
        };

        let body = if is_handle {
            let fields = fields.iter().map(|(_, signature, _)| {
                let kind = if is_winrt {
                    signature.gen_winrt(gen)
                } else {
                    signature.gen_win32(gen)
                };

                quote! {
                    pub #kind
                }
            });

            quote! {
                ( #(#fields),* );
            }
        } else {
            let fields = fields.iter().map(|(_, signature, name)| {
                let kind = if is_winrt {
                    signature.gen_winrt(gen)
                } else if is_union {
                    signature.gen_win32_abi(gen)
                } else {
                    signature.gen_win32(gen)
                };

                quote! {
                    pub #name: #kind
                }
            });

            quote! {
                { #(#fields),* }
            }
        };

        let struct_or_union = if is_union {
            quote! { union }
        } else {
            quote! { struct }
        };

        let abi = if self.0.is_blittable() {
            quote! {
                unsafe impl ::windows::Abi for #name {
                    type Abi = Self;
                }
            }
        } else {
            let abi_name = self.0.gen_abi_name(gen);

            let fields = if is_winrt {
                let fields = fields.iter().map(|(_, signature, name)| {
                    let kind = signature.gen_winrt_abi(gen);
                    quote! { pub #name: #kind }
                });
                quote! { #(#fields),* }
            } else {
                let fields = fields.iter().map(|(_, signature, name)| {
                    let kind = signature.gen_win32_abi(gen);
                    quote! { pub #name: #kind }
                });
                quote! { #(#fields),* }
            };

            quote! {
                #repr
                #[doc(hidden)]
                #[derive(::std::clone::Clone, ::std::marker::Copy)]
                pub #struct_or_union #abi_name{ #fields }
                unsafe impl ::windows::Abi for #name {
                    type Abi = #abi_name;
                }
            }
        };

        let constants = self.0.fields().filter_map(|f| {
            if f.flags().literal() {
                if let Some(constant) = f.constant() {
                    let name = to_ident(f.name());
                    let value = constant.value().gen();

                    return Some(quote! {
                        pub const #name: #value;
                    });
                }
            }

            None
        });

        let compare = if is_union | has_union | has_complex_array | is_packed {
            quote! {}
        } else {
            let compare = fields
                .iter()
                .enumerate()
                .map(|(index, (_, signature, name))| {
                    let is_callback = signature.kind.is_callback();

                    if is_callback && signature.pointers == 0 {
                        quote! {
                            self.#name.map(|f| f as usize) == other.#name.map(|f| f as usize)
                        }
                    } else if is_handle {
                        let index = Literal::usize_unsuffixed(index);

                        quote! {
                            self.#index == other.#index
                        }
                    } else {
                        quote! {
                            self.#name == other.#name
                        }
                    }
                });

            if layout.is_some() {
                quote! {
                    impl ::std::cmp::PartialEq for #name {
                        fn eq(&self, other: &Self) -> bool {
                            unsafe { #(#compare)&&* }
                        }
                    }
                    impl ::std::cmp::Eq for #name {}
                }
            } else {
                quote! {
                    impl ::std::cmp::PartialEq for #name {
                        fn eq(&self, other: &Self) -> bool {
                            #(#compare)&&*
                        }
                    }
                    impl ::std::cmp::Eq for #name {}
                }
            }
        };

        let default = if is_union || has_union || has_complex_array || is_packed {
            quote! {}
        } else {
            let defaults = fields.iter().map(|(_, signature, name)| {
                let value = if is_winrt {
                    signature.gen_winrt_default()
                } else {
                    signature.gen_win32_default()
                };

                if is_handle {
                    value
                } else {
                    quote! {
                        #name: #value
                    }
                }
            });

            let defaults = quote! { #(#defaults),* };

            if is_handle {
                quote! {
                    impl ::std::default::Default for #name {
                        fn default() -> Self {
                            Self(#defaults)
                        }
                    }
                    impl #name {
                        pub const NULL: Self = Self(#defaults);
                        pub fn is_null(&self) -> bool {
                            self.0 == #defaults
                        }
                    }
                }
            } else {
                quote! {
                    impl ::std::default::Default for #name {
                        fn default() -> Self {
                            Self{ #defaults }
                        }
                    }
                }
            }
        };

        let debug = if is_union || has_union || has_complex_array || is_packed {
            quote! {}
        } else {
            let debug_name = self.0.name();

            let debug_fields =
                fields
                    .iter()
                    .enumerate()
                    .filter_map(|(index, (_, signature, name))| {
                        // TODO: there must be a simpler way to implement Debug just to exclude this type.
                        if signature.kind.is_callback() {
                            return None;
                        }

                        if let ElementType::Array((kind, _)) = &signature.kind {
                            if kind.kind.is_callback() {
                                return None;
                            }
                        }

                        let field = name.as_str();

                        if is_handle {
                            let index = Literal::usize_unsuffixed(index);

                            Some(quote! {
                                .field(#field, &format_args!("{:?}", self.#index))
                            })
                        } else {
                            Some(quote! {
                                .field(#field, &format_args!("{:?}", self.#name))
                            })
                        }
                    });

            if layout.is_some() {
                quote! {
                    impl ::std::fmt::Debug for #name {
                        fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                            unsafe {
                                fmt.debug_struct(#debug_name)
                                    #(#debug_fields)*
                                    .finish()
                            }
                        }
                    }
                }
            } else {
                quote! {
                    impl ::std::fmt::Debug for #name {
                        fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                            fmt.debug_struct(#debug_name)
                                #(#debug_fields)*
                                .finish()
                        }
                    }
                }
            }
        };

        let extensions = self.gen_extensions();
        let nested_types = gen_nested_types(struct_name, &self.0, gen);

        let convertible = if let Some(dependency) = self.0.is_convertible_to() {
            let dependency = dependency.gen_name(gen);

            quote! {
                impl<'a> ::windows::IntoParam<'a, #dependency> for #name {
                    fn into_param(self) -> ::windows::Param<'a, #dependency> {
                        ::windows::Param::Owned(#dependency(self.0))
                    }
                }
            }
        } else {
            quote! {}
        };

        quote! {
            #repr
            #clone_or_copy
            pub #struct_or_union #name #body
            impl #name {
                #(#constants)*
            }
            #default
            #debug
            #compare
            #abi
            #runtime_type
            #extensions
            #nested_types
            #convertible
        }
    }

    fn gen_replacement(&self) -> Option<TokenStream> {
        match self.0.full_name() {
            ("Windows.Win32.Foundation", "BOOL") => Some(gen_bool32()),
            ("Windows.Win32.Foundation", "PWSTR") => Some(gen_pwstr()),
            ("Windows.Win32.Foundation", "PSTR") => Some(gen_pstr()),
            ("Windows.Win32.Foundation", "BSTR") => Some(gen_bstr()),
            _ => None,
        }
    }

    fn gen_extensions(&self) -> TokenStream {
        match self.0.full_name() {
            ("Windows.Foundation", "TimeSpan") => gen_timespan(),
            ("Windows.Foundation.Numerics", "Vector2") => gen_vector2(),
            ("Windows.Foundation.Numerics", "Vector3") => gen_vector3(),
            ("Windows.Foundation.Numerics", "Vector4") => gen_vector4(),
            ("Windows.Foundation.Numerics", "Matrix3x2") => gen_matrix3x2(),
            ("Windows.Foundation.Numerics", "Matrix4x4") => gen_matrix4x4(),
            ("Windows.Win32.Foundation", "HANDLE") => gen_handle(),
            _ => TokenStream::new(),
        }
    }
}

fn gen_nested_types<'a>(
    enclosing_name: &'a str,
    enclosing_type: &'a tables::TypeDef,
    gen: &Gen,
) -> TokenStream {
    if let Some(nested_types) = enclosing_type.nested_types() {
        nested_types
            .iter()
            .enumerate()
            .map(|(index, (_, nested_type))| {
                let nested_name = format!("{}_{}", enclosing_name, index);
                Struct(nested_type.clone()).gen_struct(&nested_name, gen)
            })
            .collect()
    } else {
        TokenStream::new()
    }
}

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

    #[test]
    fn test_signature() {
        let t = TypeReader::get().resolve_type_def("Windows.Foundation", "Point");
        assert_eq!(t.type_signature(), "struct(Windows.Foundation.Point;f4;f4)");
    }

    #[test]
    fn test_fields() {
        let t = TypeReader::get()
            .resolve_type_def("Windows.Win32.Graphics.Dxgi", "DXGI_FRAME_STATISTICS_MEDIA");
        let f: Vec<tables::Field> = t.fields().collect();
        assert_eq!(f.len(), 7);

        assert_eq!(f[0].name(), "PresentCount");
        assert_eq!(f[1].name(), "PresentRefreshCount");
        assert_eq!(f[2].name(), "SyncRefreshCount");
        assert_eq!(f[3].name(), "SyncQPCTime");
        assert_eq!(f[4].name(), "SyncGPUTime");
        assert_eq!(f[5].name(), "CompositionMode");
        assert_eq!(f[6].name(), "ApprovedPresentDuration");

        assert_eq!(f[0].signature().kind, ElementType::U32);
        assert_eq!(f[1].signature().kind, ElementType::U32);
        assert_eq!(f[2].signature().kind, ElementType::U32);
        assert_eq!(f[3].signature().kind, ElementType::I64);
        assert_eq!(f[4].signature().kind, ElementType::I64);
        assert_eq!(f[5].signature().kind.name(), "DXGI_FRAME_PRESENTATION_MODE");
        assert_eq!(f[6].signature().kind, ElementType::U32);
    }

    #[test]
    fn test_blittable() {
        assert_eq!(
            TypeReader::get()
                .resolve_type_def("Windows.Foundation", "Point")
                .is_blittable(),
            true
        );
        assert_eq!(
            TypeReader::get()
                .resolve_type_def("Windows.UI.Xaml.Interop", "TypeName")
                .is_blittable(),
            false
        );
    }
}