// Byte-exact, position-tracking tokenizer for Paradox Clausewitz syntax // (EU4 history/common/events/decisions/missions files). // // The lexer NEVER regenerates text — it only locates things. Every token // keeps the exact source slice it came from (`raw`), and concatenating every // token's `raw` in order reproduces the input byte-for-byte. This is the // load-bearing property tested by test/roundtrip.test.mjs: a past tool that // decoded+re-encoded a file silently reformatted thousands of lines (indent // style, comment position, blank lines) while leaving values unchanged, and // that must be structurally impossible here. // // Grammar notes (measured against real vanilla EU4 data — see the task // writeup this package was built from): // - Only `=` occurs as an operator. `>=`, `<=`, `!=`, `><`, `hsv{...}`, and // `@variable` are confirmed absent from EU4 and are deliberately not // special-cased; any of those characters appearing in source text just // fall into an ordinary bare token or standalone character, which still // round-trips correctly even though the lexer attaches no special // meaning to it. // - No `\`-escaped quotes were found in any real string token (backslashes // that appear near quotes in vanilla data are inside `#comment` text, // never inside an actual `"..."` value), so strings are lexed as // `"` ... next unescaped `"` with no escape processing. // - A `#` inside a quoted string is not a comment start, and a `"` inside a // comment is not a string start. Handling this requires one real state // machine (in-string / in-comment / code) rather than independently // regexing for quotes and comments — naive independent scans // desynchronize permanently after the first line where the two collide // (see common/countries/*.txt: `monarch_names = { # ... "nori"` and // Silesia.txt's `"#LIST#|leader_names|Hoppe"`, which is a string that // itself starts with `#`). /** @typedef {'comment'|'string'|'bare'|'lbrace'|'rbrace'|'operator'|'whitespace'} TokenKind */ /** * @typedef {Object} Token * @property {TokenKind} kind * @property {string} value - semantic content (comment text sans '#', string sans quotes, etc.) * @property {string} raw - exact source slice, quotes/braces/# included * @property {number} index - 0-based character offset into the input text * @property {number} line - 1-based line number of the token's first character * @property {number} col - 1-based column of the token's first character * @property {number} length - raw.length */ const WHITESPACE = new Set([' ', '\t', '\r', '\n']); const SINGLE_CHAR_KIND = new Map([ ['{', 'lbrace'], ['}', 'rbrace'], ['=', 'operator'], ]); // Characters that end a bare token: whitespace, structural punctuation, and // the two characters that switch lexer state (# and "). const BARE_STOP = new Set([' ', '\t', '\r', '\n', '{', '}', '=', '"', '#']); /** * Tokenize Clausewitz source text into a position-tracked token stream. * * @param {string} text * @returns {Token[]} */ export function tokenize(text) { const tokens = []; const length = text.length; let index = 0; let line = 1; let col = 1; // Advance the line/col cursor over `slice` (which may contain newlines), // shared by every branch below so position bookkeeping lives in one place. function advance(slice) { for (let i = 0; i < slice.length; i += 1) { if (slice[i] === '\n') { line += 1; col = 1; } else { col += 1; } } } function push(kind, value, raw) { tokens.push({ kind, value, raw, index, line, col, length: raw.length }); index += raw.length; advance(raw); } while (index < length) { const char = text[index]; if (WHITESPACE.has(char)) { let end = index + 1; while (end < length && WHITESPACE.has(text[end])) end += 1; const raw = text.slice(index, end); push('whitespace', raw, raw); continue; } if (char === '#') { // Unquoted '#' to end of line (exclusive of the line terminator, so // the terminator itself is tokenized separately as whitespace). let end = index + 1; while (end < length && text[end] !== '\n' && text[end] !== '\r') end += 1; const raw = text.slice(index, end); push('comment', raw.slice(1), raw); continue; } if (char === '"') { // Quoted string: '"' ... next '"' (or EOF, for a truncated/malformed // file — we still must not throw, since the round-trip test asserts // over every real vanilla+mod file and a single malformed one must // not crash the whole run; it simply won't find a closing quote). let end = index + 1; while (end < length && text[end] !== '"') end += 1; const closed = end < length; const stringEnd = closed ? end + 1 : end; const raw = text.slice(index, stringEnd); const value = closed ? text.slice(index + 1, end) : text.slice(index + 1, end); push('string', value, raw); continue; } const single = SINGLE_CHAR_KIND.get(char); if (single) { push(single, char, char); continue; } // Bare token: run until the next character that starts a new kind. let end = index + 1; while (end < length && !BARE_STOP.has(text[end])) end += 1; const raw = text.slice(index, end); push('bare', raw, raw); } return tokens; }