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
//! Macro and string expression generation
//!
//! Handles generation of:
//! - Macro invocations (println!, format!, vec!, etc.)
//! - String concatenation operations
//! - Format string optimization
use crate::parser::{Expression, Type};
use super::{string_analysis, CodeGenerator};
impl<'ast> CodeGenerator<'ast> {
/// Generate code for macro invocation expression
/// Handles format!, println!, vec!, and other macros with special semantics
pub(in crate::codegen::rust) fn generate_macro_invocation(
&mut self,
is_repeat: bool,
name: &str,
args: &[&Expression<'ast>],
delimiter: &crate::parser::MacroDelimiter,
) -> String {
use crate::parser::{Literal, MacroDelimiter};
// Macro arguments must never have context-level string coercion applied.
// format!("...".to_string(), ...) is invalid Rust (requires literal first arg).
let prev_coerce = self.coerce_string_literals_to_owned;
self.coerce_string_literals_to_owned = false;
let prev_match_arm = self.in_match_arm_needing_string;
self.in_match_arm_needing_string = false;
let prev_suppress = self.suppress_string_conversion.get();
self.suppress_string_conversion.set(true);
// PHASE 4 OPTIMIZATION: Check for format! with capacity hints
if name == "format" {
if let Some(&capacity) = self.string_capacity_hints.get(&self.current_statement_idx) {
// Clone capacity to avoid borrow issues
let capacity_val = capacity;
// Generate optimized String::with_capacity + write! instead of format!
self.needs_write_import = true;
// write! expects the first argument to be a &str format template, not String.
let arg_strs: Vec<String> = if args.is_empty() {
Vec::new()
} else {
let fmt = self.format_macro_template_arg(args[0]);
let rest: Vec<String> = args[1..]
.iter()
.map(|e| self.generate_expression(e))
.collect();
let mut v = Vec::with_capacity(1 + rest.len());
v.push(fmt);
v.extend(rest);
v
};
self.coerce_string_literals_to_owned = prev_coerce;
self.in_match_arm_needing_string = prev_match_arm;
self.suppress_string_conversion.set(prev_suppress);
return format!(
"{{\n{} let mut __s = String::with_capacity({});\n{} write!(&mut __s, {}).unwrap();\n{} __s\n{}}}",
self.indent(),
capacity_val,
self.indent(),
arg_strs.join(", "),
self.indent(),
self.indent()
);
}
}
// Special case: if this is println!/eprintln!/print!/eprint! and first arg is format!, flatten it
let should_flatten = (name == "println"
|| name == "eprintln"
|| name == "print"
|| name == "eprint")
&& !args.is_empty()
&& matches!(&args[0], Expression::MacroInvocation { name: macro_name, .. } if macro_name == "format");
let arg_strs: Vec<String> = if should_flatten {
// Flatten format! macro arguments into the print macro
if let Expression::MacroInvocation {
is_repeat: _,
args: format_args,
..
} = &args[0]
{
format_args
.iter()
.map(|e| self.generate_expression(e))
.collect()
} else {
args.iter().map(|e| self.generate_expression(e)).collect()
}
} else {
// Special case: if this is println!/eprintln!/print!/eprint! with a single non-literal arg,
// wrap it with "{}" to make it valid Rust: println!(var) -> println!("{}", var)
// Also wrap format!() calls: println!(format!(...)) -> println!("{}", format!(...))
if (name == "println" || name == "eprintln" || name == "print" || name == "eprint")
&& args.len() == 1
&& !matches!(
&args[0],
Expression::Literal {
value: Literal::String(_),
..
}
)
{
vec!["\"{}\"".to_string(), self.generate_expression(args[0])]
} else if name == "format" && !args.is_empty() {
let mut out = Vec::with_capacity(args.len());
out.push(self.format_macro_template_arg(args[0]));
for e in args.iter().skip(1) {
out.push(self.generate_expression(e));
}
out
} else {
args.iter().map(|e| self.generate_expression(e)).collect()
}
};
self.coerce_string_literals_to_owned = prev_coerce;
self.in_match_arm_needing_string = prev_match_arm;
self.suppress_string_conversion.set(prev_suppress);
let (open, close) = match delimiter {
MacroDelimiter::Parens => ("(", ")"),
MacroDelimiter::Brackets => ("[", "]"),
MacroDelimiter::Braces => ("{", "}"),
};
// WINDJAMMER FIX: vec![value; count] repeat syntax
// The parser sets is_repeat=true for vec![x; n] syntax
// Use semicolon for repeat, comma for regular args
let separator = if is_repeat { "; " } else { ", " };
// WINDJAMMER FIX: String literal coercion in vec![]
// In Windjammer, `string` maps to Rust `String`, so vec!["a", "b"] must
// become vec!["a".to_string(), "b".to_string()] for Vec<String>.
// Only apply when: macro is vec, brackets delimiter, has string literal args.
let final_arg_strs: Vec<String> =
if name == "vec" && matches!(delimiter, MacroDelimiter::Brackets) && !is_repeat {
arg_strs
.iter()
.enumerate()
.map(|(idx, s)| {
// Check if the original arg is a string literal
if idx < args.len() {
if let Expression::Literal {
value: Literal::String(_),
..
} = &args[idx]
{
// Add .to_string() if not already present
if !s.ends_with(".to_string()") {
return format!("{}.to_string()", s);
}
}
}
s.clone()
})
.collect()
} else {
arg_strs
};
format!(
"{}!{}{}{}",
name,
open,
final_arg_strs.join(separator),
close
)
}
pub(in crate::codegen::rust) fn generate_string_concat(
&mut self,
left: &Expression<'ast>,
right: &Expression<'ast>,
) -> String {
let mut parts = Vec::new();
string_analysis::collect_concat_parts_static(left, &mut parts);
string_analysis::collect_concat_parts_static(right, &mut parts);
let use_additive = parts
.iter()
.any(string_analysis::expression_produces_string);
if use_additive {
let mut acc = self.generate_expression(&parts[0]);
for p in parts.iter().skip(1) {
let rhs = self.generate_expression(p);
let amp = string_analysis::expression_produces_string(p)
|| self.infer_expression_type(p).as_ref().is_some_and(|ty| {
matches!(ty, Type::String)
|| matches!(
ty,
Type::Custom(n) if n == "string" || n == "String"
)
});
acc = if amp {
format!("{} + &{}", acc, rhs)
} else {
format!("{} + {}", acc, rhs)
};
}
return acc;
}
let format_str = "{}".repeat(parts.len());
let mut args = Vec::new();
for expr in &parts {
// format! placeholders accept &str — never emit `.into()` on literal args.
args.push(self.format_macro_template_arg(expr));
}
format!("format!(\"{}\", {})", format_str, args.join(", "))
}
/// First argument to `format!` must stay a string literal (never `.to_string()`).
pub(in crate::codegen::rust) fn format_macro_template_arg(
&mut self,
expr: &Expression<'ast>,
) -> String {
use crate::parser::Literal;
if let Expression::Literal { value, .. } = expr {
if matches!(value, Literal::String(_)) {
return self.generate_literal(value);
}
}
self.generate_expression(expr)
}
}