| 49 | |
| 50 | // JSONC only uses the strict mode to locate errors after JSON.parse fails. |
| 51 | export const parse = (text: string, format: Format): unknown => { |
| 52 | const json5 = format === "JSON5" |
| 53 | const space = json5 ? json5Space : jsoncSpace |
| 54 | // JSON strings forbid raw characters below U+0020; JSON5 strings only forbid line breaks. |
| 55 | const plainFloor = json5 ? 0 : 0x20 |
| 56 | let i = 0 |
| 57 | |
| 58 | const fail = (at: number): never => { |
| 59 | throw syntaxError(text, at, format) |
| 60 | } |
| 61 | |
| 62 | /** Skips whitespace and comments, rejecting a `/` that starts neither. */ |
| 63 | const skip = () => { |
| 64 | // ASCII whitespace dominates formatted documents; the pattern handles the rest. |
| 65 | let code = text.charCodeAt(i) |
| 66 | while (code === 0x20 || code === 0x0a || code === 0x0d || code === 0x09) code = text.charCodeAt(++i) |
| 67 | if (code > 0x20 && code !== 0x2f && code < 0xa0) return |
| 68 | space.lastIndex = i |
| 69 | space.test(text) |
| 70 | i = space.lastIndex |
| 71 | if (text.charCodeAt(i) === 0x2f) { |
| 72 | fail(text.charAt(i + 1) === "*" ? text.length : i + 1) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /** Advances past a sticky pattern at `i`, returning the matched length. */ |
| 77 | const run = (pattern: RegExp) => { |
| 78 | pattern.lastIndex = i |
| 79 | const length = pattern.test(text) ? pattern.lastIndex - i : 0 |
| 80 | i += length |
| 81 | return length |
| 82 | } |
| 83 | |
| 84 | const word = <A>(literal: string, result: A): A => { |
| 85 | if (!text.startsWith(literal, i)) { |
| 86 | let at = i |
| 87 | while (text.charAt(at) === literal[at - i]) at++ |
| 88 | fail(at) |
| 89 | } |
| 90 | i += literal.length |
| 91 | return result |
| 92 | } |
| 93 | |
| 94 | const hex = (count: number) => { |
| 95 | let value = 0 |
| 96 | for (const end = i + count; i < end; i++) { |
| 97 | const code = text.charCodeAt(i) |
| 98 | const lower = code | 0x20 |
| 99 | if (isDigit(code)) value = value * 16 + code - 0x30 |
| 100 | else if (lower >= 0x61 && lower <= 0x66) value = value * 16 + lower - 0x57 |
| 101 | else fail(i) |
| 102 | } |
| 103 | return String.fromCharCode(value) |
| 104 | } |
| 105 | |
| 106 | const number = () => { |
| 107 | if (!json5) { |
| 108 | const start = i |