@atscript/core 0.1.97 → 0.1.99

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.mjs CHANGED
@@ -369,6 +369,9 @@ var Token = class Token {
369
369
  ...replace
370
370
  });
371
371
  }
372
+ /** The underlying lexical token (for re-iterating its children). */ get lexicalToken() {
373
+ return this._data;
374
+ }
372
375
  get text() {
373
376
  return this._data.text || "";
374
377
  }
@@ -392,6 +395,9 @@ var Token = class Token {
392
395
  get isAnnotation() {
393
396
  return this._data.type === "annotation";
394
397
  }
398
+ /** The parsed tree of a backtick argument — whichever of the three it was parsed as. */ get backtickNode() {
399
+ return this.queryNode ?? this.exprNode ?? this.orderNode;
400
+ }
395
401
  constructor(_data) {
396
402
  _define_property$13(this, "_data", void 0);
397
403
  /**
@@ -426,6 +432,12 @@ var Token = class Token {
426
432
  /**
427
433
  * Parsed query expression tree (for query-type annotation arguments)
428
434
  */ _define_property$13(this, "queryNode", void 0);
435
+ /**
436
+ * Parsed arithmetic expression (for expr-type annotation arguments)
437
+ */ _define_property$13(this, "exprNode", void 0);
438
+ /**
439
+ * Parsed ordering (for order-type annotation arguments)
440
+ */ _define_property$13(this, "orderNode", void 0);
429
441
  this._data = _data;
430
442
  }
431
443
  };
@@ -784,15 +796,20 @@ function _define_property$9(obj, key, value) {
784
796
  }
