Skip to main content

atmos/os_lib/
json.rs

1// src/json.rs - Lightweight JSON parser and serializer for AtmOS
2#![allow(dead_code)]
3
4extern crate alloc;
5use alloc::collections::BTreeMap;
6use alloc::string::String;
7use alloc::vec::Vec;
8use core::iter::Peekable;
9use core::str::Chars;
10
11#[derive(Debug, Clone, PartialEq)]
12pub enum JsonValue {
13    Null,
14    Bool(bool),
15    Number(f64),
16    String(String),
17    Array(Vec<JsonValue>),
18    Object(BTreeMap<String, JsonValue>),
19    /// キーの出現順を保つオブジェクト(`parse_js` が返す。JS の `JSON.parse` 用)。
20    OrderedObject(Vec<(String, JsonValue)>),
21}
22
23/// 解析の設定。起動時の設定ファイルと JS の `JSON.parse` では事情が違う。
24#[derive(Clone, Copy)]
25struct Options {
26    /// ネストの上限(ネイティブの再帰の深さ)。
27    max_depth: usize,
28    /// オブジェクトのキーの順序を保つ(`OrderedObject` で返す)。
29    ordered: bool,
30}
31
32const NATIVE: Options = Options { max_depth: 30, ordered: false };
33/// JS は大きなスタックのスレッドで動くので深く読める(YouTube の `next` の応答は深さ 36。上限 30 では
34/// `JSON.parse` が失敗し、自動再生の後の視聴ページがオフラインの代替表示になっていた、2026-11-01)。
35const JS: Options = Options { max_depth: 512, ordered: true };
36
37pub fn parse(input: &str) -> Result<JsonValue, String> {
38    let mut chars = input.chars().peekable();
39    parse_value(&mut chars, 0, NATIVE)
40}
41
42/// JS の `JSON.parse` 用: 深いネストを読み、キーの順序を保ち、値の後の余りを拒否する。
43pub fn parse_js(input: &str) -> Result<JsonValue, String> {
44    let mut chars = input.chars().peekable();
45    let v = parse_value(&mut chars, 0, JS)?;
46    skip_whitespace(&mut chars);
47    match chars.peek() {
48        Some(c) => Err(alloc::format!("Unexpected character after value: {}", c)),
49        None => Ok(v),
50    }
51}
52
53pub use parse as parse_json;
54
55fn skip_whitespace(chars: &mut Peekable<Chars>) {
56    while let Some(&c) = chars.peek() {
57        if c.is_whitespace() {
58            chars.next();
59        } else {
60            break;
61        }
62    }
63}
64
65// `depth` はRustのネイティブ再帰(`parse_value`→`parse_array`/`parse_object`→
66// `parse_value`…の相互再帰)による呼出しの深さを追跡する。この処理系はブート時点の
67// 初期コアスタックがわずか64KB(`boot.S`の`(CoreID+1)*64KB`)しか無く、`structuredClone`
68// の深いネスト保護テストで一度実際にRustコールスタックオーバーフローによる無応答を
69// 起こしている(2026-07-18、walkthrough.md参照)。同じ危険性が`JSON.parse`(この関数の
70// JS側入口)にも及ぶため、既定は同じ閾値30で打ち切る(JS 用は `JS` の設定)。
71fn parse_value(chars: &mut Peekable<Chars>, depth: usize, opts: Options) -> Result<JsonValue, String> {
72    if depth > opts.max_depth {
73        return Err(String::from("Maximum nesting depth exceeded"));
74    }
75    skip_whitespace(chars);
76    match chars.peek() {
77        Some(&'n') => parse_null(chars),
78        Some(&'t') | Some(&'f') => parse_bool(chars),
79        Some(&'"') => parse_string(chars).map(JsonValue::String),
80        Some(&'[') => parse_array(chars, depth, opts),
81        Some(&'{') => parse_object(chars, depth, opts),
82        Some(&c) if c == '-' || c.is_ascii_digit() => parse_number(chars),
83        Some(c) => Err(alloc::format!("Unexpected character: {}", c)),
84        None => Err(String::from("Unexpected end of input")),
85    }
86}
87
88fn parse_null(chars: &mut Peekable<Chars>) -> Result<JsonValue, String> {
89    let expected = "null";
90    for ec in expected.chars() {
91        if chars.next() != Some(ec) {
92            return Err(String::from("Expected null"));
93        }
94    }
95    Ok(JsonValue::Null)
96}
97
98fn parse_bool(chars: &mut Peekable<Chars>) -> Result<JsonValue, String> {
99    let is_true = chars.peek() == Some(&'t');
100    let expected = if is_true { "true" } else { "false" };
101    for ec in expected.chars() {
102        if chars.next() != Some(ec) {
103            return Err(String::from("Expected bool"));
104        }
105    }
106    Ok(JsonValue::Bool(is_true))
107}
108
109fn parse_string(chars: &mut Peekable<Chars>) -> Result<String, String> {
110    chars.next(); // consume '"'
111    let mut s = String::new();
112    while let Some(&c) = chars.peek() {
113        if c == '"' {
114            chars.next();
115            return Ok(s);
116        } else if c == '\\' {
117            chars.next();
118            if let Some(ec) = chars.next() {
119                match ec {
120                    '"' => s.push('"'),
121                    '\\' => s.push('\\'),
122                    '/' => s.push('/'),
123                    'b' => s.push('\x08'),
124                    'f' => s.push('\x0C'),
125                    'n' => s.push('\n'),
126                    'r' => s.push('\r'),
127                    't' => s.push('\t'),
128                    'u' => s.push(parse_unicode_escape(chars)?),
129                    _ => s.push(ec), // simplisitc fallback
130                }
131            } else {
132                return Err(String::from("Unexpected end of input in escape sequence"));
133            }
134        } else {
135            s.push(c);
136            chars.next();
137        }
138    }
139    Err(String::from("Unterminated string"))
140}
141
142/// `\\u` の後の 16 進 4 桁。
143fn parse_hex4(chars: &mut Peekable<Chars>) -> Result<u32, String> {
144    let mut v = 0u32;
145    for _ in 0..4 {
146        let d = chars.next().and_then(|c| c.to_digit(16));
147        v = v * 16 + d.ok_or_else(|| String::from("Invalid unicode escape"))?;
148    }
149    Ok(v)
150}
151
152/// `\\uXXXX`(`\\u` は読み終えた位置)。サロゲートペアは 1 文字にまとめる。対になっていない
153/// サロゲートは Rust の文字列に入らないので置換文字にする。
154fn parse_unicode_escape(chars: &mut Peekable<Chars>) -> Result<char, String> {
155    let hi = parse_hex4(chars)?;
156    if (0xD800..0xDC00).contains(&hi) {
157        let mut ahead = chars.clone();
158        if ahead.next() == Some('\\') && ahead.next() == Some('u') {
159            if let Ok(lo) = parse_hex4(&mut ahead) {
160                if (0xDC00..0xE000).contains(&lo) {
161                    *chars = ahead;
162                    let cp = 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00);
163                    return Ok(char::from_u32(cp).unwrap_or('\u{FFFD}'));
164                }
165            }
166        }
167    }
168    Ok(char::from_u32(hi).unwrap_or('\u{FFFD}'))
169}
170
171fn parse_number(chars: &mut Peekable<Chars>) -> Result<JsonValue, String> {
172    let mut buf = [0u8; 64];
173    let mut len = 0usize;
174    while let Some(&c) = chars.peek() {
175        if c == '-' || c == '+' || c == '.' || c == 'e' || c == 'E' || c.is_ascii_digit() {
176            if len < buf.len() && c.is_ascii() {
177                buf[len] = c as u8;
178                len += 1;
179            }
180            chars.next();
181        } else {
182            break;
183        }
184    }
185    if let Ok(s) = core::str::from_utf8(&buf[..len]) {
186        match s.parse::<f64>() {
187            Ok(n) => Ok(JsonValue::Number(n)),
188            Err(_) => Err(alloc::format!("Invalid number: {}", s)),
189        }
190    } else {
191        Err(String::from("Invalid UTF-8 in number"))
192    }
193}
194
195fn parse_array(chars: &mut Peekable<Chars>, depth: usize, opts: Options) -> Result<JsonValue, String> {
196    chars.next(); // consume '['
197    let mut arr = Vec::new();
198    skip_whitespace(chars);
199    if chars.peek() == Some(&']') {
200        chars.next();
201        return Ok(JsonValue::Array(arr));
202    }
203    loop {
204        arr.push(parse_value(chars, depth + 1, opts)?);
205        skip_whitespace(chars);
206        match chars.next() {
207            Some(',') => continue,
208            Some(']') => break,
209            _ => return Err(String::from("Expected ',' or ']' in array")),
210        }
211    }
212    Ok(JsonValue::Array(arr))
213}
214
215fn parse_object(chars: &mut Peekable<Chars>, depth: usize, opts: Options) -> Result<JsonValue, String> {
216    chars.next(); // consume '{'
217    let mut items: Vec<(String, JsonValue)> = Vec::new();
218    skip_whitespace(chars);
219    if chars.peek() == Some(&'}') {
220        chars.next();
221        return Ok(make_object(items, opts));
222    }
223    loop {
224        skip_whitespace(chars);
225        if chars.peek() != Some(&'"') {
226            return Err(String::from("Expected string key in object"));
227        }
228        let key = parse_string(chars)?;
229        skip_whitespace(chars);
230        if chars.next() != Some(':') {
231            return Err(String::from("Expected ':' after key"));
232        }
233        let val = parse_value(chars, depth + 1, opts)?;
234        items.push((key, val));
235        skip_whitespace(chars);
236        match chars.next() {
237            Some(',') => continue,
238            Some('}') => break,
239            _ => return Err(String::from("Expected ',' or '}' in object")),
240        }
241    }
242    Ok(make_object(items, opts))
243}
244
245fn make_object(items: Vec<(String, JsonValue)>, opts: Options) -> JsonValue {
246    if opts.ordered {
247        JsonValue::OrderedObject(items)
248    } else {
249        JsonValue::Object(items.into_iter().collect())
250    }
251}
252
253pub fn to_string(value: &JsonValue) -> String {
254    let mut out = String::new();
255    stringify_to(value, &mut out);
256    out
257}
258
259pub fn stringify_to(value: &JsonValue, out: &mut String) {
260    match value {
261        JsonValue::Null => out.push_str("null"),
262        JsonValue::Bool(true) => out.push_str("true"),
263        JsonValue::Bool(false) => out.push_str("false"),
264        JsonValue::Number(n) => {
265            use core::fmt::Write;
266            let _ = write!(out, "{}", n);
267        }
268        JsonValue::String(s) => {
269            out.push('"');
270            for c in s.chars() {
271                match c {
272                    '"' => out.push_str("\\\""),
273                    '\\' => out.push_str("\\\\"),
274                    '\n' => out.push_str("\\n"),
275                    '\r' => out.push_str("\\r"),
276                    '\t' => out.push_str("\\t"),
277                    c => out.push(c),
278                }
279            }
280            out.push('"');
281        }
282        JsonValue::Array(arr) => {
283            out.push('[');
284            for (i, v) in arr.iter().enumerate() {
285                if i > 0 {
286                    out.push_str(", ");
287                }
288                stringify_to(v, out);
289            }
290            out.push(']');
291        }
292        JsonValue::Object(obj) => stringify_object(obj.iter(), out),
293        JsonValue::OrderedObject(items) => stringify_object(items.iter().map(|(k, v)| (k, v)), out),
294    }
295}
296
297fn stringify_object<'a>(items: impl Iterator<Item = (&'a String, &'a JsonValue)>, out: &mut String) {
298    out.push('{');
299    let mut first = true;
300    for (k, v) in items {
301        if !first {
302            out.push_str(", ");
303        }
304        first = false;
305        out.push('"');
306        out.push_str(k);
307        out.push_str("\": ");
308        stringify_to(v, out);
309    }
310    out.push('}');
311}