File size: 6,889 Bytes
37a34fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// 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 };
}