785
797
  var SemanticQueryNode = class extends SemanticNode {
786
798
  registerAtDocument(doc) {
787
- this.propagateQueryArgToken(this.expression);
799
+ for (const ref of this.fieldRefs()) ref.queryArgToken = this.sourceToken;
788
800
  this.expression.registerAtDocument(doc);
789
801
  }
790
- propagateQueryArgToken(expr) {
791
- if ("left" in expr) {
792
- expr.left.queryArgToken = this.sourceToken;
793
- const right = expr.right;
794
- if (right && "fieldRef" in right) right.queryArgToken = this.sourceToken;
795
- } else if ("operands" in expr) for (const operand of expr.operands) this.propagateQueryArgToken(operand);
802
+ /** Every field ref of the predicate (both sides of comparisons), in source order. */ fieldRefs() {
803
+ const refs = [];
804
+ const walk = (expr) => {
805
+ if ("left" in expr) {
806
+ refs.push(expr.left);
807
+ const right = expr.right;
808
+ if (right && "fieldRef" in right) refs.push(right);
809
+ } else if ("operands" in expr) for (const operand of expr.operands) walk(operand);
810
+ };
811
+ walk(this.expression);
812
+ return refs;
796
813
  }
797
814
  constructor() {
798
815
  super("query"), _define_property$9(this, "expression", void 0), _define_property$9(this, "sourceToken", void 0);
@@ -847,6 +864,74 @@ var SemanticQueryValueListNode = class extends SemanticNode {
847
864
  super("query-value-list"), _define_property$9(this, "values", void 0);
848
865
  }
849
866
  };
867
+ /** Set `queryArgToken` on every field-ref leaf and register the leaves at the document. */ function registerFieldRefs(refs, sourceToken, doc) {
868
+ for (const ref of refs) {
869
+ ref.queryArgToken = sourceToken;
870
+ ref.registerAtDocument(doc);
871
+ }
872
+ }
873
+ /** Root of a parsed `expr` argument (closed arithmetic over field refs). */ var SemanticExprNode = class extends SemanticNode {
874
+ /** Every field-ref leaf of the expression, in source order. */ fieldRefs() {
875
+ const refs = [];
876
+ collectExprFieldRefs(this.expression, refs);
877
+ return refs;
878
+ }
879
+ registerAtDocument(doc) {
880
+ registerFieldRefs(this.fieldRefs(), this.sourceToken, doc);
881
+ }
882
+ constructor() {
883
+ super("query-expr"), _define_property$9(this, "expression", void 0), _define_property$9(this, "sourceToken", void 0);
884
+ }
885
+ };
886
+ function collectExprFieldRefs(node, out) {
887
+ switch (node.entity) {
888
+ case "query-field-ref":
889
+ out.push(node);
890
+ break;
891
+ case "query-expr-binary":
892
+ collectExprFieldRefs(node.left, out);
893
+ collectExprFieldRefs(node.right, out);
894
+ break;
895
+ case "query-expr-unary":
896
+ collectExprFieldRefs(node.operand, out);
897
+ break;
898
+ case "query-expr-call":
899
+ for (const arg of node.args) collectExprFieldRefs(arg, out);
900
+ break;
901
+ default:
902
+ }
903
+ }
904
+ var SemanticExprBinaryNode = class extends SemanticNode {
905
+ constructor() {
906
+ super("query-expr-binary"), _define_property$9(this, "op", void 0), _define_property$9(this, "left", void 0), _define_property$9(this, "right", void 0);
907
+ }
908
+ };
909
+ var SemanticExprUnaryNode = class extends SemanticNode {
910
+ constructor() {
911
+ super("query-expr-unary"), _define_property$9(this, "op", "neg"), _define_property$9(this, "operand", void 0);
912
+ }
913
+ };
914
+ var SemanticExprCallNode = class extends SemanticNode {
915
+ constructor() {
916
+ super("query-expr-call"), _define_property$9(this, "fn", "coalesce"), _define_property$9(this, "args", void 0);
917
+ }
918
+ };
919
+ var SemanticExprNumberNode = class extends SemanticNode {
920
+ constructor() {
921
+ super("query-expr-number"), _define_property$9(this, "valueToken", void 0), _define_property$9(this, "value", void 0);
922
+ }
923
+ };
924
+ /** Root of a parsed `order` argument: `key (asc|desc)?, …`. */ var SemanticOrderNode = class extends SemanticNode {
925
+ /** Every order key, in source order. */ fieldRefs() {
926
+ return this.items.map((i) => i.ref);
927
+ }
928
+ registerAtDocument(doc) {
929
+ registerFieldRefs(this.fieldRefs(), this.sourceToken, doc);
930
+ }
931
+ constructor() {
932
+ super("query-order"), _define_property$9(this, "items", void 0), _define_property$9(this, "sourceToken", void 0);
933
+ }
934
+ };
850
935
 
851
936
  //#endregion
852
937
  //#region packages/core/src/parser/nodes/index.ts
@@ -922,6 +1007,14 @@ function _define_property$8(obj, key, value) {
922
1007
  else obj[key] = value;
923
1008
  return obj;
924
1009
  }
1010
+ /** Whether an annotation argument type is written in backticks (`query`, `expr`, `order`). */ function isBacktickArgType(type) {
1011
+ return type === "query" || type === "expr" || type === "order";
1012
+ }
1013
+ const BACKTICK_TYPE_MESSAGES = {
1014
+ query: "query expression expected (use backticks).",
1015
+ expr: "expression expected (use backticks).",
1016
+ order: "order list expected (use backticks)."
1017
+ };
925
1018
  var AnnotationSpec = class {
926
1019
  get arguments() {
927
1020
  if (!this.config.argument) return [];
@@ -932,7 +1025,7 @@ var AnnotationSpec = class {
932
1025
  return this.arguments.map((arg, index) => {
933
1026
  const placeholderIndex = index + 1;
934
1027
  const defaultValue = this.getDefaultValueForType(arg.name, arg.type);
935
- const quote = arg.type === "string" ? `'` : arg.type === "query" ? "`" : "";
1028
+ const quote = arg.type === "string" ? `'` : isBacktickArgType(arg.type) ? "`" : "";
936
1029
  return `${quote}\${${placeholderIndex}:${defaultValue}}${quote}`;
937
1030
  }).join(", ");
938
1031
  }
@@ -942,7 +1035,9 @@ var AnnotationSpec = class {
942
1035
  case "number": return tokenType === "number" ? void 0 : "number expected.";
943
1036
  case "boolean": return tokenType === "identifier" ? void 0 : "boolean expected.";
944
1037
  case "ref": return tokenType === "identifier" ? void 0 : "type reference expected.";
945
- case "query": return tokenType === "query" ? void 0 : "query expression expected (use backticks).";
1038
+ case "query":
1039
+ case "expr":
1040
+ case "order": return tokenType === "query" ? void 0 : BACKTICK_TYPE_MESSAGES[type];
946
1041
  default: return `unknown type "${type}".`;
947
1042
  }
948
1043
  }
@@ -1064,6 +1159,8 @@ var AnnotationSpec = class {
1064
1159
  case "boolean": return "true";
1065
1160
  case "ref": return "TypeName";
1066
1161
  case "query": return "field = value";
1162
+ case "expr": return "field + 1";
1163
+ case "order": return "field asc";
1067
1164
  default: return "";
1068
1165
  }
1069
1166
  }
@@ -1386,421 +1483,30 @@ async function loadConfig(configPath, forceFormat) {
1386
1483
  }
1387
1484
 
1388
1485
  //#endregion
1389
- //#region packages/core/src/lsp/legacy-db-query-scope.ts
1390
- /**
1391
- * @deprecated Built-in editor scopes for the `@db.view.filter`, `@db.view.joins` and
1392
- * `@db.rel.filter` query arguments. They are a fallback for DB plugin versions whose
1393
- * argument specs do not declare a `fieldScope` hook yet — the DB plugin owns these
1394
- * rules now. Scheduled for removal in `@atscript/core` 0.2.0 (next minor).
1395
- */
1396
- /**
1397
- * @deprecated Query scope of a built-in `@db.*` query argument (see the module note);
1398
- * `undefined` for any other annotation.
1399
- */ function getLegacyDbQueryScope(queryArgToken) {
1400
- const owner = queryArgToken.parentNode;
1401
- if (!owner) return;
1402
- switch (queryArgToken.annotationRef?.text.slice(1)) {
1403
- case "db.view.filter": return getViewFilterScope(owner);
1404
- case "db.view.joins": return getViewJoinsScope(owner, queryArgToken);
1405
- case "db.rel.filter": return getRelFilterScope(owner);
1406
- default: return;
1407
- }
1486
+ //#region packages/core/src/parser/iterator.ts
1487
+ function _define_property$7(obj, key, value) {
1488
+ if (key in obj) Object.defineProperty(obj, key, {
1489
+ value,
1490
+ enumerable: true,
1491
+ configurable: true,
1492
+ writable: true
1493
+ });
1494
+ else obj[key] = value;
1495
+ return obj;
1408
1496
  }
1409
- function getViewFilterScope(owner) {
1410
- const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
1411
- if (!entryTypeName) return;
1412
- const allowedTypes = [entryTypeName];
1413
- const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
1414
- if (joinsAnnotations) {
1415
- for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
1497
+ var NodeIterator = class NodeIterator {
1498
+ get index() {
1499
+ return this.i;
1416
1500
  }
1417
- return {
1418
- allowedTypes,
1419
- unqualifiedTarget: entryTypeName
1420
- };
1421
- }
1422
- function getViewJoinsScope(owner, queryArgToken) {
1423
- const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
1424
- if (!entryTypeName) return;
1425
- const joinTargetName = (owner.annotations?.find((a) => a.name === "db.view.joins" && a.args.includes(queryArgToken)))?.args[0]?.text;
1426
- if (!joinTargetName) return;
1427
- return {
1428
- allowedTypes: [joinTargetName, entryTypeName],
1429
- unqualifiedTarget: entryTypeName
1430
- };
1431
- }
1432
- function getRelFilterScope(owner) {
1433
- let def = owner.getDefinition();
1434
- if (isArray(def)) def = def?.getDefinition();
1435
- if (!isRef(def)) return;
1436
- const targetTypeName = def.id;
1437
- const allowedTypes = [targetTypeName];
1438
- const viaAnnotation = owner.annotations?.find((a) => a.name === "db.rel.via");
1439
- if (viaAnnotation?.args[0]) allowedTypes.push(viaAnnotation.args[0].text);
1440
- return {
1441
- allowedTypes,
1442
- unqualifiedTarget: targetTypeName
1443
- };
1444
- }
1445
-
1446
- //#endregion
1447
- //#region packages/core/src/lsp/field-refs.ts
1448
- function getArgSpec(argToken, doc) {
1449
- const annotationRef = argToken.annotationRef;
1450
- if (!annotationRef || typeof argToken.index !== "number") return;
1451
- return doc.resolveAnnotation(annotationRef.text.slice(1))?.arguments[argToken.index];
1452
- }
1453
- /**
1454
- * Field scope of an annotation argument: the answer of the argument spec's `fieldScope`
1455
- * hook when it declares one, otherwise the deprecated built-in `@db.*` query rules.
1456
- */ function getQueryScope(argToken, doc) {
1457
- const argSpec = getArgSpec(argToken, doc);
1458
- return argSpec?.fieldScope ? argSpec.fieldScope(argToken, doc) : getLegacyDbQueryScope(argToken);
1459
- }
1460
- /**
1461
- * Type a field-path `string` argument names a field of: the `unqualifiedTarget` of the
1462
- * argument spec's `fieldScope`. `undefined` for any other token.
1463
- */ function getFieldPathTarget(argToken, doc) {
1464
- if (argToken.type !== "text") return;
1465
- const argSpec = getArgSpec(argToken, doc);
1466
- if (argSpec?.type !== "string" || !argSpec.fieldScope) return;
1467
- return argSpec.fieldScope(argToken, doc)?.unqualifiedTarget ?? void 0;
1468
- }
1469
- /**
1470
- * Resolve a (possibly dotted) field path of a type to the property it names and the
1471
- * document that declares that property.
1472
- */ function resolveFieldPath(doc, typeName, segment) {
1473
- const chain = segment.path.split(".");
1474
- const [name] = chain.splice(-1);
1475
- const parent = doc.unwindType(typeName, chain);
1476
- if (!parent || !(isStructure(parent.def) || isInterface(parent.def))) return;
1477
- const prop = parent.def.props.get(name);
1478
- return prop && {
1479
- typeName,
1480
- range: segment.range,
1481
- prop,
1482
- doc: parent.doc
1483
- };
1484
- }
1485
- /**
1486
- * Segments of a field-path string argument (`'address.city'` → `address`, `city`), with
1487
- * ranges that exclude the quotes. A string spanning several lines is a single segment.
1488
- */ function fieldPathSegments(argToken) {
1489
- const { text, range } = argToken;
1490
- if (range.start.line !== range.end.line) return [{
1491
- path: text,
1492
- range
1493
- }];
1494
- const line = range.start.line;
1495
- const contentStart = range.start.character + 1;
1496
- const segments = [];
1497
- let start = 0;
1498
- for (const part of text.split(".")) {
1499
- const end = start + part.length;
1500
- segments.push({
1501
- path: text.slice(0, end),
1502
- range: {
1503
- start: {
1504
- line,
1505
- character: contentStart + start
1506
- },
1507
- end: {
1508
- line,
1509
- character: contentStart + end
1510
- }
1511
- }
1512
- });
1513
- start = end + 1;
1501
+ get lastNode() {
1502
+ return this.nodes[this.nodes.length - 1];
1514
1503
  }
1515
- return segments;
1516
- }
1517
- /** The segment under `character`, or the last segment when `character` is omitted. */ function fieldPathSegmentAt(argToken, character) {
1518
- const segments = fieldPathSegments(argToken);
1519
- return (character === void 0 ? void 0 : segments.find((s) => s.range.end.character >= character)) ?? segments[segments.length - 1];
1520
- }
1521
- /**
1522
- * Resolve a field reference token to the property it names:
1523
- * - a field ref inside a `query` argument (`amount`, `Customer.name` in backticks);
1524
- * - a `string` argument whose spec declares `fieldScope`: a (dotted) field path of the
1525
- * scope's `unqualifiedTarget`. With `character` (a cursor column), the path resolves
1526
- * only up to the segment under the cursor — `'address.city'` with the cursor on
1527
- * `address` resolves `address` — and `range` is that segment's range.
1528
- *
1529
- * Returns `undefined` for any other token, or when the scope or the path does not resolve.
1530
- */ function resolveFieldRefAt(token, doc, character) {
1531
- if (isQueryFieldRef(token.parentNode)) {
1532
- const { fieldRef, typeRef, queryArgToken } = token.parentNode;
1533
- const scope = token === fieldRef && queryArgToken ? getQueryScope(queryArgToken, doc) : void 0;
1534
- const typeName = scope && (typeRef?.text ?? scope.unqualifiedTarget);
1535
- return typeName ? resolveFieldPath(doc, typeName, {
1536
- path: token.text,
1537
- range: token.range
1538
- }) : void 0;
1504
+ unexpectedEOB() {
1505
+ this.issues.unexpectedEOB = true;
1539
1506
  }
1540
- const typeName = getFieldPathTarget(token, doc);
1541
- return typeName ? resolveFieldPath(doc, typeName, fieldPathSegmentAt(token, character)) : void 0;
1542
- }
1543
- /**
1544
- * Resolve the segments named `fieldName` of a field-path `string` argument
1545
- * (`'address.city'` has the segments `address` and `city`). Supports find-references.
1546
- */ function resolveFieldPathArgSegments(argToken, doc, fieldName) {
1547
- const segments = fieldPathSegments(argToken).filter((s) => s.path === fieldName || s.path.endsWith(`.${fieldName}`));
1548
- const typeName = segments.length > 0 ? getFieldPathTarget(argToken, doc) : void 0;
1549
- if (!typeName) return [];
1550
- const targets = [];
1551
- for (const segment of segments) {
1552
- const target = resolveFieldPath(doc, typeName, segment);
1553
- if (target) targets.push(target);
1554
- }
1555
- return targets;
1556
- }
1557
- /**
1558
- * Resolve a query field ref node to a property definition.
1559
- */ function resolveQueryFieldRef(fieldRefNode, doc, scope) {
1560
- const typeName = fieldRefNode.typeRef?.text ?? scope.unqualifiedTarget;
1561
- const { fieldRef } = fieldRefNode;
1562
- const resolved = typeName ? resolveFieldPath(doc, typeName, {
1563
- path: fieldRef.text,
1564
- range: fieldRef.range
1565
- }) : void 0;
1566
- return resolved && {
1567
- targetUri: resolved.doc.id,
1568
- doc: resolved.doc,
1569
- prop: resolved.prop
1570
- };
1571
- }
1572
- /**
1573
- * Get fields available for a type (resolving extends/intersections).
1574
- * With `chain`, returns the fields of the nested object that field path leads to.
1575
- */ function getFieldsForType(doc, typeName, chain = []) {
1576
- const unwound = doc.unwindType(typeName, chain);
1577
- if (!unwound?.def) return [];
1578
- let def = unwound.doc.mergeIntersection(unwound.def);
1579
- if (isInterface(def)) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
1580
- if (isStructure(def) || isInterface(def)) return Array.from(def.props.values());
1581
- return [];
1582
- }
1583
- /**
1584
- * Completion scope of a field-path `string` argument (spec declares `fieldScope`) at the
1585
- * cursor column `character`: the fields of the level being typed — `'address.ci'` offers
1586
- * the fields of `address` (`chain` = `['address']`).
1587
- */ function getFieldPathCompletionScope(argToken, doc, character) {
1588
- const typeName = getFieldPathTarget(argToken, doc);
1589
- if (!typeName) return;
1590
- const chain = fieldPathSegmentAt(argToken, character).path.split(".").slice(0, -1);
1591
- return {
1592
- typeName,
1593
- chain,
1594
- fields: getFieldsForType(doc, typeName, chain)
1595
- };
1596
- }
1597
- /**
1598
- * Get completion scope data for a query context.
1599
- */ function getQueryCompletionScope(queryArgToken, doc) {
1600
- const scope = getQueryScope(queryArgToken, doc);
1601
- if (!scope) return;
1602
- return {
1603
- typeNames: scope.allowedTypes,
1604
- unqualifiedTarget: scope.unqualifiedTarget,
1605
- getFields: (typeName) => getFieldsForType(doc, typeName)
1606
- };
1607
- }
1608
- const SYMBOLIC_OPS$1 = new Set([
1609
- "=",
1610
- "!=",
1611
- ">",
1612
- ">=",
1613
- "<",
1614
- "<="
1615
- ]);
1616
- const KEYWORD_OPS = new Set([
1617
- "in",
1618
- "matches",
1619
- "exists"
1620
- ]);
1621
- const LOGICAL_KEYWORDS = new Set([
1622
- "and",
1623
- "or",
1624
- "not"
1625
- ]);
1626
- const VALUE_KEYWORDS$1 = new Set([
1627
- "true",
1628
- "false",
1629
- "null",
1630
- "undefined"
1631
- ]);
1632
- /**
1633
- * Analyze text inside backticks up to cursor position
1634
- * to determine what kind of completions to offer.
1635
- * Uses lightweight text scanning, not full AST parsing,
1636
- * so it works on incomplete/mid-typing input.
1637
- */ function analyzeQueryCursorContext(textBeforeCursor) {
1638
- const trimmed = textBeforeCursor.trimEnd();
1639
- const hasTrailingSpace = textBeforeCursor.length > trimmed.length;
1640
- if (trimmed.length === 0) return { type: "field-start" };
1641
- if (trimmed.endsWith(".")) {
1642
- const before = trimmed.slice(0, -1).trimEnd();
1643
- const match = /(\w+)$/u.exec(before);
1644
- if (match) return {
1645
- type: "after-dot",
1646
- typeName: match[1]
1647
- };
1648
- return { type: "field-start" };
1649
- }
1650
- const tokens = tokenizeQueryText(trimmed);
1651
- if (tokens.length === 0) return { type: "field-start" };
1652
- const last = tokens[tokens.length - 1];
1653
- if (LOGICAL_KEYWORDS.has(last) || last === "(") return { type: "field-start" };
1654
- if (SYMBOLIC_OPS$1.has(last)) return { type: "after-operator" };
1655
- if (last === "in" || last === "matches") return { type: "after-operator" };
1656
- if (last === "exists") return { type: "after-comparison" };
1657
- if (VALUE_KEYWORDS$1.has(last)) return { type: "after-comparison" };
1658
- if (/^['"]/.test(last) || /^\d/.test(last)) return { type: "after-comparison" };
1659
- if (tokens.length >= 2) {
1660
- const prev = tokens[tokens.length - 2];
1661
- if (SYMBOLIC_OPS$1.has(prev) || KEYWORD_OPS.has(prev)) return { type: "after-comparison" };
1662
- }
1663
- if (/^\w+$/u.test(last)) {
1664
- if (!hasTrailingSpace) return { type: "field-start" };
1665
- return { type: "after-field" };
1666
- }
1667
- return { type: "field-start" };
1668
- }
1669
- /**
1670
- * Simple tokenizer for query text — splits into identifiers, operators, and punctuation.
1671
- * Does NOT need to handle all edge cases; just enough for cursor context analysis.
1672
- */ function tokenizeQueryText(text) {
1673
- const tokens = [];
1674
- let i = 0;
1675
- while (i < text.length) {
1676
- if (/\s/.test(text[i])) {
1677
- i++;
1678
- continue;
1679
- }
1680
- if (text[i] === "'" || text[i] === "\"") {
1681
- const quote = text[i];
1682
- let j = i + 1;
1683
- while (j < text.length && text[j] !== quote) {
1684
- if (text[j] === "\\") j++;
1685
- j++;
1686
- }
1687
- tokens.push(text.slice(i, j + 1));
1688
- i = j + 1;
1689
- continue;
1690
- }
1691
- if (i + 1 < text.length) {
1692
- const two = text.slice(i, i + 2);
1693
- if (two === "!=" || two === ">=" || two === "<=") {
1694
- tokens.push(two);
1695
- i += 2;
1696
- continue;
1697
- }
1698
- }
1699
- if ("=><(),".includes(text[i])) {
1700
- tokens.push(text[i]);
1701
- i++;
1702
- continue;
1703
- }
1704
- if (text[i] === ".") {
1705
- tokens.push(".");
1706
- i++;
1707
- continue;
1708
- }
1709
- if (/[\w]/u.test(text[i])) {
1710
- let j = i;
1711
- while (j < text.length && /[\w]/u.test(text[j])) j++;
1712
- tokens.push(text.slice(i, j));
1713
- i = j;
1714
- continue;
1715
- }
1716
- i++;
1717
- }
1718
- return tokens;
1719
- }
1720
-
1721
- //#endregion
1722
- //#region packages/core/src/parser/id-registry.ts
1723
- function _define_property$7(obj, key, value) {
1724
- if (key in obj) Object.defineProperty(obj, key, {
1725
- value,
1726
- enumerable: true,
1727
- configurable: true,
1728
- writable: true
1729
- });
1730
- else obj[key] = value;
1731
- return obj;
1732
- }
1733
- var IdRegistry = class {
1734
- clear() {
1735
- this.definitions.clear();
1736
- this.duplicates.clear();
1737
- this.forbidden.clear();
1738
- }
1739
- registerDefinition(token) {
1740
- if (!token) return;
1741
- if (this.reserved.has(token.text)) this.forbidden.add(token);
1742
- else if (this.definitions.has(token.text)) this.duplicates.add(token);
1743
- else this.definitions.set(token.text, token);
1744
- }
1745
- isDefined(t) {
1746
- const text = typeof t === "string" ? t : t.text;
1747
- return this.definitions.has(text) || this.globalTypes.has(text);
1748
- }
1749
- getErrors() {
1750
- return [...Array.from(this.duplicates, (t) => ({
1751
- severity: 1,
1752
- message: `Duplicate identifier "${t.text}"`,
1753
- range: t.range
1754
- })), ...Array.from(this.forbidden, (t) => ({
1755
- severity: 1,
1756
- message: `Reserved keyword "${t.text}"`,
1757
- range: t.range
1758
- }))];
1759
- }
1760
- constructor(globalTypes = []) {
1761
- _define_property$7(this, "reserved", void 0);
1762
- _define_property$7(this, "globalTypes", void 0);
1763
- _define_property$7(this, "definitions", /* @__PURE__ */ new Map());
1764
- _define_property$7(this, "duplicates", /* @__PURE__ */ new Set());
1765
- _define_property$7(this, "forbidden", /* @__PURE__ */ new Set());
1766
- this.reserved = new Set([
1767
- "interface",
1768
- "type",
1769
- "import",
1770
- "from",
1771
- "export",
1772
- "annotate",
1773
- "as"
1774
- ].concat(globalTypes));
1775
- this.globalTypes = new Set(globalTypes);
1776
- }
1777
- };
1778
-
1779
- //#endregion
1780
- //#region packages/core/src/parser/iterator.ts
1781
- function _define_property$6(obj, key, value) {
1782
- if (key in obj) Object.defineProperty(obj, key, {
1783
- value,
1784
- enumerable: true,
1785
- configurable: true,
1786
- writable: true
1787
- });
1788
- else obj[key] = value;
1789
- return obj;
1790
- }
1791
- var NodeIterator = class NodeIterator {
1792
- get index() {
1793
- return this.i;
1794
- }
1795
- get lastNode() {
1796
- return this.nodes[this.nodes.length - 1];
1797
- }
1798
- unexpectedEOB() {
1799
- this.issues.unexpectedEOB = true;
1800
- }
1801
- unfork(fork) {
1802
- this.i = fork.index;
1803
- this.update();
1507
+ unfork(fork) {
1508
+ this.i = fork.index;
1509
+ this.update();
1804
1510
  }
1805
1511
  accepted() {
1806
1512
  if (this.$ && this.$.accepted !== false) {
@@ -1891,13 +1597,13 @@ var NodeIterator = class NodeIterator {
1891
1597
  })).concat(this.messages);
1892
1598
  }
1893
1599
  constructor(nodes, messages = [], badNodes = /* @__PURE__ */ new Map(), issues = {}, parent, i = -1) {
1894
- _define_property$6(this, "nodes", void 0);
1895
- _define_property$6(this, "messages", void 0);
1896
- _define_property$6(this, "badNodes", void 0);
1897
- _define_property$6(this, "issues", void 0);
1898
- _define_property$6(this, "parent", void 0);
1899
- _define_property$6(this, "i", void 0);
1900
- _define_property$6(this, "$", void 0);
1600
+ _define_property$7(this, "nodes", void 0);
1601
+ _define_property$7(this, "messages", void 0);
1602
+ _define_property$7(this, "badNodes", void 0);
1603
+ _define_property$7(this, "issues", void 0);
1604
+ _define_property$7(this, "parent", void 0);
1605
+ _define_property$7(this, "i", void 0);
1606
+ _define_property$7(this, "$", void 0);
1901
1607
  this.nodes = nodes;
1902
1608
  this.messages = messages;
1903
1609
  this.badNodes = badNodes;
@@ -1908,891 +1614,1560 @@ var NodeIterator = class NodeIterator {
1908
1614
  };
1909
1615
 
1910
1616
  //#endregion
1911
- //#region packages/core/src/tokenizer/tokens/a-identifier.token.ts
1912
- /**
1913
- * Annotation (@) Identifier node
1914
- */ const AIdentifierToken = new Node({
1915
- name: "annotation",
1916
- start: { token: RegExp("@[\\p{ID_Continue}$.]*", "u") },
1917
- end: {
1918
- token: RegExp("[^\\p{ID_Continue}$.]", "u"),
1919
- eject: true
1920
- },
1921
- eofClose: true,
1922
- data: {
1923
- type: "annotation",
1924
- text: ""
1617
+ //#region packages/core/src/parser/pipes/query.pipe.ts
1618
+ const SYMBOLIC_OPS = new Set([
1619
+ "=",
1620
+ "!=",
1621
+ ">",
1622
+ ">=",
1623
+ "<",
1624
+ "<="
1625
+ ]);
1626
+ const VALUE_KEYWORDS = new Set([
1627
+ "true",
1628
+ "false",
1629
+ "null",
1630
+ "undefined"
1631
+ ]);
1632
+ const ZERO_RANGE = {
1633
+ start: {
1634
+ line: 0,
1635
+ character: 0
1925
1636
  },
1926
- mapContent: "text"
1927
- });
1928
-
1929
- //#endregion
1930
- //#region packages/core/src/tokenizer/tokens/block.token.ts
1637
+ end: {
1638
+ line: 0,
1639
+ character: 0
1640
+ }
1641
+ };
1931
1642
  /**
1932
- * Builds a block node that opens on any key of `pairs` and closes on the
1933
- * matching value; the opening character is kept as the token's `text`.
1934
- */ function createBlockToken(pairs) {
1935
- const opening = Object.keys(pairs).map((c) => c.replace(/[\\^$.*+?()[\]{}|/-]/gu, "\\$&")).join("");
1936
- return new Node({
1937
- name: "block",
1938
- start: {
1939
- token: new RegExp(`(?<text>[${opening}])`, "u"),
1940
- omit: true
1941
- },
1942
- end: {
1943
- token: (ctx) => pairs[ctx.node.data.text] || "",
1944
- omit: true
1945
- },
1946
- skip: /\s/u,
1947
- eofClose: true,
1948
- data: {
1949
- type: "block",
1950
- text: ""
1643
+ * Parse a backtick-delimited query expression.
1644
+ *
1645
+ * `ni` iterates the query token's children and carries that token as its
1646
+ * `parent` — the range to blame when a diagnostic has no token of its own —
1647
+ * so fork it from the annotation iterator while the query token is current.
1648
+ * Returns a SemanticQueryNode or undefined if the content is empty.
1649
+ */ function parseQueryExpression(ni, sourceToken) {
1650
+ if (!ni.$) return;
1651
+ const expr = parseOrExpr(ni);
1652
+ if (!expr) return;
1653
+ if (ni.$) pushError(ni, `Unexpected token in query expression: "${ni.$.text}"`);
1654
+ const node = new SemanticQueryNode();
1655
+ node.expression = expr;
1656
+ node.sourceToken = sourceToken;
1657
+ return node;
1658
+ }
1659
+ function parseOrExpr(ni) {
1660
+ const left = parseAndExpr(ni);
1661
+ if (!left) return;
1662
+ const operands = [left];
1663
+ while (ni.$?.type === "identifier" && ni.$.text === "or") {
1664
+ ni.move();
1665
+ const right = parseAndExpr(ni);
1666
+ if (!right) {
1667
+ pushError(ni, "Expected expression after \"or\"");
1668
+ break;
1951
1669
  }
1952
- });
1670
+ operands.push(right);
1671
+ }
1672
+ if (operands.length === 1) return operands[0];
1673
+ const node = new SemanticQueryLogicalNode();
1674
+ node.operator = "or";
1675
+ node.operands = operands;
1676
+ return node;
1953
1677
  }
1954
- /**
1955
- * Block node
1956
- */ const BlockToken = createBlockToken({
1957
- "{": "}",
1958
- "(": ")",
1959
- "[": "]"
1960
- });
1961
-
1962
- //#endregion
1963
- //#region packages/core/src/tokenizer/tokens/comment.token.ts
1964
- const inline = new Node({
1965
- name: "inline-comment",
1966
- start: {
1967
- token: "//",
1968
- omit: true
1969
- },
1970
- end: {
1971
- token: /$/mu,
1972
- omit: true
1973
- },
1974
- eofClose: true,
1975
- data: {
1976
- type: "comment",
1977
- text: ""
1978
- },
1979
- mapContent: "text"
1980
- });
1981
- const block$1 = new Node({
1982
- name: "block-comment",
1983
- start: {
1984
- token: "/*",
1985
- omit: true
1986
- },
1987
- end: {
1988
- token: "*/",
1989
- omit: true
1990
- },
1991
- eofClose: true,
1992
- data: {
1993
- type: "comment",
1994
- text: ""
1995
- },
1996
- mapContent: "text"
1997
- });
1998
- /**
1999
- * Block and inline comments
2000
- */ const commentNodes = {
2001
- inline,
2002
- block: block$1,
2003
- all: [inline, block$1]
2004
- };
2005
-
2006
- //#endregion
2007
- //#region packages/core/src/tokenizer/tokens/identifier.token.ts
2008
- /**
2009
- * Identifier node
2010
- */ const IdentifierToken = new Node({
2011
- name: "identifier",
2012
- start: { token: RegExp("[\\p{ID_Start}$_][\\p{ID_Continue}$]*", "u") },
2013
- end: {
2014
- token: RegExp("[^\\p{ID_Continue}$]", "u"),
2015
- eject: true
2016
- },
2017
- eofClose: true,
2018
- data: {
2019
- type: "identifier",
2020
- text: ""
2021
- },
2022
- mapContent: "text"
2023
- });
2024
-
2025
- //#endregion
2026
- //#region packages/core/src/tokenizer/tokens/number.token.ts
2027
- /**
2028
- * Number node
2029
- */ const NumberToken = new Node({
2030
- name: "number",
2031
- start: { token: /[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?/u },
2032
- end: {
2033
- token: /[^\d]/u,
2034
- eject: true
2035
- },
2036
- eofClose: true,
2037
- data: {
2038
- type: "number",
2039
- text: ""
2040
- },
2041
- mapContent: "text"
2042
- });
2043
-
2044
- //#endregion
2045
- //#region packages/core/src/tokenizer/tokens/punctuation.token.ts
2046
- /**
2047
- * Punctuation node
2048
- */ const PunctuationToken = new Node({
2049
- name: "punctuation",
2050
- start: {
2051
- token: RegExp("(?<text>[\\n!&+,./:;=?|])", "u"),
2052
- omit: true
2053
- },
2054
- end: {
2055
- token: "",
2056
- omit: true
2057
- },
2058
- eofClose: true,
2059
- data: {
2060
- type: "punctuation",
2061
- text: ""
1678
+ function parseAndExpr(ni) {
1679
+ const left = parseUnaryExpr(ni);
1680
+ if (!left) return;
1681
+ const operands = [left];
1682
+ while (ni.$?.type === "identifier" && ni.$.text === "and") {
1683
+ ni.move();
1684
+ const right = parseUnaryExpr(ni);
1685
+ if (!right) {
1686
+ pushError(ni, "Expected expression after \"and\"");
1687
+ break;
1688
+ }
1689
+ operands.push(right);
2062
1690
  }
2063
- });
2064
-
2065
- //#endregion
2066
- //#region packages/core/src/tokenizer/tokens/query-block.token.ts
2067
- /**
2068
- * Query block node — parenthesized sub-expressions inside backtick queries.
2069
- *
2070
- * Same definition as `BlockToken` narrowed to `(`, so it produces the same
2071
- * token shape (`type: 'block'`, `text: '('`) and every consumer keeps working,
2072
- * but it recognizes `QueryOperatorToken` inside (see `tokens/index.ts`), which
2073
- * makes `!=`, `>=`, `<=`, `>`, `<` work within parentheses — the generic block
2074
- * only knows `PunctuationToken`, whose charset has no `<` / `>`.
2075
- *
2076
- * Only registered inside `QueryToken` (and itself, for nested parens) —
2077
- * the generic `BlockToken` is left untouched so tokenization of `(`/`[`/`{`
2078
- * outside queries does not change.
2079
- */ const QueryBlockToken = createBlockToken({ "(": ")" });
2080
-
2081
- //#endregion
2082
- //#region packages/core/src/tokenizer/tokens/query-operator.token.ts
2083
- /**
2084
- * Query operator token — matches symbolic comparison operators
2085
- * inside backtick-delimited query expressions.
2086
- *
2087
- * Multi-character operators (!=, >=, <=) are matched as single tokens.
2088
- * Only recognized inside QueryToken — not in root or BlockToken.
2089
- */ const QueryOperatorToken = new Node({
2090
- name: "punctuation",
2091
- start: {
2092
- token: RegExp("(?<text>!=|>=|<=|[=><])", "u"),
2093
- omit: true
2094
- },
2095
- end: {
2096
- token: "",
2097
- omit: true
2098
- },
2099
- eofClose: true,
2100
- data: {
2101
- type: "punctuation",
2102
- text: ""
1691
+ if (operands.length === 1) return operands[0];
1692
+ const node = new SemanticQueryLogicalNode();
1693
+ node.operator = "and";
1694
+ node.operands = operands;
1695
+ return node;
1696
+ }
1697
+ function parseUnaryExpr(ni) {
1698
+ if (ni.$?.type === "identifier" && ni.$.text === "not") {
1699
+ ni.move();
1700
+ const operand = parseUnaryExpr(ni);
1701
+ if (!operand) {
1702
+ pushError(ni, "Expected expression after \"not\"");
1703
+ return;
1704
+ }
1705
+ const node = new SemanticQueryLogicalNode();
1706
+ node.operator = "not";
1707
+ node.operands = [operand];
1708
+ return node;
2103
1709
  }
2104
- });
2105
-
2106
- //#endregion
2107
- //#region packages/core/src/tokenizer/tokens/query.token.ts
2108
- /**
2109
- * Query node — backtick-delimited filter expressions
2110
- * Content inside backticks is tokenized into children.
2111
- */ const QueryToken = new Node({
2112
- name: "query",
2113
- start: {
2114
- token: /`/u,
2115
- omit: true
2116
- },
2117
- end: {
2118
- token: /`/u,
2119
- omit: true
2120
- },
2121
- skip: /\s/u,
2122
- eofClose: true,
2123
- data: {
2124
- type: "query",
2125
- text: ""
1710
+ if (ni.$?.type === "block" && ni.$.text === "(") {
1711
+ const subNi = ni.fork(ni.$.children || []);
1712
+ ni.move();
1713
+ if (!subNi.$) {
1714
+ pushError(subNi, "Empty parenthesized expression");
1715
+ return;
1716
+ }
1717
+ const expr = parseOrExpr(subNi);
1718
+ if (subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
1719
+ return expr;
2126
1720
  }
2127
- });
2128
-
2129
- //#endregion
2130
- //#region packages/core/src/tokenizer/tokens/regexp.token.ts
2131
- const REGEXP_LITERAL_RE = /\/(?![/*])(?:\\.|\[.*?]|[^/\\\n\r[])*\/[dgimsuy]*/;
2132
- /**
2133
- * RegExp literal – `/pattern/flags`
2134
- * • Starts with `/` but *not* `//` or `/*`
2135
- * • Ends with `/` followed by zero-or-more valid flags
2136
- */ const RegExpToken = new Node({
2137
- name: "regexp",
2138
- start: {
2139
- token: REGEXP_LITERAL_RE,
2140
- omit: true
2141
- },
2142
- end: {
2143
- token: "",
2144
- omit: true
2145
- },
2146
- eofClose: true,
2147
- data: {
2148
- type: "regexp",
2149
- text: ""
2150
- }
2151
- }).onOpen((node, match) => {
2152
- node.data.text = match?.text ?? "";
2153
- });
2154
-
2155
- //#endregion
2156
- //#region packages/core/src/tokenizer/tokens/text.node.ts
2157
- /**
2158
- * Text node single or doublequoted
2159
- */ const TextToken = new Node({
2160
- name: "text",
2161
- start: {
2162
- token: RegExp("(?<quote>[\"'])", "u"),
2163
- omit: true
2164
- },
2165
- end: {
2166
- token: (ctx) => new RegExp(`(?<end>${ctx.node.data.quote || ""}|\\n)`),
2167
- omit: true,
2168
- backslash: true
2169
- },
2170
- eofClose: true,
2171
- data: {
2172
- type: "text",
2173
- quote: "",
2174
- end: "",
2175
- text: ""
2176
- },
2177
- mapContent: "text"
2178
- }).onClose((node) => {
2179
- node.data.multiline = node.data.end === "\n";
2180
- });
2181
-
2182
- //#endregion
2183
- //#region packages/core/src/tokenizer/tokens/index.ts
2184
- const tokens = {
2185
- aIdentifier: AIdentifierToken,
2186
- punctuation: PunctuationToken,
2187
- comments: commentNodes.all,
2188
- inlineComment: commentNodes.inline,
2189
- blockComment: commentNodes.block,
2190
- block: BlockToken,
2191
- identifier: IdentifierToken,
2192
- number: NumberToken,
2193
- text: TextToken,
2194
- regexp: RegExpToken,
2195
- query: QueryToken,
2196
- queryBlock: QueryBlockToken,
2197
- root: void 0
2198
- };
2199
- const root = new Node({
2200
- name: "root",
2201
- skip: /\s/u,
2202
- eofClose: true,
2203
- recognizes: [
2204
- ...commentNodes.all,
2205
- BlockToken,
2206
- QueryToken,
2207
- AIdentifierToken,
2208
- IdentifierToken,
2209
- TextToken,
2210
- NumberToken,
2211
- PunctuationToken
2212
- ]
2213
- });
2214
- tokens.root = root;
2215
- BlockToken.recognize(RegExpToken, ...commentNodes.all, BlockToken, QueryToken, AIdentifierToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2216
- QueryToken.recognize(RegExpToken, QueryOperatorToken, QueryBlockToken, BlockToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2217
- QueryBlockToken.recognize(RegExpToken, QueryOperatorToken, QueryBlockToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2218
- /** 1-based parser position → 0-based VSCode position, shifted by `offset` characters. */ function toPos(p, offset = 0) {
2219
- return {
2220
- line: p.line - 1,
2221
- character: p.column - 1 + offset
2222
- };
1721
+ return parseComparison(ni);
2223
1722
  }
2224
- /**
2225
- * Recursively extract TLexicalToken[] from a ParsedNode tree.
2226
- * Replaces the v0.5 mapContent('children', callback) + global loop.
2227
- *
2228
- * v0.6 Position has { offset, line, column }.
2229
- * line is 1-based, column is 1-based.
2230
- * VSCode expects 0-based line, 0-based character.
2231
- */ function extractTokens(node) {
2232
- const content = node.content;
2233
- return content.map((item, index) => {
2234
- if (typeof item === "string") {
2235
- const prev = content[index - 1];
2236
- const next = content[index + 1];
2237
- const start = typeof prev === "object" ? prev.end : node.start;
2238
- const end = typeof next === "object" ? next.start : node.end;
2239
- return {
2240
- type: "unknown",
2241
- text: item,
2242
- getRange: () => ({
2243
- start: toPos(start),
2244
- end: toPos(end)
2245
- })
2246
- };
1723
+ function parseComparison(ni) {
1724
+ const left = parseFieldRef(ni);
1725
+ if (!left) return;
1726
+ if (ni.$?.type === "punctuation" && SYMBOLIC_OPS.has(ni.$.text)) {
1727
+ const opText = ni.$.text;
1728
+ ni.move();
1729
+ const right = parseValueOrFieldRef(ni);
1730
+ if (!right) {
1731
+ pushError(ni, `Expected value or field reference after "${opText}"`);
1732
+ return;
2247
1733
  }
2248
- const data = item.data;
2249
- data.getRange = () => ({
2250
- start: toPos(item.start, data.startOffset),
2251
- end: toPos(item.end, data.endOffset)
2252
- });
2253
- data.children = extractTokens(item);
2254
- return data;
2255
- });
1734
+ const node = new SemanticQueryComparisonNode();
1735
+ node.left = left;
1736
+ node.operator = opText;
1737
+ node.right = right;
1738
+ return node;
1739
+ }
1740
+ if (ni.$?.type === "identifier") {
1741
+ const opText = ni.$.text;
1742
+ if (opText === "in") {
1743
+ ni.move();
1744
+ const right = parseValueList(ni);
1745
+ if (!right) return;
1746
+ const node = new SemanticQueryComparisonNode();
1747
+ node.left = left;
1748
+ node.operator = "in";
1749
+ node.right = right;
1750
+ return node;
1751
+ }
1752
+ if (opText === "matches") {
1753
+ ni.move();
1754
+ const right = parseValueOrFieldRef(ni);
1755
+ if (!right) {
1756
+ pushError(ni, "Expected value after \"matches\"");
1757
+ return;
1758
+ }
1759
+ const node = new SemanticQueryComparisonNode();
1760
+ node.left = left;
1761
+ node.operator = "matches";
1762
+ node.right = right;
1763
+ return node;
1764
+ }
1765
+ if (opText === "exists") {
1766
+ ni.move();
1767
+ const node = new SemanticQueryComparisonNode();
1768
+ node.left = left;
1769
+ node.operator = "exists";
1770
+ return node;
1771
+ }
1772
+ if (opText === "not") return parseNotComparison(ni, left);
1773
+ pushError(ni, `Unknown operator "${opText}"`);
1774
+ return;
1775
+ }
1776
+ pushError(ni, "Expected operator after field reference");
2256
1777
  }
2257
-
2258
- //#endregion
2259
- //#region packages/core/src/tokenizer/index.ts
2260
- function tokenize(source, debug = false) {
2261
- const result = root.parse(source);
2262
- if (debug) console.log(printTree(result));
2263
- return extractTokens(result);
1778
+ function parseNotComparison(ni, left) {
1779
+ ni.move();
1780
+ if (ni.$?.type === "identifier" && ni.$.text === "in") {
1781
+ ni.move();
1782
+ const right = parseValueList(ni);
1783
+ if (!right) return;
1784
+ const node = new SemanticQueryComparisonNode();
1785
+ node.left = left;
1786
+ node.operator = "not in";
1787
+ node.right = right;
1788
+ return node;
1789
+ }
1790
+ if (ni.$?.type === "identifier" && ni.$.text === "exists") {
1791
+ ni.move();
1792
+ const node = new SemanticQueryComparisonNode();
1793
+ node.left = left;
1794
+ node.operator = "not exists";
1795
+ return node;
1796
+ }
1797
+ pushError(ni, "Expected \"in\" or \"exists\" after \"not\"");
2264
1798
  }
2265
-
2266
- //#endregion
2267
- //#region packages/core/src/parser/pipes/tokens.pipe.ts
2268
- const identifier = (...text) => $token("identifier", text.length > 0 ? text : void 0);
2269
- const text = (...text) => $token("text", text.length > 0 ? text : void 0);
2270
- const block = (...text) => $token("block", text.length > 0 ? text.map((v) => v[0]) : void 0);
2271
- const pun = (...text) => $token("punctuation", text.length > 0 ? text : void 0);
2272
- function $token(name, text) {
2273
- const opts = {
2274
- optional: false,
2275
- saveAs: void 0,
2276
- skip: void 0,
2277
- expect: [{
2278
- node: name,
2279
- text
2280
- }],
2281
- contains: void 0,
2282
- isGlobal: false,
2283
- empty: false,
2284
- wrapper: void 0,
2285
- wrapMultiple: false,
2286
- debug: false,
2287
- eob: false,
2288
- suppressEobError: false,
2289
- lookBehind: false
2290
- };
2291
- return {
2292
- expect: [{
2293
- node: name,
2294
- text
2295
- }],
2296
- handler(ni, target) {
2297
- if (opts.debug) debugger;
2298
- let firstRun = true;
2299
- while (firstRun || opts.wrapMultiple) {
2300
- firstRun = false;
2301
- if (!ni.$) {
2302
- const ok = opts.eob || opts.optional;
2303
- if (!ok && !opts.suppressEobError) ni.unexpectedEOB();
2304
- return ok;
2305
- }
2306
- let matched = ni.satisfies(...opts.expect);
2307
- if (!matched && opts.lookBehind) {
2308
- matched = ni.fork().move(-1).satisfies(...opts.expect);
2309
- if (matched) ni.move(-1);
2310
- }
2311
- if (matched) {
2312
- if (opts.empty && ni.$.children?.length) {
2313
- ni.unexpected(false, `Expected empty block`);
2314
- return opts.optional;
2315
- }
2316
- if (opts.contains) {
2317
- if (!ni.$.children?.length) {
2318
- ni.unexpected(false, `Expected ${opts.contains.map((v) => v.text).join(", ")}`);
2319
- return opts.optional;
2320
- }
2321
- if (ni.$.children[0].type !== opts.contains[0].node || ni.$.children[0].text !== opts.contains[0].text) {
2322
- ni.unexpected(false, `Expected ${opts.contains.map((v) => v.text).join(", ")}`);
2323
- return opts.optional;
2324
- }
2325
- }
2326
- if (opts.saveAs) target.node.saveToken(new Token(ni.$), opts.saveAs);
2327
- ni.accepted();
2328
- if (opts.wrapper) {
2329
- const wrapped = target.node;
2330
- target.node = opts.wrapper().wrap(wrapped, new Token(ni.$));
2331
- }
2332
- ni.move();
2333
- if (opts.skip) ni.skip(opts.skip);
2334
- if (opts.wrapMultiple) continue;
2335
- else return true;
2336
- } else {
2337
- if (!opts.optional) ni.unexpected();
2338
- return opts.optional;
1799
+ function parseFieldRef(ni) {
1800
+ if (ni.$?.type !== "identifier") {
1801
+ pushError(ni, "Expected field reference");
1802
+ return;
1803
+ }
1804
+ const firstToken = new Token(ni.$);
1805
+ ni.move();
1806
+ if (ni.$?.type === "punctuation" && ni.$.text === ".") {
1807
+ ni.move();
1808
+ if (ni.$?.type === "identifier") {
1809
+ const secondToken = new Token(ni.$);
1810
+ ni.move();
1811
+ let fieldText = secondToken.text;
1812
+ while (ni.$?.type === "punctuation" && ni.$.text === ".") {
1813
+ ni.move();
1814
+ if (ni.$?.type === "identifier") {
1815
+ fieldText += `.${ni.$.text}`;
1816
+ ni.move();
1817
+ } else {
1818
+ pushError(ni, "Expected identifier after \".\"");
1819
+ break;
2339
1820
  }
2340
1821
  }
2341
- return true;
2342
- },
2343
- saveAs(v) {
2344
- opts.saveAs = v;
2345
- return this;
2346
- },
2347
- wrap(sn, multiple = false) {
2348
- opts.wrapper = sn;
2349
- opts.wrapMultiple = multiple;
2350
- return this;
2351
- },
2352
- optional() {
2353
- opts.optional = true;
2354
- return this;
2355
- },
2356
- empty() {
2357
- opts.empty = true;
2358
- return this;
2359
- },
2360
- contains(t) {
2361
- opts.contains = t.expect;
2362
- return this;
2363
- },
2364
- skip(...p) {
2365
- opts.skip = p;
2366
- return this;
2367
- },
2368
- or(t) {
2369
- opts.expect.push(...t.expect);
2370
- return this;
2371
- },
2372
- orEob() {
2373
- opts.eob = true;
2374
- return this;
2375
- },
2376
- suppressEobError() {
2377
- opts.suppressEobError = true;
2378
- return this;
2379
- },
2380
- global() {
2381
- opts.isGlobal = true;
2382
- return this;
2383
- },
2384
- lookBehind() {
2385
- opts.lookBehind = true;
2386
- return this;
2387
- },
2388
- debug() {
2389
- opts.debug = true;
2390
- return this;
1822
+ const node = new SemanticQueryFieldRefNode();
1823
+ node.typeRef = firstToken;
1824
+ node.fieldRef = fieldText === secondToken.text ? secondToken : secondToken.clone({ text: fieldText });
1825
+ return node;
2391
1826
  }
2392
- };
1827
+ pushError(ni, "Expected identifier after \".\"");
1828
+ const node = new SemanticQueryFieldRefNode();
1829
+ node.fieldRef = firstToken;
1830
+ return node;
1831
+ }
1832
+ const node = new SemanticQueryFieldRefNode();
1833
+ node.fieldRef = firstToken;
1834
+ return node;
2393
1835
  }
2394
-
2395
- //#endregion
2396
- //#region packages/core/src/parser/pipes/core.pipe.ts
2397
- function $pipe(entity, pipe = []) {
2398
- pipe.forEach((p, i) => Object.assign(p, { toString: () => `${entity}.${i}` }));
2399
- return {
2400
- targetFactory: () => {
2401
- switch (entity) {
2402
- case "interface": return new $n.SemanticInterfaceNode();
2403
- case "array": return new $n.SemanticArrayNode();
2404
- case "const": return new $n.SemanticConstNode();
2405
- case "group": return new $n.SemanticGroup();
2406
- case "prop": return new $n.SemanticPropNode();
2407
- case "type": return new $n.SemanticTypeNode();
2408
- case "ref": return new $n.SemanticRefNode();
2409
- case "structure": return new $n.SemanticStructureNode();
2410
- case "tuple": return new $n.SemanticTupleNode();
2411
- case "import": return new $n.SemanticImportNode();
2412
- case "annotate": return new $n.SemanticAnnotateNode();
2413
- case "primitive": throw new Error("Can't create pipe for primitive node");
2414
- default: throw new Error(`Can't create pipe for ${entity} node`);
2415
- }
2416
- },
2417
- pipe,
2418
- toString: () => entity,
2419
- skipTokens: [],
2420
- stopCondition: void 0,
2421
- skip(...s) {
2422
- this.skipTokens.push(...s);
2423
- return this;
2424
- },
2425
- stop(sc) {
2426
- this.stopCondition = sc;
2427
- return this;
2428
- },
2429
- t(node, skip = []) {
2430
- this.pipe.push($token(node).saveAs("identifier").skip(...skip));
2431
- return this;
2432
- }
2433
- };
1836
+ function parseValueOrFieldRef(ni) {
1837
+ if (!ni.$) return;
1838
+ if (ni.$.type === "text" || ni.$.type === "number" || ni.$.type === "regexp") return parseValue(ni);
1839
+ if (ni.$.type === "identifier") {
1840
+ if (VALUE_KEYWORDS.has(ni.$.text)) return parseValue(ni);
1841
+ return parseFieldRef(ni);
1842
+ }
1843
+ pushError(ni, "Expected value or field reference");
2434
1844
  }
2435
- function runPipes(pipes, ni, singlePass = false) {
2436
- const nodes = [];
2437
- while (ni.$) {
2438
- let matched = true;
2439
- let depth = ni.index;
2440
- for (const { targetFactory, pipe, skipTokens: skip, stopCondition } of pipes) {
2441
- const target = { node: targetFactory() };
2442
- const fork = ni.fork();
2443
- fork.skip(skip);
2444
- if (!fork.$) {
2445
- ni.unfork(fork);
2446
- break;
2447
- }
2448
- matched = true;
2449
- for (const { handler } of pipe) if (!handler(fork, target)) {
2450
- matched = false;
2451
- break;
2452
- }
2453
- if (fork.index > depth) depth = fork.index;
2454
- if (matched) {
2455
- nodes.push(target.node);
2456
- ni.unfork(fork);
2457
- if (stopCondition && stopCondition(fork)) return nodes;
2458
- ni.move(-1);
2459
- break;
2460
- }
2461
- }
2462
- if (singlePass) return nodes;
2463
- if (!matched) {
2464
- ni.shouldHaveError(depth);
2465
- ni.move(depth - ni.index);
2466
- }
1845
+ function parseValue(ni) {
1846
+ if (!ni.$) {
1847
+ pushError(ni, "Expected value");
1848
+ return;
1849
+ }
1850
+ const token = ni.$;
1851
+ if (token.type === "text" || token.type === "number" || token.type === "regexp" || token.type === "identifier" && VALUE_KEYWORDS.has(token.text)) {
1852
+ const node = new SemanticQueryValueNode();
1853
+ node.valueToken = new Token(token);
2467
1854
  ni.move();
2468
- if (matched) {} else {
2469
- ni.confirmIssues();
2470
- ni.skipUntil([";", "\n"]);
1855
+ return node;
1856
+ }
1857
+ pushError(ni, `Unexpected token "${token.text}" where value expected`);
1858
+ }
1859
+ function parseValueList(ni) {
1860
+ if (ni.$?.type === "block" && ni.$.text === "(") {
1861
+ const subNi = ni.fork(ni.$.children || []);
1862
+ ni.move();
1863
+ if (!subNi.$) {
1864
+ pushError(subNi, "Empty value list in \"in\" expression");
1865
+ return;
1866
+ }
1867
+ const values = [];
1868
+ const first = parseValue(subNi);
1869
+ if (first) values.push(first);
1870
+ while (subNi.$?.type === "punctuation" && subNi.$.text === ",") {
1871
+ subNi.move();
1872
+ const v = parseValue(subNi);
1873
+ if (v) values.push(v);
2471
1874
  }
1875
+ if (subNi.$) pushError(subNi, `Unexpected token in value list: "${subNi.$.text}"`);
1876
+ const node = new SemanticQueryValueListNode();
1877
+ node.values = values;
1878
+ return node;
2472
1879
  }
2473
- return nodes;
1880
+ pushError(ni, "Expected parenthesized value list after \"in\"");
2474
1881
  }
2475
- function runPipesOnce(pipes, ni) {
2476
- return runPipes(pipes, ni, true)[0];
1882
+ /**
1883
+ * Range to blame for a diagnostic: the current token, else the enclosing
1884
+ * query token / "(...)" block the iterator was forked from.
1885
+ */ function rangeOf(ni) {
1886
+ return ni.$?.getRange?.() ?? ni.parent?.getRange?.() ?? ZERO_RANGE;
1887
+ }
1888
+ function pushError(ni, message) {
1889
+ ni.messages.push({
1890
+ severity: 1,
1891
+ message,
1892
+ range: rangeOf(ni)
1893
+ });
2477
1894
  }
2478
1895
 
2479
1896
  //#endregion
2480
- //#region packages/core/src/parser/grouping.ts
2481
- function groupByPriority(nodes, priority) {
2482
- if (nodes.length === 1) return nodes[0];
2483
- if (nodes.length === 0) return;
2484
- if (nodes.length % 2 === 0) throw new Error(`Invalid number of nodes ${nodes.length}. Odd number expected`);
2485
- let currentPass = nodes;
2486
- let temporaryResult = [];
2487
- let groupped = [];
2488
- for (const p of priority) {
2489
- for (const [i, node] of currentPass.entries()) {
2490
- const isOperator = i % 2 === 1;
2491
- if (!isOperator && node instanceof Token) throw new Error(`Unexpected token ${node.toString()} at ${i}`);
2492
- else if (isOperator && !(node instanceof Token)) throw new Error(`Unexpected token ${isGroup(node) ? node.op : node.token.toString()} at ${i}`);
2493
- if (isOperator) {
2494
- if (node.text !== p) temporaryResult.push(node);
2495
- continue;
2496
- }
2497
- const prev = currentPass[i - 1]?.text;
2498
- const next = currentPass[i + 1]?.text;
2499
- if (prev !== p && next !== p) {
2500
- temporaryResult.push(node);
2501
- continue;
2502
- }
2503
- if (prev === p || next === p) {
2504
- groupped.push(node);
2505
- if (next !== p) {
2506
- temporaryResult.push(new $n.SemanticGroup(groupped, p));
2507
- groupped = [];
2508
- }
2509
- }
2510
- }
2511
- currentPass = temporaryResult;
2512
- temporaryResult = [];
1897
+ //#region packages/core/src/parser/pipes/expr.pipe.ts
1898
+ /**
1899
+ * Parse a backtick annotation argument as the given kind and attach the tree to
1900
+ * the token (`queryNode`, `exprNode` or `orderNode`). Returns the diagnostics.
1901
+ */ function parseBacktickArg(argToken, kind) {
1902
+ const messages = [];
1903
+ const ni = new NodeIterator(argToken.children, messages, /* @__PURE__ */ new Map(), {}, argToken.lexicalToken, 0).update();
1904
+ switch (kind) {
1905
+ case "expr":
1906
+ argToken.exprNode = parseExprExpression(ni, argToken);
1907
+ break;
1908
+ case "order":
1909
+ argToken.orderNode = parseOrderList(ni, argToken);
1910
+ break;
1911
+ default: argToken.queryNode = parseQueryExpression(ni, argToken);
2513
1912
  }
2514
- const output = currentPass[0];
2515
- return output.length === 1 ? output.first : output;
1913
+ return messages;
2516
1914
  }
2517
-
2518
- //#endregion
2519
- //#region packages/core/src/parser/pipes/query.pipe.ts
2520
- const SYMBOLIC_OPS = new Set([
2521
- "=",
2522
- "!=",
2523
- ">",
2524
- ">=",
2525
- "<",
2526
- "<="
2527
- ]);
2528
- const VALUE_KEYWORDS = new Set([
2529
- "true",
2530
- "false",
2531
- "null",
2532
- "undefined"
2533
- ]);
2534
- const ZERO_RANGE = {
2535
- start: {
2536
- line: 0,
2537
- character: 0
2538
- },
2539
- end: {
2540
- line: 0,
2541
- character: 0
2542
- }
1915
+ /** Vocabulary of `expr` / `order` arguments: arithmetic operators, functions, order directions. */ const BACKTICK_ARG_VOCABULARY = {
1916
+ arithmeticOps: [
1917
+ "+",
1918
+ "-",
1919
+ "*",
1920
+ "/"
1921
+ ],
1922
+ functions: ["coalesce"],
1923
+ orderDirections: ["asc", "desc"]
2543
1924
  };
1925
+ const ORDER_DIRECTIONS = new Set(BACKTICK_ARG_VOCABULARY.orderDirections);
2544
1926
  /**
2545
- * Parse a backtick-delimited query expression.
1927
+ * Parse a backtick arithmetic expression:
2546
1928
  *
2547
- * `ni` iterates the query token's children and carries that token as its
2548
- * `parent` — the range to blame when a diagnostic has no token of its own —
2549
- * so fork it from the annotation iterator while the query token is current.
2550
- * Returns a SemanticQueryNode or undefined if the content is empty.
2551
- */ function parseQueryExpression(ni, sourceToken) {
2552
- if (!ni.$) return;
2553
- const expr = parseOrExpr(ni);
1929
+ * ```
1930
+ * expr := additive
1931
+ * additive := mult (('+' | '-') mult)*
1932
+ * mult := unary (('*' | '/') unary)*
1933
+ * unary := '-' unary | primary
1934
+ * primary := NUMBER | fieldRef | 'coalesce' '(' expr (',' expr)+ ')' | '(' expr ')'
1935
+ * ```
1936
+ *
1937
+ * A signed number in binary-operator position (`a -5`, `a+1`) is split into the
1938
+ * operator and an unsigned operand. Returns `undefined` when the content is empty.
1939
+ */ function parseExprExpression(ni, sourceToken) {
1940
+ if (!ni.$) {
1941
+ pushError(ni, "Empty expression");
1942
+ return;
1943
+ }
1944
+ const expr = parseAdditive(ni);
2554
1945
  if (!expr) return;
2555
- if (ni.$) pushError(ni, `Unexpected token in query expression: "${ni.$.text}"`);
2556
- const node = new SemanticQueryNode();
1946
+ if (ni.$) pushError(ni, `Unexpected token in expression: "${ni.$.text}"`);
1947
+ const node = new SemanticExprNode();
2557
1948
  node.expression = expr;
2558
1949
  node.sourceToken = sourceToken;
2559
1950
  return node;
2560
1951
  }
2561
- function parseOrExpr(ni) {
2562
- const left = parseAndExpr(ni);
1952
+ function isPunct(t, chars) {
1953
+ return t?.type === "punctuation" && t.text.length === 1 && chars.includes(t.text);
1954
+ }
1955
+ function isParenBlock(t) {
1956
+ return t?.type === "block" && t.text === "(";
1957
+ }
1958
+ /** A number token whose text carries a sign (`-5`, `+1`). */ function signedNumber(t) {
1959
+ if (t?.type !== "number") return;
1960
+ const c = t.text.charAt(0);
1961
+ return c === "-" || c === "+" ? c : void 0;
1962
+ }
1963
+ function binary(op, left, right) {
1964
+ const node = new SemanticExprBinaryNode();
1965
+ node.op = op;
1966
+ node.left = left;
1967
+ node.right = right;
1968
+ return node;
1969
+ }
1970
+ function parseAdditive(ni) {
1971
+ let left = parseMult(ni);
2563
1972
  if (!left) return;
2564
- const operands = [left];
2565
- while (ni.$?.type === "identifier" && ni.$.text === "or") {
2566
- ni.move();
2567
- const right = parseAndExpr(ni);
1973
+ for (;;) {
1974
+ const punct = isPunct(ni.$, "+-");
1975
+ const op = punct ? ni.$?.text : signedNumber(ni.$);
1976
+ if (!op) break;
1977
+ if (punct) ni.move();
1978
+ const right = parseMult(ni, !punct);
2568
1979
  if (!right) {
2569
- pushError(ni, "Expected expression after \"or\"");
2570
- break;
1980
+ pushError(ni, `Expected operand after "${op}"`);
1981
+ return;
2571
1982
  }
2572
- operands.push(right);
1983
+ left = binary(op, left, right);
2573
1984
  }
2574
- if (operands.length === 1) return operands[0];
2575
- const node = new SemanticQueryLogicalNode();
2576
- node.operator = "or";
2577
- node.operands = operands;
2578
- return node;
1985
+ return left;
2579
1986
  }
2580
- function parseAndExpr(ni) {
2581
- const left = parseUnaryExpr(ni);
1987
+ function parseMult(ni, unsignFirst = false) {
1988
+ let left = parseUnary(ni, unsignFirst);
2582
1989
  if (!left) return;
2583
- const operands = [left];
2584
- while (ni.$?.type === "identifier" && ni.$.text === "and") {
1990
+ for (let t = ni.$; isPunct(t, "*/"); t = ni.$) {
1991
+ const op = t.text;
2585
1992
  ni.move();
2586
- const right = parseUnaryExpr(ni);
1993
+ const right = parseUnary(ni);
2587
1994
  if (!right) {
2588
- pushError(ni, "Expected expression after \"and\"");
2589
- break;
1995
+ pushError(ni, `Expected operand after "${op}"`);
1996
+ return;
2590
1997
  }
2591
- operands.push(right);
1998
+ left = binary(op, left, right);
2592
1999
  }
2593
- if (operands.length === 1) return operands[0];
2594
- const node = new SemanticQueryLogicalNode();
2595
- node.operator = "and";
2596
- node.operands = operands;
2597
- return node;
2000
+ return left;
2598
2001
  }
2599
- function parseUnaryExpr(ni) {
2600
- if (ni.$?.type === "identifier" && ni.$.text === "not") {
2002
+ function parseUnary(ni, unsign = false) {
2003
+ if (!unsign && isPunct(ni.$, "-")) {
2601
2004
  ni.move();
2602
- const operand = parseUnaryExpr(ni);
2005
+ const operand = parseUnary(ni);
2603
2006
  if (!operand) {
2604
- pushError(ni, "Expected expression after \"not\"");
2007
+ pushError(ni, "Expected operand after \"-\"");
2605
2008
  return;
2606
2009
  }
2607
- const node = new SemanticQueryLogicalNode();
2608
- node.operator = "not";
2609
- node.operands = [operand];
2010
+ const node = new SemanticExprUnaryNode();
2011
+ node.operand = operand;
2610
2012
  return node;
2611
2013
  }
2612
- if (ni.$?.type === "block" && ni.$.text === "(") {
2613
- const subNi = ni.fork(ni.$.children || []);
2014
+ return parsePrimary(ni, unsign);
2015
+ }
2016
+ function parsePrimary(ni, unsign = false) {
2017
+ const t = ni.$;
2018
+ if (!t) {
2019
+ pushError(ni, "Expected operand");
2020
+ return;
2021
+ }
2022
+ if (t.type === "number") return parseNumber(ni, t, unsign);
2023
+ if (isParenBlock(t)) {
2024
+ const subNi = ni.fork(t.children || []);
2614
2025
  ni.move();
2615
2026
  if (!subNi.$) {
2616
2027
  pushError(subNi, "Empty parenthesized expression");
2617
2028
  return;
2618
2029
  }
2619
- const expr = parseOrExpr(subNi);
2620
- if (subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
2030
+ const expr = parseAdditive(subNi);
2031
+ if (expr && subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
2621
2032
  return expr;
2622
2033
  }
2623
- return parseComparison(ni);
2624
- }
2625
- function parseComparison(ni) {
2626
- const left = parseFieldRef(ni);
2627
- if (!left) return;
2628
- if (ni.$?.type === "punctuation" && SYMBOLIC_OPS.has(ni.$.text)) {
2629
- const opText = ni.$.text;
2630
- ni.move();
2631
- const right = parseValueOrFieldRef(ni);
2632
- if (!right) {
2633
- pushError(ni, `Expected value or field reference after "${opText}"`);
2034
+ if (t.type === "identifier") {
2035
+ if (VALUE_KEYWORDS.has(t.text)) {
2036
+ pushError(ni, `"${t.text}" is not allowed in an arithmetic expression`);
2634
2037
  return;
2635
2038
  }
2636
- const node = new SemanticQueryComparisonNode();
2637
- node.left = left;
2638
- node.operator = opText;
2639
- node.right = right;
2640
- return node;
2641
- }
2642
- if (ni.$?.type === "identifier") {
2643
- const opText = ni.$.text;
2644
- if (opText === "in") {
2645
- ni.move();
2646
- const right = parseValueList(ni);
2647
- if (!right) return;
2648
- const node = new SemanticQueryComparisonNode();
2649
- node.left = left;
2650
- node.operator = "in";
2651
- node.right = right;
2652
- return node;
2653
- }
2654
- if (opText === "matches") {
2655
- ni.move();
2656
- const right = parseValueOrFieldRef(ni);
2657
- if (!right) {
2658
- pushError(ni, "Expected value after \"matches\"");
2659
- return;
2660
- }
2661
- const node = new SemanticQueryComparisonNode();
2662
- node.left = left;
2663
- node.operator = "matches";
2664
- node.right = right;
2665
- return node;
2666
- }
2667
- if (opText === "exists") {
2039
+ if (t.text === "coalesce" && isParenBlock(ni.next().$)) {
2668
2040
  ni.move();
2669
- const node = new SemanticQueryComparisonNode();
2670
- node.left = left;
2671
- node.operator = "exists";
2672
- return node;
2041
+ return parseCoalesce(ni);
2673
2042
  }
2674
- if (opText === "not") return parseNotComparison(ni, left);
2675
- pushError(ni, `Unknown operator "${opText}"`);
2043
+ return parseFieldRef(ni);
2044
+ }
2045
+ pushError(ni, `Unexpected token in expression: "${t.text}"`);
2046
+ }
2047
+ /** Why a number literal cannot be used in an expression (or `undefined` when it can). */ function numberLiteralProblem(text, value) {
2048
+ if (!Number.isFinite(value)) return "is out of range";
2049
+ if (value === 0 && /[1-9]/.test(text.replace(/[eE].*$/, ""))) return "underflows to 0";
2050
+ if (Math.abs(value) > Number.MAX_SAFE_INTEGER) return "exceeds the safe integer range (±2^53 - 1)";
2051
+ }
2052
+ function parseNumber(ni, lexical, unsign) {
2053
+ const token = new Token(lexical);
2054
+ const text = unsign ? token.text.slice(1) : token.text;
2055
+ const value = Number(text);
2056
+ const problem = numberLiteralProblem(text, value);
2057
+ if (problem) {
2058
+ pushError(ni, `Number literal "${token.text}" ${problem}`);
2059
+ ni.move();
2676
2060
  return;
2677
2061
  }
2678
- pushError(ni, "Expected operator after field reference");
2062
+ ni.move();
2063
+ const node = new SemanticExprNumberNode();
2064
+ node.valueToken = token;
2065
+ node.value = value;
2066
+ return node;
2679
2067
  }
2680
- function parseNotComparison(ni, left) {
2068
+ function parseCoalesce(ni) {
2069
+ const subNi = ni.fork(ni.$?.children || []);
2681
2070
  ni.move();
2682
- if (ni.$?.type === "identifier" && ni.$.text === "in") {
2683
- ni.move();
2684
- const right = parseValueList(ni);
2685
- if (!right) return;
2686
- const node = new SemanticQueryComparisonNode();
2687
- node.left = left;
2688
- node.operator = "not in";
2689
- node.right = right;
2690
- return node;
2071
+ const args = [];
2072
+ if (subNi.$) for (;;) {
2073
+ const arg = parseAdditive(subNi);
2074
+ if (!arg) return;
2075
+ args.push(arg);
2076
+ if (!isPunct(subNi.$, ",")) break;
2077
+ subNi.move();
2078
+ }
2079
+ if (subNi.$) {
2080
+ pushError(subNi, `Unexpected token in coalesce(): "${subNi.$.text}"`);
2081
+ return;
2691
2082
  }
2692
- if (ni.$?.type === "identifier" && ni.$.text === "exists") {
2693
- ni.move();
2694
- const node = new SemanticQueryComparisonNode();
2695
- node.left = left;
2696
- node.operator = "not exists";
2697
- return node;
2083
+ if (args.length < 2) {
2084
+ pushError(subNi, "coalesce() requires at least 2 arguments");
2085
+ return;
2698
2086
  }
2699
- pushError(ni, "Expected \"in\" or \"exists\" after \"not\"");
2087
+ const node = new SemanticExprCallNode();
2088
+ node.args = args;
2089
+ return node;
2700
2090
  }
2701
- function parseFieldRef(ni) {
2702
- if (ni.$?.type !== "identifier") {
2703
- pushError(ni, "Expected field reference");
2091
+ /**
2092
+ * Parse a backtick ordering: `key (asc|desc)? (, key (asc|desc)?)*`.
2093
+ * Returns `undefined` when the content is empty or a key does not parse.
2094
+ */ function parseOrderList(ni, sourceToken) {
2095
+ if (!ni.$) {
2096
+ pushError(ni, "Empty order list");
2704
2097
  return;
2705
2098
  }
2706
- const firstToken = new Token(ni.$);
2707
- ni.move();
2708
- if (ni.$?.type === "punctuation" && ni.$.text === ".") {
2709
- ni.move();
2710
- if (ni.$?.type === "identifier") {
2711
- const secondToken = new Token(ni.$);
2099
+ const items = [];
2100
+ for (;;) {
2101
+ const ref = parseFieldRef(ni);
2102
+ if (!ref) return;
2103
+ const item = {
2104
+ ref,
2105
+ desc: false
2106
+ };
2107
+ if (ni.$?.type === "identifier" && ORDER_DIRECTIONS.has(ni.$.text)) {
2108
+ item.desc = ni.$.text === "desc";
2109
+ item.dirToken = new Token(ni.$);
2712
2110
  ni.move();
2713
- let fieldText = secondToken.text;
2714
- while (ni.$?.type === "punctuation" && ni.$.text === ".") {
2715
- ni.move();
2716
- if (ni.$?.type === "identifier") {
2717
- fieldText += `.${ni.$.text}`;
2111
+ }
2112
+ items.push(item);
2113
+ if (!ni.$) break;
2114
+ if (isPunct(ni.$, ",")) {
2115
+ ni.move();
2116
+ continue;
2117
+ }
2118
+ pushError(ni, `Unexpected token in order list: "${ni.$.text}" (expected "," or "asc" / "desc")`);
2119
+ return;
2120
+ }
2121
+ const node = new SemanticOrderNode();
2122
+ node.items = items;
2123
+ node.sourceToken = sourceToken;
2124
+ return node;
2125
+ }
2126
+
2127
+ //#endregion
2128
+ //#region packages/core/src/lsp/legacy-db-query-scope.ts
2129
+ /**
2130
+ * @deprecated Built-in editor scopes for the `@db.view.filter`, `@db.view.joins` and
2131
+ * `@db.rel.filter` query arguments. They are a fallback for DB plugin versions whose
2132
+ * argument specs do not declare a `fieldScope` hook yet — the DB plugin owns these
2133
+ * rules now. Scheduled for removal in `@atscript/core` 0.2.0 (next minor).
2134
+ */
2135
+ /**
2136
+ * @deprecated Query scope of a built-in `@db.*` query argument (see the module note);
2137
+ * `undefined` for any other annotation.
2138
+ */ function getLegacyDbQueryScope(queryArgToken) {
2139
+ const owner = queryArgToken.parentNode;
2140
+ if (!owner) return;
2141
+ switch (queryArgToken.annotationRef?.text.slice(1)) {
2142
+ case "db.view.filter": return getViewFilterScope(owner);
2143
+ case "db.view.joins": return getViewJoinsScope(owner, queryArgToken);
2144
+ case "db.rel.filter": return getRelFilterScope(owner);
2145
+ default: return;
2146
+ }
2147
+ }
2148
+ function getViewFilterScope(owner) {
2149
+ const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
2150
+ if (!entryTypeName) return;
2151
+ const allowedTypes = [entryTypeName];
2152
+ const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
2153
+ if (joinsAnnotations) {
2154
+ for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
2155
+ }
2156
+ return {
2157
+ allowedTypes,
2158
+ unqualifiedTarget: entryTypeName
2159
+ };
2160
+ }
2161
+ function getViewJoinsScope(owner, queryArgToken) {
2162
+ const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
2163
+ if (!entryTypeName) return;
2164
+ const joinTargetName = (owner.annotations?.find((a) => a.name === "db.view.joins" && a.args.includes(queryArgToken)))?.args[0]?.text;
2165
+ if (!joinTargetName) return;
2166
+ return {
2167
+ allowedTypes: [joinTargetName, entryTypeName],
2168
+ unqualifiedTarget: entryTypeName
2169
+ };
2170
+ }
2171
+ function getRelFilterScope(owner) {
2172
+ let def = owner.getDefinition();
2173
+ if (isArray(def)) def = def?.getDefinition();
2174
+ if (!isRef(def)) return;
2175
+ const targetTypeName = def.id;
2176
+ const allowedTypes = [targetTypeName];
2177
+ const viaAnnotation = owner.annotations?.find((a) => a.name === "db.rel.via");
2178
+ if (viaAnnotation?.args[0]) allowedTypes.push(viaAnnotation.args[0].text);
2179
+ return {
2180
+ allowedTypes,
2181
+ unqualifiedTarget: targetTypeName
2182
+ };
2183
+ }
2184
+
2185
+ //#endregion
2186
+ //#region packages/core/src/lsp/field-refs.ts
2187
+ function getArgSpec(argToken, doc) {
2188
+ const annotationRef = argToken.annotationRef;
2189
+ if (!annotationRef || typeof argToken.index !== "number") return;
2190
+ return doc.resolveAnnotation(annotationRef.text.slice(1))?.arguments[argToken.index];
2191
+ }
2192
+ /**
2193
+ * Field scope of an annotation argument: the answer of the argument spec's `fieldScope`
2194
+ * hook when it declares one, otherwise the deprecated built-in `@db.*` query rules.
2195
+ */ function getQueryScope(argToken, doc) {
2196
+ const argSpec = getArgSpec(argToken, doc);
2197
+ return argSpec?.fieldScope ? argSpec.fieldScope(argToken, doc) : getLegacyDbQueryScope(argToken);
2198
+ }
2199
+ /**
2200
+ * Type a field-path `string` argument names a field of: the `unqualifiedTarget` of the
2201
+ * argument spec's `fieldScope`. `undefined` for any other token.
2202
+ */ function getFieldPathTarget(argToken, doc) {
2203
+ if (argToken.type !== "text") return;
2204
+ const argSpec = getArgSpec(argToken, doc);
2205
+ if (argSpec?.type !== "string" || !argSpec.fieldScope) return;
2206
+ return argSpec.fieldScope(argToken, doc)?.unqualifiedTarget ?? void 0;
2207
+ }
2208
+ /**
2209
+ * Resolve a (possibly dotted) field path of a type to the property it names and the
2210
+ * document that declares that property.
2211
+ */ function resolveFieldPath(doc, typeName, segment) {
2212
+ const chain = segment.path.split(".");
2213
+ const [name] = chain.splice(-1);
2214
+ const parent = doc.unwindType(typeName, chain);
2215
+ if (!parent || !(isStructure(parent.def) || isInterface(parent.def))) return;
2216
+ const prop = parent.def.props.get(name);
2217
+ return prop && {
2218
+ typeName,
2219
+ range: segment.range,
2220
+ prop,
2221
+ doc: parent.doc
2222
+ };
2223
+ }
2224
+ /**
2225
+ * Segments of a field-path string argument (`'address.city'` → `address`, `city`), with
2226
+ * ranges that exclude the quotes. A string spanning several lines is a single segment.
2227
+ */ function fieldPathSegments(argToken) {
2228
+ const { text, range } = argToken;
2229
+ if (range.start.line !== range.end.line) return [{
2230
+ path: text,
2231
+ range
2232
+ }];
2233
+ const line = range.start.line;
2234
+ const contentStart = range.start.character + 1;
2235
+ const segments = [];
2236
+ let start = 0;
2237
+ for (const part of text.split(".")) {
2238
+ const end = start + part.length;
2239
+ segments.push({
2240
+ path: text.slice(0, end),
2241
+ range: {
2242
+ start: {
2243
+ line,
2244
+ character: contentStart + start
2245
+ },
2246
+ end: {
2247
+ line,
2248
+ character: contentStart + end
2249
+ }
2250
+ }
2251
+ });
2252
+ start = end + 1;
2253
+ }
2254
+ return segments;
2255
+ }
2256
+ /** The segment under `character`, or the last segment when `character` is omitted. */ function fieldPathSegmentAt(argToken, character) {
2257
+ const segments = fieldPathSegments(argToken);
2258
+ return (character === void 0 ? void 0 : segments.find((s) => s.range.end.character >= character)) ?? segments[segments.length - 1];
2259
+ }
2260
+ /**
2261
+ * Resolve a field reference token to the property it names:
2262
+ * - a field ref inside a `query` argument (`amount`, `Customer.name` in backticks);
2263
+ * - a `string` argument whose spec declares `fieldScope`: a (dotted) field path of the
2264
+ * scope's `unqualifiedTarget`. With `character` (a cursor column), the path resolves
2265
+ * only up to the segment under the cursor — `'address.city'` with the cursor on
2266
+ * `address` resolves `address` — and `range` is that segment's range.
2267
+ *
2268
+ * Returns `undefined` for any other token, or when the scope or the path does not resolve.
2269
+ */ function resolveFieldRefAt(token, doc, character) {
2270
+ if (isQueryFieldRef(token.parentNode)) {
2271
+ const { fieldRef, typeRef, queryArgToken } = token.parentNode;
2272
+ const scope = token === fieldRef && queryArgToken ? getQueryScope(queryArgToken, doc) : void 0;
2273
+ const typeName = scope && (typeRef?.text ?? scope.unqualifiedTarget);
2274
+ return typeName ? resolveFieldPath(doc, typeName, {
2275
+ path: token.text,
2276
+ range: token.range
2277
+ }) : void 0;
2278
+ }
2279
+ const typeName = getFieldPathTarget(token, doc);
2280
+ return typeName ? resolveFieldPath(doc, typeName, fieldPathSegmentAt(token, character)) : void 0;
2281
+ }
2282
+ /**
2283
+ * Resolve the segments named `fieldName` of a field-path `string` argument
2284
+ * (`'address.city'` has the segments `address` and `city`). Supports find-references.
2285
+ */ function resolveFieldPathArgSegments(argToken, doc, fieldName) {
2286
+ const segments = fieldPathSegments(argToken).filter((s) => s.path === fieldName || s.path.endsWith(`.${fieldName}`));
2287
+ const typeName = segments.length > 0 ? getFieldPathTarget(argToken, doc) : void 0;
2288
+ if (!typeName) return [];
2289
+ const targets = [];
2290
+ for (const segment of segments) {
2291
+ const target = resolveFieldPath(doc, typeName, segment);
2292
+ if (target) targets.push(target);
2293
+ }
2294
+ return targets;
2295
+ }
2296
+ /**
2297
+ * Resolve a query field ref node to a property definition.
2298
+ */ function resolveQueryFieldRef(fieldRefNode, doc, scope) {
2299
+ const typeName = fieldRefNode.typeRef?.text ?? scope.unqualifiedTarget;
2300
+ const { fieldRef } = fieldRefNode;
2301
+ const resolved = typeName ? resolveFieldPath(doc, typeName, {
2302
+ path: fieldRef.text,
2303
+ range: fieldRef.range
2304
+ }) : void 0;
2305
+ return resolved && {
2306
+ targetUri: resolved.doc.id,
2307
+ doc: resolved.doc,
2308
+ prop: resolved.prop
2309
+ };
2310
+ }
2311
+ /**
2312
+ * Get fields available for a type (resolving extends/intersections).
2313
+ * With `chain`, returns the fields of the nested object that field path leads to.
2314
+ */ function getFieldsForType(doc, typeName, chain = []) {
2315
+ const unwound = doc.unwindType(typeName, chain);
2316
+ if (!unwound?.def) return [];
2317
+ let def = unwound.doc.mergeIntersection(unwound.def);
2318
+ if (isInterface(def)) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
2319
+ if (isStructure(def) || isInterface(def)) return Array.from(def.props.values());
2320
+ return [];
2321
+ }
2322
+ /**
2323
+ * Completion scope of a field-path `string` argument (spec declares `fieldScope`) at the
2324
+ * cursor column `character`: the fields of the level being typed — `'address.ci'` offers
2325
+ * the fields of `address` (`chain` = `['address']`).
2326
+ */ function getFieldPathCompletionScope(argToken, doc, character) {
2327
+ const typeName = getFieldPathTarget(argToken, doc);
2328
+ if (!typeName) return;
2329
+ const chain = fieldPathSegmentAt(argToken, character).path.split(".").slice(0, -1);
2330
+ return {
2331
+ typeName,
2332
+ chain,
2333
+ fields: getFieldsForType(doc, typeName, chain)
2334
+ };
2335
+ }
2336
+ /**
2337
+ * Get completion scope data for a query context.
2338
+ */ function getQueryCompletionScope(queryArgToken, doc) {
2339
+ const scope = getQueryScope(queryArgToken, doc);
2340
+ if (!scope) return;
2341
+ return {
2342
+ typeNames: scope.allowedTypes,
2343
+ unqualifiedTarget: scope.unqualifiedTarget,
2344
+ getFields: (typeName) => getFieldsForType(doc, typeName)
2345
+ };
2346
+ }
2347
+ const KEYWORD_OPS = new Set([
2348
+ "in",
2349
+ "matches",
2350
+ "exists"
2351
+ ]);
2352
+ const LOGICAL_KEYWORDS = new Set([
2353
+ "and",
2354
+ "or",
2355
+ "not"
2356
+ ]);
2357
+ /**
2358
+ * Analyze text inside backticks up to cursor position
2359
+ * to determine what kind of completions to offer.
2360
+ * Uses lightweight text scanning, not full AST parsing,
2361
+ * so it works on incomplete/mid-typing input.
2362
+ *
2363
+ * `mode` selects the grammar of the argument (default `query`).
2364
+ */ function analyzeQueryCursorContext(textBeforeCursor, mode = "query") {
2365
+ const trimmed = textBeforeCursor.trimEnd();
2366
+ const hasTrailingSpace = textBeforeCursor.length > trimmed.length;
2367
+ if (trimmed.length === 0) return { type: "field-start" };
2368
+ if (trimmed.endsWith(".")) {
2369
+ const before = trimmed.slice(0, -1).trimEnd();
2370
+ const match = /(\w+)$/u.exec(before);
2371
+ if (match) return {
2372
+ type: "after-dot",
2373
+ typeName: match[1]
2374
+ };
2375
+ return { type: "field-start" };
2376
+ }
2377
+ if (mode !== "query") return analyzeArgCursorContext(trimmed, hasTrailingSpace, mode);
2378
+ const tokens = tokenizeQueryText(trimmed);
2379
+ if (tokens.length === 0) return { type: "field-start" };
2380
+ const last = tokens[tokens.length - 1];
2381
+ if (LOGICAL_KEYWORDS.has(last) || last === "(") return { type: "field-start" };
2382
+ if (SYMBOLIC_OPS.has(last)) return { type: "after-operator" };
2383
+ if (last === "in" || last === "matches") return { type: "after-operator" };
2384
+ if (last === "exists") return { type: "after-comparison" };
2385
+ if (VALUE_KEYWORDS.has(last)) return { type: "after-comparison" };
2386
+ if (/^['"]/.test(last) || /^\d/.test(last)) return { type: "after-comparison" };
2387
+ if (tokens.length >= 2) {
2388
+ const prev = tokens[tokens.length - 2];
2389
+ if (SYMBOLIC_OPS.has(prev) || KEYWORD_OPS.has(prev)) return { type: "after-comparison" };
2390
+ }
2391
+ if (/^\w+$/u.test(last)) {
2392
+ if (!hasTrailingSpace) return { type: "field-start" };
2393
+ return { type: "after-field" };
2394
+ }
2395
+ return { type: "field-start" };
2396
+ }
2397
+ const ARITHMETIC_OPS = new Set(BACKTICK_ARG_VOCABULARY.arithmeticOps);
2398
+ /** An order key (an identifier other than `asc` / `desc`). */ function isOrderKey(token) {
2399
+ return token !== void 0 && /^\w+$/u.test(token) && !ORDER_DIRECTIONS.has(token);
2400
+ }
2401
+ /**
2402
+ * Cursor context inside an `expr` or `order` argument — `trimmed` is the
2403
+ * non-empty text before the cursor that does not end with `.`.
2404
+ */ function analyzeArgCursorContext(trimmed, hasTrailingSpace, mode) {
2405
+ const tokens = tokenizeQueryText(trimmed, true);
2406
+ const last = tokens[tokens.length - 1];
2407
+ if (last === void 0 || last === "," || last === "(" || ARITHMETIC_OPS.has(last)) return { type: "field-start" };
2408
+ if (mode === "order") {
2409
+ if (!/^\w+$/u.test(last)) return { type: "after-order-direction" };
2410
+ if (!hasTrailingSpace) return isOrderKey(tokens[tokens.length - 2]) ? { type: "after-order-key" } : { type: "field-start" };
2411
+ return isOrderKey(last) ? { type: "after-order-key" } : { type: "after-order-direction" };
2412
+ }
2413
+ if (/^[a-z_$]\w*$/iu.test(last) && !hasTrailingSpace) return { type: "field-start" };
2414
+ return { type: "after-operand" };
2415
+ }
2416
+ /**
2417
+ * Simple tokenizer for query text — splits into identifiers, operators, and punctuation.
2418
+ * Does NOT need to handle all edge cases; just enough for cursor context analysis.
2419
+ * With `arithmetic`, `+ - * /` are tokens too (otherwise they are skipped).
2420
+ */ function tokenizeQueryText(text, arithmetic = false) {
2421
+ const tokens = [];
2422
+ let i = 0;
2423
+ while (i < text.length) {
2424
+ if (/\s/.test(text[i])) {
2425
+ i++;
2426
+ continue;
2427
+ }
2428
+ if (text[i] === "'" || text[i] === "\"") {
2429
+ const quote = text[i];
2430
+ let j = i + 1;
2431
+ while (j < text.length && text[j] !== quote) {
2432
+ if (text[j] === "\\") j++;
2433
+ j++;
2434
+ }
2435
+ tokens.push(text.slice(i, j + 1));
2436
+ i = j + 1;
2437
+ continue;
2438
+ }
2439
+ if (i + 1 < text.length) {
2440
+ const two = text.slice(i, i + 2);
2441
+ if (two === "!=" || two === ">=" || two === "<=") {
2442
+ tokens.push(two);
2443
+ i += 2;
2444
+ continue;
2445
+ }
2446
+ }
2447
+ if ("=><(),".includes(text[i]) || arithmetic && ARITHMETIC_OPS.has(text[i])) {
2448
+ tokens.push(text[i]);
2449
+ i++;
2450
+ continue;
2451
+ }
2452
+ if (text[i] === ".") {
2453
+ tokens.push(".");
2454
+ i++;
2455
+ continue;
2456
+ }
2457
+ if (/[\w]/u.test(text[i])) {
2458
+ let j = i;
2459
+ while (j < text.length && /[\w]/u.test(text[j])) j++;
2460
+ tokens.push(text.slice(i, j));
2461
+ i = j;
2462
+ continue;
2463
+ }
2464
+ i++;
2465
+ }
2466
+ return tokens;
2467
+ }
2468
+
2469
+ //#endregion
2470
+ //#region packages/core/src/parser/id-registry.ts
2471
+ function _define_property$6(obj, key, value) {
2472
+ if (key in obj) Object.defineProperty(obj, key, {
2473
+ value,
2474
+ enumerable: true,
2475
+ configurable: true,
2476
+ writable: true
2477
+ });
2478
+ else obj[key] = value;
2479
+ return obj;
2480
+ }
2481
+ var IdRegistry = class {
2482
+ clear() {
2483
+ this.definitions.clear();
2484
+ this.duplicates.clear();
2485
+ this.forbidden.clear();
2486
+ }
2487
+ registerDefinition(token) {
2488
+ if (!token) return;
2489
+ if (this.reserved.has(token.text)) this.forbidden.add(token);
2490
+ else if (this.definitions.has(token.text)) this.duplicates.add(token);
2491
+ else this.definitions.set(token.text, token);
2492
+ }
2493
+ isDefined(t) {
2494
+ const text = typeof t === "string" ? t : t.text;
2495
+ return this.definitions.has(text) || this.globalTypes.has(text);
2496
+ }
2497
+ getErrors() {
2498
+ return [...Array.from(this.duplicates, (t) => ({
2499
+ severity: 1,
2500
+ message: `Duplicate identifier "${t.text}"`,
2501
+ range: t.range
2502
+ })), ...Array.from(this.forbidden, (t) => ({
2503
+ severity: 1,
2504
+ message: `Reserved keyword "${t.text}"`,
2505
+ range: t.range
2506
+ }))];
2507
+ }
2508
+ constructor(globalTypes = []) {
2509
+ _define_property$6(this, "reserved", void 0);
2510
+ _define_property$6(this, "globalTypes", void 0);
2511
+ _define_property$6(this, "definitions", /* @__PURE__ */ new Map());
2512
+ _define_property$6(this, "duplicates", /* @__PURE__ */ new Set());
2513
+ _define_property$6(this, "forbidden", /* @__PURE__ */ new Set());
2514
+ this.reserved = new Set([
2515
+ "interface",
2516
+ "type",
2517
+ "import",
2518
+ "from",
2519
+ "export",
2520
+ "annotate",
2521
+ "as"
2522
+ ].concat(globalTypes));
2523
+ this.globalTypes = new Set(globalTypes);
2524
+ }
2525
+ };
2526
+
2527
+ //#endregion
2528
+ //#region packages/core/src/tokenizer/tokens/a-identifier.token.ts
2529
+ /**
2530
+ * Annotation (@) Identifier node
2531
+ */ const AIdentifierToken = new Node({
2532
+ name: "annotation",
2533
+ start: { token: RegExp("@[\\p{ID_Continue}$.]*", "u") },
2534
+ end: {
2535
+ token: RegExp("[^\\p{ID_Continue}$.]", "u"),
2536
+ eject: true
2537
+ },
2538
+ eofClose: true,
2539
+ data: {
2540
+ type: "annotation",
2541
+ text: ""
2542
+ },
2543
+ mapContent: "text"
2544
+ });
2545
+
2546
+ //#endregion
2547
+ //#region packages/core/src/tokenizer/tokens/block.token.ts
2548
+ /**
2549
+ * Builds a block node that opens on any key of `pairs` and closes on the
2550
+ * matching value; the opening character is kept as the token's `text`.
2551
+ */ function createBlockToken(pairs) {
2552
+ const opening = Object.keys(pairs).map((c) => c.replace(/[\\^$.*+?()[\]{}|/-]/gu, "\\$&")).join("");
2553
+ return new Node({
2554
+ name: "block",
2555
+ start: {
2556
+ token: new RegExp(`(?<text>[${opening}])`, "u"),
2557
+ omit: true
2558
+ },
2559
+ end: {
2560
+ token: (ctx) => pairs[ctx.node.data.text] || "",
2561
+ omit: true
2562
+ },
2563
+ skip: /\s/u,
2564
+ eofClose: true,
2565
+ data: {
2566
+ type: "block",
2567
+ text: ""
2568
+ }
2569
+ });
2570
+ }
2571
+ /**
2572
+ * Block node
2573
+ */ const BlockToken = createBlockToken({
2574
+ "{": "}",
2575
+ "(": ")",
2576
+ "[": "]"
2577
+ });
2578
+
2579
+ //#endregion
2580
+ //#region packages/core/src/tokenizer/tokens/comment.token.ts
2581
+ const inline = new Node({
2582
+ name: "inline-comment",
2583
+ start: {
2584
+ token: "//",
2585
+ omit: true
2586
+ },
2587
+ end: {
2588
+ token: /$/mu,
2589
+ omit: true
2590
+ },
2591
+ eofClose: true,
2592
+ data: {
2593
+ type: "comment",
2594
+ text: ""
2595
+ },
2596
+ mapContent: "text"
2597
+ });
2598
+ const block$1 = new Node({
2599
+ name: "block-comment",
2600
+ start: {
2601
+ token: "/*",
2602
+ omit: true
2603
+ },
2604
+ end: {
2605
+ token: "*/",
2606
+ omit: true
2607
+ },
2608
+ eofClose: true,
2609
+ data: {
2610
+ type: "comment",
2611
+ text: ""
2612
+ },
2613
+ mapContent: "text"
2614
+ });
2615
+ /**
2616
+ * Block and inline comments
2617
+ */ const commentNodes = {
2618
+ inline,
2619
+ block: block$1,
2620
+ all: [inline, block$1]
2621
+ };
2622
+
2623
+ //#endregion
2624
+ //#region packages/core/src/tokenizer/tokens/identifier.token.ts
2625
+ /**
2626
+ * Identifier node
2627
+ */ const IdentifierToken = new Node({
2628
+ name: "identifier",
2629
+ start: { token: RegExp("[\\p{ID_Start}$_][\\p{ID_Continue}$]*", "u") },
2630
+ end: {
2631
+ token: RegExp("[^\\p{ID_Continue}$]", "u"),
2632
+ eject: true
2633
+ },
2634
+ eofClose: true,
2635
+ data: {
2636
+ type: "identifier",
2637
+ text: ""
2638
+ },
2639
+ mapContent: "text"
2640
+ });
2641
+
2642
+ //#endregion
2643
+ //#region packages/core/src/tokenizer/tokens/number.token.ts
2644
+ /**
2645
+ * Number node
2646
+ */ const NumberToken = new Node({
2647
+ name: "number",
2648
+ start: { token: /[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?/u },
2649
+ end: {
2650
+ token: /[^\d]/u,
2651
+ eject: true
2652
+ },
2653
+ eofClose: true,
2654
+ data: {
2655
+ type: "number",
2656
+ text: ""
2657
+ },
2658
+ mapContent: "text"
2659
+ });
2660
+
2661
+ //#endregion
2662
+ //#region packages/core/src/tokenizer/tokens/punctuation.token.ts
2663
+ /**
2664
+ * Punctuation node
2665
+ */ const PunctuationToken = new Node({
2666
+ name: "punctuation",
2667
+ start: {
2668
+ token: RegExp("(?<text>[\\n!&+,./:;=?|])", "u"),
2669
+ omit: true
2670
+ },
2671
+ end: {
2672
+ token: "",
2673
+ omit: true
2674
+ },
2675
+ eofClose: true,
2676
+ data: {
2677
+ type: "punctuation",
2678
+ text: ""
2679
+ }
2680
+ });
2681
+
2682
+ //#endregion
2683
+ //#region packages/core/src/tokenizer/tokens/query-arith.token.ts
2684
+ /**
2685
+ * Arithmetic operator token — `*` and `-` inside backtick expressions
2686
+ * (`+` and `/` are already generic punctuation).
2687
+ *
2688
+ * Registered after `NumberToken`, so a sign written adjacent to a number
2689
+ * (`-5`, `+1`) still lexes as a signed number; the expression parser splits a
2690
+ * signed number found in binary-operator position (`a -5` → `a - 5`).
2691
+ * Only recognized inside queries — not in root or generic blocks.
2692
+ */ const QueryArithmeticToken = new Node({
2693
+ name: "punctuation",
2694
+ start: {
2695
+ token: RegExp("(?<text>[*-])", "u"),
2696
+ omit: true
2697
+ },
2698
+ end: {
2699
+ token: "",
2700
+ omit: true
2701
+ },
2702
+ eofClose: true,
2703
+ data: {
2704
+ type: "punctuation",
2705
+ text: ""
2706
+ }
2707
+ });
2708
+
2709
+ //#endregion
2710
+ //#region packages/core/src/tokenizer/tokens/query-block.token.ts
2711
+ /**
2712
+ * Query block node — parenthesized sub-expressions inside backtick queries.
2713
+ *
2714
+ * Same definition as `BlockToken` narrowed to `(`, so it produces the same
2715
+ * token shape (`type: 'block'`, `text: '('`) and every consumer keeps working,
2716
+ * but it recognizes `QueryOperatorToken` inside (see `tokens/index.ts`), which
2717
+ * makes `!=`, `>=`, `<=`, `>`, `<` work within parentheses — the generic block
2718
+ * only knows `PunctuationToken`, whose charset has no `<` / `>`.
2719
+ *
2720
+ * Only registered inside `QueryToken` (and itself, for nested parens) —
2721
+ * the generic `BlockToken` is left untouched so tokenization of `(`/`[`/`{`
2722
+ * outside queries does not change.
2723
+ */ const QueryBlockToken = createBlockToken({ "(": ")" });
2724
+
2725
+ //#endregion
2726
+ //#region packages/core/src/tokenizer/tokens/query-operator.token.ts
2727
+ /**
2728
+ * Query operator token — matches symbolic comparison operators
2729
+ * inside backtick-delimited query expressions.
2730
+ *
2731
+ * Multi-character operators (!=, >=, <=) are matched as single tokens.
2732
+ * Only recognized inside QueryToken — not in root or BlockToken.
2733
+ */ const QueryOperatorToken = new Node({
2734
+ name: "punctuation",
2735
+ start: {
2736
+ token: RegExp("(?<text>!=|>=|<=|[=><])", "u"),
2737
+ omit: true
2738
+ },
2739
+ end: {
2740
+ token: "",
2741
+ omit: true
2742
+ },
2743
+ eofClose: true,
2744
+ data: {
2745
+ type: "punctuation",
2746
+ text: ""
2747
+ }
2748
+ });
2749
+
2750
+ //#endregion
2751
+ //#region packages/core/src/tokenizer/tokens/query.token.ts
2752
+ /**
2753
+ * Query node — backtick-delimited filter expressions
2754
+ * Content inside backticks is tokenized into children.
2755
+ */ const QueryToken = new Node({
2756
+ name: "query",
2757
+ start: {
2758
+ token: /`/u,
2759
+ omit: true
2760
+ },
2761
+ end: {
2762
+ token: /`/u,
2763
+ omit: true
2764
+ },
2765
+ skip: /\s/u,
2766
+ eofClose: true,
2767
+ data: {
2768
+ type: "query",
2769
+ text: ""
2770
+ }
2771
+ });
2772
+
2773
+ //#endregion
2774
+ //#region packages/core/src/tokenizer/tokens/regexp.token.ts
2775
+ const REGEXP_LITERAL_RE = /\/(?![/*])(?:\\.|\[.*?]|[^/\\\n\r[])*\/[dgimsuy]*/;
2776
+ /**
2777
+ * Regexp literal inside a backtick expression: only directly after the
2778
+ * `matches` keyword (the one operator that takes a regexp), so `/` elsewhere
2779
+ * stays the division operator (`a / b / c` is not the regexp `/ b /`).
2780
+ * The lookbehind works because the parser scans the full source from the
2781
+ * current position.
2782
+ */ const QUERY_REGEXP_LITERAL_RE = new RegExp(`(?<=\\bmatches\\s*)${REGEXP_LITERAL_RE.source}`);
2783
+ /** A regexp-literal token node starting at `start`. */ function regExpNode(start) {
2784
+ return new Node({
2785
+ name: "regexp",
2786
+ start: {
2787
+ token: start,
2788
+ omit: true
2789
+ },
2790
+ end: {
2791
+ token: "",
2792
+ omit: true
2793
+ },
2794
+ eofClose: true,
2795
+ data: {
2796
+ type: "regexp",
2797
+ text: ""
2798
+ }
2799
+ }).onOpen((node, match) => {
2800
+ node.data.text = match?.text ?? "";
2801
+ });
2802
+ }
2803
+ /**
2804
+ * RegExp literal – `/pattern/flags`
2805
+ * • Starts with `/` but *not* `//` or `/*`
2806
+ * • Ends with `/` followed by zero-or-more valid flags
2807
+ */ const RegExpToken = regExpNode(REGEXP_LITERAL_RE);
2808
+ /** RegExp literal inside backtick expressions — recognized only after `matches`. */ const QueryRegExpToken = regExpNode(QUERY_REGEXP_LITERAL_RE);
2809
+
2810
+ //#endregion
2811
+ //#region packages/core/src/tokenizer/tokens/text.node.ts
2812
+ /**
2813
+ * Text node single or doublequoted
2814
+ */ const TextToken = new Node({
2815
+ name: "text",
2816
+ start: {
2817
+ token: RegExp("(?<quote>[\"'])", "u"),
2818
+ omit: true
2819
+ },
2820
+ end: {
2821
+ token: (ctx) => new RegExp(`(?<end>${ctx.node.data.quote || ""}|\\n)`),
2822
+ omit: true,
2823
+ backslash: true
2824
+ },
2825
+ eofClose: true,
2826
+ data: {
2827
+ type: "text",
2828
+ quote: "",
2829
+ end: "",
2830
+ text: ""
2831
+ },
2832
+ mapContent: "text"
2833
+ }).onClose((node) => {
2834
+ node.data.multiline = node.data.end === "\n";
2835
+ });
2836
+
2837
+ //#endregion
2838
+ //#region packages/core/src/tokenizer/tokens/index.ts
2839
+ const tokens = {
2840
+ aIdentifier: AIdentifierToken,
2841
+ punctuation: PunctuationToken,
2842
+ comments: commentNodes.all,
2843
+ inlineComment: commentNodes.inline,
2844
+ blockComment: commentNodes.block,
2845
+ block: BlockToken,
2846
+ identifier: IdentifierToken,
2847
+ number: NumberToken,
2848
+ text: TextToken,
2849
+ regexp: RegExpToken,
2850
+ query: QueryToken,
2851
+ queryBlock: QueryBlockToken,
2852
+ root: void 0
2853
+ };
2854
+ const root = new Node({
2855
+ name: "root",
2856
+ skip: /\s/u,
2857
+ eofClose: true,
2858
+ recognizes: [
2859
+ ...commentNodes.all,
2860
+ BlockToken,
2861
+ QueryToken,
2862
+ AIdentifierToken,
2863
+ IdentifierToken,
2864
+ TextToken,
2865
+ NumberToken,
2866
+ PunctuationToken
2867
+ ]
2868
+ });
2869
+ tokens.root = root;
2870
+ BlockToken.recognize(RegExpToken, ...commentNodes.all, BlockToken, QueryToken, AIdentifierToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2871
+ QueryToken.recognize(QueryRegExpToken, QueryOperatorToken, QueryBlockToken, BlockToken, IdentifierToken, TextToken, NumberToken, QueryArithmeticToken, PunctuationToken);
2872
+ QueryBlockToken.recognize(QueryRegExpToken, QueryOperatorToken, QueryBlockToken, IdentifierToken, TextToken, NumberToken, QueryArithmeticToken, PunctuationToken);
2873
+ /** 1-based parser position → 0-based VSCode position, shifted by `offset` characters. */ function toPos(p, offset = 0) {
2874
+ return {
2875
+ line: p.line - 1,
2876
+ character: p.column - 1 + offset
2877
+ };
2878
+ }
2879
+ /**
2880
+ * Recursively extract TLexicalToken[] from a ParsedNode tree.
2881
+ * Replaces the v0.5 mapContent('children', callback) + global loop.
2882
+ *
2883
+ * v0.6 Position has { offset, line, column }.
2884
+ * line is 1-based, column is 1-based.
2885
+ * VSCode expects 0-based line, 0-based character.
2886
+ */ function extractTokens(node) {
2887
+ const content = node.content;
2888
+ return content.map((item, index) => {
2889
+ if (typeof item === "string") {
2890
+ const prev = content[index - 1];
2891
+ const next = content[index + 1];
2892
+ const start = typeof prev === "object" ? prev.end : node.start;
2893
+ const end = typeof next === "object" ? next.start : node.end;
2894
+ return {
2895
+ type: "unknown",
2896
+ text: item,
2897
+ getRange: () => ({
2898
+ start: toPos(start),
2899
+ end: toPos(end)
2900
+ })
2901
+ };
2902
+ }
2903
+ const data = item.data;
2904
+ data.getRange = () => ({
2905
+ start: toPos(item.start, data.startOffset),
2906
+ end: toPos(item.end, data.endOffset)
2907
+ });
2908
+ data.children = extractTokens(item);
2909
+ return data;
2910
+ });
2911
+ }
2912
+
2913
+ //#endregion
2914
+ //#region packages/core/src/tokenizer/index.ts
2915
+ function tokenize(source, debug = false) {
2916
+ const result = root.parse(source);
2917
+ if (debug) console.log(printTree(result));
2918
+ return extractTokens(result);
2919
+ }
2920
+
2921
+ //#endregion
2922
+ //#region packages/core/src/parser/pipes/tokens.pipe.ts
2923
+ const identifier = (...text) => $token("identifier", text.length > 0 ? text : void 0);
2924
+ const text = (...text) => $token("text", text.length > 0 ? text : void 0);
2925
+ const block = (...text) => $token("block", text.length > 0 ? text.map((v) => v[0]) : void 0);
2926
+ const pun = (...text) => $token("punctuation", text.length > 0 ? text : void 0);
2927
+ function $token(name, text) {
2928
+ const opts = {
2929
+ optional: false,
2930
+ saveAs: void 0,
2931
+ skip: void 0,
2932
+ expect: [{
2933
+ node: name,
2934
+ text
2935
+ }],
2936
+ contains: void 0,
2937
+ isGlobal: false,
2938
+ empty: false,
2939
+ wrapper: void 0,
2940
+ wrapMultiple: false,
2941
+ debug: false,
2942
+ eob: false,
2943
+ suppressEobError: false,
2944
+ lookBehind: false
2945
+ };
2946
+ return {
2947
+ expect: [{
2948
+ node: name,
2949
+ text
2950
+ }],
2951
+ handler(ni, target) {
2952
+ if (opts.debug) debugger;
2953
+ let firstRun = true;
2954
+ while (firstRun || opts.wrapMultiple) {
2955
+ firstRun = false;
2956
+ if (!ni.$) {
2957
+ const ok = opts.eob || opts.optional;
2958
+ if (!ok && !opts.suppressEobError) ni.unexpectedEOB();
2959
+ return ok;
2960
+ }
2961
+ let matched = ni.satisfies(...opts.expect);
2962
+ if (!matched && opts.lookBehind) {
2963
+ matched = ni.fork().move(-1).satisfies(...opts.expect);
2964
+ if (matched) ni.move(-1);
2965
+ }
2966
+ if (matched) {
2967
+ if (opts.empty && ni.$.children?.length) {
2968
+ ni.unexpected(false, `Expected empty block`);
2969
+ return opts.optional;
2970
+ }
2971
+ if (opts.contains) {
2972
+ if (!ni.$.children?.length) {
2973
+ ni.unexpected(false, `Expected ${opts.contains.map((v) => v.text).join(", ")}`);
2974
+ return opts.optional;
2975
+ }
2976
+ if (ni.$.children[0].type !== opts.contains[0].node || ni.$.children[0].text !== opts.contains[0].text) {
2977
+ ni.unexpected(false, `Expected ${opts.contains.map((v) => v.text).join(", ")}`);
2978
+ return opts.optional;
2979
+ }
2980
+ }
2981
+ if (opts.saveAs) target.node.saveToken(new Token(ni.$), opts.saveAs);
2982
+ ni.accepted();
2983
+ if (opts.wrapper) {
2984
+ const wrapped = target.node;
2985
+ target.node = opts.wrapper().wrap(wrapped, new Token(ni.$));
2986
+ }
2718
2987
  ni.move();
2988
+ if (opts.skip) ni.skip(opts.skip);
2989
+ if (opts.wrapMultiple) continue;
2990
+ else return true;
2719
2991
  } else {
2720
- pushError(ni, "Expected identifier after \".\"");
2721
- break;
2992
+ if (!opts.optional) ni.unexpected();
2993
+ return opts.optional;
2722
2994
  }
2723
2995
  }
2724
- const node = new SemanticQueryFieldRefNode();
2725
- node.typeRef = firstToken;
2726
- node.fieldRef = fieldText === secondToken.text ? secondToken : secondToken.clone({ text: fieldText });
2727
- return node;
2996
+ return true;
2997
+ },
2998
+ saveAs(v) {
2999
+ opts.saveAs = v;
3000
+ return this;
3001
+ },
3002
+ wrap(sn, multiple = false) {
3003
+ opts.wrapper = sn;
3004
+ opts.wrapMultiple = multiple;
3005
+ return this;
3006
+ },
3007
+ optional() {
3008
+ opts.optional = true;
3009
+ return this;
3010
+ },
3011
+ empty() {
3012
+ opts.empty = true;
3013
+ return this;
3014
+ },
3015
+ contains(t) {
3016
+ opts.contains = t.expect;
3017
+ return this;
3018
+ },
3019
+ skip(...p) {
3020
+ opts.skip = p;
3021
+ return this;
3022
+ },
3023
+ or(t) {
3024
+ opts.expect.push(...t.expect);
3025
+ return this;
3026
+ },
3027
+ orEob() {
3028
+ opts.eob = true;
3029
+ return this;
3030
+ },
3031
+ suppressEobError() {
3032
+ opts.suppressEobError = true;
3033
+ return this;
3034
+ },
3035
+ global() {
3036
+ opts.isGlobal = true;
3037
+ return this;
3038
+ },
3039
+ lookBehind() {
3040
+ opts.lookBehind = true;
3041
+ return this;
3042
+ },
3043
+ debug() {
3044
+ opts.debug = true;
3045
+ return this;
2728
3046
  }
2729
- pushError(ni, "Expected identifier after \".\"");
2730
- const node = new SemanticQueryFieldRefNode();
2731
- node.fieldRef = firstToken;
2732
- return node;
2733
- }
2734
- const node = new SemanticQueryFieldRefNode();
2735
- node.fieldRef = firstToken;
2736
- return node;
2737
- }
2738
- function parseValueOrFieldRef(ni) {
2739
- if (!ni.$) return;
2740
- if (ni.$.type === "text" || ni.$.type === "number" || ni.$.type === "regexp") return parseValue(ni);
2741
- if (ni.$.type === "identifier") {
2742
- if (VALUE_KEYWORDS.has(ni.$.text)) return parseValue(ni);
2743
- return parseFieldRef(ni);
2744
- }
2745
- pushError(ni, "Expected value or field reference");
3047
+ };
2746
3048
  }
2747
- function parseValue(ni) {
2748
- if (!ni.$) {
2749
- pushError(ni, "Expected value");
2750
- return;
2751
- }
2752
- const token = ni.$;
2753
- if (token.type === "text" || token.type === "number" || token.type === "regexp" || token.type === "identifier" && VALUE_KEYWORDS.has(token.text)) {
2754
- const node = new SemanticQueryValueNode();
2755
- node.valueToken = new Token(token);
2756
- ni.move();
2757
- return node;
2758
- }
2759
- pushError(ni, `Unexpected token "${token.text}" where value expected`);
3049
+
3050
+ //#endregion
3051
+ //#region packages/core/src/parser/pipes/core.pipe.ts
3052
+ function $pipe(entity, pipe = []) {
3053
+ pipe.forEach((p, i) => Object.assign(p, { toString: () => `${entity}.${i}` }));
3054
+ return {
3055
+ targetFactory: () => {
3056
+ switch (entity) {
3057
+ case "interface": return new $n.SemanticInterfaceNode();
3058
+ case "array": return new $n.SemanticArrayNode();
3059
+ case "const": return new $n.SemanticConstNode();
3060
+ case "group": return new $n.SemanticGroup();
3061
+ case "prop": return new $n.SemanticPropNode();
3062
+ case "type": return new $n.SemanticTypeNode();
3063
+ case "ref": return new $n.SemanticRefNode();
3064
+ case "structure": return new $n.SemanticStructureNode();
3065
+ case "tuple": return new $n.SemanticTupleNode();
3066
+ case "import": return new $n.SemanticImportNode();
3067
+ case "annotate": return new $n.SemanticAnnotateNode();
3068
+ case "primitive": throw new Error("Can't create pipe for primitive node");
3069
+ default: throw new Error(`Can't create pipe for ${entity} node`);
3070
+ }
3071
+ },
3072
+ pipe,
3073
+ toString: () => entity,
3074
+ skipTokens: [],
3075
+ stopCondition: void 0,
3076
+ skip(...s) {
3077
+ this.skipTokens.push(...s);
3078
+ return this;
3079
+ },
3080
+ stop(sc) {
3081
+ this.stopCondition = sc;
3082
+ return this;
3083
+ },
3084
+ t(node, skip = []) {
3085
+ this.pipe.push($token(node).saveAs("identifier").skip(...skip));
3086
+ return this;
3087
+ }
3088
+ };
2760
3089
  }
2761
- function parseValueList(ni) {
2762
- if (ni.$?.type === "block" && ni.$.text === "(") {
2763
- const subNi = ni.fork(ni.$.children || []);
2764
- ni.move();
2765
- if (!subNi.$) {
2766
- pushError(subNi, "Empty value list in \"in\" expression");
2767
- return;
3090
+ function runPipes(pipes, ni, singlePass = false) {
3091
+ const nodes = [];
3092
+ while (ni.$) {
3093
+ let matched = true;
3094
+ let depth = ni.index;
3095
+ for (const { targetFactory, pipe, skipTokens: skip, stopCondition } of pipes) {
3096
+ const target = { node: targetFactory() };
3097
+ const fork = ni.fork();
3098
+ fork.skip(skip);
3099
+ if (!fork.$) {
3100
+ ni.unfork(fork);
3101
+ break;
3102
+ }
3103
+ matched = true;
3104
+ for (const { handler } of pipe) if (!handler(fork, target)) {
3105
+ matched = false;
3106
+ break;
3107
+ }
3108
+ if (fork.index > depth) depth = fork.index;
3109
+ if (matched) {
3110
+ nodes.push(target.node);
3111
+ ni.unfork(fork);
3112
+ if (stopCondition && stopCondition(fork)) return nodes;
3113
+ ni.move(-1);
3114
+ break;
3115
+ }
2768
3116
  }
2769
- const values = [];
2770
- const first = parseValue(subNi);
2771
- if (first) values.push(first);
2772
- while (subNi.$?.type === "punctuation" && subNi.$.text === ",") {
2773
- subNi.move();
2774
- const v = parseValue(subNi);
2775
- if (v) values.push(v);
3117
+ if (singlePass) return nodes;
3118
+ if (!matched) {
3119
+ ni.shouldHaveError(depth);
3120
+ ni.move(depth - ni.index);
3121
+ }
3122
+ ni.move();
3123
+ if (matched) {} else {
3124
+ ni.confirmIssues();
3125
+ ni.skipUntil([";", "\n"]);
2776
3126
  }
2777
- if (subNi.$) pushError(subNi, `Unexpected token in value list: "${subNi.$.text}"`);
2778
- const node = new SemanticQueryValueListNode();
2779
- node.values = values;
2780
- return node;
2781
3127
  }
2782
- pushError(ni, "Expected parenthesized value list after \"in\"");
3128
+ return nodes;
2783
3129
  }
2784
- /**
2785
- * Range to blame for a diagnostic: the current token, else the enclosing
2786
- * query token / "(...)" block the iterator was forked from.
2787
- */ function rangeOf(ni) {
2788
- return ni.$?.getRange?.() ?? ni.parent?.getRange?.() ?? ZERO_RANGE;
3130
+ function runPipesOnce(pipes, ni) {
3131
+ return runPipes(pipes, ni, true)[0];
2789
3132
  }
2790
- function pushError(ni, message) {
2791
- ni.messages.push({
2792
- severity: 1,
2793
- message,
2794
- range: rangeOf(ni)
2795
- });
3133
+
3134
+ //#endregion
3135
+ //#region packages/core/src/parser/grouping.ts
3136
+ function groupByPriority(nodes, priority) {
3137
+ if (nodes.length === 1) return nodes[0];
3138
+ if (nodes.length === 0) return;
3139
+ if (nodes.length % 2 === 0) throw new Error(`Invalid number of nodes ${nodes.length}. Odd number expected`);
3140
+ let currentPass = nodes;
3141
+ let temporaryResult = [];
3142
+ let groupped = [];
3143
+ for (const p of priority) {
3144
+ for (const [i, node] of currentPass.entries()) {
3145
+ const isOperator = i % 2 === 1;
3146
+ if (!isOperator && node instanceof Token) throw new Error(`Unexpected token ${node.toString()} at ${i}`);
3147
+ else if (isOperator && !(node instanceof Token)) throw new Error(`Unexpected token ${isGroup(node) ? node.op : node.token.toString()} at ${i}`);
3148
+ if (isOperator) {
3149
+ if (node.text !== p) temporaryResult.push(node);
3150
+ continue;
3151
+ }
3152
+ const prev = currentPass[i - 1]?.text;
3153
+ const next = currentPass[i + 1]?.text;
3154
+ if (prev !== p && next !== p) {
3155
+ temporaryResult.push(node);
3156
+ continue;
3157
+ }
3158
+ if (prev === p || next === p) {
3159
+ groupped.push(node);
3160
+ if (next !== p) {
3161
+ temporaryResult.push(new $n.SemanticGroup(groupped, p));
3162
+ groupped = [];
3163
+ }
3164
+ }
3165
+ }
3166
+ currentPass = temporaryResult;
3167
+ temporaryResult = [];
3168
+ }
3169
+ const output = currentPass[0];
3170
+ return output.length === 1 ? output.first : output;
2796
3171
  }
2797
3172
 
2798
3173
  //#endregion
@@ -2914,10 +3289,6 @@ function annotations() {
2914
3289
  }
2915
3290
  while (ni.satisfies(...opts.argument)) {
2916
3291
  let argToken = new Token(ni.$);
2917
- if (argToken.type === "query") {
2918
- const queryNode = parseQueryExpression(ni.fork(argToken.children), argToken);
2919
- if (queryNode) argToken.queryNode = queryNode;
2920
- }
2921
3292
  ni.accepted();
2922
3293
  ni.move();
2923
3294
  if (argToken.type === "identifier" && ![
@@ -3498,7 +3869,8 @@ var AtscriptDoc = class {
3498
3869
  update(text, debug = false) {
3499
3870
  this._text = text;
3500
3871
  this.cleanup();
3501
- const ni = new NodeIterator(tokenize(text, debug), []).move();
3872
+ const rawTokens = tokenize(text, debug);
3873
+ const ni = new NodeIterator(rawTokens, []).move();
3502
3874
  this.nodes = runPipes([
3503
3875
  pipes.importPipe,
3504
3876
  pipes.type,
@@ -3508,6 +3880,43 @@ var AtscriptDoc = class {
3508
3880
  if (debug) console.log(this.nodes.map((n) => n.toString()).join("\n"));
3509
3881
  this.semanticMessages = ni.getErrors();
3510
3882
  this.registerNodes(this.nodes);
3883
+ this.parseUnregisteredBacktickArgs(rawTokens);
3884
+ }
3885
+ /**
3886
+ * Backtick arguments of annotations that never get registered (dangling at
3887
+ * EOF, or followed by a syntax error) are still parsed for diagnostics — by
3888
+ * the argument spec of the preceding annotation when it resolves, else as a
3889
+ * query predicate.
3890
+ */ parseUnregisteredBacktickArgs(tokens) {
3891
+ for (let i = 0; i < tokens.length; i++) {
3892
+ const t = tokens[i];
3893
+ if (t.type === "block" && t.children) {
3894
+ this.parseUnregisteredBacktickArgs(t.children);
3895
+ continue;
3896
+ }
3897
+ if (t.type !== "query" || this.parsedBacktickArgs.has(t)) continue;
3898
+ let argIndex = 0;
3899
+ let annotation;
3900
+ for (let j = i - 1; j >= 0; j--) {
3901
+ const p = tokens[j];
3902
+ if (p.type === "annotation") {
3903
+ annotation = p;
3904
+ break;
3905
+ }
3906
+ if (p.type === "block" || p.type === "punctuation" && (p.text === "\n" || p.text === ";")) break;
3907
+ if (p.type === "punctuation" && p.text === ",") argIndex++;
3908
+ }
3909
+ if (!annotation) continue;
3910
+ this.parseBacktickArgAs(new Token(t), this.resolveAnnotation(annotation.text.slice(1))?.arguments[argIndex]?.type);
3911
+ }
3912
+ }
3913
+ /**
3914
+ * Parse a backtick argument by its spec type: `expr` / `order` get their own
3915
+ * grammar; anything else (unknown annotation, position beyond the spec) parses
3916
+ * as a query predicate.
3917
+ */ parseBacktickArgAs(arg, specType) {
3918
+ this.parsedBacktickArgs.add(arg.lexicalToken);
3919
+ this.registerMessages(parseBacktickArg(arg, isBacktickArgType(specType) ? specType : "query"));
3511
3920
  }
3512
3921
  cleanup() {
3513
3922
  this.exports.clear();
@@ -3525,6 +3934,7 @@ var AtscriptDoc = class {
3525
3934
  this.blocksIndex = new BlocksIndex();
3526
3935
  this.resolvedAnnotations = [];
3527
3936
  this.annotations = [];
3937
+ this.parsedBacktickArgs = /* @__PURE__ */ new WeakSet();
3528
3938
  }
3529
3939
  registerNodes(nodes) {
3530
3940
  for (const node of nodes) {
@@ -3543,11 +3953,14 @@ var AtscriptDoc = class {
3543
3953
  this.tokensIndex.add(mainToken);
3544
3954
  args?.forEach((a) => this.tokensIndex.add(a));
3545
3955
  const annotationSpec = this.resolveAnnotation(mainToken.text.slice(1));
3956
+ const specArgs = annotationSpec?.arguments ?? [];
3957
+ args?.forEach((a, i) => {
3958
+ if (a.type === "query") this.parseBacktickArgAs(a, specArgs[i]?.type);
3959
+ });
3546
3960
  if (annotationSpec) {
3547
3961
  this.registerMessages(annotationSpec.validate(mainToken, args || [], this));
3548
3962
  annotationSpec.modify(mainToken, args || [], this);
3549
3963
  this.resolvedAnnotations.push(mainToken);
3550
- const specArgs = annotationSpec.arguments;
3551
3964
  for (let i = 0; i < (args?.length ?? 0); i++) {
3552
3965
  const argSpec = specArgs[i];
3553
3966
  if (argSpec?.type === "ref" && args?.[i]) {
@@ -3562,7 +3975,7 @@ var AtscriptDoc = class {
3562
3975
  this.referred.push(refToken);
3563
3976
  }
3564
3977
  }
3565
- if (argSpec?.type === "query" && args?.[i]?.queryNode) args[i].queryNode.registerAtDocument(this);
3978
+ if (isBacktickArgType(argSpec?.type)) args?.[i]?.backtickNode?.registerAtDocument(this);
3566
3979
  if (argSpec?.type === "string" && argSpec.fieldScope && args?.[i]) this.fieldPathArgs.push(args[i]);
3567
3980
  }
3568
3981
  } else {
@@ -4488,6 +4901,7 @@ var AtscriptDoc = class {
4488
4901
  _define_property$3(this, "nodes", void 0);
4489
4902
  _define_property$3(this, "_text", void 0);
4490
4903
  _define_property$3(this, "_annotateNodesByTarget", void 0);
4904
+ /** Lexical backtick tokens already parsed by `registerAnnotation`. */ _define_property$3(this, "parsedBacktickArgs", void 0);
4491
4905
  _define_property$3(this, "resolvedAnnotations", void 0);
4492
4906
  _define_property$3(this, "annotations", void 0);
4493
4907
  _define_property$3(this, "_nextTypeId", void 0);
@@ -4512,6 +4926,7 @@ var AtscriptDoc = class {
4512
4926
  this._annotationSpecCache = /* @__PURE__ */ new Map();
4513
4927
  this.nodes = [];
4514
4928
  this._text = "";
4929
+ this.parsedBacktickArgs = /* @__PURE__ */ new WeakSet();
4515
4930
  this.resolvedAnnotations = [];
4516
4931
  this.annotations = [];
4517
4932
  this._nextTypeId = 0;
@@ -5236,7 +5651,9 @@ var AtscriptRepo = class {
5236
5651
  async getUsedAnnotations() {
5237
5652
  const ANNOTATION_TYPE_MAP = {
5238
5653
  ref: "import(\"@atscript/typescript/utils\").AtscriptRef",
5239
- query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode"
5654
+ query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode",
5655
+ expr: "import(\"@atscript/typescript/utils\").AtscriptExprNode",
5656
+ order: "import(\"@atscript/typescript/utils\").AtscriptOrderItem[]"
5240
5657
  };
5241
5658
  const mapArgType = (t) => ANNOTATION_TYPE_MAP[t] || t;
5242
5659
  const manager = await this.getSharedPluginManager();
@@ -5896,4 +6313,4 @@ function walkArrayElement(doc, arrayNode, prefix, parentOptional, flatMap, stack
5896
6313
  }
5897
6314
 
5898
6315
  //#endregion
5899
- export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticQueryComparisonNode, SemanticQueryFieldRefNode, SemanticQueryLogicalNode, SemanticQueryNode, SemanticQueryValueListNode, SemanticQueryValueNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, analyzeQueryCursorContext, build, clearResolveBareCache, createAtscriptPlugin, defineConfig, fileUriToPath, flattenInterfaceNode, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, parseBareSpecifier, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveQueryFieldRef };
6316
+ export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BACKTICK_ARG_VOCABULARY, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticExprBinaryNode, SemanticExprCallNode, SemanticExprNode, SemanticExprNumberNode, SemanticExprUnaryNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticOrderNode, SemanticPrimitiveNode, SemanticPropNode, SemanticQueryComparisonNode, SemanticQueryFieldRefNode, SemanticQueryLogicalNode, SemanticQueryNode, SemanticQueryValueListNode, SemanticQueryValueNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, analyzeQueryCursorContext, build, clearResolveBareCache, createAtscriptPlugin, defineConfig, fileUriToPath, flattenInterfaceNode, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isBacktickArgType, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, parseBareSpecifier, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveQueryFieldRef };