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
//! Format string validation for print statements
//!
//! This module validates format strings and their arguments during compilation,
//! ensuring correct placeholder count and syntax.
use crate::script::ast::Expr;
use crate::script::parser::ParseError;
pub struct FormatValidator;
impl FormatValidator {
/// Validate that format string placeholders match the number of arguments
pub fn validate_format_arguments(format: &str, args: &[Expr]) -> Result<(), ParseError> {
let (placeholders, star_extras) = Self::count_required_args(format)?;
let required_args = placeholders + star_extras;
if required_args != args.len() {
let args_len = args.len();
return Err(ParseError::TypeError(format!(
"Format string '{format}' expects {required_args} argument(s) but received {args_len} argument(s)"
)));
}
// TODO (phase 2): validate expression types against format specifiers
// e.g., {:x} requires integer or pointer; {:s} requires char*/bytes
Ok(())
}
/// Count the number of placeholders in a format string
/// Supports basic {} placeholders and escape sequences {{, }}
/// Extended: supports {:x}, {:X}, {:p}, {:s}, and optional length suffixes .N or .*
/// Returns (placeholders, star_extras) where star_extras is the number of additional
/// dynamic-length arguments required by `.*` occurrences.
fn count_required_args(format: &str) -> Result<(usize, usize), ParseError> {
let mut placeholders = 0usize;
let mut star_extras = 0usize;
let mut chars = format.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'{' => {
if chars.peek() == Some(&'{') {
chars.next(); // Skip escaped '{{'
} else {
// Found a placeholder, look for closing '}'
let mut found_closing = false;
let mut placeholder_content = String::new();
for inner_ch in chars.by_ref() {
if inner_ch == '}' {
found_closing = true;
break;
}
placeholder_content.push(inner_ch);
}
if !found_closing {
return Err(ParseError::InvalidExpression);
}
// Accept: empty "{}" or extended forms like ":x", ":X", ":p", ":s", optionally with
// a length suffix ".N" (digits) or ".*" (dynamic length consumes one extra argument)
if placeholder_content.is_empty() {
placeholders += 1;
} else {
// Must start with ':'
if !placeholder_content.starts_with(':') {
return Err(ParseError::TypeError(format!(
"Invalid format specifier '{{{placeholder_content}}}': expected ':' prefix"
)));
}
// Extract conv and optional suffix
let tail = &placeholder_content[1..];
// conv is first char
let mut iter = tail.chars();
let conv = iter.next().ok_or_else(|| {
ParseError::TypeError("Empty format after ':'".to_string())
})?;
match conv {
'x' | 'X' | 'p' | 's' => {}
_ => {
return Err(ParseError::TypeError(format!(
"Unsupported format conversion '{{:{conv}}}'"
)));
}
}
// Remaining should be empty or ".N" or ".*" or ".name$" (capture variable)
let rest: String = iter.collect();
if rest.is_empty() {
// ok
} else if let Some(rem) = rest.strip_prefix('.') {
if rem == "*" {
star_extras += 1; // dynamic length consumes next arg
} else if let Some(name) = rem.strip_suffix('$') {
// capture variable name: [A-Za-z_][A-Za-z0-9_]*$
let mut chars = name.chars();
let valid = if let Some(first) = chars.next() {
(first.is_ascii_alphabetic() || first == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
} else {
false
};
if !valid {
return Err(ParseError::TypeError(format!(
"Invalid capture variable in specifier '{{:{conv}.{rem}}}'"
)));
}
} else if rem.chars().all(|c| c.is_ascii_digit())
|| (rem.starts_with("0x")
&& rem.len() > 2
&& rem[2..].chars().all(|c| c.is_ascii_hexdigit()))
|| (rem.starts_with("0o")
&& rem.len() > 2
&& rem[2..].chars().all(|c| matches!(c, '0'..='7')))
|| (rem.starts_with("0b")
&& rem.len() > 2
&& rem[2..].chars().all(|c| matches!(c, '0' | '1')))
{
// static length with base support: decimal / 0x.. / 0o.. / 0b..
} else {
return Err(ParseError::TypeError(format!(
"Invalid length in specifier '{{:{conv}{rest}}}'"
)));
}
} else {
return Err(ParseError::TypeError(format!(
"Invalid specifier syntax '{{:{conv}{rest}}}'"
)));
}
placeholders += 1;
}
}
}
'}' => {
if chars.peek() == Some(&'}') {
chars.next(); // Skip escaped '}}'
} else {
return Err(ParseError::InvalidExpression); // Unmatched '}'
}
}
_ => {}
}
}
Ok((placeholders, star_extras))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::script::ast::Expr;
#[test]
fn test_count_placeholders() -> Result<(), ParseError> {
// Basic cases
assert_eq!(FormatValidator::count_required_args("hello world")?, (0, 0));
assert_eq!(FormatValidator::count_required_args("hello {}")?, (1, 0));
assert_eq!(FormatValidator::count_required_args("{} {}")?, (2, 0));
assert_eq!(
FormatValidator::count_required_args("pid: {}, name: {}")?,
(2, 0)
);
// Escape sequences
assert_eq!(
FormatValidator::count_required_args("use {{}} for braces")?,
(0, 0)
);
assert_eq!(
FormatValidator::count_required_args("value: {}, braces: {{}}")?,
(1, 0)
);
// Error cases
assert!(FormatValidator::count_required_args("unclosed {").is_err());
assert!(FormatValidator::count_required_args("unmatched }").is_err());
// Extended specifiers
assert_eq!(FormatValidator::count_required_args("{:x}")?, (1, 0));
assert_eq!(FormatValidator::count_required_args("{:X}")?, (1, 0));
assert_eq!(FormatValidator::count_required_args("{:p}")?, (1, 0));
assert_eq!(FormatValidator::count_required_args("{:s}")?, (1, 0));
assert_eq!(FormatValidator::count_required_args("{:x.16}")?, (1, 0));
assert_eq!(FormatValidator::count_required_args("{:s.*}")?, (1, 1));
assert_eq!(FormatValidator::count_required_args("{:x.len$}")?, (1, 0));
// Static length with hex/oct/bin
assert_eq!(FormatValidator::count_required_args("{:x.0x10}")?, (1, 0));
assert_eq!(FormatValidator::count_required_args("{:s.0o20}")?, (1, 0));
assert_eq!(FormatValidator::count_required_args("{:X.0b1000}")?, (1, 0));
assert!(FormatValidator::count_required_args("{:x.1a$}").is_err());
Ok(())
}
#[test]
fn test_validate_format_arguments() {
let args_empty: Vec<Expr> = vec![];
let args_one = vec![Expr::Variable("pid".to_string())];
let args_two = vec![
Expr::Variable("pid".to_string()),
Expr::String("test".to_string()),
];
// Matching cases
assert!(FormatValidator::validate_format_arguments("no placeholders", &args_empty).is_ok());
assert!(FormatValidator::validate_format_arguments("pid: {}", &args_one).is_ok());
assert!(FormatValidator::validate_format_arguments("pid: {}, name: {}", &args_two).is_ok());
// Mismatched cases
assert!(FormatValidator::validate_format_arguments("need one: {}", &args_empty).is_err());
assert!(FormatValidator::validate_format_arguments("no placeholders", &args_one).is_err());
assert!(FormatValidator::validate_format_arguments("need two: {} {}", &args_one).is_err());
}
}