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
//! Shared S-expression reader for DjVu text chunks.
//!
//! Both the ANTa/ANTz annotation parser ([`crate::annotation`]) and the
//! METa/METz metadata parser ([`crate::metadata`]) consume the same
//! S-expression syntax: parenthesised lists of unquoted atoms and `"`-quoted
//! strings, with `;` line comments. This module owns the single tokenizer and
//! recursive-descent reader they share, including the recursion-depth guard
//! that bounds stack usage on crafted (deeply nested) input.
//!
//! The reader is lenient and best-effort: malformed fragments (unmatched
//! parens, payload past the depth limit) are dropped rather than reported, so
//! that a partially-valid chunk still yields the forms it can. Each caller
//! keeps its own `&[u8]` → `&str` decode policy; metadata and annotation
//! payloads both decode leniently via [`crate::lenient_text`] since #524/#553,
//! before applying their own interpretation of the tree.
#[cfg(not(feature = "std"))]
use alloc::{
string::{String, ToString},
vec::Vec,
};
/// A node in a parsed S-expression tree.
///
/// Unquoted atoms and `"`-quoted strings stay distinct so that a form the
/// caller does not interpret can be printed back unchanged
/// ([`SExpr::write_to`]); readers that do not care use [`SExpr::text`].
#[derive(Debug)]
pub(crate) enum SExpr {
Atom(String),
Str(String),
List(Vec<SExpr>),
}
impl SExpr {
/// The text of an atom or a quoted string; `None` for a list.
pub(crate) fn text(&self) -> Option<&str> {
match self {
SExpr::Atom(s) | SExpr::Str(s) => Some(s),
SExpr::List(_) => None,
}
}
/// Print the node back as S-expression text: one space between list
/// items, quoted strings re-escaped. Reading the output back yields the
/// same tree.
pub(crate) fn write_to(&self, out: &mut String) {
match self {
SExpr::Atom(s) => out.push_str(s),
SExpr::Str(s) => write_quoted(s, out),
SExpr::List(items) => {
out.push('(');
for (index, item) in items.iter().enumerate() {
if index > 0 {
out.push(' ');
}
item.write_to(out);
}
out.push(')');
}
}
}
}
/// Append `s` as a `"`-quoted string, backslash-escaping `"` and `\`.
pub(crate) fn write_quoted(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
if c == '"' || c == '\\' {
out.push('\\');
}
out.push(c);
}
out.push('"');
}
/// Maximum nesting depth for parsed lists.
///
/// Bounds recursion in [`parse_sexprs`] so a deeply nested payload cannot
/// overflow the stack. Lists deeper than this are truncated at the limit.
const MAX_SEXPR_DEPTH: usize = 64;
/// Minimal S-expression token.
#[derive(Debug, PartialEq)]
enum Token<'a> {
LParen,
RParen,
Atom(&'a str),
Quoted(String),
}
/// Parse `input` into a flat list of top-level S-expressions.
///
/// Lenient: see the module docs.
pub(crate) fn parse_sexprs(input: &str) -> Vec<SExpr> {
let tokens = tokenize(input);
let mut result = Vec::new();
let mut pos = 0usize;
while pos < tokens.len() {
if let Some(expr) = parse_one(&tokens, &mut pos, 0) {
result.push(expr);
}
}
result
}
/// Tokenize an S-expression string into a flat `Vec` of tokens.
fn tokenize(input: &str) -> Vec<Token<'_>> {
let mut tokens = Vec::new();
let bytes = input.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes.get(i) {
Some(b'(') => {
tokens.push(Token::LParen);
i += 1;
}
Some(b')') => {
tokens.push(Token::RParen);
i += 1;
}
Some(b'"') => {
i += 1;
// Collect the raw bytes and decode once at the end. Pushing
// each byte as a char would Latin-1-ize multi-byte UTF-8
// ("Café" → "Café"); deleting backslashes can never split a
// multi-byte char (its bytes are all ≥ 0x80, '\\' is ASCII),
// so the collected bytes stay valid UTF-8 (#524).
let mut s = Vec::new();
while i < bytes.len() {
match bytes.get(i) {
Some(b'\\') if i + 1 < bytes.len() => {
i += 1;
if let Some(&c) = bytes.get(i) {
s.push(c);
}
i += 1;
}
Some(b'"') => {
i += 1;
break;
}
Some(&c) => {
s.push(c);
i += 1;
}
None => break,
}
}
tokens.push(Token::Quoted(crate::lenient_text::decode_lossy_string(&s)));
}
Some(b' ') | Some(b'\t') | Some(b'\n') | Some(b'\r') => {
i += 1;
}
Some(b';') => {
// line comment
while i < bytes.len() && bytes.get(i) != Some(&b'\n') {
i += 1;
}
}
_ => {
let start = i;
while i < bytes.len() {
match bytes.get(i) {
Some(b'(') | Some(b')') | Some(b'"') | Some(b' ') | Some(b'\t')
| Some(b'\n') | Some(b'\r') => break,
_ => i += 1,
}
}
if let Some(slice) = input.get(start..i)
&& !slice.is_empty()
{
tokens.push(Token::Atom(slice));
}
}
}
}
tokens
}
fn parse_one(tokens: &[Token<'_>], pos: &mut usize, depth: usize) -> Option<SExpr> {
if depth > MAX_SEXPR_DEPTH {
return None;
}
match tokens.get(*pos) {
Some(Token::LParen) => {
*pos += 1;
let mut items = Vec::new();
loop {
match tokens.get(*pos) {
Some(Token::RParen) => {
*pos += 1;
break;
}
None => break,
_ => {
if let Some(child) = parse_one(tokens, pos, depth + 1) {
items.push(child);
} else {
break;
}
}
}
}
Some(SExpr::List(items))
}
Some(Token::RParen) => {
// Unexpected RParen — skip
*pos += 1;
None
}
Some(Token::Atom(s)) => {
let s = s.to_string();
*pos += 1;
Some(SExpr::Atom(s))
}
Some(Token::Quoted(s)) => {
let s = s.clone();
*pos += 1;
Some(SExpr::Str(s))
}
None => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn atom(e: &SExpr) -> Option<&str> {
e.text()
}
#[test]
fn quoted_utf8_survives_tokenizing() {
// Regression (#524 review): the tokenizer used to push each byte as a
// char, Latin-1-izing multi-byte UTF-8 ("Café" → "Café").
let exprs = parse_sexprs("(title \"Café — Кафе\")");
let SExpr::List(items) = &exprs[0] else {
panic!("expected list")
};
let SExpr::Str(s) = &items[1] else {
panic!("expected quoted string")
};
assert_eq!(s, "Café — Кафе");
}
#[test]
fn parses_flat_list() {
let exprs = parse_sexprs("(zoom 100)");
assert_eq!(exprs.len(), 1);
let SExpr::List(items) = &exprs[0] else {
panic!("expected list")
};
assert_eq!(atom(&items[0]), Some("zoom"));
assert_eq!(atom(&items[1]), Some("100"));
}
#[test]
fn quoted_and_atom_share_text() {
let exprs = parse_sexprs(r#"(title "My Book")"#);
let SExpr::List(items) = &exprs[0] else {
panic!("expected list")
};
assert!(matches!(items[0], SExpr::Atom(_)));
assert!(matches!(items[1], SExpr::Str(_)));
assert_eq!(atom(&items[1]), Some("My Book"));
}
#[test]
fn write_to_prints_back_an_equivalent_tree() {
let source = "(metadata (Title \"A \\\"quoted\\\" \\\\ name\")\n (Year 1999) ( ) )";
let exprs = parse_sexprs(source);
let mut printed = String::new();
exprs[0].write_to(&mut printed);
assert_eq!(
printed,
"(metadata (Title \"A \\\"quoted\\\" \\\\ name\") (Year 1999) ())"
);
let mut again = String::new();
parse_sexprs(&printed)[0].write_to(&mut again);
assert_eq!(again, printed);
}
#[test]
fn line_comment_is_skipped() {
let exprs = parse_sexprs("; a comment\n(a b)");
assert_eq!(exprs.len(), 1);
}
#[test]
fn escaped_quote_inside_string() {
let exprs = parse_sexprs(r#"(k "a\"b")"#);
let SExpr::List(items) = &exprs[0] else {
panic!("expected list")
};
assert_eq!(atom(&items[1]), Some("a\"b"));
}
#[test]
fn depth_guard_bounds_recursion() {
// Far deeper than MAX_SEXPR_DEPTH — must not overflow the stack and
// must still return (truncated) rather than panic.
let deep = format!("{}{}", "(".repeat(10_000), ")".repeat(10_000));
let exprs = parse_sexprs(&deep);
assert_eq!(exprs.len(), 1);
}
#[test]
fn unterminated_quoted_string_does_not_panic() {
// EOF inside a quoted string — tokenizer must break out of the loop
// rather than panic or loop infinitely.
let exprs = parse_sexprs(r#"(k "unterminated"#);
// Produces one list containing the atom "k" plus the partial string.
assert_eq!(exprs.len(), 1);
}
#[test]
fn unclosed_parenthesis_does_not_panic() {
// EOF inside a list — parser must break out rather than panic.
let exprs = parse_sexprs("(unclosed");
assert_eq!(exprs.len(), 1);
}
#[test]
fn unclosed_quoted_string_does_not_panic() {
// Line 98: EOF inside a quoted string — tokenizer hits None => break.
let exprs = parse_sexprs("\"unclosed");
assert_eq!(exprs.len(), 1);
assert_eq!(atom(&exprs[0]), Some("unclosed"));
}
}