tla-ts 0.0.3-dev.bfd303f → 0.0.3-dev.c949d82

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/evaluate.ts CHANGED
@@ -10,10 +10,9 @@ import {
10
10
  type NumberExpression,
11
11
  type OperatorParam,
12
12
  type RecordField,
13
- type SourceRange,
14
13
  } from "./ast";
15
14
  import { getKindString } from "./builtins";
16
- import { TlaEvaluationError } from "./errors";
15
+ import { formatRange, TlaEvaluationError } from "./errors";
17
16
  import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
18
17
  import { generateEvaluator } from "./codegen";
19
18
  import type { CheckerRuntime } from "./runtime";
@@ -146,9 +145,6 @@ const EXCEPT_AT = "@";
146
145
  export const describeLocation = (expression: Expression) =>
147
146
  `line ${expression.location.line}, column ${expression.location.column}`;
148
147
 
149
- export const formatRange = (range: SourceRange) =>
150
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
151
-
152
148
  export const describeRange = (expression: Expression) => {
153
149
  const range = expression.location.range;
154
150
  return range ? formatRange(range) : describeLocation(expression);
package/src/live-check.ts CHANGED
@@ -100,7 +100,9 @@ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
100
100
  }
101
101
  };
102
102
 
103
- const isWritten = (check: Check, node: number) => check.offsets[node] !== -1;
103
+ // Without a tableau a node is a state, so a successor the search hasn't expanded yet may lie past
104
+ // the per-node arrays.
105
+ const isWritten = (check: Check, node: number) => (check.offsets[node] ?? -1) !== -1;
104
106
 
105
107
  const getPending = (check: Check, node: number) => (check.pending[node] ??= []);
106
108
 
package/src/parser.ts CHANGED
@@ -22,7 +22,7 @@ import type {
22
22
  StepBody,
23
23
  UseOrHide,
24
24
  } from "./ast";
25
- import { TlaSyntaxError } from "./errors";
25
+ import { createSanyError, formatRange, TlaSyntaxError } from "./errors";
26
26
  import { getNumeralValue, tokenize, type Token } from "./lexer";
27
27
 
28
28
  interface InfixOperator {
@@ -631,11 +631,15 @@ const parse = (source: string, isTlapm: boolean): Module => {
631
631
  return parseExpression();
632
632
  };
633
633
 
634
+ const lastArguments: { range: SourceRange | undefined } = { range: undefined };
635
+
634
636
  const parseArguments = () =>
635
637
  withoutOffside(() => {
638
+ const start = cursor.index;
636
639
  expect("(");
637
640
  const args = parseSeparated(parseArgument);
638
641
  expect(")");
642
+ lastArguments.range = getRange(start);
639
643
  return args;
640
644
  });
641
645
 
@@ -856,7 +860,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
856
860
  const args = hasArguments ? parseArguments() : [];
857
861
  if (!isSelectorAhead()) {
858
862
  return hasArguments
859
- ? { kind: "Apply", operator: name, args, location }
863
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
860
864
  : { kind: "Identifier", name, location };
861
865
  }
862
866
  const instance = openModules
@@ -885,9 +889,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
885
889
  const argumentCounts = selectors.map((selector) =>
886
890
  "args" in selector ? selector.args.length : 0,
887
891
  );
892
+ const argumentsRange = lastArguments.range;
888
893
  return argumentCounts.slice(0, -1).some((count) => count > 0)
889
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, location }
890
- : { kind: "Apply", operator, args: qualifiedArgs, location };
894
+ ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, argumentsRange, location }
895
+ : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
891
896
  }
892
897
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
893
898
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -1423,11 +1428,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1423
1428
  location: getLocation(keyword),
1424
1429
  };
1425
1430
  const invalid =
