tla-ts 0.0.3-dev.fe239f8 → 0.0.4-dev.5f6a4bf

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/src/resolve.ts CHANGED
@@ -58,11 +58,14 @@ interface Goal {
58
58
  }
59
59
 
60
60
  // isPending holds for an operator a RECURSIVE declaration names until its definition.
61
+ // isNonFact holds for the name of a USE, HIDE, DEFINE or INSTANCE step, which SANY takes neither as
62
+ // a fact nor as an expression.
61
63
  interface LocalName extends Binding {
62
64
  name: string;
63
65
  parent: LocalName | undefined;
64
66
  goal?: Goal;
65
67
  isPending?: boolean;
68
+ isNonFact?: boolean;
66
69
  }
67
70
 
68
71
  // A name the module binds, from position on.
@@ -285,6 +288,18 @@ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
285
288
  end: { line: location.line, column: location.column + name.length - 1 },
286
289
  });
287
290
 
291
+ // SANY reports a name at its tokens, such as M ! ⊕ for M!\oplus.
292
+ const getSpelledNameRange = (
293
+ expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
294
+ name: string,
295
+ ): SourceRange => {
296
+ const selectorRange =
297
+ expression.kind === "OperatorReference" ? undefined : expression.selectorRanges?.at(-1);
298
+ return selectorRange
299
+ ? { module: selectorRange.module, start: expression.location, end: selectorRange.end }
300
+ : getNameRange(expression.location, expression.spelling ?? name);
301
+ };
302
+
288
303
  // SANY reports an operator symbol applied to operands as one it cannot resolve.
