@nova-energy/openamx 0.11.0 → 0.14.0

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.
@@ -1,4 +1,4 @@
1
- import { declarationNameRange, sourceTokenRange } from "./sourceRanges";
1
+ import { declarationNameRange, sourceOffset, sourceTokenRange } from "./sourceRanges";
2
2
  function statementsOf(document) {
3
3
  return document.nodes.flatMap(node => node.type === "executableCodeBlock" ? node.statements : []);
4
4
  }
@@ -28,6 +28,13 @@ function declaration(text, file, statement) {
28
28
  function moduleRecord(analysis, file) {
29
29
  return analysis?.modules?.get(file);
30
30
  }
31
+ function enumMemberSource(text, source) {
32
+ const dot = source && sourceOffset(text, source);
33
+ if (dot === undefined || text[dot] !== ".")
34
+ return undefined;
35
+ const whitespace = text.slice(dot + 1).match(/^\s*/)?.[0].length ?? 0;
36
+ return { line: source.line, column: source.column + 1 + whitespace };
37
+ }
31
38
  /** Build identity-bearing symbol occurrences; uncertain parser spans and duplicate declarations have no target. */
32
39
  export function editorSymbolFacts(text, entryFile, entryDocument, analysis, moduleSources = new Map()) {
33
40
  const documents = new Map();
@@ -36,6 +43,37 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
36
43
  documents.set(file, module.document);
37
44
  documents.set(entryFile, entryDocument);
38
45
  const result = [];
46
+ const enumMemberTargets = new Map();
47
+ for (const [file, document] of documents) {
48
+ const moduleText = file === entryFile ? text : moduleSources.get(file);
49
+ if (moduleText === undefined)
50
+ continue;
51
+ const statements = statementsOf(document);
52
+ const enumDeclarations = statements.filter((statement) => statement.type === "enumDeclaration");
53
+ for (const declarationNode of enumDeclarations) {
54
+ const nameCount = enumDeclarations.filter(item => item.name === declarationNode.name).length;
55
+ const memberCounts = new Map();
56
+ declarationNode.members.forEach(member => memberCounts.set(member.name, (memberCounts.get(member.name) ?? 0) + 1));
57
+ if (nameCount !== 1 || [...memberCounts.values()].some(count => count > 1))
58
+ continue;
59
+ for (const member of declarationNode.members) {
60
+ const range = sourceTokenRange(moduleText, member.nameSource, member.name);
61
+ if (!range)
62
+ continue;
63
+ const parent = declaration(moduleText, file, declarationNode)?.target;
64
+ enumMemberTargets.set(`${file}\0${declarationNode.name}\0${member.name}`, {
65
+ ...range,
66
+ file,
67
+ name: member.name,
68
+ target: { file, ...range },
69
+ parent,
70
+ declaration: true,
71
+ kind: "enumMember",
72
+ detail: `enum member ${declarationNode.name}.${member.name}`
73
+ });
74
+ }
75
+ }
76
+ }
39
77
  for (const [file, document] of documents) {
40
78
  const moduleText = file === entryFile ? text : moduleSources.get(file);
41
79
  if (moduleText === undefined)
@@ -45,6 +83,7 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
45
83
  const declarations = statements.filter(statement => "name" in statement && declarationNameRange(moduleText, statement));
46
84
  const duplicates = new Set(declarations.filter((candidate, index) => declarations.some((other, otherIndex) => otherIndex !== index && "name" in other && "name" in candidate && other.name === candidate.name)).map(statement => "name" in statement ? statement.name : ""));
47
85
  const visible = new Map();
86
+ const visibleEnums = new Map();
48
87
  const add = (source, name, target) => {
49
88
  if (!target)
50
89
  return;
@@ -52,67 +91,116 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
52
91
  if (range)
53
92
  result.push({ ...target, ...range, file, declaration: false });
54
93
  };
55
- const expression = (node) => {
94
+ const typeReference = (reference, scope) => {
95
+ if (reference.type === "namedType" && reference.name)
96
+ add(reference.source, reference.name, scope.get(reference.name));
97
+ else if (reference.element)
98
+ typeReference(reference.element, scope);
99
+ };
100
+ const expression = (node, scope = visible) => {
56
101
  if (!analysis && statements.some(statement => statement.type === "importDeclaration"))
57
102
  return;
58
103
  switch (node.type) {
59
104
  case "stringInterpolation":
60
105
  node.parts.forEach(part => { if (typeof part !== "string")
61
- expression(part); });
106
+ expression(part, scope); });
62
107
  break;
63
108
  case "identifier":
64
- add(node.source, node.name, visible.get(node.name));
109
+ add(node.source, node.name, scope.get(node.name));
65
110
  break;
66
111
  case "functionCall":
67
- add(node.source, node.callee, visible.get(node.callee));
68
- node.arguments.forEach(expression);
112
+ add(node.source, node.callee, scope.get(node.callee));
113
+ node.arguments.forEach(argument => expression(argument, scope));
69
114
  break;
70
115
  case "recordConstructor":
71
- add(node.source, node.name, visible.get(node.name));
72
- node.fields.forEach(field => expression(field.expression));
116
+ add(node.source, node.name, scope.get(node.name));
117
+ node.fields.forEach(field => expression(field.expression, scope));
73
118
  break;
74
119
  case "binaryExpression":
75
- expression(node.left);
76
- expression(node.right);
120
+ expression(node.left, scope);
121
+ expression(node.right, scope);
122
+ break;
123
+ case "typeTestExpression":
124
+ expression(node.value, scope);
125
+ typeReference(node.target, scope);
77
126
  break;
78
127
  case "measurementAttachment":
79
128
  case "measurementConversion":
80
- add(node.unitSource, node.unit, visible.get(node.unit));
81
- expression(node.value);
129
+ add(node.unitSource, node.unit, scope.get(node.unit));
130
+ expression(node.value, scope);
82
131
  break;
83
132
  case "unaryExpression":
84
- expression(node.argument);
133
+ expression(node.argument, scope);
85
134
  break;
86
135
  case "conditionalExpression":
87
- expression(node.test);
88
- expression(node.consequent);
89
- expression(node.alternate);
136
+ expression(node.test, scope);
137
+ expression(node.consequent, scope);
138
+ expression(node.alternate, scope);
90
139
  break;
91
140
  case "listLiteral":
92
- node.elements.forEach(expression);
141
+ node.elements.forEach(element => expression(element, scope));
93
142
  break;
94
143
  case "rangeExpression":
95
- expression(node.start);
96
- expression(node.end);
144
+ expression(node.start, scope);
145
+ expression(node.end, scope);
97
146
  break;
98
147
  case "matchExpression":
99
- expression(node.expression);
100
- node.cases.forEach(arm => expression(arm.expression));
101
- expression(node.defaultExpression);
148
+ expression(node.expression, scope);
149
+ node.cases.forEach(arm => expression(arm.expression, scope));
150
+ expression(node.defaultExpression, scope);
102
151
  break;
103
- case "fieldAccess":
104
- expression(node.receiver);
152
+ case "fieldAccess": {
153
+ expression(node.receiver, scope);
154
+ if (node.receiver.type === "identifier") {
155
+ const visibleEnum = visibleEnums.get(node.receiver.name);
156
+ const member = visibleEnum && enumMemberTargets.get(`${visibleEnum.file}\0${visibleEnum.declaration.name}\0${node.field}`);
157
+ add(enumMemberSource(moduleText, node.source), node.field, member);
158
+ }
105
159
  break;
160
+ }
106
161
  case "listAccess":
107
- expression(node.receiver);
108
- expression(node.index);
162
+ expression(node.receiver, scope);
163
+ expression(node.index, scope);
109
164
  break;
110
165
  case "forExpression":
111
- expression(node.iterable);
166
+ expression(node.iterable, scope);
167
+ node.body.forEach(statement => nestedStatement(statement, scope));
168
+ break;
169
+ case "bracedIfExpression":
170
+ expression(node.test, scope);
171
+ node.consequent.forEach(statement => nestedStatement(statement, scope));
172
+ node.alternate.forEach(statement => nestedStatement(statement, scope));
112
173
  break;
113
174
  default: break;
114
175
  }
115
176
  };
177
+ const nestedStatement = (statement, scope = visible) => {
178
+ if (statement.type === "variableDeclaration")
179
+ expression(statement.expression, scope);
180
+ else if (statement.type === "typeDeclaration") {
181
+ for (const parent of statement.parents ?? [])
182
+ add(parent.source, parent.name, scope.get(parent.name));
183
+ for (const field of statement.fields)
184
+ if (field.defaultExpression)
185
+ expression(field.defaultExpression, scope);
186
+ }
187
+ else if (statement.type === "enumDeclaration") {
188
+ for (const member of statement.members)
189
+ if (member.value)
190
+ expression(member.value, scope);
191
+ }
192
+ else if (statement.type === "forStatement") {
193
+ expression(statement.iterable, scope);
194
+ statement.body.forEach(item => nestedStatement(item, scope));
195
+ }
196
+ else if (statement.type === "bracedIfStatement") {
197
+ expression(statement.test, scope);
198
+ statement.consequent.forEach(item => nestedStatement(item, scope));
199
+ statement.alternate?.forEach(item => nestedStatement(item, scope));
200
+ }
201
+ else if ("expression" in statement && statement.expression)
202
+ expression(statement.expression, scope);
203
+ };
116
204
  for (const statement of statements) {
117
205
  if (statement.type === "importDeclaration") {
118
206
  for (const imported of statement.names) {
@@ -134,6 +222,9 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
134
222
  if (importedTarget) {
135
223
  const importedOccurrence = { ...importedTarget, origin: declarationFile };
136
224
  visible.set(imported.name, importedOccurrence);
225
+ if (targetStatement?.type === "enumDeclaration" && declarationFile) {
226
+ visibleEnums.set(imported.name, { declaration: targetStatement, file: declarationFile });
227
+ }
137
228
  add(imported.source, imported.name, importedOccurrence);
138
229
  }
139
230
  }
@@ -153,6 +244,70 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
153
244
  }
154
245
  if (statement.type === "variableDeclaration")
155
246
  expression(statement.expression);
247
+ if (statement.type === "diagramDeclaration") {
248
+ const diagram = declaration(moduleText, file, statement);
249
+ const diagramParent = !duplicates.has(statement.name) ? diagram?.target : undefined;
250
+ const diagramScope = new Map(visible);
251
+ for (const property of statement.properties)
252
+ expression(property.expression);
253
+ for (const time of statement.times) {
254
+ expression(time.from);
255
+ expression(time.to);
256
+ expression(time.duration);
257
+ const range = sourceTokenRange(moduleText, time.nameSource, time.name);
258
+ if (!range || !diagramParent)
259
+ continue;
260
+ const localTime = {
261
+ ...range,
262
+ file,
263
+ name: time.name,
264
+ target: { file, ...range },
265
+ parent: diagramParent,
266
+ declaration: true,
267
+ kind: "diagramTime",
268
+ detail: `time ${time.name}`
269
+ };
270
+ result.push(localTime);
271
+ diagramScope.set(time.name, localTime);
272
+ }
273
+ const elementNames = new Set();
274
+ for (const element of statement.elements) {
275
+ const range = sourceTokenRange(moduleText, element.nameSource, element.name);
276
+ if (range && diagramParent && !elementNames.has(element.name)) {
277
+ elementNames.add(element.name);
278
+ result.push({
279
+ ...range,
280
+ file,
281
+ name: element.name,
282
+ target: { file, ...range },
283
+ parent: diagramParent,
284
+ declaration: true,
285
+ kind: "diagramElement",
286
+ detail: `${element.primitive} ${element.name}`
287
+ });
288
+ }
289
+ for (const property of element.properties)
290
+ expression(property.expression, diagramScope);
291
+ }
292
+ }
293
+ if (statement.type === "typeDeclaration") {
294
+ for (const parent of statement.parents ?? [])
295
+ add(parent.source, parent.name, visible.get(parent.name));
296
+ for (const field of statement.fields) {
297
+ if (field.annotation.type === "namedType" && field.annotation.name)
298
+ add(field.annotation.source, field.annotation.name, visible.get(field.annotation.name));
299
+ if (field.defaultExpression)
300
+ expression(field.defaultExpression);
301
+ }
302
+ }
303
+ if (statement.type === "enumDeclaration") {
304
+ const memberFacts = statement.members.map(member => enumMemberTargets.get(`${file}\0${statement.name}\0${member.name}`)).filter((fact) => !!fact);
305
+ result.push(...memberFacts);
306
+ visibleEnums.set(statement.name, { declaration: statement, file });
307
+ for (const member of statement.members)
308
+ if (member.value)
309
+ expression(member.value);
310
+ }
156
311
  if (statement.type === "variableDeclaration" || statement.type === "inputDeclaration") {
157
312
  const annotation = statement.annotation;
158
313
  if (annotation?.type === "namedType" && annotation.name)
@@ -178,8 +333,17 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
178
333
  if (statement.index)
179
334
  expression(statement.index);
180
335
  }
181
- if (statement.type === "forStatement")
336
+ if (statement.type === "forStatement") {
182
337
  expression(statement.iterable);
338
+ statement.body.forEach(item => nestedStatement(item));
339
+ }
340
+ if (statement.type === "bracedIfStatement") {
341
+ expression(statement.test);
342
+ statement.consequent.forEach(item => nestedStatement(item));
343
+ statement.alternate?.forEach(item => nestedStatement(item));
344
+ }
345
+ if (statement.type === "functionDeclaration")
346
+ expression(statement.body);
183
347
  const declared = declaration(moduleText, file, statement);
184
348
  if (declared && "name" in statement && !duplicates.has(statement.name)) {
185
349
  if (statement.type === "variableDeclaration") {
@@ -187,13 +351,14 @@ export function editorSymbolFacts(text, entryFile, entryDocument, analysis, modu
187
351
  if (inferred)
188
352
  declared.detail = `binding ${statement.name}: ${typeText(inferred)}`;
189
353
  }
190
- visible.set(statement.name, declared);
354
+ if (statement.type !== "diagramDeclaration")
355
+ visible.set(statement.name, declared);
191
356
  result.push(declared);
192
357
  if (statement.type === "typeDeclaration")
193
358
  for (const field of statement.fields) {
194
359
  const range = sourceTokenRange(moduleText, field.source, field.name);
195
360
  if (range)
196
- result.push({ ...range, file, name: field.name, target: { file, ...range }, declaration: true, kind: "field", detail: `field ${field.name}: ${field.annotation.name ?? field.annotation.type}` });
361
+ result.push({ ...range, file, name: field.name, target: { file, ...range }, parent: declared.target, declaration: true, kind: "field", detail: `field ${field.name}: ${field.annotation.name ?? field.annotation.type}` });
197
362
  }
198
363
  }
199
364
  }
@@ -33,21 +33,97 @@ export function formatAmx(source) {
33
33
  lines.pop();
34
34
  if (lines.length === 0)
35
35
  return '';
36
- parseStatements(lines.join('\n'));
36
+ const statements = parseStatements(lines.join('\n'));
37
+ const diagramsByLine = new Map();
38
+ collectDiagramDeclarations(statements, diagramsByLine);
37
39
  let depth = 0;
38
- const formatted = lines.map((rawLine) => {
40
+ const formatted = [];
41
+ for (let index = 0; index < lines.length; index++) {
42
+ const diagram = diagramsByLine.get(index);
43
+ if (diagram) {
44
+ formatted.push(...formatDiagram(diagram, depth));
45
+ index = diagramEndLine(lines, index);
46
+ continue;
47
+ }
48
+ const rawLine = lines[index];
39
49
  const line = rawLine.replace(/[ \t]+$/, '');
40
- if (line.trim().length === 0)
41
- return '';
50
+ if (line.trim().length === 0) {
51
+ formatted.push('');
52
+ continue;
53
+ }
42
54
  const content = line.trimStart();
43
55
  const braces = scanBraces(content);
44
56
  const lineDepth = Math.max(0, depth - braces.leadingClosures);
45
- const result = `${' '.repeat(lineDepth)}${content}`;
57
+ formatted.push(`${' '.repeat(lineDepth)}${content}`);
46
58
  depth = Math.max(0, depth + braces.opens - braces.closes);
47
- return result;
48
- });
59
+ }
49
60
  return `${formatted.join('\n')}\n`;
50
61
  }
62
+ function collectDiagramDeclarations(statements, result) {
63
+ for (const statement of statements) {
64
+ if (statement.type === 'diagramDeclaration') {
65
+ if (statement.source)
66
+ result.set(statement.source.line - 1, statement);
67
+ }
68
+ else if (statement.type === 'forStatement') {
69
+ collectDiagramDeclarations(statement.body, result);
70
+ }
71
+ else if (statement.type === 'bracedIfStatement') {
72
+ collectDiagramDeclarations(statement.consequent, result);
73
+ if (statement.alternate)
74
+ collectDiagramDeclarations(statement.alternate, result);
75
+ }
76
+ }
77
+ }
78
+ function diagramEndLine(lines, start) {
79
+ let depth = 0;
80
+ for (let index = start; index < lines.length; index++) {
81
+ const braces = scanBraces(lines[index]);
82
+ depth += braces.opens - braces.closes;
83
+ if (depth === 0)
84
+ return index;
85
+ }
86
+ return lines.length - 1;
87
+ }
88
+ function orderedProperties(properties, order) {
89
+ const positions = new Map(order.map((name, index) => [name, index]));
90
+ return [...properties].sort((left, right) => (positions.get(left.name) ?? Number.MAX_SAFE_INTEGER) - (positions.get(right.name) ?? Number.MAX_SAFE_INTEGER));
91
+ }
92
+ function formatProperty(property, level) {
93
+ const indentation = ' '.repeat(level);
94
+ const continuationIndentation = ' '.repeat(level + 1);
95
+ const valueLines = property.rawValue.split('\n');
96
+ return [
97
+ `${indentation}${property.name}: ${valueLines[0]}`,
98
+ ...valueLines.slice(1).map(line => `${continuationIndentation}${line.trimStart()}`)
99
+ ];
100
+ }
101
+ function elementPropertyOrder(element) {
102
+ switch (element.primitive) {
103
+ case 'line': return ['x1', 'y1', 'x2', 'y2', 'stroke', 'lineWidth', 'arrow'];
104
+ case 'rectangle': return ['x', 'y', 'width', 'height', 'stroke', 'fill', 'lineWidth'];
105
+ case 'circle': return ['cx', 'cy', 'r', 'stroke', 'fill', 'lineWidth'];
106
+ case 'text': return ['x', 'y', 'value', 'fill'];
107
+ default: return [];
108
+ }
109
+ }
110
+ function formatDiagram(diagram, level) {
111
+ const indentation = ' '.repeat(level);
112
+ const output = [`${indentation}diagram ${diagram.name} {`];
113
+ output.push(...orderedProperties(diagram.properties, ['title', 'description', 'width', 'height'])
114
+ .flatMap(property => formatProperty(property, level + 1)));
115
+ for (const time of diagram.times) {
116
+ output.push(`${' '.repeat(level + 1)}time ${time.name} from ${time.fromText} to ${time.toText} duration ${time.durationText}`);
117
+ }
118
+ for (const element of diagram.elements) {
119
+ output.push(`${' '.repeat(level + 1)}${element.primitive} ${element.name} {`);
120
+ output.push(...orderedProperties(element.properties, elementPropertyOrder(element))
121
+ .flatMap(property => formatProperty(property, level + 2)));
122
+ output.push(`${' '.repeat(level + 1)}}`);
123
+ }
124
+ output.push(`${indentation}}`);
125
+ return output;
126
+ }
51
127
  function scanBraces(line) {
52
128
  let opens = 0;
53
129
  let closes = 0;
@@ -1,4 +1,5 @@
1
1
  import { parseForExpression } from './parseFor';
2
+ import { findBracedIfExpressionEnd, parseBracedIfExpression } from './parseIf';
2
3
  import { AmxError, syntaxError } from '../diagnostics/errors';
3
4
  import { findInterpolationEnd as findInterpolationClose, findStringLiteralEnd } from './stringScanner';
4
5
  function tokenize(text, source) {
@@ -14,6 +15,15 @@ function tokenize(text, source) {
14
15
  if (i >= len)
15
16
  break;
16
17
  const ch = text[i];
18
+ if (text.startsWith('if', i) && !/[A-Za-z0-9_]/.test(text[i + 2] ?? '')) {
19
+ const end = findBracedIfExpressionEnd(text, i);
20
+ if (end !== undefined) {
21
+ const ifText = text.slice(i, end + 1);
22
+ tokens.push({ type: 'bracedIfExpression', value: ifText, text: ifText, offset: i });
23
+ i = end + 1;
24
+ continue;
25
+ }
26
+ }
17
27
  if (text.startsWith('for', i) && !/[A-Za-z0-9_]/.test(text[i + 3] ?? '')) {
18
28
  const end = findForExpressionEnd(text, i, source);
19
29
  const loopText = text.slice(i, end + 1);
@@ -91,7 +101,7 @@ function tokenize(text, source) {
91
101
  continue;
92
102
  }
93
103
  // Single-character operators and grouping
94
- if ('+-*/%^()[].,{}:='.includes(ch)) {
104
+ if ('+-*/%^()[].,{}:=?'.includes(ch)) {
95
105
  if (ch === '(') {
96
106
  tokens.push({ type: 'lparen', text: ch, offset: i });
97
107
  }
@@ -107,6 +117,9 @@ function tokenize(text, source) {
107
117
  else if (ch === ',') {
108
118
  tokens.push({ type: 'comma', text: ch, offset: i });
109
119
  }
120
+ else if (ch === '?') {
121
+ tokens.push({ type: 'question', text: ch, offset: i });
122
+ }
110
123
  else if (ch === '{' || ch === '}' || ch === ':' || ch === '=' || ch === '.') {
111
124
  tokens.push({ type: { '{': 'lbrace', '}': 'rbrace', ':': 'colon', '=': 'equals', '.': 'dot' }[ch], text: ch, offset: i });
112
125
  }
@@ -436,7 +449,7 @@ export function parseExpression(text, source) {
436
449
  // power: ^ (right-assoc)
437
450
  // * / %
438
451
  // + -
439
- // comparison: == != > >= < <=
452
+ // comparison: == != > >= < <= is
440
453
  // logical and
441
454
  // logical or
442
455
  // conditional if/then/else (lowest)
@@ -448,6 +461,7 @@ export function parseExpression(text, source) {
448
461
  '>=': 2,
449
462
  '<': 2,
450
463
  '<=': 2,
464
+ 'is': 2,
451
465
  // Measurement conversion binds below arithmetic and above comparisons.
452
466
  'in': 2.5,
453
467
  // arithmetic
@@ -468,7 +482,7 @@ export function parseExpression(text, source) {
468
482
  const t = current();
469
483
  const attach = (value) => {
470
484
  const unit = current();
471
- if (unit.type !== 'identifier' || unit.name === 'in' || unit.name === 'to')
485
+ if (unit.type !== 'identifier' || unit.name === 'in' || unit.name === 'to' || unit.name === 'is')
472
486
  return value;
473
487
  advance();
474
488
  return {
@@ -487,6 +501,10 @@ export function parseExpression(text, source) {
487
501
  advance();
488
502
  return parseForExpression(t.value, source);
489
503
  }
504
+ if (t.type === 'bracedIfExpression') {
505
+ advance();
506
+ return parseBracedIfExpression(t.value, locationAt(text, t.offset, source));
507
+ }
490
508
  if (t.type === 'number') {
491
509
  advance();
492
510
  return attach({ type: 'numberLiteral', value: t.value, source: locationAt(text, t.offset, source) });
@@ -623,6 +641,52 @@ export function parseExpression(text, source) {
623
641
  }
624
642
  throw new Error(`Unexpected token in expression: ${t.type} ${t.op || t.name || t.word || ''}`);
625
643
  }
644
+ function parseIsTarget() {
645
+ const name = current();
646
+ if (name.type !== 'identifier') {
647
+ syntaxError("Expected target type after 'is'", locationAt(text, tokenOffset(name, text.length), source));
648
+ }
649
+ advance();
650
+ let target = {
651
+ type: 'namedType',
652
+ name: name.name,
653
+ source: locationAt(text, name.offset, source)
654
+ };
655
+ let suffixEnd = name.offset + name.text.length;
656
+ while (current().type === 'lbracket' || current().type === 'question') {
657
+ const suffix = current();
658
+ const suffixOffset = tokenOffset(suffix, text.length);
659
+ if (suffixOffset !== suffixEnd) {
660
+ syntaxError("Invalid type suffix in 'is' target", locationAt(text, suffixOffset, source));
661
+ }
662
+ if (suffix.type === 'question') {
663
+ if (target.type === 'nullableType') {
664
+ syntaxError("Invalid type suffix in 'is' target", locationAt(text, suffixOffset, source));
665
+ }
666
+ advance();
667
+ target = {
668
+ type: 'nullableType',
669
+ element: target,
670
+ source: locationAt(text, suffixOffset, source)
671
+ };
672
+ suffixEnd = suffixOffset + 1;
673
+ continue;
674
+ }
675
+ advance();
676
+ const close = current();
677
+ if (close.type !== 'rbracket' || tokenOffset(close, text.length) !== suffixOffset + 1) {
678
+ syntaxError("Invalid type suffix in 'is' target", locationAt(text, suffixOffset, source));
679
+ }
680
+ advance();
681
+ target = {
682
+ type: 'listType',
683
+ element: target,
684
+ source: locationAt(text, suffixOffset, source)
685
+ };
686
+ suffixEnd = tokenOffset(close, text.length) + 1;
687
+ }
688
+ return target;
689
+ }
626
690
  function parseExpr(minPrec) {
627
691
  // Handle leading conditional (lowest precedence) before calling parsePrimary.
628
692
  // Conditionals only start at the top level of an expression (minPrec === 0).
@@ -651,6 +715,21 @@ export function parseExpression(text, source) {
651
715
  let left = parsePrimary();
652
716
  while (true) {
653
717
  const t = current();
718
+ if (t.type === 'identifier' && t.name === 'is') {
719
+ const prec = PREC.is;
720
+ if (prec < minPrec)
721
+ break;
722
+ advance();
723
+ const target = parseIsTarget();
724
+ left = {
725
+ type: 'typeTestExpression',
726
+ value: left,
727
+ target,
728
+ operatorSource: locationAt(text, t.offset, source),
729
+ source
730
+ };
731
+ continue;
732
+ }
654
733
  if (t.type === 'identifier' && t.name === 'in') {
655
734
  const prec = PREC.in;
656
735
  if (prec < minPrec)