1426
- use.kind === "Hide" && !isTlapm ? use.facts.find((fact) => !isHideFact(fact)) : undefined;
1427
- if (invalid) {
1428
- throw createError(
1429
- "The only expression allowed as a fact in a HIDE is the name of a theorem, assumption, or step",
1430
- invalid.location,
1431
+ use.kind === "Hide" && !isTlapm ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1432
+ if (invalid.length > 0) {
1433
+ throw createSanyError(
1434
+ invalid.map((fact) => ({
1435
+ location: formatRange(fact.location.range ?? getRange(start)),
1436
+ message:
1437
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1438
+ })),
1431
1439
  );
1432
1440
  }
1433
1441
  return withRange(use, start);
package/src/resolve.ts CHANGED
@@ -13,9 +13,10 @@ import {
13
13
  type Proof,
14
14
  type ProofStep,
15
15
  type SourceLocation,
16
+ type SourceRange,
16
17
  type Theorem,
17
18
  } from "./ast";
18
- import { TlaSyntaxError } from "./errors";
19
+ import { createSanyError, createSemanticError, formatRange, TlaSyntaxError } from "./errors";
19
20
 
20
21
  export interface ModuleSymbol {
21
22
  key: string;
@@ -103,6 +104,21 @@ const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
103
104
  : unit.imported.get(name);
104
105
  };
105
106
 
107
+ // SANY reports a name at the range of its text.
108
+ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
109
+ module: location.range?.module ?? "",
110
+ start: location,
111
+ end: { line: location.line, column: location.column + name.length - 1 },
112
+ });
113
+
114
+ // SANY reports an operator symbol applied to operands as one it cannot resolve.
115
+ const getFixity = (expression: Expression) => {
116
+ if (expression.kind !== "Apply") return undefined;
117
+ if (expression.args.length === 2) return "infix";
118
+ if (expression.args.length !== 1) return undefined;
119
+ return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
120
+ };
121
+
106
122
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
107
123
  const isOperatorSymbol = (name: string) =>
108
124
  name[0].toLowerCase() === name[0].toUpperCase() &&
@@ -135,7 +151,7 @@ const getSymbolArity = (
135
151
  }
136
152
  // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
137
153
  // arguments.
138
- const prefix = name.slice(0, name.indexOf("!"));
154
+ const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
139
155
  const isSelected =
140
156
  prefix !== "" &&