289
304
  const getFixity = (expression: Expression) => {
290
305
  if (expression.kind !== "Apply") return undefined;
@@ -294,10 +309,7 @@ const getFixity = (expression: Expression) => {
294
309
  };
295
310
 
296
311
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
297
- const isOperatorSymbol = (name: string) =>
298
- name[0].toLowerCase() === name[0].toUpperCase() &&
299
- name[0] !== "_" &&
300
- (name[0] < "0" || name[0] > "9");
312
+ const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
301
313
 
302
314
  const isStepName = (name: string) =>
303
315
  name.startsWith("<") && ((name[1] >= "0" && name[1] <= "9") || name[1] === "*");
@@ -714,10 +726,17 @@ const getSymbolArity = (
714
726
  const renamed = renamedArities.get(expression);
715
727
  if (renamed !== undefined) return renamed;
716
728
  if (isKey(name)) return expression.kind === "Apply" ? expression.args.length : 0;
717
- if (checkReference(expression, scope, unit, false) || isStepName(name)) {
729
+ const local = lookupLocal(scope, name);
730
+ if (local?.isNonFact) {
731
+ unit.errors.push({
732
+ location: formatRange(getSpelledNameRange(expression, name)),
733
+ message: "Step number of non-expression step used as an expression.",
734
+ });
735
+ return undefined;
736
+ }
737
+ if (checkReference(expression, scope, unit, false) || (isStepName(name) && local)) {
718
738
  return expression.kind === "Apply" ? expression.args.length : 0;
719
739
  }
720
- const local = lookupLocal(scope, name);
721
740
  if (local && expression.kind !== "OperatorReference") expression.resolution = LOCAL_RESOLUTION;
722
741
  if (local) return local.arity;
723
742
  const symbol = findSymbol(name, unit);
@@ -740,9 +759,11 @@ const getSymbolArity = (
740
759
  }
741
760
  const spelling = (expression.kind === "Identifier" ? undefined : expression.spelling) ?? name;
742
761
  const range = formatRange(
743
- getNameRange(location, expression.kind === "Apply" && spelling === "-." ? "-" : spelling),
762
+ expression.kind === "Apply" && spelling === "-."
763
+ ? getNameRange(location, "-")
764
+ : getSpelledNameRange(expression, name),
744
765
  );
745
- if (!isOperatorSymbol(name)) {
766
+ if (!isOperatorSymbol(name) || isStepName(name)) {
746
767
  unit.errors.push({ location: range, message: `Unknown operator: \`${name}'.` });
747
768
  return undefined;
748
769
  }
@@ -874,7 +895,7 @@ const resolveDefinitions = (
874
895
  const count = pending.findIndex((instance) => !isDue(instance));
875
896
  return pending
876
897
  .splice(0, count === -1 ? pending.length : count)
877
- .reduce((parent, instance) => resolveInstance(instance, parent, unit), current);
898
+ .reduce((parent, instance) => resolveLocalInstance(instance, parent, unit), current);
878
899
  };
879
900
  const resolved = definitions.reduce<LocalName | undefined>((previous, definition) => {
880
901
  const current = isKey(definition.name)
@@ -902,6 +923,43 @@ const resolveDefinitions = (
902
923
  return resolveInstances(resolved, () => true);
903
924
  };
904
925
 
926
+ // The INSTANCE that a name such as K!C starts with, whose arguments SANY requires at its name.
927
+ const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
928
+ const prefix = name.split("!")[0];
929
+ const binding =
930
+ prefix === name
931
+ ? undefined
932
+ : (lookupLocal(scope, prefix) ?? getModuleBinding(prefix, unit, undefined));
933
+ return binding?.kind === "Instance" ? { name: prefix, arity: binding.arity } : undefined;
934
+ };
935
+
936
+ // Generator.selectorToNode reports an INSTANCE given the wrong number of arguments at its name,
937
+ // as in K!C or K(1, 2)!C, and goes on without analyzing them. Tells whether it reports one.
938
+ const isInstanceArityReported = (
939
+ expression: Expression,
940
+ scope: LocalName | undefined,
941
+ unit: Unit,
942
+ ) => {
943
+ if (expression.kind !== "Identifier" && expression.kind !== "Apply") return false;
944
+ const instance = findInstance(
945
+ expression.kind === "Identifier" ? expression.name : expression.operator,
946
+ scope,
947
+ unit,
948
+ );
949
+ const count = expression.kind === "Apply" ? (expression.argumentCounts?.[0] ?? 0) : 0;
950
+ if (!instance || count === instance.arity) return false;
951
+ const range =
952
+ (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ??
953
+ expression.location.range;
954
+ if (range) {
955
+ unit.errors.push({
956
+ location: formatRange(range),
957
+ message: `The operator ${instance.name} requires ${instance.arity} arguments.`,
958
+ });
959
+ }
960
+ return true;
961
+ };
962
+
905
963
  // Generator.generateExprOrOpArg analyzes an argument as an expression, unless a defined operator
906
964
  // takes an operator in its place, which a name, a built-in operator, or a LAMBDA of the parameter's
907
965
  // arity must give. OpDefNode#match then reports each argument that gives no such operator, or one
@@ -912,16 +970,15 @@ const resolveApply = (
912
970
  scope: LocalName | undefined,
913
971
  unit: Unit,
914
972
  ) => {
973
+ if (isInstanceArityReported(expression, scope, unit)) return;
915
974
  const operator = expression.operator;
916
975
  const callee = findBinding(operator, scope, unit);
917
976
  const arity = getSymbolArity(expression, operator, scope, unit);
918
977
  if (arity === undefined) return;
919
978
  if (arity !== expression.args.length) {
920
979
  unit.errors.push({
921
- location: formatRange(
922
- expression.argumentsRange ?? getNameRange(expression.location, operator),
923
- ),
924
- message: `The operator ${operator} requires ${arity} arguments.`,
980
+ location: formatRange(expression.argumentsRange ?? getSpelledNameRange(expression, operator)),
981
+ message: `The operator ${operator} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
925
982
  });
926
983
  return;
927
984
  }
@@ -963,7 +1020,7 @@ const resolveApply = (
963
1020
  );
964
1021
  } else if (!isMatched && range && arg.operator === undefined) {
965
1022
  report(
966
- expression.selectorRanges?.at(-1) ?? getNameRange(expression.location, operator),
1023
+ expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator),
967
1024
  `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
968
1025
  );
969
1026
  }
@@ -973,6 +1030,16 @@ const resolveApply = (
973
1030
  resolveExpression(arg, scope, unit);
974
1031
  return true;
975
1032
  }
1033
+ // Generator.selectorToNode: a name such as K(1)!C names an operator, but none of its parts
1034
+ // may take arguments.
1035
+ if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
1036
+ const index = arg.argumentCounts.findIndex((count) => count > 0);
1037
+ report(
1038
+ arg.selectorRanges?.[index],
1039
+ `Selector \`${arg.operator.split("!")[index]}' should not have argument(s).`,
1040
+ );
1041
+ return false;
1042
+ }
976
1043
  if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
977
1044
  report(
978
1045
  range,
@@ -985,7 +1052,7 @@ const resolveApply = (
985
1052
  const argArity = getSymbolArity(arg, name, scope, unit);
986
1053
  if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
987
1054
  report(
988
- getNameRange(arg.location, name),
1055
+ getSpelledNameRange(arg, name),
989
1056
  `Expected arity ${expected} but found operator of arity ${argArity}.`,
990
1057
  );
991
1058
  }
@@ -1038,11 +1105,12 @@ const resolveExpression = (
1038
1105
  case "ExceptAt":
1039
1106
  return;
1040
1107
  case "Identifier": {
1108
+ if (isInstanceArityReported(expression, scope, unit)) return;
1041
1109
  const name = expression.name;
1042
1110
  const arity = getSymbolArity(expression, name, scope, unit);
1043
1111
  if (arity !== undefined && arity > 0) {
1044
1112
  unit.errors.push({
1045
- location: formatRange(getNameRange(expression.location, name)),
1113
+ location: formatRange(getSpelledNameRange(expression, name)),
1046
1114
  message: `The operator ${name} requires ${arity} arguments.`,
1047
1115
  });
1048
1116
  }
@@ -1187,10 +1255,21 @@ const resolveExpression = (
1187
1255
  // and analyzes any other fact as an expression.
1188
1256
  const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) =>
1189
1257
  facts.forEach((fact) => {
1190
- if (fact.kind === "ModuleFact" || checkReference(fact, scope, unit, true)) return;
1258
+ if (
1259
+ fact.kind === "ModuleFact" ||
1260
+ isInstanceArityReported(fact, scope, unit) ||
1261
+ checkReference(fact, scope, unit, true)
1262
+ ) {
1263
+ return;
1264
+ }
1191
1265
  const name =
1192
1266
  fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1193
- if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
1267
+ if (fact.kind === "Identifier" && lookupLocal(scope, name)?.isNonFact) {
1268
+ unit.errors.push({
1269
+ location: formatRange(getSpelledNameRange(fact, name)),
1270
+ message: "Step number of non-fact used as a fact",
1271
+ });
1272
+ } else if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
1194
1273
  });
1195
1274
 
1196
1275
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
@@ -1249,8 +1328,8 @@ const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, ou
1249
1328
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
1250
1329
  };
1251
1330
 
1252
- // A step binds the name of the INSTANCE after the names it adds.
1253
- const resolveStepInstance = (instance: Instance, scope: LocalName | undefined, unit: Unit) => {
1331
+ // A LET or a step binds the name of the INSTANCE after the names it adds.
1332
+ const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined, unit: Unit) => {
1254
1333
  const instanced = resolveInstance(instance, scope, unit);
1255
1334
  return instance.name === undefined
1256
1335
  ? instanced
@@ -1262,6 +1341,8 @@ const resolveStepInstance = (instance: Instance, scope: LocalName | undefined, u
1262
1341
  );
1263
1342
  };
1264
1343
 
1344
+ // Generator.generateProof binds the name of a step after its statement and before its proof, or
1345
+ // after the step where it takes no proof.
1265
1346
  const resolveStep = (
1266
1347
  step: ProofStep,
1267
1348
  scope: LocalName | undefined,
@@ -1272,6 +1353,12 @@ const resolveStep = (
1272
1353
  step.name === undefined
1273
1354
  ? unit
1274
1355
  : { ...unit, hasLabelScope: true, labelParams: [], labels: new Set<string>() };
1356
+ const bindStep = (parent: LocalName | undefined): LocalName | undefined =>
1357
+ step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent };
1358
+ const bindNonFactStep = (parent: LocalName | undefined): LocalName | undefined =>
1359
+ step.name === undefined
1360
+ ? parent
1361
+ : { name: step.name, arity: 0, kind: "Theorem", parent, isNonFact: true };
1275
1362
  switch (body.kind) {
1276
1363
  // The NEW symbols of a SUFFICES ASSUME are in scope after its proof, and those of any other
1277
1364
  // ASSUME in its proof.
@@ -1291,31 +1378,35 @@ const resolveStep = (
1291
1378
  case "Use":
1292
1379
  case "Hide":
1293
1380
  checkFacts(body.facts, scope, unit);
1294
- return scope;
1381
+ return bindNonFactStep(scope);
1295
1382
  case "Instance":
1296
- return resolveStepInstance(body, scope, stepUnit);
1383
+ return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit));
1297
1384
  case "Define":
1298
- return body.definitions.reduce(
1299
- (current, definition) =>
1300
- definition.kind === "Instance"
1301
- ? resolveStepInstance(definition, current, stepUnit)
1302
- : resolveDefinitions([definition], current, unit),
1303
- scope,
1385
+ return bindNonFactStep(
1386
+ body.definitions.reduce(
1387
+ (current, definition) =>
1388
+ definition.kind === "Instance"
1389
+ ? resolveLocalInstance(definition, current, stepUnit)
1390
+ : resolveDefinitions([definition], current, unit),
1391
+ scope,
1392
+ ),
1304
1393
  );
1305
1394
  case "Have":
1306
1395
  case "Case":
1307
1396
  resolveExpression(body.expression, scope, stepUnit);
1308
- resolveProof(step.proof, scope, unit);
1309
- return scope;
1397
+ resolveProof(step.proof, bindStep(scope), unit);
1398
+ return bindStep(scope);
1310
1399
  case "Witness":
1311
1400
  body.expressions.forEach((expression) => resolveExpression(expression, scope, stepUnit));
1312
- return scope;
1401
+ return bindStep(scope);
1313
1402
  case "Take":
1314
- return bindNames(
1315
- resolveBounds(body.bounds, scope, stepUnit),
1316
- body.names,
1317
- body.nameRanges,
1318
- stepUnit,
1403
+ return bindStep(
1404
+ bindNames(
1405
+ resolveBounds(body.bounds, scope, stepUnit),
1406
+ body.names,
1407
+ body.nameRanges,
1408
+ stepUnit,
1409
+ ),
1319
1410
  );
1320
1411
  case "Pick": {
1321
1412
  const picked = bindNames(
@@ -1328,12 +1419,12 @@ const resolveStep = (
1328
1419
  ...stepUnit,
1329
1420
  labelParams: [...stepUnit.labelParams, ...getBoundNames(body.bounds), ...body.names],
1330
1421
  });
1331
- resolveProof(step.proof, scope, unit);
1332
- return picked;
1422
+ resolveProof(step.proof, bindStep(scope), unit);
1423
+ return bindStep(picked);
1333
1424
  }
1334
1425
  default:
1335
- resolveProof(step.proof, scope, unit);
1336
- return scope;
1426
+ resolveProof(step.proof, bindStep(scope), unit);
1427
+ return bindStep(scope);
1337
1428
  }
1338
1429
  };
1339
1430
 
package/src/run-cli.ts CHANGED
@@ -168,6 +168,7 @@ const USAGE = [
168
168
  ` ${PROVE_COMMAND.usage}`,
169
169
  " tla-ts prove [<tlapm option>]... <Module.tla|glob>...",
170
170
  " tla-ts [<JVM option>]... tlc2.TLC <TLC option>... <Spec>",
171
+ " (-cp tla2tools.jar or -Dtla-ts.tlc=1.7.4 picks the TLC to reproduce)",
171
172
  " tla-ts [<JVM option>]... tla2sany.xml.XMLExporter [-I <directory>]... [-o] [-t] [-r] [-u] <Module.tla>",
172
173
  ].join("\n");
173
174
 
@@ -931,9 +932,7 @@ const checkSpec = async (
931
932
  const specName = isAbsoluteSpec ? fileName : specPath.replace(/\.tla$/, "");
932
933
  const jar = getJar(java);
933
934
  const reportMissingFile =
934
- version === "1.7.4" && jar !== undefined
935
- ? createMissingFilePrinter174(specPath, java, jar)
936
- : undefined;
935
+ version === "1.7.4" ? createMissingFilePrinter174(specPath, java, jar) : undefined;
937
936
  if (reportMissingFile) {
938
937
  if (!existsSync(specPath) && !SANY_174_STANDARD_MODULES.has(fileName)) {
939
938
  reportMissingFile(`${fileName}.tla`);
@@ -1248,7 +1247,7 @@ const checkSpecs = async (args: string[], java: JavaProperties) => {
1248
1247
  ? path
1249
1248
  : (java.libraries.map((directory) => join(directory, path)).find(existsSync) ?? path);
1250
1249
  const paths = [...new Set(specPaths.map(findSpec))];
1251
- const tlcVersion = getTlcVersion(getJar(java));
1250
+ const tlcVersion = getJavaTlcVersion(java);
1252
1251
  return runEach(
1253
1252
  paths,
1254
1253
  (path, printer) => {
@@ -1354,10 +1353,11 @@ const exportXml = (args: string[]) => {
1354
1353
  };
1355
1354
 
1356
1355
  // TLC 1.7.4's FileUtil.createNamedInputStream names the last file that SimpleFilenameToStream
1357
- // looked for a module in, and the directories it looks in, the standard modules in the jar last.
1358
- const printMissingFile174 = (path: string, libraries: string[], jar: string) =>
1356
+ // looked for a module in, and the directories it looks in, the standard modules in the jar last,
1357
+ // which tla-ts leaves out without a jar.
1358
+ const printMissingFile174 = (path: string, libraries: string[], jar: string | undefined) =>
1359
1359
  console.error(
1360
- `File does not exist: ${isAbsolute(path) ? path : `${process.cwd()}/${path}`} while looking in these directories: ${[...libraries, getStandardModulesUrl(jar)].join(", ")}`,
1360
+ `File does not exist: ${isAbsolute(path) ? path : `${process.cwd()}/${path}`} while looking in these directories: ${[...libraries, ...(jar === undefined ? [] : [getStandardModulesUrl(jar)])].join(", ")}`,
1361
1361
  );
1362
1362
 
1363
1363
  // SimpleFilenameToStream ends a library directory with a separator.
@@ -1367,7 +1367,11 @@ const toLibraryPath = (directory: string) =>
1367
1367
  // TLC 1.7.4's SimpleFilenameToStream looks for a module in the directory of a spec that TLC is
1368
1368
  // given by an absolute path, then in the directory that a relative path names, or else in the
1369
1369
  // TLA-Library directories.
1370
- const createMissingFilePrinter174 = (specPath: string, java: JavaProperties, jar: string) => {
1370
+ const createMissingFilePrinter174 = (
1371
+ specPath: string,
1372
+ java: JavaProperties,
1373
+ jar: string | undefined,
1374
+ ) => {
1371
1375
  const specDirectory = specPath.slice(0, specPath.lastIndexOf("/") + 1);
1372
1376
  const isRelativeToDirectory = !isAbsolute(specPath) && specDirectory !== "";
1373
1377
  const libraries = (isRelativeToDirectory ? [specDirectory] : java.libraries).map(toLibraryPath);
@@ -1400,7 +1404,7 @@ const printXmlExporterException = (exception: string, line: number) => {
1400
1404
 
1401
1405
  // TLC 1.7.4's XMLExporter.main, which takes only -o, as it can't validate the XML without
1402
1406
  // fetching its schema, and -I, and exports a specification that SANY finds errors in.
1403
- const exportXml174 = (args: string[], jar: string) => {
1407
+ const exportXml174 = (args: string[], jar: string | undefined) => {
1404
1408
  if (args.length === 0) {
1405
1409
  return printXmlExporterException(
1406
1410
  "java.lang.IllegalArgumentException: at least one .tla file must be given",
@@ -1461,25 +1465,32 @@ const exportXml174 = (args: string[], jar: string) => {
1461
1465
  // java, as in `tla-ts -DTLA-Library=lib -cp tla2tools.jar tlc2.TLC Spec`. tla-ts searches the
1462
1466
  // TLA-Library directories for modules as TLC does, though not as XMLExporter, which ignores them,
1463
1467
  // names the files in java.io.tmpdir and the jar on the class path that TLC would copy and read
1464
- // modules from, and ignores the other options.
1468
+ // modules from, and ignores the other options. It reproduces the TLC of that jar, or the one that
1469
+ // -Dtla-ts.tlc names without a jar, as in `tla-ts -Dtla-ts.tlc=1.7.4 tlc2.TLC Spec`.
1465
1470
  const JAVA_MAIN_CLASSES = ["tlc2.TLC", "tla2sany.xml.XMLExporter"];
1466
1471
 
1467
1472
  const TLA_LIBRARY_PROPERTY = "-DTLA-Library=";
1468
1473
 
1469
1474
  const TEMPORARY_DIRECTORY_PROPERTY = "-Djava.io.tmpdir=";
1470
1475
 
1476
+ const TLC_VERSION_PROPERTY = "-Dtla-ts.tlc=";
1477
+
1471
1478
  // What the java command sets for TLC: the TLA-Library directories it searches for modules, the
1472
1479
  // class path it finds its standard modules on, and java.io.tmpdir, where it copies them.
1473
1480
  interface JavaProperties {
1474
1481
  libraries: string[];
1475
1482
  classPath?: string;
1476
1483
  temporaryDirectory?: string;
1484
+ tlcVersion?: TlcVersion;
1477
1485
  }
1478
1486
 
1479
1487
  // The tla2tools.jar on the class path.
1480
1488
  const getJar = (java: JavaProperties) =>
1481
1489
  java.classPath?.split(delimiter).find((entry) => entry.endsWith(".jar"));
1482
1490
 
1491
+ // The TLC that -Dtla-ts.tlc names, or else the one of the jar on the class path.
1492
+ const getJavaTlcVersion = (java: JavaProperties) => java.tlcVersion ?? getTlcVersion(getJar(java));
1493
+
1483
1494
  interface JavaLaunch {
1484
1495
  mainClass: string;
1485
1496
  args: string[];
@@ -1500,6 +1511,8 @@ const getJavaLaunch = (args: string[]): JavaLaunch | undefined => {
1500
1511
  java.libraries.push(...arg.slice(TLA_LIBRARY_PROPERTY.length).split(delimiter));
1501
1512
  } else if (arg.startsWith(TEMPORARY_DIRECTORY_PROPERTY)) {
1502
1513
  java.temporaryDirectory = arg.slice(TEMPORARY_DIRECTORY_PROPERTY.length);
1514
+ } else if (arg.startsWith(TLC_VERSION_PROPERTY)) {
1515
+ java.tlcVersion = arg.slice(TLC_VERSION_PROPERTY.length) === "1.7.4" ? "1.7.4" : "master";
1503
1516
  } else if (!arg.startsWith("-D") && !arg.startsWith("-X")) {
1504
1517
  const isLaunch = index > 0 || JAVA_MAIN_CLASSES.includes(arg);
1505
1518
  return isLaunch ? { mainClass: arg, args: args.slice(index + 1), java } : undefined;
@@ -1511,10 +1524,9 @@ const getJavaLaunch = (args: string[]): JavaLaunch | undefined => {
1511
1524
  const runJavaClass = (launch: JavaLaunch) => {
1512
1525
  if (launch.mainClass === "tlc2.TLC") return checkSpecs(launch.args, launch.java);
1513
1526
  if (launch.mainClass === "tla2sany.xml.XMLExporter") {
1514
- const jar = getJar(launch.java);
1515
1527
  return reportErrors(() =>
1516
- jar !== undefined && getTlcVersion(jar) === "1.7.4"
1517
- ? exportXml174(launch.args, jar)
1528
+ getJavaTlcVersion(launch.java) === "1.7.4"
1529
+ ? exportXml174(launch.args, getJar(launch.java))
1518
1530
  : exportXml(launch.args),
1519
1531
  );
1520
1532
  }
@@ -164,6 +164,9 @@ export interface SanySpecification {
164
164
  export interface SanyGenerationOptions {
165
165
  // The name of the root module's file, which SANY requires to match the module's name.
166
166
  rootFileName?: string;
167
+ // The path of the root module's file as SANY's caller gives it, which SANY names when it cannot
168
+ // parse the file, rather than the file name it gives the other modules.
169
+ rootFilePath?: string;
167
170
  // Called before SANY parses the file of each module, and before it analyzes each external
168
171
  // module, in its order.
169
172
  onParse?: (name: string) => void;
@@ -342,6 +345,12 @@ const OPERATOR_ARGUMENT_KINDS = new Set<Expression["kind"]>([
342
345
  "Lambda",
343
346
  ]);
344
347
 
348
+ // A name such as K(1)!C, whose last part takes no arguments, is a GeneralId too.
349
+ const isOperatorArgument = (argument: Expression) => {
350
+ const items = argument.kind === "Apply" ? getSelectorItems(argument) : undefined;
351
+ return OPERATOR_ARGUMENT_KINDS.has(argument.kind) || (items !== undefined && isGeneralId(items));
352
+ };
353
+
345
354
  // The parts of a DEF clause entry that isn't a name, as Generator.genIdToSelector reads them.
346
355
  interface DefEntryParts {
347
356
  hasChildlessFirstChild: boolean | undefined;
@@ -476,12 +485,9 @@ export const generateSanySpecification = (
476
485
  const sources = new Map<string, { file: SourceFile; module: Module }>();
477
486
 
478
487
  const parseSource = (name: string, text: string) => {
488
+ const file = (name === options.rootFileName && options.rootFilePath) || `${name}.tla`;
479
489
  const getParseFailure = (parseError: string) =>
480
- new TlaSanyFatalError(
481
- `Could not parse module ${name} from file ${name}.tla`,
482
- name,
483
- parseError,
484
- );
490
+ new TlaSanyFatalError(`Could not parse module ${name} from file ${file}`, name, parseError);
485
491
  const lexicalError = options.version === "1.7.4" ? getSany174LexicalError(text) : undefined;
486
492
  if (lexicalError !== undefined) throw getParseFailure(lexicalError);
487
493
  // HACK: the parser's errors are not SANY's, so a module that fails to parse gets the report
@@ -1006,27 +1012,31 @@ export const generateSanySpecification = (
1006
1012
  ? argument.body.operator
1007
1013
  : file.tokens[getTokenIndex(file, argument.location)].text;
1008
1014
 
1009
- const generateOperatorArgument = (argument: Expression, expectedArity: number): OpArgNode => {
1015
+ // Generator.generateOpArg: after an error, SANY gives its nullOpArg.
1016
+ const generateOperatorArgument = (
1017
+ argument: Expression,
1018
+ target: OpDeclNode,
1019
+ ): OpArgNode | OpApplNode => {
1010
1020
  const location = getLocation(argument);
1011
1021
  if (argument.kind === "Lambda") {
1012
1022
  if (argument.location.range !== undefined)
1013
1023
  return createOpArg(generateLambda(argument), location);
1014
1024
  return createOpArg(resolveName(getOperatorArgumentName(argument), location), location);
1015
1025
  }
1016
- if (argument.kind === "Identifier" || argument.kind === "Subexpression") {
1017
- const node = generateSelector(argument, expectedArity, false, false);
1018
- if (node.kind !== "OpArg") {
1019
- throw new TlaSyntaxError(
1020
- `Expected an operator argument at line ${location.beginLine}, column ${location.beginColumn}`,
1021
- );
1022
- }
1023
- return node;
1026
+ if (!isOperatorArgument(argument)) {
1027
+ addError(
1028
+ location,
1029
+ `Arity ${target.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${target.name}'.`,
1030
+ );
1031
+ return createNullNode();
1024
1032
  }
1025
1033
  if (argument.kind === "OperatorReference") {
1026
1034
  return createOpArg(resolveName(argument.operator, location), location);
1027
1035
  }
1036
+ const node = generateSelector(argument, target.arity, false, false);
1037
+ if (node.kind === "OpArg" || (node.kind === "OpAppl" && node.isNull === true)) return node;
1028
1038
  throw new TlaSyntaxError(
1029
- `An expression appears where an operator is required at line ${location.beginLine}`,
1039
+ `Expected an operator argument at line ${location.beginLine}, column ${location.beginColumn}`,
1030
1040
  );
1031
1041
  };
1032
1042
 
@@ -1047,14 +1057,18 @@ export const generateSanySpecification = (
1047
1057
  const location = getSpanLocation(file, span);
1048
1058
  const position = `${index + 1} (counting from 1)`;
1049
1059
  const argumentSpan = getArgumentSpan(file, span);
1050
- if (argumentSpan !== span || !OPERATOR_ARGUMENT_KINDS.has(argument.kind)) {
1060
+ if (argumentSpan !== span || !isOperatorArgument(argument)) {
1051
1061
  addError(
1052
1062
  getSpanLocation(file, argumentSpan),
1053
1063
  `An expression appears as argument number ${position} to operator '${operator.name}', in a position an operator is required.`,
1054
1064
  );
1055
1065
  return createNullNode();
1056
1066
  }
1057
- if (argument.kind === "Identifier" || argument.kind === "Subexpression") {
1067
+ if (
1068
+ argument.kind === "Identifier" ||
1069
+ argument.kind === "Subexpression" ||
1070
+ argument.kind === "Apply"
1071
+ ) {
1058
1072
  // The selector names the operator, or reports why not and gives SANY's nullOAN.
1059
1073
  const node = generateSelector(argument, expectedArity, false, false);
1060
1074
  if (node.kind === "OpArg" || node.kind === "OpAppl") return node;
@@ -1969,10 +1983,12 @@ export const generateSanySpecification = (
1969
1983
  },
1970
1984
  ];
1971
1985
  });
1972
- // Generator.checkSubstitutionForCorrectArity.
1986
+ // Generator.checkSubstitutionForCorrectArity, which SANY locates in its builtins for the
1987
+ // nullOpArg it substitutes after an error.
1973
1988
  const checkArity = (target: OpDeclNode, expr: ExprOrOpArgNode) => {
1974
1989
  const arity = expr.kind === "OpArg" ? getSymbolArity(expr.op) : 0;
1975
- if (arity !== target.arity) {
1990
+ const isNullOpArg = target.arity > 0 && expr.kind === "OpAppl" && expr.isNull === true;
1991
+ if (arity !== target.arity && !isNullOpArg) {
1976
1992
  addError(
1977
1993
  expr.location,
1978
1994
  `An operator must be substituted for symbol '${target.name}', and it must have arity ${target.arity}.`,
@@ -1999,7 +2015,7 @@ export const generateSanySpecification = (
1999
2015
  const expr =
2000
2016
  target.arity === 0
2001
2017
  ? generateExpression(substitution.expression)
2002
- : generateOperatorArgument(substitution.expression, target.arity);
2018
+ : generateOperatorArgument(substitution.expression, target);
2003
2019
  checkArity(target, expr);
2004
2020
  const existing = substs.find((subst) => subst.op.name === target.name);
2005
2021
  if (existing && !existing.isImplicit) {
@@ -265,6 +265,8 @@ export const getSanyReport = (
265
265
  loadValidatedModule(rootName, source);
266
266
  return generateSanySpecification(source, loadSource, {
267
267
  rootFileName: rootName,
268
+ // XMLExporter gives SANY the file it is asked for, and TLC the name of the module.
269
+ rootFilePath: options.isXmlExport ? `${name.replace(/\.tla$/, "")}.tla` : undefined,
268
270
  version: options.version,
269
271
  rootExtendees: options.rootExtendees,
270
272
  onParse: (moduleName) => {
@@ -550,6 +550,10 @@ export const SANY_NODE_NAMES = [
550
550
  "N_AssertStep",
551
551
  ];
552
552
 
553
+ // The standard modules that a spec may ship its own file of, such as CommunityModules' Json.tla,
554
+ // which SANY reads in place of its own.
555
+ export const USER_STANDARD_MODULES = new Set(["Bags", "Json", "Randomization", "TLCExt"]);
556
+
553
557
  export const TLC_MODULE_SOURCES = new Map([
554
558
  [
555
559
  "Naturals",
package/src/tlc-order.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  TLC_MODULE_SOURCES,
14
14
  TLC_RUNTIME_STRINGS,
15
15
  TLC_STARTUP_STRINGS,
16
+ USER_STANDARD_MODULES,
16
17
  } from "./tlc-modules";
17
18
 
18
19
  type SymbolKind = "builtin" | "constant" | "variable" | "definition" | "theorem" | "module";
@@ -259,7 +260,10 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
259
260
  const text =
260
261
  name === undefined
261
262
  ? source
262
- : (TLC_MODULE_SOURCES.get(name) ?? loadModule?.(name) ?? extractModule(source, name));
263
+ : ((USER_STANDARD_MODULES.has(name) ? loadModule?.(name) : undefined) ??
264
+ TLC_MODULE_SOURCES.get(name) ??
265
+ loadModule?.(name) ??
266
+ extractModule(source, name));
263
267
  const tokens = text === undefined ? [] : tokenize(text);
264
268
  const ranges = getRanges(tokens);
265
269
  const range = ranges.get(getModuleName(tokens) ?? "") ?? { start: 0, end: 0 };
package/src/values.ts CHANGED
@@ -489,8 +489,24 @@ export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>
489
489
  return value;
490
490
  };
491
491
 
492
+ // The sets that stream their elements apart from the normalized set until TLC caches them.
493
+ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
494
+ "Union",
495
+ "SetOperation",
496
+ "FilteredSet",
497
+ "ProductSet",
498
+ "RecordSet",
499
+ "FunctionSet",
500
+ ]);
501
+
492
502
  const cacheSet = (value: Value) => {
493
- if (streamedSetPresence.isPresent && typeof value === "object") cachedSets.add(value);
503
+ if (
504
+ streamedSetPresence.isPresent &&
505
+ typeof value === "object" &&
506
+ STREAMING_KINDS.has(value.kind)
507
+ ) {
508
+ cachedSets.add(value);
509
+ }
494
510
  };
495
511
 
496
512
  // FcnLambdaValue#fingerPrint caches the FcnRcdValue the function enumerates to, which applies it