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
use super::*;
impl CodeGenerator {
/// Resolve a `{name}` format part: emit code leaving the runtime value
/// (or pointer) in rax, and classify what was found. This is THE single
/// name-resolution path shared by every format-string sink - Print, the
/// buffer set/copy/append writers, and the expression materializer that
/// write payloads, paths, and text initializers go through. Special
/// names, variable/global lookup, and the constant fallback must never
/// be re-implemented per sink: that duplication is exactly how the
/// buffer sinks shipped without `{current time's hour}` support while
/// Print had it.
pub(crate) fn resolve_format_variable(&mut self, name: &str) -> FormatPartValue {
match name {
"current time's hour" => {
self.emit_indent("TIME_GET");
self.emit_indent("TIME_GET_HOUR rax");
self.uses_time = true;
FormatPartValue::Loaded(Some(VarType::Integer))
}
"current time's minute" => {
self.emit_indent("TIME_GET");
self.emit_indent("TIME_GET_MINUTE rax");
self.uses_time = true;
FormatPartValue::Loaded(Some(VarType::Integer))
}
"current time's second" => {
self.emit_indent("TIME_GET");
self.emit_indent("TIME_GET_SECOND rax");
self.uses_time = true;
FormatPartValue::Loaded(Some(VarType::Integer))
}
"arguments's count" | "argument's count" => {
self.generate_expr(&Expr::ArgumentCount);
FormatPartValue::Loaded(Some(VarType::Integer))
}
"arguments's name" | "argument's name" => {
self.generate_expr(&Expr::ArgumentName);
FormatPartValue::Loaded(Some(VarType::String))
}
"arguments's first" | "argument's first" => {
self.generate_expr(&Expr::ArgumentFirst);
FormatPartValue::Loaded(Some(VarType::String))
}
"arguments's last" | "argument's last" => {
self.generate_expr(&Expr::ArgumentLast);
FormatPartValue::Loaded(Some(VarType::String))
}
_ => {
if let Some(offset) = self.get_var(name) {
self.emit_indent(&format!("mov rax, [rbp-{}]", offset));
FormatPartValue::Loaded(self.variable_types.get(name).cloned())
} else if let Some(label) = self.global_var_label(name).cloned() {
self.emit_indent(&format!("mov rax, [rel {}]", label));
FormatPartValue::Loaded(self.variable_types.get(name).cloned())
} else if let Some(expr) = self.global_constants.get(name).cloned() {
match expr {
Expr::StringLit(s) => FormatPartValue::Literal(s),
Expr::IntegerLit(n) => {
self.emit_indent(&format!("mov rax, {}", n));
FormatPartValue::Loaded(Some(VarType::Integer))
}
Expr::BoolLit(b) => {
self.emit_indent(&format!("mov rax, {}", if b { 1 } else { 0 }));
FormatPartValue::Loaded(Some(VarType::Integer))
}
_ => FormatPartValue::Unknown,
}
} else {
FormatPartValue::Unknown
}
}
}
}
pub(crate) fn emit_format_parts_into_buffer_slot(&mut self, offset: i64, parts: &[FormatPart], clear_first: bool) {
if clear_first {
self.emit_clear_buffer_slot(offset);
}
for part in parts {
match part {
FormatPart::Literal(s) => self.emit_append_literal_to_buffer_slot(offset, s),
FormatPart::Variable { name, format } => {
match self.resolve_format_variable(name) {
FormatPartValue::Loaded(value_type) => {
let fmt_spec = self.parse_format_spec(format.as_deref());
self.emit_append_runtime_value_to_buffer_slot(offset, value_type, fmt_spec);
}
FormatPartValue::Literal(s) => {
self.emit_append_literal_to_buffer_slot(offset, &s);
}
FormatPartValue::Unknown => {
// Same placeholder Print renders for unknown names
let placeholder = format!("{{{}}}", name);
self.emit_append_literal_to_buffer_slot(offset, &placeholder);
}
}
}
FormatPart::Expression { expr, format } => {
self.generate_expr(expr);
let expr_type = self.infer_expr_type(expr);
let fmt_spec = self.parse_format_spec(format.as_deref());
self.emit_append_runtime_value_to_buffer_slot(offset, expr_type, fmt_spec);
}
}
}
}
pub(crate) fn emit_format_parts_into_buffer(
&mut self,
dst_local: Option<i64>,
dst_global: Option<&str>,
parts: &[FormatPart],
) {
let load_dst = |this: &mut Self| {
if let Some(offset) = dst_local {
this.emit_indent(&format!("mov rdi, [rbp-{}]", offset));
} else if let Some(label) = dst_global {
this.emit_indent(&format!("mov rdi, [rel {}]", label));
}
};
for part in parts {
load_dst(self);
self.emit_indent("push rdi ; save destination buffer pointer");
match part {
FormatPart::Literal(s) => {
let label = self.add_string(s);
self.emit_indent(&format!("lea rsi, [rel {}]", label));
self.emit_indent(&format!("mov rdx, {}_len", label));
self.emit_indent("call _buffer_append_bytes");
}
FormatPart::Variable { name, format } => {
match self.resolve_format_variable(name) {
FormatPartValue::Loaded(value_type) => {
let fmt_spec = self.parse_format_spec(format.as_deref());
self.emit_append_runtime_value_to_buffer_ptr(value_type, fmt_spec);
}
FormatPartValue::Literal(s) => {
let label = self.add_string(&s);
self.emit_indent(&format!("lea rsi, [rel {}]", label));
self.emit_indent(&format!("mov rdx, {}_len", label));
self.emit_indent("call _buffer_append_bytes");
}
FormatPartValue::Unknown => {
let placeholder = format!("{{{}}}", name);
let label = self.add_string(&placeholder);
self.emit_indent(&format!("lea rsi, [rel {}]", label));
self.emit_indent(&format!("mov rdx, {}_len", label));
self.emit_indent("call _buffer_append_bytes");
}
}
}
FormatPart::Expression { expr, format } => {
self.generate_expr(expr);
let expr_type = self.infer_expr_type(expr);
let fmt_spec = self.parse_format_spec(format.as_deref());
self.emit_append_runtime_value_to_buffer_ptr(expr_type, fmt_spec);
}
}
if let Some(offset) = dst_local {
self.emit_indent(&format!("mov [rbp-{}], rax", offset));
} else if let Some(label) = dst_global {
self.emit_indent(&format!("mov [rel {}], rax", label));
}
self.emit_indent("pop rsi ; discard saved pointer copy");
}
}
pub(crate) fn parse_format_spec(&self, fmt: Option<&str>) -> FormatSpec {
match fmt {
None => FormatSpec {
width: None,
zero_pad: false,
base: IntegerBase::Decimal,
precision: None,
},
Some(fmt_str) => {
let mut spec = FormatSpec {
width: None,
zero_pad: false,
base: IntegerBase::Decimal,
precision: None,
};
// Check for precision format first (starts with '.')
if fmt_str.starts_with('.') {
// Float precision format like .2, .4, etc.
if let Some(precision) = fmt_str.strip_prefix('.').and_then(|s| s.parse::<i32>().ok()) {
spec.precision = Some(precision);
}
return spec;
}
// Parse width and zero padding
let mut remaining = fmt_str;
let mut has_width = false;
// Check if it starts with digit or '0' for width/padding
if remaining.chars().next().map(|c| c.is_ascii_digit() || c == '0').unwrap_or(false) {
let zero_pad = remaining.starts_with('0');
let width_str = if zero_pad {
remaining.trim_start_matches('0')
} else {
remaining
};
// Extract digits for width
let width_end = width_str.chars().take_while(|c| c.is_ascii_digit()).count();
if width_end > 0 {
let width_digits = &width_str[..width_end];
if let Ok(width) = width_digits.parse::<i32>() {
spec.width = Some(width);
spec.zero_pad = zero_pad;
has_width = true;
remaining = &fmt_str[if zero_pad { 1 + width_end } else { width_end }..];
}
}
}
// Parse base specifier from remaining characters
if !remaining.is_empty() {
match remaining {
"x" => spec.base = IntegerBase::HexLower,
"X" => spec.base = IntegerBase::HexUpper,
"b" => spec.base = IntegerBase::Binary,
"o" => spec.base = IntegerBase::Octal,
_ => {
// If we parsed a width but no base, treat as decimal
if has_width {
spec.base = IntegerBase::Decimal;
}
}
}
}
spec
}
}
}
pub(crate) fn emit_formatted_value(&mut self, value_type: Option<VarType>, fmt: FormatSpec) {
// Handle precision format for floats
if let Some(precision) = fmt.precision {
self.emit_indent("movq xmm0, rdi");
self.emit_indent(&format!("mov rdi, {}", precision));
self.emit_indent("call _print_float_precision");
self.uses_floats = true;
self.uses_format = true;
return;
}
// A width must never change what a value IS (docs/BUGS_FOUND.md #36).
//
// The integer paths further down reinterpret rdi as a signed 64-bit
// integer, which is right for a `number` and catastrophic for anything
// else: a `float` printed its raw IEEE-754 bits, and a `text` printed
// the string's ADDRESS - silent wrong data, and an information leak in
// the text case. This dispatch used to be gated on `fmt.width.is_none()`,
// so writing a width skipped the type check entirely, precisely when
// the compiler knows the type best.
//
// Non-integer types are therefore rendered by type whether or not a
// width was given. The width itself is not yet APPLIED to them - there
// is no string/float padding primitive in coreasm, only the integer and
// hex ones - so a width on a float or text is currently ignored rather
// than honoured. That matches what the runtime-tagged `value` path
// already does, so both paths now agree, and it turns the worst class
// of defect (a wrong value) into the mildest (a cosmetic gap).
if matches!(fmt.base, IntegerBase::Decimal) {
match value_type {
Some(VarType::Float) => {
self.emit_indent("movq xmm0, rdi");
self.emit_indent("PRINT_FLOAT");
self.uses_floats = true;
return;
}
Some(VarType::String) => {
self.emit_indent("PRINT_CSTR rdi");
return;
}
Some(VarType::Buffer) if fmt.width.is_some() => {
// With a spec present, print.rs has already advanced rdi to
// the buffer's DATA area, so the struct-pointer macro
// PRINT_BUF would read the header as bytes. The data area is
// NUL-terminated, so print it as a C string. The no-width
// case below still receives the struct pointer and still
// uses PRINT_BUF - the two callers differ, deliberately.
self.emit_indent("PRINT_CSTR rdi");
return;
}
_ => {}
}
}
// If no specific format (default case), handle by type
if fmt.width.is_none() && matches!(fmt.base, IntegerBase::Decimal) {
match value_type {
Some(VarType::Float) => {
self.emit_indent("movq xmm0, rdi");
self.emit_indent("PRINT_FLOAT");
self.uses_floats = true;
}
Some(VarType::Buffer) => {
// rdi must be the struct pointer (not data area) here.
// The fixed call sites guarantee this; it's documented on
// each one. Kept separate from VarType::String to make the
// contract explicit and catch any future callers that get
// it wrong (PRINT_BUF on a data pointer would print garbage).
self.emit_indent("PRINT_BUF rdi");
}
Some(VarType::String) => {
self.emit_indent("PRINT_CSTR rdi");
}
_ => {
self.emit_indent("PRINT_INT rdi");
}
}
return;
}
// Handle integer formatting with width and base
match fmt.base {
IntegerBase::Decimal => {
match (fmt.width, fmt.zero_pad) {
(Some(width), true) => {
self.emit_indent(&format!("PRINT_INT_ZEROPAD rdi, {}", width));
}
(Some(width), false) => {
self.emit_indent(&format!("PRINT_INT_PADDED rdi, {}", width));
}
_ => {
self.emit_indent("PRINT_INT rdi");
}
}
self.uses_format = true;
}
IntegerBase::HexLower => {
if fmt.width.is_some() {
match (fmt.width, fmt.zero_pad) {
(Some(width), true) => {
self.emit_indent(&format!("PRINT_HEX_LOWER_ZEROPAD rdi, {}", width));
}
(Some(width), false) => {
self.emit_indent(&format!("PRINT_HEX_LOWER_PADDED rdi, {}", width));
}
_ => {
self.emit_indent("PRINT_HEX_LOWER rdi");
}
}
} else {
self.emit_indent("PRINT_HEX_LOWER rdi");
}
self.uses_format = true;
}
IntegerBase::HexUpper => {
if fmt.width.is_some() {
match (fmt.width, fmt.zero_pad) {
(Some(width), true) => {
self.emit_indent(&format!("PRINT_HEX_UPPER_ZEROPAD rdi, {}", width));
}
(Some(width), false) => {
self.emit_indent(&format!("PRINT_HEX_UPPER_PADDED rdi, {}", width));
}
_ => {
self.emit_indent("PRINT_HEX_UPPER rdi");
}
}
} else {
self.emit_indent("PRINT_HEX_UPPER rdi");
}
self.uses_format = true;
}
IntegerBase::Binary => {
if fmt.width.is_some() {
match (fmt.width, fmt.zero_pad) {
(Some(width), true) => {
self.emit_indent(&format!("PRINT_BINARY_ZEROPAD rdi, {}", width));
}
(Some(width), false) => {
self.emit_indent(&format!("PRINT_BINARY_PADDED rdi, {}", width));
}
_ => {
self.emit_indent("PRINT_BINARY rdi");
}
}
} else {
self.emit_indent("PRINT_BINARY rdi");
}
self.uses_format = true;
}
IntegerBase::Octal => {
if fmt.width.is_some() {
match (fmt.width, fmt.zero_pad) {
(Some(width), true) => {
self.emit_indent(&format!("PRINT_OCTAL_ZEROPAD rdi, {}", width));
}
(Some(width), false) => {
self.emit_indent(&format!("PRINT_OCTAL_PADDED rdi, {}", width));
}
_ => {
self.emit_indent("PRINT_OCTAL rdi");
}
}
} else {
self.emit_indent("PRINT_OCTAL rdi");
}
self.uses_format = true;
}
}
}
}