-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathdebug_printf.rs
More file actions
249 lines (215 loc) · 7.72 KB
/
debug_printf.rs
File metadata and controls
249 lines (215 loc) · 7.72 KB
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
use proc_macro::TokenStream;
use proc_macro2::Span;
use std::fmt::Write;
pub struct DebugPrintfInput {
pub span: Span,
pub format_string: String,
pub variables: Vec<syn::Expr>,
}
impl syn::parse::Parse for DebugPrintfInput {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::parse::Result<Self> {
let span = input.span();
if input.is_empty() {
return Ok(Self {
span,
format_string: Default::default(),
variables: Default::default(),
});
}
let format_string = input.parse::<syn::LitStr>()?;
if !input.is_empty() {
input.parse::<syn::token::Comma>()?;
}
let variables =
syn::punctuated::Punctuated::<syn::Expr, syn::token::Comma>::parse_terminated(input)?;
Ok(Self {
span,
format_string: format_string.value(),
variables: variables.into_iter().collect(),
})
}
}
fn parse_error(message: &str, span: Span) -> TokenStream {
syn::Error::new(span, message).to_compile_error().into()
}
enum FormatType {
Scalar {
ty: proc_macro2::TokenStream,
},
Vector {
ty: proc_macro2::TokenStream,
width: usize,
},
}
pub fn debug_printf_inner(input: DebugPrintfInput) -> TokenStream {
let DebugPrintfInput {
format_string,
variables,
span,
} = input;
fn map_specifier_to_type(
specifier: char,
chars: &mut std::str::Chars<'_>,
) -> Option<proc_macro2::TokenStream> {
let mut peekable = chars.peekable();
Some(match specifier {
'd' | 'i' => quote::quote! { i32 },
'o' | 'x' | 'X' => quote::quote! { u32 },
'a' | 'A' | 'e' | 'E' | 'f' | 'F' | 'g' | 'G' => quote::quote! { f32 },
'u' => {
if matches!(peekable.peek(), Some('l')) {
chars.next();
quote::quote! { u64 }
} else {
quote::quote! { u32 }
}
}
'l' => {
if matches!(peekable.peek(), Some('u' | 'x')) {
chars.next();
quote::quote! { u64 }
} else {
return None;
}
}
_ => return None,
})
}
let mut chars = format_string.chars();
let mut format_arguments = Vec::new();
while let Some(mut ch) = chars.next() {
if ch == '%' {
ch = match chars.next() {
Some('%') => continue,
None => return parse_error("Unterminated format specifier", span),
Some(ch) => ch,
};
let mut has_precision = false;
while ch.is_ascii_digit() {
ch = match chars.next() {
Some(ch) => ch,
None => {
return parse_error(
"Unterminated format specifier: missing type after precision",
span,
);
}
};
has_precision = true;
}
if has_precision && ch == '.' {
ch = match chars.next() {
Some(ch) => ch,
None => {
return parse_error(
"Unterminated format specifier: missing type after decimal point",
span,
);
}
};
while ch.is_ascii_digit() {
ch = match chars.next() {
Some(ch) => ch,
None => {
return parse_error(
"Unterminated format specifier: missing type after fraction precision",
span,
);
}
};
}
}
if ch == 'v' {
let width = match chars.next() {
Some('2') => 2,
Some('3') => 3,
Some('4') => 4,
Some(ch) => {
return parse_error(&format!("Invalid width for vector: {ch}"), span);
}
None => return parse_error("Missing vector dimensions specifier", span),
};
ch = match chars.next() {
Some(ch) => ch,
None => return parse_error("Missing vector type specifier", span),
};
let ty = match map_specifier_to_type(ch, &mut chars) {
Some(ty) => ty,
_ => {
return parse_error(
&format!("Unrecognised vector type specifier: '{ch}'"),
span,
);
}
};
format_arguments.push(FormatType::Vector { ty, width });
} else {
let ty = match map_specifier_to_type(ch, &mut chars) {
Some(ty) => ty,
_ => {
return parse_error(
&format!("Unrecognised format specifier: '{ch}'"),
span,
);
}
};
format_arguments.push(FormatType::Scalar { ty });
}
}
}
if format_arguments.len() != variables.len() {
return syn::Error::new(
span,
format!(
"{} % arguments were found, but {} variables were given",
format_arguments.len(),
variables.len()
),
)
.to_compile_error()
.into();
}
let mut variable_idents = String::new();
let mut input_registers = Vec::new();
let mut op_loads = Vec::new();
for (i, (variable, format_argument)) in variables.into_iter().zip(format_arguments).enumerate()
{
let ident = quote::format_ident!("_{}", i);
let _ = write!(variable_idents, "%{ident} ");
let assert_fn = match format_argument {
FormatType::Scalar { ty } => {
quote::quote! { spirv_std::debug_printf::assert_is_type::<#ty> }
}
FormatType::Vector { ty, width } => {
quote::quote! { spirv_std::debug_printf::assert_is_vector::<#ty, _, #width> }
}
};
input_registers.push(quote::quote! {
#ident = in(reg) &#assert_fn(#variable),
});
let op_load = format!("%{ident} = OpLoad _ {{{ident}}}");
op_loads.push(quote::quote! {
#op_load,
});
}
let input_registers = input_registers
.into_iter()
.collect::<proc_macro2::TokenStream>();
let op_loads = op_loads.into_iter().collect::<proc_macro2::TokenStream>();
// Escapes the '{' and '}' characters in the format string.
// Since the `asm!` macro expects '{' '}' to surround its arguments, we have to use '{{' and '}}' instead.
// The `asm!` macro will then later turn them back into '{' and '}'.
let format_string = format_string.replace('{', "{{").replace('}', "}}");
let op_string = format!("%string = OpString {format_string:?}");
let output = quote::quote! {
::core::arch::asm!(
"%void = OpTypeVoid",
#op_string,
"%debug_printf = OpExtInstImport \"NonSemantic.DebugPrintf\"",
#op_loads
concat!("%result = OpExtInst %void %debug_printf 1 %string ", #variable_idents),
#input_registers
)
};
output.into()
}