@ts-model-checker/core 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1158,6 +1158,735 @@ Terminated ==
1158
1158
  };
1159
1159
  }
1160
1160
 
1161
+ // src/transpiler/tlaParser.ts
1162
+ var MAX_TLA_INPUT_BYTES = 512 * 1024;
1163
+ var MAX_PARSE_DEPTH = 256;
1164
+ var FORBIDDEN_KEYS3 = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1165
+ function tokenizeTlaExpr(input) {
1166
+ const tokens = [];
1167
+ let i = 0;
1168
+ while (i < input.length) {
1169
+ const ch = input[i];
1170
+ if (/\s/.test(ch)) {
1171
+ i++;
1172
+ continue;
1173
+ }
1174
+ if (ch === '"') {
1175
+ let str = "";
1176
+ i++;
1177
+ while (i < input.length && input[i] !== '"') {
1178
+ if (input[i] === "\\" && i + 1 < input.length) {
1179
+ const next = input[i + 1];
1180
+ if (next === "n") str += "\n";
1181
+ else if (next === "t") str += " ";
1182
+ else str += next;
1183
+ i += 2;
1184
+ } else {
1185
+ str += input[i];
1186
+ i++;
1187
+ }
1188
+ }
1189
+ if (input[i] !== '"') {
1190
+ throw new Error("Unterminated string literal in TLA+ expression");
1191
+ }
1192
+ i++;
1193
+ tokens.push({ type: "STRING", value: str });
1194
+ continue;
1195
+ }
1196
+ if (/[0-9]/.test(ch)) {
1197
+ let num = "";
1198
+ while (i < input.length && /[0-9]/.test(input[i])) {
1199
+ num += input[i++];
1200
+ }
1201
+ tokens.push({ type: "NUMBER", value: num });
1202
+ continue;
1203
+ }
1204
+ const two = input.slice(i, i + 2);
1205
+ const three = input.slice(i, i + 3);
1206
+ if (three === "|->") {
1207
+ tokens.push({ type: "OP", value: "|->" });
1208
+ i += 3;
1209
+ continue;
1210
+ }
1211
+ if (two === "..") {
1212
+ tokens.push({ type: "DOTDOT", value: ".." });
1213
+ i += 2;
1214
+ continue;
1215
+ }
1216
+ if (two === "/\\" || two === "\\/" || two === "=>" || two === "<=" || two === ">=" || two === "/=" || two === "~>" || two === "<>" || two === "<<" || two === ">>") {
1217
+ tokens.push({ type: "OP", value: two });
1218
+ i += 2;
1219
+ continue;
1220
+ }
1221
+ if (ch === "\\") {
1222
+ let cmd = "\\";
1223
+ i++;
1224
+ while (i < input.length && /[A-Za-z]/.test(input[i])) {
1225
+ cmd += input[i++];
1226
+ }
1227
+ tokens.push({ type: "OP", value: cmd });
1228
+ continue;
1229
+ }
1230
+ if (ch === "(") {
1231
+ tokens.push({ type: "LPAREN", value: "(" });
1232
+ i++;
1233
+ continue;
1234
+ }
1235
+ if (ch === ")") {
1236
+ tokens.push({ type: "RPAREN", value: ")" });
1237
+ i++;
1238
+ continue;
1239
+ }
1240
+ if (ch === "{") {
1241
+ tokens.push({ type: "LBRACE", value: "{" });
1242
+ i++;
1243
+ continue;
1244
+ }
1245
+ if (ch === "}") {
1246
+ tokens.push({ type: "RBRACE", value: "}" });
1247
+ i++;
1248
+ continue;
1249
+ }
1250
+ if (ch === "[") {
1251
+ tokens.push({ type: "LBRACKET", value: "[" });
1252
+ i++;
1253
+ continue;
1254
+ }
1255
+ if (ch === "]") {
1256
+ tokens.push({ type: "RBRACKET", value: "]" });
1257
+ i++;
1258
+ continue;
1259
+ }
1260
+ if (ch === ",") {
1261
+ tokens.push({ type: "COMMA", value: "," });
1262
+ i++;
1263
+ continue;
1264
+ }
1265
+ if (ch === ":") {
1266
+ tokens.push({ type: "COLON", value: ":" });
1267
+ i++;
1268
+ continue;
1269
+ }
1270
+ if (ch === ".") {
1271
+ tokens.push({ type: "DOT", value: "." });
1272
+ i++;
1273
+ continue;
1274
+ }
1275
+ if (ch === "'") {
1276
+ tokens.push({ type: "PRIME", value: "'" });
1277
+ i++;
1278
+ continue;
1279
+ }
1280
+ if ("=#<>+-*%~".includes(ch)) {
1281
+ tokens.push({ type: "OP", value: ch });
1282
+ i++;
1283
+ continue;
1284
+ }
1285
+ if (/[A-Za-z_]/.test(ch)) {
1286
+ let ident = "";
1287
+ while (i < input.length && /[A-Za-z0-9_]/.test(input[i])) {
1288
+ ident += input[i++];
1289
+ }
1290
+ if (FORBIDDEN_KEYS3.has(ident)) {
1291
+ throw new Error(`Forbidden identifier in TLA+ input: '${ident}'`);
1292
+ }
1293
+ tokens.push({ type: "IDENT", value: ident });
1294
+ continue;
1295
+ }
1296
+ throw new Error(`Unexpected character '${ch}' in TLA+ expression`);
1297
+ }
1298
+ tokens.push({ type: "EOF", value: "" });
1299
+ return tokens;
1300
+ }
1301
+ var ExprParser = class {
1302
+ constructor(tokens) {
1303
+ this.tokens = tokens;
1304
+ }
1305
+ tokens;
1306
+ pos = 0;
1307
+ peek(offset = 0) {
1308
+ return this.tokens[this.pos + offset] ?? { type: "EOF", value: "" };
1309
+ }
1310
+ consume() {
1311
+ const tok = this.peek();
1312
+ this.pos++;
1313
+ return tok;
1314
+ }
1315
+ expect(type, value) {
1316
+ const tok = this.peek();
1317
+ if (tok.type !== type || value !== void 0 && tok.value !== value) {
1318
+ throw new Error(
1319
+ `Expected ${type}${value ? ` '${value}'` : ""}, got ${tok.type} '${tok.value}'`
1320
+ );
1321
+ }
1322
+ return this.consume();
1323
+ }
1324
+ parse(depth = 0) {
1325
+ if (depth > MAX_PARSE_DEPTH) {
1326
+ throw new Error("TLA+ expression exceeds maximum nesting depth");
1327
+ }
1328
+ return this.parseIfQuantifier(depth);
1329
+ }
1330
+ parseIfQuantifier(depth) {
1331
+ const tok = this.peek();
1332
+ if (tok.type === "IDENT" && tok.value === "IF") {
1333
+ this.consume();
1334
+ const condition = this.parse(depth + 1);
1335
+ this.expect("IDENT", "THEN");
1336
+ const thenBranch = this.parse(depth + 1);
1337
+ this.expect("IDENT", "ELSE");
1338
+ const elseBranch = this.parse(depth + 1);
1339
+ return { kind: "IfThenElse", condition, thenBranch, elseBranch };
1340
+ }
1341
+ if (tok.type === "OP" && (tok.value === "\\A" || tok.value === "\\E")) {
1342
+ const q = tok.value === "\\A" ? "FORALL" : "EXISTS";
1343
+ this.consume();
1344
+ const boundVar = this.expect("IDENT").value;
1345
+ this.expect("OP", "\\in");
1346
+ const domain = this.parseImplies(depth + 1);
1347
+ this.expect("COLON");
1348
+ const predicate = this.parse(depth + 1);
1349
+ return {
1350
+ kind: "Quantifier",
1351
+ quantifier: q,
1352
+ boundVar,
1353
+ domain,
1354
+ predicate
1355
+ };
1356
+ }
1357
+ return this.parseImplies(depth);
1358
+ }
1359
+ parseImplies(depth) {
1360
+ let left = this.parseOr(depth);
1361
+ while (this.peek().type === "OP" && this.peek().value === "=>") {
1362
+ this.consume();
1363
+ const right = this.parseOr(depth + 1);
1364
+ left = { kind: "BinaryOp", op: "=>", left, right };
1365
+ }
1366
+ return left;
1367
+ }
1368
+ parseOr(depth) {
1369
+ if (this.peek().type === "OP" && this.peek().value === "\\/") {
1370
+ this.consume();
1371
+ }
1372
+ let left = this.parseAnd(depth);
1373
+ while (this.peek().type === "OP" && this.peek().value === "\\/") {
1374
+ this.consume();
1375
+ const right = this.parseAnd(depth + 1);
1376
+ left = { kind: "BinaryOp", op: "||", left, right };
1377
+ }
1378
+ return left;
1379
+ }
1380
+ parseAnd(depth) {
1381
+ if (this.peek().type === "OP" && this.peek().value === "/\\") {
1382
+ this.consume();
1383
+ }
1384
+ let left = this.parseComparison(depth);
1385
+ while (this.peek().type === "OP" && this.peek().value === "/\\") {
1386
+ this.consume();
1387
+ const right = this.parseComparison(depth + 1);
1388
+ left = { kind: "BinaryOp", op: "&&", left, right };
1389
+ }
1390
+ return left;
1391
+ }
1392
+ parseComparison(depth) {
1393
+ let left = this.parseSetOp(depth);
1394
+ const tok = this.peek();
1395
+ if (tok.type === "OP") {
1396
+ const map = {
1397
+ "=": "==",
1398
+ "#": "!=",
1399
+ "/=": "!=",
1400
+ "<": "<",
1401
+ "<=": "<=",
1402
+ ">": ">",
1403
+ ">=": ">=",
1404
+ "\\in": "IN",
1405
+ "\\notin": "NOT_IN",
1406
+ "\\subseteq": "SUBSET_EQ"
1407
+ };
1408
+ if (tok.value in map) {
1409
+ this.consume();
1410
+ const right = this.parseSetOp(depth + 1);
1411
+ left = {
1412
+ kind: "BinaryOp",
1413
+ op: map[tok.value],
1414
+ left,
1415
+ right
1416
+ };
1417
+ }
1418
+ }
1419
+ return left;
1420
+ }
1421
+ parseSetOp(depth) {
1422
+ let left = this.parseRange(depth);
1423
+ while (this.peek().type === "OP" && (this.peek().value === "\\cup" || this.peek().value === "\\cap" || this.peek().value === "\\")) {
1424
+ const opTok = this.consume().value;
1425
+ const op = opTok === "\\cup" ? "UNION" : opTok === "\\cap" ? "INTERSECT" : "DIFF";
1426
+ const right = this.parseRange(depth + 1);
1427
+ left = { kind: "BinaryOp", op, left, right };
1428
+ }
1429
+ return left;
1430
+ }
1431
+ parseRange(depth) {
1432
+ const left = this.parseAdditive(depth);
1433
+ if (this.peek().type === "DOTDOT") {
1434
+ this.consume();
1435
+ const right = this.parseAdditive(depth + 1);
1436
+ return { kind: "Range", start: left, end: right };
1437
+ }
1438
+ return left;
1439
+ }
1440
+ parseAdditive(depth) {
1441
+ let left = this.parseMultiplicative(depth);
1442
+ while (this.peek().type === "OP" && (this.peek().value === "+" || this.peek().value === "-")) {
1443
+ const op = this.consume().value;
1444
+ const right = this.parseMultiplicative(depth + 1);
1445
+ left = { kind: "BinaryOp", op, left, right };
1446
+ }
1447
+ return left;
1448
+ }
1449
+ parseMultiplicative(depth) {
1450
+ let left = this.parseUnary(depth);
1451
+ while (this.peek().type === "OP" && (this.peek().value === "*" || this.peek().value === "\\div" || this.peek().value === "%")) {
1452
+ const raw = this.consume().value;
1453
+ const op = raw === "\\div" ? "/" : raw;
1454
+ const right = this.parseUnary(depth + 1);
1455
+ left = { kind: "BinaryOp", op, left, right };
1456
+ }
1457
+ return left;
1458
+ }
1459
+ parseUnary(depth) {
1460
+ const tok = this.peek();
1461
+ if (tok.type === "OP" && (tok.value === "~" || tok.value === "-")) {
1462
+ this.consume();
1463
+ const op = tok.value === "~" ? "!" : "-";
1464
+ return { kind: "UnaryOp", op, operand: this.parseUnary(depth + 1) };
1465
+ }
1466
+ return this.parsePostfix(depth);
1467
+ }
1468
+ parsePostfix(depth) {
1469
+ let expr = this.parsePrimary(depth);
1470
+ while (this.peek().type === "DOT") {
1471
+ this.consume();
1472
+ const field = this.expect("IDENT").value;
1473
+ if (FORBIDDEN_KEYS3.has(field)) {
1474
+ throw new Error(`Forbidden field name: '${field}'`);
1475
+ }
1476
+ expr = { kind: "FieldAccess", target: expr, field };
1477
+ }
1478
+ return expr;
1479
+ }
1480
+ parsePrimary(depth) {
1481
+ const tok = this.peek();
1482
+ if (tok.type === "LPAREN") {
1483
+ this.consume();
1484
+ const inner = this.parse(depth + 1);
1485
+ this.expect("RPAREN");
1486
+ return inner;
1487
+ }
1488
+ if (tok.type === "LBRACE") {
1489
+ this.consume();
1490
+ const elements = [];
1491
+ if (this.peek().type !== "RBRACE") {
1492
+ elements.push(this.parse(depth + 1));
1493
+ while (this.peek().type === "COMMA") {
1494
+ this.consume();
1495
+ elements.push(this.parse(depth + 1));
1496
+ }
1497
+ }
1498
+ this.expect("RBRACE");
1499
+ return { kind: "SetLiteral", elements };
1500
+ }
1501
+ if (tok.type === "LBRACKET") {
1502
+ this.consume();
1503
+ const fields = {};
1504
+ if (this.peek().type !== "RBRACKET") {
1505
+ const parseField = () => {
1506
+ const key = this.expect("IDENT").value;
1507
+ if (FORBIDDEN_KEYS3.has(key)) {
1508
+ throw new Error(`Forbidden record field: '${key}'`);
1509
+ }
1510
+ this.expect("OP", "|->");
1511
+ const val = this.parse(depth + 1);
1512
+ Object.defineProperty(fields, key, {
1513
+ value: val,
1514
+ enumerable: true,
1515
+ writable: true,
1516
+ configurable: true
1517
+ });
1518
+ };
1519
+ parseField();
1520
+ while (this.peek().type === "COMMA") {
1521
+ this.consume();
1522
+ parseField();
1523
+ }
1524
+ }
1525
+ this.expect("RBRACKET");
1526
+ return { kind: "RecordLiteral", fields };
1527
+ }
1528
+ if (tok.type === "NUMBER") {
1529
+ this.consume();
1530
+ return { kind: "Literal", value: Number(tok.value) };
1531
+ }
1532
+ if (tok.type === "STRING") {
1533
+ this.consume();
1534
+ return { kind: "Literal", value: tok.value === "NULL" ? null : tok.value };
1535
+ }
1536
+ if (tok.type === "IDENT") {
1537
+ this.consume();
1538
+ if (tok.value === "TRUE") return { kind: "Literal", value: true };
1539
+ if (tok.value === "FALSE") return { kind: "Literal", value: false };
1540
+ if (tok.value === "Cardinality" && this.peek().type === "LPAREN") {
1541
+ this.consume();
1542
+ const operand = this.parse(depth + 1);
1543
+ this.expect("RPAREN");
1544
+ return { kind: "UnaryOp", op: "CARDINALITY", operand };
1545
+ }
1546
+ return { kind: "Var", name: tok.value };
1547
+ }
1548
+ throw new Error(`Unexpected token ${tok.type} '${tok.value}' in TLA+ expression`);
1549
+ }
1550
+ };
1551
+ function parseTlaExpr(exprText) {
1552
+ const tokens = tokenizeTlaExpr(exprText);
1553
+ const parser = new ExprParser(tokens);
1554
+ const node = parser.parse();
1555
+ return node;
1556
+ }
1557
+ function stripTlaComments(source) {
1558
+ let out = "";
1559
+ let i = 0;
1560
+ let inString = false;
1561
+ while (i < source.length) {
1562
+ if (source[i] === '"' && source[i - 1] !== "\\") {
1563
+ inString = !inString;
1564
+ out += source[i++];
1565
+ continue;
1566
+ }
1567
+ if (!inString && source.slice(i, i + 2) === "(*") {
1568
+ i += 2;
1569
+ while (i < source.length && source.slice(i, i + 2) !== "*)") {
1570
+ i++;
1571
+ }
1572
+ i += 2;
1573
+ continue;
1574
+ }
1575
+ if (!inString && source.slice(i, i + 2) === "\\*") {
1576
+ while (i < source.length && source[i] !== "\n") {
1577
+ i++;
1578
+ }
1579
+ continue;
1580
+ }
1581
+ out += source[i++];
1582
+ }
1583
+ return out;
1584
+ }
1585
+ function inferVarType(val) {
1586
+ if (typeof val === "number") return "number";
1587
+ if (typeof val === "boolean") return "boolean";
1588
+ if (Array.isArray(val)) return "set";
1589
+ if (val !== null && typeof val === "object") return "record";
1590
+ return "string";
1591
+ }
1592
+ function evalConstantExpr(node) {
1593
+ switch (node.kind) {
1594
+ case "Literal":
1595
+ return node.value;
1596
+ case "UnaryOp":
1597
+ if (node.op === "-") {
1598
+ const inner = evalConstantExpr(node.operand);
1599
+ if (typeof inner === "number") return -inner;
1600
+ }
1601
+ throw new Error("Non-constant expression in Init state");
1602
+ case "SetLiteral":
1603
+ return Object.freeze(node.elements.map(evalConstantExpr));
1604
+ case "RecordLiteral": {
1605
+ const rec = {};
1606
+ for (const [k, v] of Object.entries(node.fields)) {
1607
+ Object.defineProperty(rec, k, {
1608
+ value: evalConstantExpr(v),
1609
+ enumerable: true,
1610
+ writable: true,
1611
+ configurable: true
1612
+ });
1613
+ }
1614
+ return Object.freeze(rec);
1615
+ }
1616
+ default:
1617
+ throw new Error(`Unsupported Init value kind: ${node.kind}`);
1618
+ }
1619
+ }
1620
+ function splitTopLevelBy(text, sep) {
1621
+ const parts = [];
1622
+ let depthParen = 0;
1623
+ let depthBrace = 0;
1624
+ let depthBracket = 0;
1625
+ let inString = false;
1626
+ let start = 0;
1627
+ for (let i = 0; i < text.length; i++) {
1628
+ const ch = text[i];
1629
+ if (ch === '"' && text[i - 1] !== "\\") {
1630
+ inString = !inString;
1631
+ continue;
1632
+ }
1633
+ if (inString) continue;
1634
+ if (ch === "(") depthParen++;
1635
+ else if (ch === ")") depthParen--;
1636
+ else if (ch === "{") depthBrace++;
1637
+ else if (ch === "}") depthBrace--;
1638
+ else if (ch === "[") depthBracket++;
1639
+ else if (ch === "]") depthBracket--;
1640
+ if (depthParen === 0 && depthBrace === 0 && depthBracket === 0 && text.slice(i, i + 2) === sep) {
1641
+ const chunk = text.slice(start, i).trim();
1642
+ if (chunk) parts.push(chunk);
1643
+ start = i + 2;
1644
+ i += 1;
1645
+ }
1646
+ }
1647
+ const tail = text.slice(start).trim();
1648
+ if (tail) parts.push(tail);
1649
+ return parts;
1650
+ }
1651
+ function parseInitStates(initBody, varNames) {
1652
+ const disjuncts = splitTopLevelBy(initBody, "\\/");
1653
+ const states = [];
1654
+ for (const rawDisjunct of disjuncts) {
1655
+ let cleaned = rawDisjunct.trim();
1656
+ if (cleaned.startsWith("(") && cleaned.endsWith(")")) {
1657
+ cleaned = cleaned.slice(1, -1).trim();
1658
+ }
1659
+ const conjuncts = splitTopLevelBy(cleaned, "/\\");
1660
+ const st = {};
1661
+ for (const conj of conjuncts) {
1662
+ const eqIdx = conj.indexOf("=");
1663
+ if (eqIdx === -1) continue;
1664
+ const lhs = conj.slice(0, eqIdx).trim();
1665
+ const rhs = conj.slice(eqIdx + 1).trim();
1666
+ if (FORBIDDEN_KEYS3.has(lhs)) {
1667
+ throw new Error(`Forbidden variable name in Init: '${lhs}'`);
1668
+ }
1669
+ st[lhs] = evalConstantExpr(parseTlaExpr(rhs));
1670
+ }
1671
+ if (Object.keys(st).length > 0) {
1672
+ for (const v of varNames) {
1673
+ if (!(v in st)) {
1674
+ st[v] = null;
1675
+ }
1676
+ }
1677
+ states.push(Object.freeze(st));
1678
+ }
1679
+ }
1680
+ return states;
1681
+ }
1682
+ function parseTlaToSpec(tlaContent, options = {}) {
1683
+ if (tlaContent.length > MAX_TLA_INPUT_BYTES) {
1684
+ throw new Error(`TLA+ input exceeds maximum size (${MAX_TLA_INPUT_BYTES} bytes)`);
1685
+ }
1686
+ const warnings = [];
1687
+ const noComments = stripTlaComments(tlaContent);
1688
+ const moduleMatch = noComments.match(/----+\s*MODULE\s+([A-Za-z_][A-Za-z0-9_]*)\s*----+/);
1689
+ const moduleName = moduleMatch?.[1] ?? "ImportedTlaModel";
1690
+ const body = noComments.replace(/----+\s*MODULE\s+[A-Za-z_][A-Za-z0-9_]*\s*----+/, "").replace(/====+/g, "").replace(/^\s*EXTENDS\s+[^\n]+/m, "");
1691
+ const varMatch = body.match(/^\s*VARIABLES?\s+([^\n]+)/m);
1692
+ const declaredVarNames = varMatch ? varMatch[1].split(",").map((s) => s.trim()).filter((s) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(s) && !FORBIDDEN_KEYS3.has(s)) : [];
1693
+ const defRegex = /^([A-Za-z_][A-Za-z0-9_]*)\s*==\s*/gm;
1694
+ const matches = [];
1695
+ let m;
1696
+ while ((m = defRegex.exec(body)) !== null) {
1697
+ matches.push({
1698
+ name: m[1],
1699
+ start: m.index,
1700
+ bodyStart: m.index + m[0].length
1701
+ });
1702
+ }
1703
+ const defs = /* @__PURE__ */ new Map();
1704
+ for (let i = 0; i < matches.length; i++) {
1705
+ const end = i + 1 < matches.length ? matches[i + 1].start : body.length;
1706
+ defs.set(matches[i].name, body.slice(matches[i].bodyStart, end).trim());
1707
+ }
1708
+ const initBody = defs.get("Init");
1709
+ if (!initBody) {
1710
+ throw new Error("TLA+ specification must define 'Init == ...'");
1711
+ }
1712
+ const initialStates = parseInitStates(initBody, declaredVarNames);
1713
+ if (initialStates.length === 0) {
1714
+ throw new Error("Could not parse any initial state from 'Init'");
1715
+ }
1716
+ const allVarNames = declaredVarNames.length > 0 ? declaredVarNames : Object.keys(initialStates[0]).sort();
1717
+ const variables = allVarNames.map((name) => ({
1718
+ name,
1719
+ type: inferVarType(initialStates[0][name])
1720
+ }));
1721
+ const cfgInvariants = /* @__PURE__ */ new Set();
1722
+ const cfgProperties = /* @__PURE__ */ new Set();
1723
+ if (options.cfgContent) {
1724
+ for (const line of options.cfgContent.split(/\r?\n/)) {
1725
+ const invM = line.match(/^\s*INVARIANT\s+([A-Za-z_][A-Za-z0-9_]*)/);
1726
+ if (invM) cfgInvariants.add(invM[1]);
1727
+ const propM = line.match(/^\s*PROPERTY\s+([A-Za-z_][A-Za-z0-9_]*)/);
1728
+ if (propM) cfgProperties.add(propM[1]);
1729
+ }
1730
+ }
1731
+ const nextBody = defs.get("Next");
1732
+ const actionNames = nextBody ? splitTopLevelBy(nextBody, "\\/").map((s) => s.trim()) : [...defs.keys()].filter(
1733
+ (k) => k !== "Init" && k !== "Next" && k !== "Spec" && k !== "vars" && !k.startsWith("Inv_") && !k.startsWith("Live_") && !cfgInvariants.has(k) && !cfgProperties.has(k)
1734
+ );
1735
+ let terminalCondition;
1736
+ const actions = [];
1737
+ actionNames.forEach((actName, idx) => {
1738
+ const rawBody = defs.get(actName);
1739
+ if (!rawBody) {
1740
+ warnings.push(`Action '${actName}' referenced in Next has no definition.`);
1741
+ return;
1742
+ }
1743
+ const conjuncts = splitTopLevelBy(rawBody, "/\\");
1744
+ const guardExprs = [];
1745
+ const effects = [];
1746
+ for (const conj of conjuncts) {
1747
+ if (/^UNCHANGED\b/.test(conj)) {
1748
+ continue;
1749
+ }
1750
+ const primedMatch = conj.match(/^([A-Za-z_][A-Za-z0-9_]*)'\s*=\s*([\s\S]+)$/);
1751
+ if (primedMatch) {
1752
+ const targetVar = primedMatch[1];
1753
+ if (FORBIDDEN_KEYS3.has(targetVar)) {
1754
+ throw new Error(`Forbidden target variable: '${targetVar}'`);
1755
+ }
1756
+ effects.push({
1757
+ targetVar,
1758
+ expression: parseTlaExpr(primedMatch[2].trim())
1759
+ });
1760
+ continue;
1761
+ }
1762
+ try {
1763
+ guardExprs.push(parseTlaExpr(conj));
1764
+ } catch (err) {
1765
+ warnings.push(
1766
+ `Skipped unsupported conjunct in '${actName}': ${err instanceof Error ? err.message : String(err)}`
1767
+ );
1768
+ }
1769
+ }
1770
+ const combinedGuard = guardExprs.length === 0 ? { kind: "Literal", value: true } : guardExprs.reduce((acc, cur) => ({
1771
+ kind: "BinaryOp",
1772
+ op: "&&",
1773
+ left: acc,
1774
+ right: cur
1775
+ }));
1776
+ if (actName === "Terminated" && effects.length === 0 && guardExprs.length > 0) {
1777
+ terminalCondition = combinedGuard;
1778
+ return;
1779
+ }
1780
+ actions.push({
1781
+ id: actName,
1782
+ name: actName,
1783
+ guard: combinedGuard,
1784
+ effects,
1785
+ position: {
1786
+ x: 60 + idx % 2 * 320,
1787
+ y: 200 + Math.floor(idx / 2) * 180
1788
+ }
1789
+ });
1790
+ });
1791
+ const invariants = [];
1792
+ const livenessProperties = [];
1793
+ for (const [defName, defBody] of defs.entries()) {
1794
+ if (defName === "Init" || defName === "Next" || defName === "Spec" || defName === "vars" || defName === "Terminated" || actionNames.includes(defName)) {
1795
+ continue;
1796
+ }
1797
+ const isExplicitInv = cfgInvariants.has(defName) || defName.startsWith("Inv_");
1798
+ const isExplicitProp = cfgProperties.has(defName) || defName.startsWith("Live_");
1799
+ const trimmed = defBody.trim();
1800
+ if (trimmed.startsWith("<>")) {
1801
+ const inner = trimmed.slice(2).trim();
1802
+ try {
1803
+ livenessProperties.push({
1804
+ id: defName.replace(/^Live_/, ""),
1805
+ kind: "EVENTUALLY",
1806
+ description: defName.replace(/^Live_/, ""),
1807
+ eventually: parseTlaExpr(inner)
1808
+ });
1809
+ } catch (err) {
1810
+ warnings.push(
1811
+ `Could not parse liveness property '${defName}': ${err instanceof Error ? err.message : String(err)}`
1812
+ );
1813
+ }
1814
+ continue;
1815
+ }
1816
+ if (trimmed.includes("~>")) {
1817
+ const [leftRaw, rightRaw] = trimmed.split("~>");
1818
+ try {
1819
+ const cleanLeft = leftRaw.trim().replace(/^\(/, "");
1820
+ const cleanRight = rightRaw.trim().replace(/\)$/, "");
1821
+ livenessProperties.push({
1822
+ id: defName.replace(/^Live_/, ""),
1823
+ kind: "LEADS_TO",
1824
+ description: defName.replace(/^Live_/, ""),
1825
+ trigger: parseTlaExpr(cleanLeft),
1826
+ response: parseTlaExpr(cleanRight)
1827
+ });
1828
+ } catch (err) {
1829
+ warnings.push(
1830
+ `Could not parse leads-to property '${defName}': ${err instanceof Error ? err.message : String(err)}`
1831
+ );
1832
+ }
1833
+ continue;
1834
+ }
1835
+ if (isExplicitInv && !isExplicitProp) {
1836
+ try {
1837
+ const id = defName.replace(/^Inv_/, "");
1838
+ invariants.push({
1839
+ id,
1840
+ description: id,
1841
+ predicate: parseTlaExpr(trimmed)
1842
+ });
1843
+ } catch (err) {
1844
+ warnings.push(
1845
+ `Could not parse invariant '${defName}': ${err instanceof Error ? err.message : String(err)}`
1846
+ );
1847
+ }
1848
+ }
1849
+ }
1850
+ return {
1851
+ spec: {
1852
+ schemaVersion: 1,
1853
+ moduleName,
1854
+ variables,
1855
+ initialStates,
1856
+ actions,
1857
+ invariants,
1858
+ livenessProperties,
1859
+ terminalCondition
1860
+ },
1861
+ warnings
1862
+ };
1863
+ }
1864
+ function parseJsonToSpec(jsonContent) {
1865
+ if (jsonContent.length > MAX_TLA_INPUT_BYTES) {
1866
+ throw new Error(`JSON input exceeds maximum size (${MAX_TLA_INPUT_BYTES} bytes)`);
1867
+ }
1868
+ const parsed = JSON.parse(jsonContent);
1869
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1870
+ throw new Error("Invalid VisualSpecIR JSON: root must be an object");
1871
+ }
1872
+ const obj = parsed;
1873
+ if (obj.schemaVersion !== 1 || typeof obj.moduleName !== "string") {
1874
+ throw new Error("Invalid VisualSpecIR JSON: missing schemaVersion=1 or moduleName");
1875
+ }
1876
+ const spec = {
1877
+ schemaVersion: 1,
1878
+ moduleName: obj.moduleName,
1879
+ variables: Array.isArray(obj.variables) ? obj.variables : [],
1880
+ initialStates: Array.isArray(obj.initialStates) ? obj.initialStates : [],
1881
+ actions: Array.isArray(obj.actions) ? obj.actions : [],
1882
+ invariants: Array.isArray(obj.invariants) ? obj.invariants : [],
1883
+ livenessProperties: Array.isArray(obj.livenessProperties) ? obj.livenessProperties : [],
1884
+ terminalCondition: obj.terminalCondition
1885
+ };
1886
+ const issues = validateSpec(spec);
1887
+ return { spec, issues };
1888
+ }
1889
+
1161
1890
  // src/presets/concurrentTransfer.ts
1162
1891
  var concurrentTransferBuggySpec = {
1163
1892
  schemaVersion: 1,
@@ -1885,6 +2614,9 @@ exports.hasValidationErrors = hasValidationErrors;
1885
2614
  exports.literalToTla = literalToTla;
1886
2615
  exports.mutexSpec = mutexSpec;
1887
2616
  exports.normalizeSet = normalizeSet;
2617
+ exports.parseJsonToSpec = parseJsonToSpec;
2618
+ exports.parseTlaExpr = parseTlaExpr;
2619
+ exports.parseTlaToSpec = parseTlaToSpec;
1888
2620
  exports.transpileToTla = transpileToTla;
1889
2621
  exports.twoPhaseCommitSpec = twoPhaseCommitSpec;
1890
2622
  exports.validateExecutionTrace = validateExecutionTrace;