| // Position-preserving tree over an already-tokenized Clausewitz file. | |
| // | |
| // This module NEVER synthesizes text. Every node it produces is a thin | |
| // structural wrapper around references to the original tokens (which in turn | |
| // carry the exact source slice, offset, line, and column from lexer.mjs). | |
| // Recovering the exact span of any value is just reading `.index`/`.length` | |
| // off the tokens this module already points at — nothing is recomputed or | |
| // re-derived from a serialized form. | |
| // | |
| // Grammar (measured against real vanilla+mod data, see node.mjs/edit.mjs | |
| // headers and the task writeup this package was built from): | |
| // - A file (or any `{ ... }` block) is an ordered sequence of *items*: | |
| // - a `pair`: KEY = VALUE (VALUE is a scalar token or a nested block) | |
| // - a `bare`: a lone token with no following `=` (bare-value lists like | |
| // `historical_idea_groups = { economic_ideas offensive_ideas }`, | |
| // or RGB triples like `color = { 20 50 210 }`) | |
| // - Duplicate keys and duplicate date keys are normal and are never | |
| // collapsed; `items` preserves file order and multiplicity exactly. | |
| // - Nesting is shallow in practice (max depth 2), but the parser itself | |
| // imposes no depth limit — it just recurses on `{`. | |
| // - Malformed input (missing closing brace, `=` with nothing after it) must | |
| // never throw. Real vanilla+mod data has no such cases, but the round-trip | |
| // test in Phase 1 already treats "must not crash on real files" as | |
| // load-bearing, and this module inherits that requirement. | |
| /** | |
| * @typedef {Object} PairItem | |
| * @property {'pair'} kind | |
| * @property {import('./lexer.mjs').Token} keyToken | |
| * @property {import('./lexer.mjs').Token} opToken | |
| * @property {ScalarValue|BlockValue} value | |
| * @property {number} startTokenIndex - index into the flat token array of the key token | |
| * @property {number} endTokenIndex - index into the flat token array of the last token belonging to this entry | |
| */ | |
| /** | |
| * @typedef {Object} BareItem | |
| * @property {'bare'} kind | |
| * @property {import('./lexer.mjs').Token} token | |
| * @property {number} startTokenIndex | |
| * @property {number} endTokenIndex | |
| */ | |
| /** | |
| * @typedef {Object} ScalarValue | |
| * @property {'scalar'} type | |
| * @property {import('./lexer.mjs').Token|null} token - null only for malformed `key =` with nothing after | |
| */ | |
| /** | |
| * @typedef {Object} BlockValue | |
| * @property {'block'} type | |
| * @property {(PairItem|BareItem)[]} items | |
| * @property {number} startTokenIndex - index of the `{` token | |
| * @property {number} endTokenIndex - index of the `}` token if `closed`, else the last token consumed | |
| * @property {boolean} closed - whether a matching `}` was actually found | |
| */ | |
| const SKIP_KINDS = new Set(['whitespace', 'comment']); | |
| /** | |
| * Parse a full token stream (as produced by lexer.mjs's `tokenize`) into a | |
| * position-preserving tree. | |
| * | |
| * @param {import('./lexer.mjs').Token[]} tokens | |
| * @returns {{ type: 'root', items: (PairItem|BareItem)[] }} | |
| */ | |
| export function parse(tokens) { | |
| const n = tokens.length; | |
| let pos = 0; | |
| // Look at the next significant (non-whitespace, non-comment) token's index | |
| // without consuming it. Returns -1 at end of stream. | |
| function peekSignificant() { | |
| let i = pos; | |
| while (i < n && SKIP_KINDS.has(tokens[i].kind)) i += 1; | |
| return i < n ? i : -1; | |
| } | |
| // Consume and return the index of the next significant token, skipping | |
| // over any whitespace/comment tokens along the way. | |
| function nextSignificant() { | |
| while (pos < n && SKIP_KINDS.has(tokens[pos].kind)) pos += 1; | |
| if (pos >= n) return -1; | |
| const i = pos; | |
| pos += 1; | |
| return i; | |
| } | |
| // Parse a sequence of items until EOF or (if `stopKind` given) until the | |
| // next significant token is of that kind, WITHOUT consuming the stop token | |
| // (the caller consumes it, so it can record it as the block's closing | |
| // brace). | |
| function parseItems(stopKind) { | |
| const items = []; | |
| for (;;) { | |
| const idx = peekSignificant(); | |
| if (idx === -1) break; | |
| if (stopKind && tokens[idx].kind === stopKind) break; | |
| const keyIdx = nextSignificant(); | |
| const keyToken = tokens[keyIdx]; | |
| const afterKeyIdx = peekSignificant(); | |
| const isAssignment = afterKeyIdx !== -1 | |
| && tokens[afterKeyIdx].kind === 'operator' | |
| && tokens[afterKeyIdx].value === '='; | |
| if (!isAssignment) { | |
| // Bare item: a lone value inside a value-list block, or (in | |
| // malformed data) a stray token at a position where a key was | |
| // expected. Either way: record it and move on, never throw. | |
| items.push({ | |
| kind: 'bare', | |
| token: keyToken, | |
| startTokenIndex: keyIdx, | |
| endTokenIndex: keyIdx, | |
| }); | |
| continue; | |
| } | |
| const opIdx = nextSignificant(); // consume '=' | |
| const opToken = tokens[opIdx]; | |
| const valueStartIdx = peekSignificant(); | |
| if (valueStartIdx === -1) { | |
| // `key =` with nothing after it (truncated/malformed). Must not | |
| // throw; record a null-valued scalar so callers can decide. | |
| items.push({ | |
| kind: 'pair', | |
| keyToken, | |
| opToken, | |
| value: { type: 'scalar', token: null }, | |
| startTokenIndex: keyIdx, | |
| endTokenIndex: opIdx, | |
| }); | |
| continue; | |
| } | |
| if (tokens[valueStartIdx].kind === 'lbrace') { | |
| const lbraceIdx = nextSignificant(); // consume '{' | |
| const innerItems = parseItems('rbrace'); | |
| const closeCandidateIdx = peekSignificant(); | |
| let rbraceIdx = -1; | |
| if (closeCandidateIdx !== -1 && tokens[closeCandidateIdx].kind === 'rbrace') { | |
| rbraceIdx = nextSignificant(); // consume '}' | |
| } | |
| // If there was no closing brace (malformed/truncated file), the last | |
| // token actually consumed is at pos - 1 (nextSignificant always | |
| // leaves pos one past whatever it last consumed; peekSignificant | |
| // never advances pos, so this is safe to read here). | |
| const endIdx = rbraceIdx !== -1 ? rbraceIdx : pos - 1; | |
| items.push({ | |
| kind: 'pair', | |
| keyToken, | |
| opToken, | |
| value: { | |
| type: 'block', | |
| items: innerItems, | |
| startTokenIndex: lbraceIdx, | |
| endTokenIndex: endIdx, | |
| closed: rbraceIdx !== -1, | |
| }, | |
| startTokenIndex: keyIdx, | |
| endTokenIndex: endIdx, | |
| }); | |
| continue; | |
| } | |
| // Plain scalar value: exactly one token (string or bare). | |
| const valIdx = nextSignificant(); | |
| items.push({ | |
| kind: 'pair', | |
| keyToken, | |
| opToken, | |
| value: { type: 'scalar', token: tokens[valIdx] }, | |
| startTokenIndex: keyIdx, | |
| endTokenIndex: valIdx, | |
| }); | |
| } | |
| return items; | |
| } | |
| const items = parseItems(null); | |
| return { type: 'root', items }; | |
| } | |