Skip to main content

strata_js/
json.rs

1//! Zero-dependency, pure-Rust JSON parser and serializer for JsValue.
2
3use crate::JsValue;
4use std::collections::BTreeMap;
5
6/// Parses a JSON string into a dynamic `JsValue`.
7pub fn parse_json(input: &str) -> Result<JsValue, String> {
8    let mut chars = input.chars().peekable();
9    skip_whitespace(&mut chars);
10    let val = parse_value(&mut chars)?;
11    skip_whitespace(&mut chars);
12    if chars.peek().is_some() {
13        return Err("Unexpected trailing characters after JSON value".to_string());
14    }
15    Ok(val)
16}
17
18const MAX_JSON_DEPTH: usize = 512;
19
20/// Serializes a `JsValue` into a standard JSON string.
21/// Returns an error if a circular reference is detected or maximum depth is exceeded.
22pub fn stringify_json(val: &JsValue) -> Result<String, String> {
23    let mut out = String::new();
24    let mut stack = Vec::new();
25    serialize_value(val, &mut out, &mut stack, 0)?;
26    Ok(out)
27}
28
29fn skip_whitespace<I: Iterator<Item = char>>(chars: &mut std::iter::Peekable<I>) {
30    while let Some(&c) = chars.peek() {
31        if c.is_whitespace() {
32            chars.next();
33        } else {
34            break;
35        }
36    }
37}
38
39fn parse_value<I: Iterator<Item = char>>(
40    chars: &mut std::iter::Peekable<I>,
41) -> Result<JsValue, String> {
42    skip_whitespace(chars);
43    match chars.peek() {
44        Some('{') => parse_object(chars),
45        Some('[') => parse_array(chars),
46        Some('"') => parse_string(chars).map(JsValue::String),
47        Some('t') | Some('f') => parse_bool(chars),
48        Some('n') => parse_null(chars),
49        Some('u') => parse_undefined(chars),
50        Some(&c) if c == '-' || c.is_ascii_digit() => parse_number(chars),
51        Some(&c) => Err(format!("Unexpected character '{}' while parsing JSON", c)),
52        None => Err("Unexpected end of input while parsing JSON".to_string()),
53    }
54}
55
56fn parse_object<I: Iterator<Item = char>>(
57    chars: &mut std::iter::Peekable<I>,
58) -> Result<JsValue, String> {
59    chars.next(); // consume '{'
60    skip_whitespace(chars);
61
62    let mut map = BTreeMap::new();
63
64    if let Some(&'}') = chars.peek() {
65        chars.next();
66        return Ok(JsValue::new_object(map));
67    }
68
69    loop {
70        skip_whitespace(chars);
71        let key = match chars.peek() {
72            Some('"') => parse_string(chars)?,
73            Some(&c) => return Err(format!("Expected string key in object, found '{}'", c)),
74            None => return Err("Unexpected end of object".to_string()),
75        };
76
77        skip_whitespace(chars);
78        if chars.next() != Some(':') {
79            return Err("Expected ':' after object key".to_string());
80        }
81
82        let val = parse_value(chars)?;
83        if key != "__proto__" {
84            map.insert(key, val);
85        }
86
87        skip_whitespace(chars);
88        match chars.next() {
89            Some(',') => {
90                skip_whitespace(chars);
91                // Allow trailing comma gracefully
92                if let Some(&'}') = chars.peek() {
93                    chars.next();
94                    break;
95                }
96            }
97            Some('}') => break,
98            Some(c) => return Err(format!("Expected ',' or '}}' in object, found '{}'", c)),
99            None => return Err("Unterminated object: missing '}'".to_string()),
100        }
101    }
102
103    Ok(JsValue::new_object(map))
104}
105
106fn parse_array<I: Iterator<Item = char>>(
107    chars: &mut std::iter::Peekable<I>,
108) -> Result<JsValue, String> {
109    chars.next(); // consume '['
110    skip_whitespace(chars);
111
112    let mut items = Vec::new();
113
114    if let Some(&']') = chars.peek() {
115        chars.next();
116        return Ok(JsValue::new_array(items));
117    }
118
119    loop {
120        let val = parse_value(chars)?;
121        items.push(val);
122
123        skip_whitespace(chars);
124        match chars.next() {
125            Some(',') => {
126                skip_whitespace(chars);
127                // Allow trailing comma gracefully
128                if let Some(&']') = chars.peek() {
129                    chars.next();
130                    break;
131                }
132            }
133            Some(']') => break,
134            Some(c) => return Err(format!("Expected ',' or ']' in array, found '{}'", c)),
135            None => return Err("Unterminated array: missing ']'".to_string()),
136        }
137    }
138
139    Ok(JsValue::new_array(items))
140}
141
142fn parse_string<I: Iterator<Item = char>>(
143    chars: &mut std::iter::Peekable<I>,
144) -> Result<String, String> {
145    chars.next(); // consume opening '"'
146    let mut s = String::new();
147
148    while let Some(c) = chars.next() {
149        match c {
150            '"' => return Ok(s),
151            '\\' => match chars.next() {
152                Some('"') => s.push('"'),
153                Some('\\') => s.push('\\'),
154                Some('/') => s.push('/'),
155                Some('b') => s.push('\x08'),
156                Some('f') => s.push('\x0C'),
157                Some('n') => s.push('\n'),
158                Some('r') => s.push('\r'),
159                Some('t') => s.push('\t'),
160                Some('u') => {
161                    let mut hex = String::with_capacity(4);
162                    for _ in 0..4 {
163                        if let Some(h) = chars.next() {
164                            hex.push(h);
165                        } else {
166                            return Err("Unterminated unicode escape in string".to_string());
167                        }
168                    }
169                    if let Ok(code) = u32::from_str_radix(&hex, 16) {
170                        if let Some(ch) = char::from_u32(code) {
171                            s.push(ch);
172                        } else {
173                            return Err(format!("Invalid unicode codepoint: \\u{}", hex));
174                        }
175                    } else {
176                        return Err(format!("Invalid hex digits in \\u{}", hex));
177                    }
178                }
179                Some(other) => return Err(format!("Invalid escape character: \\{}", other)),
180                None => return Err("Unterminated escape sequence in string".to_string()),
181            },
182            other => s.push(other),
183        }
184    }
185
186    Err("Unterminated string: missing closing quote".to_string())
187}
188
189fn parse_number<I: Iterator<Item = char>>(
190    chars: &mut std::iter::Peekable<I>,
191) -> Result<JsValue, String> {
192    let mut num_str = String::new();
193
194    if let Some(&'-') = chars.peek() {
195        num_str.push(chars.next().unwrap());
196    }
197
198    while let Some(&c) = chars.peek() {
199        if c.is_ascii_digit() || c == '.' || c == 'e' || c == 'E' || c == '+' || c == '-' {
200            num_str.push(chars.next().unwrap());
201        } else {
202            break;
203        }
204    }
205
206    match num_str.parse::<f64>() {
207        Ok(n) => Ok(JsValue::Number(n)),
208        Err(_) => Err(format!("Invalid numeric literal: '{}'", num_str)),
209    }
210}
211
212fn parse_bool<I: Iterator<Item = char>>(
213    chars: &mut std::iter::Peekable<I>,
214) -> Result<JsValue, String> {
215    let mut ident = String::new();
216    while let Some(&c) = chars.peek() {
217        if c.is_ascii_alphabetic() {
218            ident.push(chars.next().unwrap());
219        } else {
220            break;
221        }
222    }
223
224    match ident.as_str() {
225        "true" => Ok(JsValue::Bool(true)),
226        "false" => Ok(JsValue::Bool(false)),
227        _ => Err(format!("Unexpected identifier: '{}'", ident)),
228    }
229}
230
231fn parse_null<I: Iterator<Item = char>>(
232    chars: &mut std::iter::Peekable<I>,
233) -> Result<JsValue, String> {
234    let mut ident = String::new();
235    while let Some(&c) = chars.peek() {
236        if c.is_ascii_alphabetic() {
237            ident.push(chars.next().unwrap());
238        } else {
239            break;
240        }
241    }
242
243    if ident == "null" {
244        Ok(JsValue::Null)
245    } else {
246        Err(format!("Unexpected identifier: '{}'", ident))
247    }
248}
249
250fn parse_undefined<I: Iterator<Item = char>>(
251    chars: &mut std::iter::Peekable<I>,
252) -> Result<JsValue, String> {
253    let mut ident = String::new();
254    while let Some(&c) = chars.peek() {
255        if c.is_ascii_alphabetic() {
256            ident.push(chars.next().unwrap());
257        } else {
258            break;
259        }
260    }
261
262    if ident == "undefined" {
263        Ok(JsValue::Undefined)
264    } else {
265        Err(format!("Unexpected identifier: '{}'", ident))
266    }
267}
268
269fn serialize_value(
270    val: &JsValue,
271    out: &mut String,
272    stack: &mut Vec<*const ()>,
273    depth: usize,
274) -> Result<(), String> {
275    if depth > MAX_JSON_DEPTH {
276        return Err("RangeError: Maximum call stack size exceeded".to_string());
277    }
278
279    match val {
280        JsValue::Undefined | JsValue::Null | JsValue::Function(_) | JsValue::Symbol(_) => {
281            out.push_str("null");
282        }
283        JsValue::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
284        JsValue::Number(n) => {
285            if n.is_nan() || n.is_infinite() {
286                out.push_str("null");
287            } else if n.fract() == 0.0 && *n >= (i64::MIN as f64) && *n <= (i64::MAX as f64) {
288                out.push_str(&format!("{}", *n as i64));
289            } else {
290                out.push_str(&format!("{}", n));
291            }
292        }
293        JsValue::String(s) => {
294            out.push('"');
295            for c in s.chars() {
296                match c {
297                    '"' => out.push_str("\\\""),
298                    '\\' => out.push_str("\\\\"),
299                    '\n' => out.push_str("\\n"),
300                    '\r' => out.push_str("\\r"),
301                    '\t' => out.push_str("\\t"),
302                    '\x08' => out.push_str("\\b"),
303                    '\x0C' => out.push_str("\\f"),
304                    other if other.is_control() => {
305                        out.push_str(&format!("\\u{:04x}", other as u32));
306                    }
307                    other => out.push(other),
308                }
309            }
310            out.push('"');
311        }
312        JsValue::BigInt(bi) => out.push_str(&bi.to_decimal_string()),
313        JsValue::Array(items) => {
314            let ptr = std::rc::Rc::as_ptr(items) as *const ();
315            if stack.contains(&ptr) {
316                return Err("TypeError: Converting circular structure to JSON".to_string());
317            }
318            stack.push(ptr);
319            out.push('[');
320            let borrowed = items.borrow();
321            for (i, item) in borrowed.iter().enumerate() {
322                if i > 0 {
323                    out.push(',');
324                }
325                if let Err(e) = serialize_value(item, out, stack, depth + 1) {
326                    stack.pop();
327                    return Err(e);
328                }
329            }
330            out.push(']');
331            stack.pop();
332        }
333        JsValue::Object(map) => {
334            let ptr = std::rc::Rc::as_ptr(map) as *const ();
335            if stack.contains(&ptr) {
336                return Err("TypeError: Converting circular structure to JSON".to_string());
337            }
338            stack.push(ptr);
339            out.push('{');
340            let borrowed = map.borrow();
341            for (i, (k, v)) in borrowed.iter().enumerate() {
342                if i > 0 {
343                    out.push(',');
344                }
345                out.push('"');
346                for c in k.chars() {
347                    if c == '"' {
348                        out.push_str("\\\"");
349                    } else if c == '\\' {
350                        out.push_str("\\\\");
351                    } else {
352                        out.push(c);
353                    }
354                }
355                out.push_str("\":");
356                if let Err(e) = serialize_value(v, out, stack, depth + 1) {
357                    stack.pop();
358                    return Err(e);
359                }
360            }
361            out.push('}');
362            stack.pop();
363        }
364        JsValue::Promise(_) => {
365            out.push_str("{}");
366        }
367    }
368    Ok(())
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374    use std::cell::RefCell;
375    use std::rc::Rc;
376
377    #[test]
378    fn test_circular_json_rejection() {
379        let map = Rc::new(RefCell::new(BTreeMap::new()));
380        let obj = JsValue::Object(map.clone());
381        map.borrow_mut().insert("self".to_string(), obj.clone());
382        assert!(stringify_json(&obj).is_err());
383    }
384}