Skip to main content

lean_ctx/core/
jsonc.rs

1use serde_json::Value;
2
3/// Strip `//` line comments, `/* */` block comments and trailing commas from
4/// JSONC, then parse with serde_json. String contents are preserved verbatim.
5///
6/// This makes lean-ctx tolerant of the JSONC dialect that editors like VS Code
7/// use for `settings.json` / `mcp.json` (comments + trailing commas are valid
8/// there but rejected by strict JSON). See issue #311.
9///
10/// A single leading UTF-8 BOM is also accepted. Windows editors emit it
11/// routinely, serde_json rejects it, and callers used to read that rejection as
12/// "config is corrupt" and scaffold a fresh one over the user's file (#1586).
13pub fn parse_jsonc(input: &str) -> Result<Value, serde_json::Error> {
14    let input = input.strip_prefix('\u{feff}').unwrap_or(input);
15    let stripped = strip_json_comments(input);
16    let cleaned = strip_trailing_commas(&stripped);
17    serde_json::from_str(&cleaned)
18}
19
20fn strip_json_comments(input: &str) -> String {
21    let bytes = input.as_bytes();
22    let len = bytes.len();
23    let mut out = String::with_capacity(len);
24    let mut i = 0;
25    let mut seg = 0;
26
27    while i < len {
28        let b = bytes[i];
29
30        if b == b'"' {
31            i += 1;
32            while i < len {
33                let c = bytes[i];
34                i += 1;
35                if c == b'\\' && i < len {
36                    i += 1;
37                } else if c == b'"' {
38                    break;
39                }
40            }
41            continue;
42        }
43
44        if b == b'/' && i + 1 < len {
45            if bytes[i + 1] == b'/' {
46                out.push_str(&input[seg..i]);
47                i += 2;
48                while i < len && bytes[i] != b'\n' {
49                    i += 1;
50                }
51                seg = i;
52                continue;
53            }
54            if bytes[i + 1] == b'*' {
55                out.push_str(&input[seg..i]);
56                i += 2;
57                while i + 1 < len {
58                    if bytes[i] == b'*' && bytes[i + 1] == b'/' {
59                        i += 2;
60                        break;
61                    }
62                    i += 1;
63                }
64                seg = i;
65                continue;
66            }
67        }
68
69        i += 1;
70    }
71
72    out.push_str(&input[seg..]);
73    out
74}
75
76/// Remove trailing commas that appear before a closing `}` or `]`.
77/// String contents are preserved verbatim (commas inside strings are ignored).
78///
79/// Operates on already comment-stripped input. Uses byte-segment copying so
80/// multi-byte UTF-8 sequences are never split (all decision bytes are ASCII).
81fn strip_trailing_commas(input: &str) -> String {
82    let bytes = input.as_bytes();
83    let len = bytes.len();
84    let mut out = String::with_capacity(len);
85    let mut i = 0;
86    let mut seg = 0;
87
88    while i < len {
89        let b = bytes[i];
90
91        if b == b'"' {
92            i += 1;
93            while i < len {
94                let c = bytes[i];
95                i += 1;
96                if c == b'\\' && i < len {
97                    i += 1;
98                } else if c == b'"' {
99                    break;
100                }
101            }
102            continue;
103        }
104
105        if b == b',' {
106            let mut j = i + 1;
107            while j < len && bytes[j].is_ascii_whitespace() {
108                j += 1;
109            }
110            if j < len && (bytes[j] == b'}' || bytes[j] == b']') {
111                out.push_str(&input[seg..i]);
112                i += 1;
113                seg = i;
114                continue;
115            }
116        }
117
118        i += 1;
119    }
120
121    out.push_str(&input[seg..]);
122    out
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn leading_bom_is_accepted() {
131        // #1586: Windows editors save configs BOM-prefixed. serde_json rejects
132        // that, and callers read the rejection as "file is corrupt".
133        let v = parse_jsonc("\u{feff}{\n  // hi\n  \"a\": 1,\n}").expect("BOM config must parse");
134        assert_eq!(v["a"], 1);
135    }
136
137    #[test]
138    fn only_one_leading_bom_is_stripped() {
139        assert!(parse_jsonc("\u{feff}\u{feff}{\"a\":1}").is_err());
140    }
141
142    #[test]
143    fn strips_line_comments() {
144        let input = r#"{
145  // this is a comment
146  "key": "value"
147}"#;
148        let v = parse_jsonc(input).unwrap();
149        assert_eq!(v["key"], "value");
150    }
151
152    #[test]
153    fn strips_block_comments() {
154        let input = r#"{
155  /* block
156     comment */
157  "key": "value"
158}"#;
159        let v = parse_jsonc(input).unwrap();
160        assert_eq!(v["key"], "value");
161    }
162
163    #[test]
164    fn preserves_slashes_in_strings() {
165        let input = r#"{"url": "https://example.com/path"}"#;
166        let v = parse_jsonc(input).unwrap();
167        assert_eq!(v["url"], "https://example.com/path");
168    }
169
170    #[test]
171    fn preserves_comment_like_content_in_strings() {
172        let input = r#"{"note": "see // inline", "code": "/* not a comment */"}"#;
173        let v = parse_jsonc(input).unwrap();
174        assert_eq!(v["note"], "see // inline");
175        assert_eq!(v["code"], "/* not a comment */");
176    }
177
178    #[test]
179    fn handles_escaped_quotes_in_strings() {
180        let input = r#"{"msg": "say \"hello\" // world"}"#;
181        let v = parse_jsonc(input).unwrap();
182        assert_eq!(v["msg"], r#"say "hello" // world"#);
183    }
184
185    #[test]
186    fn handles_trailing_comma_free_json() {
187        let input = r#"{
188  "a": 1,
189  // comment between entries
190  "b": 2
191}"#;
192        let v = parse_jsonc(input).unwrap();
193        assert_eq!(v["a"], 1);
194        assert_eq!(v["b"], 2);
195    }
196
197    #[test]
198    fn empty_input() {
199        assert!(parse_jsonc("").is_err());
200    }
201
202    // --- #311: trailing comma support (VS Code / JSONC dialect) ---
203
204    #[test]
205    fn strips_trailing_comma_in_object() {
206        let input = r#"{
207  "a": 1,
208  "b": 2,
209}"#;
210        let v = parse_jsonc(input).unwrap();
211        assert_eq!(v["a"], 1);
212        assert_eq!(v["b"], 2);
213    }
214
215    #[test]
216    fn strips_trailing_comma_in_array() {
217        let input = r#"{"list": [1, 2, 3,]}"#;
218        let v = parse_jsonc(input).unwrap();
219        assert_eq!(v["list"][2], 3);
220    }
221
222    #[test]
223    fn strips_trailing_comma_with_whitespace_and_newlines() {
224        let input = "{\n  \"a\": 1  ,\n\n}";
225        let v = parse_jsonc(input).unwrap();
226        assert_eq!(v["a"], 1);
227    }
228
229    #[test]
230    fn strips_nested_trailing_commas() {
231        let input = r#"{
232  "outer": {
233    "inner": [
234      "x",
235      "y",
236    ],
237  },
238}"#;
239        let v = parse_jsonc(input).unwrap();
240        assert_eq!(v["outer"]["inner"][1], "y");
241    }
242
243    #[test]
244    fn preserves_comma_inside_string_before_brace() {
245        // A comma inside a string value must not be treated as trailing.
246        let input = r#"{"msg": "hello, world"}"#;
247        let v = parse_jsonc(input).unwrap();
248        assert_eq!(v["msg"], "hello, world");
249    }
250
251    #[test]
252    fn issue_311_vscode_settings_with_trailing_comma_and_comments() {
253        // Mirrors the real VS Code user settings.json that triggered #311:
254        // "trailing comma at line 4 column 5" plus JSONC comments.
255        let input = r#"{
256  // editor settings
257  "editor.fontSize": 14,
258  "editor.tabSize": 2,
259  "chat.mcp.enabled": true,
260}"#;
261        let v = parse_jsonc(input).unwrap();
262        assert_eq!(v["editor.fontSize"], 14);
263        assert!(v["chat.mcp.enabled"].as_bool().unwrap());
264    }
265
266    #[test]
267    fn pure_json_passthrough() {
268        let input = r#"{"key": "value", "num": 42}"#;
269        let v = parse_jsonc(input).unwrap();
270        assert_eq!(v["key"], "value");
271        assert_eq!(v["num"], 42);
272    }
273
274    #[test]
275    fn real_opencode_config_with_comments() {
276        let input = r#"{
277  // OpenCode configuration
278  "$schema": "https://opencode.ai/config.json",
279  "mcp": {
280    /* existing tool */
281    "my-tool": {
282      "type": "local",
283      "command": ["my-tool"],
284      "enabled": true
285    }
286  }
287}"#;
288        let v = parse_jsonc(input).unwrap();
289        assert_eq!(v["$schema"], "https://opencode.ai/config.json");
290        assert!(v["mcp"]["my-tool"]["enabled"].as_bool().unwrap());
291    }
292
293    #[test]
294    fn utf8_umlauts_preserved() {
295        let input = "{\n  // German names\n  \"name\": \"Müller\",\n  \"city\": \"Zürich\"\n}";
296        let v = parse_jsonc(input).unwrap();
297        assert_eq!(v["name"], "Müller");
298        assert_eq!(v["city"], "Zürich");
299    }
300
301    #[test]
302    fn utf8_cjk_with_block_comment() {
303        let input = "{\n  /* 日本語コメント */\n  \"desc\": \"日本語テスト\"\n}";
304        let v = parse_jsonc(input).unwrap();
305        assert_eq!(v["desc"], "日本語テスト");
306    }
307
308    #[test]
309    fn utf8_emoji_between_comments() {
310        let input = "{\n  // before\n  \"icon\": \"🚀🔥\",\n  /* after */\n  \"ok\": true\n}";
311        let v = parse_jsonc(input).unwrap();
312        assert_eq!(v["icon"], "🚀🔥");
313        assert!(v["ok"].as_bool().unwrap());
314    }
315
316    #[test]
317    fn utf8_in_comment_stripped_cleanly() {
318        let input = "{\n  // Achtung: ä ö ü ß\n  \"key\": \"value\"\n}";
319        let v = parse_jsonc(input).unwrap();
320        assert_eq!(v["key"], "value");
321    }
322
323    #[test]
324    fn utf8_in_key() {
325        let input = "{\"straße\": \"Hauptstraße 42\"}";
326        let v = parse_jsonc(input).unwrap();
327        assert_eq!(v["straße"], "Hauptstraße 42");
328    }
329
330    #[test]
331    fn mixed_ascii_and_utf8_values() {
332        let input = "{\n  // config\n  \"en\": \"hello\",\n  \"ru\": \"привет\",\n  \"jp\": \"こんにちは\"\n}";
333        let v = parse_jsonc(input).unwrap();
334        assert_eq!(v["en"], "hello");
335        assert_eq!(v["ru"], "привет");
336        assert_eq!(v["jp"], "こんにちは");
337    }
338
339    #[test]
340    fn escaped_unicode_unchanged() {
341        let input = r#"{"test": "\u00e4\u00f6\u00fc"}"#;
342        let v = parse_jsonc(input).unwrap();
343        assert_eq!(v["test"], "\u{00e4}\u{00f6}\u{00fc}");
344    }
345
346    #[test]
347    fn utf8_at_comment_boundary() {
348        let input = "{\n  \"before\": \"текст\"// комментарий\n, \"after\": 1\n}";
349        let v = parse_jsonc(input).unwrap();
350        assert_eq!(v["before"], "текст");
351        assert_eq!(v["after"], 1);
352    }
353
354    #[test]
355    fn empty_string_after_utf8_comment() {
356        let input = "{\n  // Ü\n  \"key\": \"\"\n}";
357        let v = parse_jsonc(input).unwrap();
358        assert_eq!(v["key"], "");
359    }
360
361    #[test]
362    fn real_claude_settings_with_german_paths() {
363        let input = r#"{
364  // Claude Code Einstellungen
365  "mcpServers": {
366    /* Lean-CTX Konfiguration für /Users/müller/Projekte */
367    "lean-ctx": {
368      "command": "/Users/müller/.local/bin/lean-ctx",
369      "args": ["--project", "/Users/müller/Projekte/größtes-projekt"]
370    }
371  }
372}"#;
373        let v = parse_jsonc(input).unwrap();
374        assert_eq!(
375            v["mcpServers"]["lean-ctx"]["command"],
376            "/Users/müller/.local/bin/lean-ctx"
377        );
378        let args = v["mcpServers"]["lean-ctx"]["args"].as_array().unwrap();
379        assert_eq!(args[1], "/Users/müller/Projekte/größtes-projekt");
380    }
381}