141
157
  (lookupLocal(scope, prefix) !== undefined ||
@@ -144,11 +160,23 @@ const getSymbolArity = (
144
160
  if (isSelected) {
145
161
  return expression.kind === "Apply" ? expression.args.length : 0;
146
162
  }
147
- const position = `at line ${location.line}, column ${location.column}`;
148
- throw new TlaSyntaxError(
149
- isOperatorSymbol(name)
150
- ? `Could not find declaration or definition of symbol '${name}' ${position}`
151
- : `Unknown operator: \`${name}' ${position}`,
163
+ const range = getNameRange(location, name === "-." ? "-" : name);
164
+ if (!isOperatorSymbol(name)) throw createSemanticError(`Unknown operator: \`${name}'.`, range);
165
+ const missing = {
166
+ location: formatRange(range),
167
+ message: `Could not find declaration or definition of symbol '${name}'.`,
168
+ };
169
+ const fixity = getFixity(expression);
170
+ throw createSanyError(
171
+ fixity && location.range
172
+ ? [
173
+ missing,
174
+ {
175
+ location: formatRange(location.range),
176
+ message: `Couldn't resolve ${fixity} operator symbol \`${name}'.`,
177
+ },
178
+ ]
179
+ : [missing],
152
180
  );
153
181
  };
154
182
 
@@ -235,13 +263,13 @@ const resolveApply = (
235
263
  scope: LocalName | undefined,
236
264
  unit: Unit,
237
265
  ) => {
238
- const callee = lookupLocal(scope, expression.operator)
239
- ? undefined
240
- : getVisibleDefinition(expression.operator, unit);
241
- const arity = getSymbolArity(expression, expression.operator, scope, unit);
266
+ const operator = expression.operator;
267
+ const callee = lookupLocal(scope, operator) ? undefined : getVisibleDefinition(operator, unit);
268
+ const arity = getSymbolArity(expression, operator, scope, unit);
242
269
  if (arity !== expression.args.length) {
243
- throw new TlaSyntaxError(
244
- `The operator ${expression.operator} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
270
+ throw createSemanticError(
271
+ `The operator ${operator} requires ${arity} arguments.`,
272
+ expression.argumentsRange ?? getNameRange(expression.location, operator),
245
273
  );
246
274
  }
247
275
  expression.args.forEach((arg, index) => {
@@ -275,10 +303,12 @@ const resolveExpression = (
275
303
  case "ExceptAt":
276
304
  return;
277
305
  case "Identifier": {
278
- const arity = getSymbolArity(expression, expression.name, scope, unit);
306
+ const name = expression.name;
307
+ const arity = getSymbolArity(expression, name, scope, unit);
279
308
  if (arity > 0) {
280
- throw new TlaSyntaxError(
281
- `The operator ${expression.name} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
309
+ throw createSemanticError(
310
+ `The operator ${name} requires ${arity} arguments.`,
311
+ getNameRange(expression.location, name),
282
312
  );
283
313
  }
284
314
  return;
package/src/run-cli.ts CHANGED
@@ -14,12 +14,14 @@ import type { CheckResult, CheckStatus, TraceStep } from "./check";
14
14
  import { defineCommand, type ParsedArgs } from "./cli-options";
15
15
  import { parseConfig } from "./config";
16
16
  import {
17
+ createSanyError,
17
18
  getErrorExitCode,
18
19
  TlaConfigError,
19
20
  TlaError,
20
21
  TlaEvaluationError,
21
22
  TlaProofError,
22
23
  TlaSyntaxError,
24
+ type SanyReport,
23
25
  } from "./errors";
24
26
  import { EXIT_STATUS } from "./exit-codes";
25
27
  import type { LineRange } from "./obligation-generate";
@@ -219,8 +221,14 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
219
221
  const fileName = basename(specPath, ".tla");
220
222
  const moduleName = parseModule(source).name;
221
223
  if (moduleName !== fileName) {
222
- throw new TlaSyntaxError(
223
- `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
224
+ throw createSanyError(
225
+ [
226
+ {
227
+ location: "Unknown location",
228
+ message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
229
+ },
230
+ ],
231
+ true,
224
232
  );
225
233
  }
226
234
  const configPath =
@@ -286,21 +294,32 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
286
294
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
287
295
  };
288
296
 
289
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
290
- const printError = (error: TlaError) => {
297
+ const formatSanyErrors = (report: SanyReport) =>
298
+ `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
299
+
300
+ // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
301
+ // others, such as a module it cannot parse.
302
+ const printError = (error: TlaError, path?: string) => {
291
303
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
292
304
  return console.log(`Error: ${error.message}`);
293
305
  }
294
- console.error(`${error.name}: ${error.message}`);
306
+ const report = error instanceof TlaSyntaxError ? error.sany : undefined;
307
+ if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
308
+ console.log(
309
+ report.isFatal
310
+ ? `\nFatal errors while parsing TLA+ spec in file ${basename(path, ".tla")}\n\n${report.errors.map((item) => `${item.location}\n\n${item.message}\n`).join("")}${formatSanyErrors(report)}\n`
311
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
312
+ );
313
+ console.log("Error: Parsing or semantic analysis failed.");
295
314
  };
296
315
 
297
316
  // Prints a TlaError and returns its exit code.
298
- const reportErrors = async (run: () => number | Promise<number>) => {
317
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
299
318
  try {
300
319
  return await run();
301
320
  } catch (error) {
302
321
  if (!(error instanceof TlaError)) throw error;
303
- printError(error);
322
+ printError(error, path);
304
323
  return getErrorExitCode(error);
305
324
  }
306
325
  };
@@ -311,7 +330,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
311
330
  const exitCodes: number[] = [];
312
331
  for (const [index, path] of paths.entries()) {
313
332
  if (index > 0) console.log("");
314
- exitCodes.push(await reportErrors(() => runPath(path)));
333
+ exitCodes.push(await reportErrors(() => runPath(path), path));
315
334
  }
316
335
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
317
336
  };
@@ -7,13 +7,12 @@ import {
7
7
  } from "./ast";
8
8
  import type { ModelConfig } from "./config";
9
9
  import type { InstanceAction } from "./environment";
10
- import { TlaError } from "./errors";
10
+ import { formatRange, TlaError } from "./errors";
11
11
  import {
12
12
  bindDefinitions,
13
13
  bindOperatorArguments,
14
14
  evaluate,
15
15
  forEachBinding,
16
- formatRange,
17
16
  getDefinition,
18
17
  isConstantLevel,
19
18
  lookupScope,