-
Notifications
You must be signed in to change notification settings - Fork 191
/
lib.rs
3082 lines (2833 loc) · 103 KB
/
lib.rs
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![recursion_limit = "256"]
#![warn(trivial_casts, trivial_numeric_casts)]
use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
use itertools::Itertools;
use nom::{
branch::alt,
bytes::complete::{tag, take_until, take_while1},
character::complete::{
char, digit1, hex_digit1, multispace0, multispace1, newline, none_of, one_of,
},
combinator::{map, map_res, opt, value},
multi::{many1, separated_list1},
sequence::{delimited, pair, preceded, separated_pair, terminated, tuple},
IResult, Parser,
};
use once_cell::sync::Lazy;
use proc_macro2::{Delimiter, Group, Literal, Span, TokenStream, TokenTree};
use quote::*;
use regex::Regex;
use std::{
borrow::Cow,
collections::{BTreeMap, HashMap, HashSet},
fmt::Display,
path::Path,
};
use syn::Ident;
const DESIRED_API: &str = "vulkan";
fn contains_desired_api(api: &str) -> bool {
api.split(',').any(|n| n == DESIRED_API)
}
macro_rules! get_variant {
($variant:path) => {
|enum_| match enum_ {
$variant(inner) => Some(inner),
_ => None,
}
};
($variant:path { $($member:ident),+ }) => {
|enum_| match enum_ {
$variant { $($member),+, .. } => Some(( $($member),+ )),
_ => None,
}
};
}
pub trait ExtensionExt {}
#[derive(Copy, Clone, Debug)]
pub enum CType {
USize,
U32,
U64,
Float,
Bool32,
}
impl CType {
fn to_string(self) -> &'static str {
match self {
Self::USize => "usize",
Self::U32 => "u32",
Self::U64 => "u64",
Self::Float => "f32",
Self::Bool32 => "Bool32",
}
}
}
impl quote::ToTokens for CType {
fn to_tokens(&self, tokens: &mut TokenStream) {
format_ident!("{}", self.to_string()).to_tokens(tokens);
}
}
fn parse_ctype(i: &str) -> IResult<&str, CType> {
(alt((value(CType::U64, tag("ULL")), value(CType::U32, tag("U")))))(i)
}
fn parse_cexpr(i: &str) -> IResult<&str, (CType, String)> {
(alt((
map(parse_cfloat, |f| (CType::Float, format!("{f:.2}"))),
parse_inverse_number,
parse_decimal_number,
parse_hexadecimal_number,
)))(i)
}
fn parse_cfloat(i: &str) -> IResult<&str, f32> {
(terminated(nom::number::complete::float, one_of("fF")))(i)
}
fn parse_inverse_number(i: &str) -> IResult<&str, (CType, String)> {
(map(
delimited(
char('('),
pair(
preceded(char('~'), parse_decimal_number),
opt(preceded(char('-'), digit1)),
),
char(')'),
),
|((ctyp, num), minus_num)| {
let expr = if let Some(minus) = minus_num {
format!("!{num}-{minus}")
} else {
format!("!{num}")
};
(ctyp, expr)
},
))(i)
}
// Like a C string, but does not support quote escaping and expects at least one character.
// If needed, use https://github.com/Geal/nom/blob/8e09f0c3029d32421b5b69fb798cef6855d0c8df/tests/json.rs#L61-L81
fn parse_c_include_string(i: &str) -> IResult<&str, String> {
(delimited(
char('"'),
map(many1(none_of("\"")), |c| {
c.iter().map(char::to_string).join("")
}),
char('"'),
))(i)
}
fn parse_c_include(i: &str) -> IResult<&str, String> {
(preceded(
tag("#include"),
preceded(multispace1, parse_c_include_string),
))(i)
}
fn parse_decimal_number(i: &str) -> IResult<&str, (CType, String)> {
(map(
pair(digit1.map(str::to_string), parse_ctype),
|(dig, ctype)| (ctype, dig),
))(i)
}
fn parse_hexadecimal_number(i: &str) -> IResult<&str, (CType, String)> {
(preceded(
alt((tag("0x"), tag("0X"))),
map(pair(hex_digit1, parse_ctype), |(num, typ)| {
(
typ,
format!("0x{}{}", num.to_ascii_lowercase(), typ.to_string()),
)
}),
))(i)
}
fn parse_c_identifier(i: &str) -> IResult<&str, &str> {
take_while1(|c: char| c == '_' || c.is_alphanumeric())(i)
}
fn parse_comment_suffix(i: &str) -> IResult<&str, Option<&str>> {
opt(delimited(tag("//"), take_until("\n"), newline))(i)
}
fn parse_parameter_names(i: &str) -> IResult<&str, Vec<&str>> {
delimited(
char('('),
separated_list1(tag(", "), parse_c_identifier),
char(')'),
)(i)
}
/// Parses a C macro define optionally prefixed by a comment and optionally
/// containing parameter names. The expression is left in the remainder
#[allow(clippy::type_complexity)]
fn parse_c_define_header(i: &str) -> IResult<&str, (Option<&str>, (&str, Option<Vec<&str>>))> {
(pair(
parse_comment_suffix,
preceded(
tag("#define "),
pair(parse_c_identifier, opt(parse_parameter_names)),
),
))(i)
}
#[derive(Debug)]
enum CReferenceType {
Value,
PointerToConst,
Pointer,
PointerToPointer,
PointerToPointerToConst,
PointerToConstPointer,
PointerToConstPointerToConst,
}
#[derive(Debug)]
struct CParameterType<'a> {
name: &'a str,
reference_type: CReferenceType,
}
fn parse_c_type(i: &str) -> IResult<&str, CParameterType> {
(map(
separated_pair(
tuple((
opt(tag("const ")),
preceded(opt(tag("struct ")), parse_c_identifier),
opt(char('*')),
)),
multispace0,
opt(pair(opt(tag("const")), char('*'))),
),
|((const_, name, firstptr), secondptr)| CParameterType {
name,
reference_type: match (firstptr, secondptr) {
(None, None) => CReferenceType::Value,
(Some(_), None) if const_.is_some() => CReferenceType::PointerToConst,
(Some(_), None) => CReferenceType::Pointer,
(Some(_), Some((Some(_), _))) if const_.is_some() => {
CReferenceType::PointerToConstPointerToConst
}
(Some(_), Some((Some(_), _))) => CReferenceType::PointerToConstPointer,
(Some(_), Some((None, _))) if const_.is_some() => {
CReferenceType::PointerToPointerToConst
}
(Some(_), Some((None, _))) => CReferenceType::PointerToPointer,
(None, Some(_)) => unreachable!(),
},
},
))(i)
}
#[derive(Debug)]
struct CParameter<'a> {
type_: CParameterType<'a>,
// Code only used to dissect the type surrounding this field name,
// not interested in the name itself.
_name: &'a str,
static_array: Option<usize>,
}
/// Parses a single C parameter instance, for example:
///
/// ```c
/// VkSparseImageMemoryRequirements2* pSparseMemoryRequirements
/// ```
fn parse_c_parameter(i: &str) -> IResult<&str, CParameter> {
(map(
separated_pair(
parse_c_type,
multispace0,
pair(
parse_c_identifier,
opt(delimited(char('['), map_res(digit1, str::parse), char(']'))),
),
),
|(type_, (name, static_array))| CParameter {
type_,
_name: name,
static_array,
},
))(i)
}
fn khronos_link<S: Display + ?Sized>(name: &S) -> Literal {
Literal::string(&format!(
"<https://www.khronos.org/registry/vulkan/specs/1.3-extensions/man/html/{name}.html>"
))
}
fn is_opaque_type(ty: &str) -> bool {
matches!(
ty,
"void"
| "wl_display"
| "wl_surface"
| "Display"
| "xcb_connection_t"
| "ANativeWindow"
| "AHardwareBuffer"
| "CAMetalLayer"
| "IDirectFB"
| "IDirectFBSurface"
)
}
#[derive(Debug, Copy, Clone)]
pub enum ConstVal {
U32(u32),
U64(u64),
Float(f32),
}
impl ConstVal {
pub fn bits(&self) -> u64 {
match self {
ConstVal::U64(n) => *n,
_ => panic!("Constval not supported"),
}
}
}
pub trait ConstantExt {
fn constant(&self, enum_name: &str) -> Constant;
fn variant_ident(&self, enum_name: &str) -> Ident;
fn notation(&self) -> Option<&str>;
fn formatted_notation(&self) -> Option<Cow<'_, str>> {
static DOC_LINK: Lazy<Regex> = Lazy::new(|| Regex::new(r#"<<([\w-]+)>>"#).unwrap());
self.notation().map(|n| {
DOC_LINK.replace(
n,
"<https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#${1}>",
)
})
}
fn is_alias(&self) -> bool {
false
}
fn is_deprecated(&self) -> bool;
fn doc_attribute(&self) -> Option<TokenStream> {
self.formatted_notation().map(|n| quote!(#[doc = #n]))
}
}
impl ConstantExt for vkxml::ExtensionEnum {
fn constant(&self, _enum_name: &str) -> Constant {
Constant::from_extension_enum(self).unwrap()
}
fn variant_ident(&self, enum_name: &str) -> Ident {
variant_ident(enum_name, &self.name)
}
fn notation(&self) -> Option<&str> {
self.notation.as_deref()
}
fn is_deprecated(&self) -> bool {
todo!()
}
}
impl ConstantExt for vk_parse::Enum {
fn constant(&self, enum_name: &str) -> Constant {
Constant::from_vk_parse_enum(self, Some(enum_name), None)
.unwrap()
.0
}
fn variant_ident(&self, enum_name: &str) -> Ident {
variant_ident(enum_name, &self.name)
}
fn notation(&self) -> Option<&str> {
self.comment.as_deref()
}
fn is_alias(&self) -> bool {
matches!(self.spec, vk_parse::EnumSpec::Alias { .. })
}
fn is_deprecated(&self) -> bool {
self.deprecated.is_some()
}
}
impl ConstantExt for vkxml::Constant {
fn constant(&self, _enum_name: &str) -> Constant {
Constant::from_constant(self)
}
fn variant_ident(&self, enum_name: &str) -> Ident {
variant_ident(enum_name, &self.name)
}
fn notation(&self) -> Option<&str> {
self.notation.as_deref()
}
fn is_deprecated(&self) -> bool {
todo!()
}
}
#[derive(Clone, Debug)]
pub enum Constant {
Number(i32),
Hex(String),
BitPos(u32),
CExpr(vkxml::CExpression),
Text(String),
Alias(Ident),
}
impl quote::ToTokens for Constant {
fn to_tokens(&self, tokens: &mut TokenStream) {
match *self {
Constant::Number(n) => {
let number = interleave_number('_', 3, &n.to_string());
syn::LitInt::new(&number, Span::call_site()).to_tokens(tokens);
}
Constant::Hex(ref s) => {
let number = interleave_number('_', 4, s);
syn::LitInt::new(&format!("0x{number}"), Span::call_site()).to_tokens(tokens);
}
Constant::Text(ref text) => text.to_tokens(tokens),
Constant::CExpr(ref expr) => {
let (rem, (_, rexpr)) = parse_cexpr(expr).expect("Unable to parse cexpr");
assert!(rem.is_empty());
tokens.extend(rexpr.parse::<TokenStream>());
}
Constant::BitPos(pos) => {
let value = 1u64 << pos;
let bit_string = format!("{value:b}");
let bit_string = interleave_number('_', 4, &bit_string);
syn::LitInt::new(&format!("0b{bit_string}"), Span::call_site()).to_tokens(tokens);
}
Constant::Alias(ref value) => tokens.extend(quote!(Self::#value)),
}
}
}
impl quote::ToTokens for ConstVal {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
ConstVal::U32(n) => n.to_tokens(tokens),
ConstVal::U64(n) => n.to_tokens(tokens),
ConstVal::Float(f) => f.to_tokens(tokens),
}
}
}
// Interleaves a number, for example 100000 => 100_000. Mostly used to make clippy happy
fn interleave_number(symbol: char, count: usize, n: &str) -> String {
let number: String = n
.chars()
.rev()
.enumerate()
.fold(String::new(), |mut acc, (idx, next)| {
if idx != 0 && idx % count == 0 {
acc.push(symbol);
}
acc.push(next);
acc
});
number.chars().rev().collect()
}
impl Constant {
pub fn value(&self) -> Option<ConstVal> {
match *self {
Constant::Number(n) => Some(ConstVal::U64(n as u64)),
Constant::Hex(ref hex) => u64::from_str_radix(hex, 16).ok().map(ConstVal::U64),
Constant::BitPos(pos) => Some(ConstVal::U64(1u64 << pos)),
_ => None,
}
}
pub fn ty(&self) -> CType {
match self {
Constant::Number(_) | Constant::Hex(_) => CType::USize,
Constant::CExpr(expr) => {
let (rem, (ty, _)) = parse_cexpr(expr).expect("Unable to parse cexpr");
assert!(rem.is_empty());
ty
}
_ => unimplemented!(),
}
}
pub fn from_extension_enum(constant: &vkxml::ExtensionEnum) -> Option<Self> {
let number = constant.number.map(Constant::Number);
let hex = constant.hex.as_ref().map(|hex| Constant::Hex(hex.clone()));
let bitpos = constant.bitpos.map(Constant::BitPos);
let expr = constant
.c_expression
.as_ref()
.map(|e| Constant::CExpr(e.clone()));
number.or(hex).or(bitpos).or(expr)
}
pub fn from_constant(constant: &vkxml::Constant) -> Self {
let number = constant.number.map(Constant::Number);
let hex = constant.hex.as_ref().map(|hex| Constant::Hex(hex.clone()));
let bitpos = constant.bitpos.map(Constant::BitPos);
let expr = constant
.c_expression
.as_ref()
.map(|e| Constant::CExpr(e.clone()));
number.or(hex).or(bitpos).or(expr).expect("")
}
/// Returns (Constant, optional base type, is_alias)
pub fn from_vk_parse_enum(
enum_: &vk_parse::Enum,
enum_name: Option<&str>,
extension_number: Option<i64>,
) -> Option<(Self, Option<String>, bool)> {
use vk_parse::EnumSpec;
match &enum_.spec {
EnumSpec::Bitpos { bitpos, extends } => {
Some((Self::BitPos(*bitpos as u32), extends.clone(), false))
}
EnumSpec::Offset {
offset,
extends,
extnumber,
dir: positive,
} => {
let ext_base = 1_000_000_000;
let ext_block_size = 1000;
let extnumber = extnumber
.or(extension_number)
.expect("Need an extension number");
let value = ext_base + (extnumber - 1) * ext_block_size + offset;
let value = if *positive { value } else { -value };
Some((Self::Number(value as i32), Some(extends.clone()), false))
}
EnumSpec::Value { value, extends } => {
let value = value
.strip_prefix("0x")
.map(|hex| Self::Hex(hex.to_owned()))
.or_else(|| value.parse::<i32>().ok().map(Self::Number))?;
Some((value, extends.clone(), false))
}
EnumSpec::Alias { alias, extends } => {
let base_type = extends.as_deref().or(enum_name)?;
let key = variant_ident(base_type, alias);
if key == "DISPATCH_BASE" {
None
} else {
Some((Self::Alias(key), Some(base_type.to_owned()), true))
}
}
_ => None,
}
}
}
pub trait FeatureExt {
fn version_string(&self) -> String;
fn is_version(&self, major: u32, minor: u32) -> bool;
}
impl FeatureExt for vkxml::Feature {
fn is_version(&self, major: u32, minor: u32) -> bool {
let self_major = self.version as u32;
let self_minor = (self.version * 10.0) as u32 - self_major * 10;
major == self_major && self_minor == minor
}
fn version_string(&self) -> String {
let mut version = format!("{}", self.version);
if version.len() == 1 {
version = format!("{version}_0")
}
version.replace('.', "_")
}
}
#[derive(Debug, Copy, Clone)]
pub enum FunctionType {
Static,
Entry,
Instance,
Device,
}
pub trait CommandExt {
fn function_type(&self) -> FunctionType;
}
impl CommandExt for vk_parse::CommandDefinition {
fn function_type(&self) -> FunctionType {
let is_first_param_device = self.params.get(0).map_or(false, |field| {
matches!(
field.definition.type_name.as_deref(),
Some("VkDevice" | "VkCommandBuffer" | "VkQueue")
)
});
match self.proto.name.as_str() {
"vkGetInstanceProcAddr" => FunctionType::Static,
"vkCreateInstance"
| "vkEnumerateInstanceLayerProperties"
| "vkEnumerateInstanceExtensionProperties"
| "vkEnumerateInstanceVersion" => FunctionType::Entry,
// This is actually not a device level function
"vkGetDeviceProcAddr" => FunctionType::Instance,
_ if is_first_param_device => FunctionType::Device,
_ => FunctionType::Instance,
}
}
}
pub trait FieldExt {
/// Returns the name of the parameter that doesn't clash with Rusts reserved
/// keywords
fn param_ident(&self) -> Ident;
/// The inner type of this field, with one level of pointers removed
fn inner_type_tokens(
&self,
lifetime: Option<TokenStream>,
inner_length: Option<usize>,
) -> TokenStream;
/// Returns reference-types wrapped in their safe variant. (Dynamic) arrays become
/// slices, pointers become Rust references.
fn safe_type_tokens(&self, lifetime: TokenStream, inner_length: Option<usize>) -> TokenStream;
/// Returns the basetype ident and removes the 'Vk' prefix. When `is_ffi_param` is `true`
/// array types (e.g. `[f32; 3]`) will be converted to pointer types (e.g. `&[f32; 3]`),
/// which is needed for `C` function parameters. Set to `false` for struct definitions.
fn type_tokens(&self, is_ffi_param: bool) -> TokenStream;
/// Whether this is C's `void` type (not to be mistaken with a void _pointer_!)
fn is_void(&self) -> bool;
/// Exceptions for pointers to static-sized arrays,
/// `vk.xml` does not annotate this.
fn is_pointer_to_static_sized_array(&self) -> bool;
}
pub trait ToTokens {
fn to_tokens(&self, is_const: bool) -> TokenStream;
/// Returns the topmost pointer as safe reference
fn to_safe_tokens(&self, is_const: bool, lifetime: TokenStream) -> TokenStream;
}
impl ToTokens for vkxml::ReferenceType {
fn to_tokens(&self, is_const: bool) -> TokenStream {
let r = if is_const {
quote!(*const)
} else {
quote!(*mut)
};
match self {
vkxml::ReferenceType::Pointer => quote!(#r),
vkxml::ReferenceType::PointerToPointer => quote!(#r *mut),
vkxml::ReferenceType::PointerToConstPointer => quote!(#r *const),
}
}
fn to_safe_tokens(&self, is_const: bool, lifetime: TokenStream) -> TokenStream {
let r = if is_const {
quote!(&#lifetime)
} else {
quote!(&#lifetime mut)
};
match self {
vkxml::ReferenceType::Pointer => quote!(#r),
vkxml::ReferenceType::PointerToPointer => quote!(#r *mut),
vkxml::ReferenceType::PointerToConstPointer => quote!(#r *const),
}
}
}
fn name_to_tokens(type_name: &str) -> Ident {
let new_name = match type_name {
"uint8_t" => "u8",
"uint16_t" => "u16",
"uint32_t" => "u32",
"uint64_t" => "u64",
"int8_t" => "i8",
"int16_t" => "i16",
"int32_t" => "i32",
"int64_t" => "i64",
"size_t" => "usize",
"int" => "c_int",
"void" => "c_void",
"char" => "c_char",
"float" => "f32",
"double" => "f64",
"long" => "c_ulong",
_ => type_name.strip_prefix("Vk").unwrap_or(type_name),
};
let new_name = new_name.replace("FlagBits", "Flags");
format_ident!("{}", new_name)
}
/// Parses and rewrites a C literal into Rust
///
/// If no special pattern is recognized the original literal is returned.
/// Any new conversions need to be added to the [`parse_cexpr()`] [`nom`] parser.
///
/// Examples:
/// - `0x3FFU` -> `0x3ffu32`
fn convert_c_literal(lit: Literal) -> Literal {
if let Ok(("", (_, rexpr))) = parse_cexpr(&lit.to_string()) {
// lit::SynInt uses the same `.parse` method to create hexadecimal
// literals because there is no `Literal` constructor for it.
let mut stream = rexpr.parse::<TokenStream>().unwrap().into_iter();
// If expression rewriting succeeds this should parse into a single literal
match (stream.next(), stream.next()) {
(Some(TokenTree::Literal(l)), None) => l,
x => panic!("Stream must contain a single literal, not {x:?}"),
}
} else {
lit
}
}
/// Parse and yield a C expression that is valid to write in Rust
/// Identifiers are replaced with their Rust vk equivalent.
///
/// Examples:
/// - `VK_MAKE_VERSION(1, 2, VK_HEADER_VERSION)` -> `make_version(1, 2, HEADER_VERSION)`
/// - `2*VK_UUID_SIZE` -> `2 * UUID_SIZE`
fn convert_c_expression(c_expr: &str, identifier_renames: &BTreeMap<String, Ident>) -> TokenStream {
fn rewrite_token_stream(
stream: TokenStream,
identifier_renames: &BTreeMap<String, Ident>,
) -> TokenStream {
stream
.into_iter()
.map(|tt| match tt {
TokenTree::Group(group) => TokenTree::Group(Group::new(
group.delimiter(),
rewrite_token_stream(group.stream(), identifier_renames),
)),
TokenTree::Ident(term) => {
let name = term.to_string();
identifier_renames
.get(&name)
.cloned()
.unwrap_or_else(|| format_ident!("{}", constant_name(&name)))
.into()
}
TokenTree::Literal(lit) => TokenTree::Literal(convert_c_literal(lit)),
tt => tt,
})
.collect::<TokenStream>()
}
let c_expr = c_expr
.parse()
.unwrap_or_else(|_| panic!("Failed to parse `{c_expr}` as Rust"));
rewrite_token_stream(c_expr, identifier_renames)
}
fn discard_outmost_delimiter(stream: TokenStream) -> TokenStream {
let stream = stream.into_iter().collect_vec();
// Discard the delimiter if this stream consists of a single top-most group
if let [TokenTree::Group(group)] = stream.as_slice() {
TokenTree::Group(Group::new(Delimiter::None, group.stream())).into()
} else {
stream.into_iter().collect::<TokenStream>()
}
}
impl FieldExt for vkxml::Field {
fn param_ident(&self) -> Ident {
let name = self.name.as_deref().unwrap_or("field");
let name_corrected = match name {
"type" => "ty",
_ => name,
};
format_ident!("{}", name_corrected.to_snake_case())
}
fn inner_type_tokens(
&self,
lifetime: Option<TokenStream>,
inner_length: Option<usize>,
) -> TokenStream {
assert!(!self.is_void());
let ty = name_to_tokens(&self.basetype);
let (const_, borrow) = match (lifetime, inner_length) {
// If the nested "dynamic array" has length 1, it's just a pointer which we convert to a safe borrow for convenience
(Some(lifetime), Some(1)) => (quote!(), quote!(&#lifetime)),
_ => (quote!(const), quote!(*)),
};
match self.reference {
Some(vkxml::ReferenceType::PointerToPointer) => quote!(#borrow mut #ty),
Some(vkxml::ReferenceType::PointerToConstPointer) => quote!(#borrow #const_ #ty),
_ => quote!(#ty),
}
}
fn safe_type_tokens(&self, lifetime: TokenStream, inner_length: Option<usize>) -> TokenStream {
assert!(!self.is_void());
match self.array {
// The outer type fn type_tokens() returns is [], which fits our "safe" prescription
Some(vkxml::ArrayType::Static) => self.type_tokens(false),
Some(vkxml::ArrayType::Dynamic) => {
let ty = self.inner_type_tokens(Some(lifetime), inner_length);
quote!([#ty])
}
None => {
let ty = name_to_tokens(&self.basetype);
let pointer = self
.reference
.as_ref()
.map(|r| r.to_safe_tokens(self.is_const, lifetime));
quote!(#pointer #ty)
}
}
}
fn type_tokens(&self, is_ffi_param: bool) -> TokenStream {
assert!(!self.is_void());
let ty = name_to_tokens(&self.basetype);
match self.array {
Some(vkxml::ArrayType::Static) => {
assert!(self.reference.is_none());
let size = self
.size
.as_ref()
.or(self.size_enumref.as_ref())
.expect("Should have size");
// Make sure we also rename the constant, that is
// used inside the static array
let size = convert_c_expression(size, &BTreeMap::new());
// arrays in c are always passed as a pointer
if is_ffi_param {
quote!(*const [#ty; #size])
} else {
quote!([#ty; #size])
}
}
_ => {
let pointer = self.reference.as_ref().map(|r| r.to_tokens(self.is_const));
if self.is_pointer_to_static_sized_array() {
let size = self.c_size.as_ref().expect("Should have c_size");
let size = convert_c_expression(size, &BTreeMap::new());
quote!(#pointer [#ty; #size])
} else {
quote!(#pointer #ty)
}
}
}
}
fn is_void(&self) -> bool {
self.basetype == "void" && self.reference.is_none()
}
fn is_pointer_to_static_sized_array(&self) -> bool {
matches!(self.array, Some(vkxml::ArrayType::Dynamic))
&& self.name.as_deref() == Some("pVersionData")
}
}
impl FieldExt for vk_parse::CommandParam {
fn param_ident(&self) -> Ident {
let name = self.definition.name.as_str();
let name_corrected = match name {
"type" => "ty",
_ => name,
};
format_ident!("{}", name_corrected.to_snake_case())
}
fn inner_type_tokens(
&self,
_lifetime: Option<TokenStream>,
_inner_length: Option<usize>,
) -> TokenStream {
unimplemented!()
}
fn safe_type_tokens(
&self,
_lifetime: TokenStream,
_inner_length: Option<usize>,
) -> TokenStream {
unimplemented!()
}
fn type_tokens(&self, is_ffi_param: bool) -> TokenStream {
assert!(!self.is_void(), "{:?}", self);
let (rem, ty) = parse_c_parameter(&self.definition.code).unwrap();
assert!(rem.is_empty());
let type_name = name_to_tokens(ty.type_.name);
let inner_ty = match ty.type_.reference_type {
CReferenceType::Value => quote!(#type_name),
CReferenceType::Pointer => {
quote!(*mut #type_name)
}
CReferenceType::PointerToConst => quote!(*const #type_name),
CReferenceType::PointerToPointer => quote!(*mut *mut #type_name),
CReferenceType::PointerToPointerToConst => quote!(*mut *const #type_name),
CReferenceType::PointerToConstPointer => quote!(*const *mut #type_name),
CReferenceType::PointerToConstPointerToConst => quote!(*const *const #type_name),
};
match ty.static_array {
None => inner_ty,
Some(len) if is_ffi_param => quote!(*const [#inner_ty; #len]),
Some(len) => quote!([#inner_ty; #len]),
}
}
fn is_void(&self) -> bool {
self.definition.type_name.as_deref() == Some("void")
&& self.len.is_none()
&& !self.definition.name.starts_with('p')
}
fn is_pointer_to_static_sized_array(&self) -> bool {
unimplemented!()
}
}
pub type CommandMap<'a> = HashMap<vkxml::Identifier, &'a vk_parse::CommandDefinition>;
fn generate_function_pointers<'a>(
ident: Ident,
commands: &[&'a vk_parse::CommandDefinition],
aliases: &HashMap<String, String>,
fn_cache: &mut HashSet<&'a str>,
) -> TokenStream {
// Commands can have duplicates inside them because they are declared per features. But we only
// really want to generate one function pointer.
let commands = commands
.iter()
.unique_by(|cmd| cmd.proto.name.as_str())
.collect::<Vec<_>>();
struct Command {
type_needs_defining: bool,
type_name: Ident,
function_name_c: String,
function_name_rust: Ident,
parameters: TokenStream,
parameters_unused: TokenStream,
returns: TokenStream,
}
let commands = commands
.iter()
.map(|cmd| {
let name = &cmd.proto.name;
let type_name = format_ident!("PFN_{}", name);
let function_name_c = if let Some(alias_name) = aliases.get(name) {
alias_name.to_string()
} else {
name.to_string()
};
let function_name_rust = format_ident!(
"{}",
function_name_c.strip_prefix("vk").unwrap().to_snake_case()
);
let params: Vec<_> = cmd
.params
.iter()
.filter(|param| matches!(param.api.as_deref(), None | Some(DESIRED_API)))
.map(|param| {
let name = param.param_ident();
let ty = param.type_tokens(true);
(name, ty)
})
.collect();
let params_iter = params
.iter()
.map(|(param_name, param_ty)| quote!(#param_name: #param_ty));
let parameters = quote!(#(#params_iter,)*);
let params_iter = params.iter().map(|(param_name, param_ty)| {
let unused_name = format_ident!("_{}", param_name);
quote!(#unused_name: #param_ty)
});
let parameters_unused = quote!(#(#params_iter,)*);
let ret = cmd
.proto
.type_name
.as_ref()
.expect("Command must have return type");
Command {
// PFN function pointers are global and can not have duplicates.
// This can happen because there are aliases to commands
type_needs_defining: fn_cache.insert(name),
type_name,
function_name_c,
function_name_rust,
parameters,
parameters_unused,
returns: if ret == "void" {
quote!()
} else {
let ret_ty_tokens = name_to_tokens(ret);
quote!(-> #ret_ty_tokens)
},
}
})
.collect::<Vec<_>>();
struct CommandToType<'a>(&'a Command);
impl<'a> quote::ToTokens for CommandToType<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let type_name = &self.0.type_name;
let parameters = &self.0.parameters;
let returns = &self.0.returns;
quote!(
#[allow(non_camel_case_types)]
pub type #type_name = unsafe extern "system" fn(#parameters) #returns;
)
.to_tokens(tokens)
}
}
struct CommandToMember<'a>(&'a Command);
impl<'a> quote::ToTokens for CommandToMember<'a> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let type_name = &self.0.type_name;
let type_name = if self.0.type_needs_defining {
// Type is defined in local scope
quote!(#type_name)
} else {