@atscript/core 0.1.98 → 0.1.100

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -400,6 +400,9 @@ var Token = class Token {
400
400
  ...replace
401
401
  });
402
402
  }
403
+ /** The underlying lexical token (for re-iterating its children). */ get lexicalToken() {
404
+ return this._data;
405
+ }
403
406
  get text() {
404
407
  return this._data.text || "";
405
408
  }
@@ -423,6 +426,9 @@ var Token = class Token {
423
426
  get isAnnotation() {
424
427
  return this._data.type === "annotation";
425
428
  }
429
+ /** The parsed tree of a backtick argument — whichever of the three it was parsed as. */ get backtickNode() {
430
+ return this.queryNode ?? this.exprNode ?? this.orderNode;
431
+ }
426
432
  constructor(_data) {
427
433
  _define_property$13(this, "_data", void 0);
428
434
  /**
@@ -457,6 +463,12 @@ var Token = class Token {
457
463
  /**
458
464
  * Parsed query expression tree (for query-type annotation arguments)
459
465
  */ _define_property$13(this, "queryNode", void 0);
466
+ /**
467
+ * Parsed arithmetic expression (for expr-type annotation arguments)
468
+ */ _define_property$13(this, "exprNode", void 0);
469
+ /**
470
+ * Parsed ordering (for order-type annotation arguments)
471
+ */ _define_property$13(this, "orderNode", void 0);
460
472
  this._data = _data;
461
473
  }
462
474
  };
@@ -815,15 +827,20 @@ function _define_property$9(obj, key, value) {
815
827
  }
816
828
  var SemanticQueryNode = class extends SemanticNode {
817
829
  registerAtDocument(doc) {
818
- this.propagateQueryArgToken(this.expression);
830
+ for (const ref of this.fieldRefs()) ref.queryArgToken = this.sourceToken;
819
831
  this.expression.registerAtDocument(doc);
820
832
  }
821
- propagateQueryArgToken(expr) {
822
- if ("left" in expr) {
823
- expr.left.queryArgToken = this.sourceToken;
824
- const right = expr.right;
825
- if (right && "fieldRef" in right) right.queryArgToken = this.sourceToken;
826
- } else if ("operands" in expr) for (const operand of expr.operands) this.propagateQueryArgToken(operand);
833
+ /** Every field ref of the predicate (both sides of comparisons), in source order. */ fieldRefs() {
834
+ const refs = [];
835
+ const walk = (expr) => {
836
+ if ("left" in expr) {
837
+ refs.push(expr.left);
838
+ const right = expr.right;
839
+ if (right && "fieldRef" in right) refs.push(right);
840
+ } else if ("operands" in expr) for (const operand of expr.operands) walk(operand);
841
+ };
842
+ walk(this.expression);
843
+ return refs;
827
844
  }
828
845
  constructor() {
829
846
  super("query"), _define_property$9(this, "expression", void 0), _define_property$9(this, "sourceToken", void 0);
@@ -878,6 +895,74 @@ var SemanticQueryValueListNode = class extends SemanticNode {
878
895
  super("query-value-list"), _define_property$9(this, "values", void 0);
879
896
  }
880
897
  };
898
+ /** Set `queryArgToken` on every field-ref leaf and register the leaves at the document. */ function registerFieldRefs(refs, sourceToken, doc) {
899
+ for (const ref of refs) {
900
+ ref.queryArgToken = sourceToken;
901
+ ref.registerAtDocument(doc);
902
+ }
903
+ }
904
+ /** Root of a parsed `expr` argument (closed arithmetic over field refs). */ var SemanticExprNode = class extends SemanticNode {
905
+ /** Every field-ref leaf of the expression, in source order. */ fieldRefs() {
906
+ const refs = [];
907
+ collectExprFieldRefs(this.expression, refs);
908
+ return refs;
909
+ }
910
+ registerAtDocument(doc) {
911
+ registerFieldRefs(this.fieldRefs(), this.sourceToken, doc);
912
+ }
913
+ constructor() {
914
+ super("query-expr"), _define_property$9(this, "expression", void 0), _define_property$9(this, "sourceToken", void 0);
915
+ }
916
+ };
917
+ function collectExprFieldRefs(node, out) {
918
+ switch (node.entity) {
919
+ case "query-field-ref":
920
+ out.push(node);
921
+ break;
922
+ case "query-expr-binary":
923
+ collectExprFieldRefs(node.left, out);
924
+ collectExprFieldRefs(node.right, out);
925
+ break;
926
+ case "query-expr-unary":
927
+ collectExprFieldRefs(node.operand, out);
928
+ break;
929
+ case "query-expr-call":
930
+ for (const arg of node.args) collectExprFieldRefs(arg, out);
931
+ break;
932
+ default:
933
+ }
934
+ }
935
+ var SemanticExprBinaryNode = class extends SemanticNode {
936
+ constructor() {
937
+ 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);
938
+ }
939
+ };
940
+ var SemanticExprUnaryNode = class extends SemanticNode {
941
+ constructor() {
942
+ super("query-expr-unary"), _define_property$9(this, "op", "neg"), _define_property$9(this, "operand", void 0);
943
+ }
944
+ };
945
+ var SemanticExprCallNode = class extends SemanticNode {
946
+ constructor() {
947
+ super("query-expr-call"), _define_property$9(this, "fn", "coalesce"), _define_property$9(this, "args", void 0);
948
+ }
949
+ };
950
+ var SemanticExprNumberNode = class extends SemanticNode {
951
+ constructor() {
952
+ super("query-expr-number"), _define_property$9(this, "valueToken", void 0), _define_property$9(this, "value", void 0);
953
+ }
954
+ };
955
+ /** Root of a parsed `order` argument: `key (asc|desc)?, …`. */ var SemanticOrderNode = class extends SemanticNode {
956
+ /** Every order key, in source order. */ fieldRefs() {
957
+ return this.items.map((i) => i.ref);
958
+ }
959
+ registerAtDocument(doc) {
960
+ registerFieldRefs(this.fieldRefs(), this.sourceToken, doc);
961
+ }
962
+ constructor() {
963
+ super("query-order"), _define_property$9(this, "items", void 0), _define_property$9(this, "sourceToken", void 0);
964
+ }
965
+ };
881
966
 
882
967
  //#endregion
883
968
  //#region packages/core/src/parser/nodes/index.ts
@@ -953,6 +1038,14 @@ function _define_property$8(obj, key, value) {
953
1038
  else obj[key] = value;
954
1039
  return obj;
955
1040
  }
1041
+ /** Whether an annotation argument type is written in backticks (`query`, `expr`, `order`). */ function isBacktickArgType(type) {
1042
+ return type === "query" || type === "expr" || type === "order";
1043
+ }
1044
+ const BACKTICK_TYPE_MESSAGES = {
1045
+ query: "query expression expected (use backticks).",
1046
+ expr: "expression expected (use backticks).",
1047
+ order: "order list expected (use backticks)."
1048
+ };
956
1049
  var AnnotationSpec = class {
957
1050
  get arguments() {
958
1051
  if (!this.config.argument) return [];
@@ -963,7 +1056,7 @@ var AnnotationSpec = class {
963
1056
  return this.arguments.map((arg, index) => {
964
1057
  const placeholderIndex = index + 1;
965
1058
  const defaultValue = this.getDefaultValueForType(arg.name, arg.type);
966
- const quote = arg.type === "string" ? `'` : arg.type === "query" ? "`" : "";
1059
+ const quote = arg.type === "string" ? `'` : isBacktickArgType(arg.type) ? "`" : "";
967
1060
  return `${quote}\${${placeholderIndex}:${defaultValue}}${quote}`;
968
1061
  }).join(", ");
969
1062
  }
@@ -973,7 +1066,9 @@ var AnnotationSpec = class {
973
1066
  case "number": return tokenType === "number" ? void 0 : "number expected.";
974
1067
  case "boolean": return tokenType === "identifier" ? void 0 : "boolean expected.";
975
1068
  case "ref": return tokenType === "identifier" ? void 0 : "type reference expected.";
976
- case "query": return tokenType === "query" ? void 0 : "query expression expected (use backticks).";
1069
+ case "query":
1070
+ case "expr":
1071
+ case "order": return tokenType === "query" ? void 0 : BACKTICK_TYPE_MESSAGES[type];
977
1072
  default: return `unknown type "${type}".`;
978
1073
  }
979
1074
  }
@@ -1095,6 +1190,8 @@ var AnnotationSpec = class {
1095
1190
  case "boolean": return "true";
1096
1191
  case "ref": return "TypeName";
1097
1192
  case "query": return "field = value";
1193
+ case "expr": return "field + 1";
1194
+ case "order": return "field asc";
1098
1195
  default: return "";
1099
1196
  }
1100
1197
  }
@@ -1417,209 +1514,874 @@ async function loadConfig(configPath, forceFormat) {
1417
1514
  }
1418
1515
 
1419
1516
  //#endregion
1420
- //#region packages/core/src/lsp/legacy-db-query-scope.ts
1421
- /**
1422
- * @deprecated Built-in editor scopes for the `@db.view.filter`, `@db.view.joins` and
1423
- * `@db.rel.filter` query arguments. They are a fallback for DB plugin versions whose
1424
- * argument specs do not declare a `fieldScope` hook yet — the DB plugin owns these
1425
- * rules now. Scheduled for removal in `@atscript/core` 0.2.0 (next minor).
1426
- */
1427
- /**
1428
- * @deprecated Query scope of a built-in `@db.*` query argument (see the module note);
1429
- * `undefined` for any other annotation.
1430
- */ function getLegacyDbQueryScope(queryArgToken) {
1431
- const owner = queryArgToken.parentNode;
1432
- if (!owner) return;
1433
- switch (queryArgToken.annotationRef?.text.slice(1)) {
1434
- case "db.view.filter": return getViewFilterScope(owner);
1435
- case "db.view.joins": return getViewJoinsScope(owner, queryArgToken);
1436
- case "db.rel.filter": return getRelFilterScope(owner);
1437
- default: return;
1438
- }
1517
+ //#region packages/core/src/parser/iterator.ts
1518
+ function _define_property$7(obj, key, value) {
1519
+ if (key in obj) Object.defineProperty(obj, key, {
1520
+ value,
1521
+ enumerable: true,
1522
+ configurable: true,
1523
+ writable: true
1524
+ });
1525
+ else obj[key] = value;
1526
+ return obj;
1439
1527
  }
1440
- function getViewFilterScope(owner) {
1441
- const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
1442
- if (!entryTypeName) return;
1443
- const allowedTypes = [entryTypeName];
1444
- const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
1445
- if (joinsAnnotations) {
1446
- for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
1528
+ var NodeIterator = class NodeIterator {
1529
+ get index() {
1530
+ return this.i;
1447
1531
  }
1448
- return {
1449
- allowedTypes,
1450
- unqualifiedTarget: entryTypeName
1451
- };
1452
- }
1453
- function getViewJoinsScope(owner, queryArgToken) {
1454
- const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
1455
- if (!entryTypeName) return;
1456
- const joinTargetName = (owner.annotations?.find((a) => a.name === "db.view.joins" && a.args.includes(queryArgToken)))?.args[0]?.text;
1457
- if (!joinTargetName) return;
1458
- return {
1459
- allowedTypes: [joinTargetName, entryTypeName],
1460
- unqualifiedTarget: entryTypeName
1461
- };
1462
- }
1463
- function getRelFilterScope(owner) {
1464
- let def = owner.getDefinition();
1465
- if (isArray(def)) def = def?.getDefinition();
1466
- if (!isRef(def)) return;
1467
- const targetTypeName = def.id;
1468
- const allowedTypes = [targetTypeName];
1469
- const viaAnnotation = owner.annotations?.find((a) => a.name === "db.rel.via");
1470
- if (viaAnnotation?.args[0]) allowedTypes.push(viaAnnotation.args[0].text);
1471
- return {
1472
- allowedTypes,
1473
- unqualifiedTarget: targetTypeName
1474
- };
1475
- }
1476
-
1477
- //#endregion
1478
- //#region packages/core/src/lsp/field-refs.ts
1479
- function getArgSpec(argToken, doc) {
1480
- const annotationRef = argToken.annotationRef;
1481
- if (!annotationRef || typeof argToken.index !== "number") return;
1482
- return doc.resolveAnnotation(annotationRef.text.slice(1))?.arguments[argToken.index];
1483
- }
1484
- /**
1485
- * Field scope of an annotation argument: the answer of the argument spec's `fieldScope`
1486
- * hook when it declares one, otherwise the deprecated built-in `@db.*` query rules.
1487
- */ function getQueryScope(argToken, doc) {
1488
- const argSpec = getArgSpec(argToken, doc);
1489
- return argSpec?.fieldScope ? argSpec.fieldScope(argToken, doc) : getLegacyDbQueryScope(argToken);
1490
- }
1491
- /**
1492
- * Type a field-path `string` argument names a field of: the `unqualifiedTarget` of the
1493
- * argument spec's `fieldScope`. `undefined` for any other token.
1494
- */ function getFieldPathTarget(argToken, doc) {
1495
- if (argToken.type !== "text") return;
1496
- const argSpec = getArgSpec(argToken, doc);
1497
- if (argSpec?.type !== "string" || !argSpec.fieldScope) return;
1498
- return argSpec.fieldScope(argToken, doc)?.unqualifiedTarget ?? void 0;
1499
- }
1500
- /**
1501
- * Resolve a (possibly dotted) field path of a type to the property it names and the
1502
- * document that declares that property.
1503
- */ function resolveFieldPath(doc, typeName, segment) {
1504
- const chain = segment.path.split(".");
1505
- const [name] = chain.splice(-1);
1506
- const parent = doc.unwindType(typeName, chain);
1507
- if (!parent || !(isStructure(parent.def) || isInterface(parent.def))) return;
1508
- const prop = parent.def.props.get(name);
1509
- return prop && {
1510
- typeName,
1511
- range: segment.range,
1512
- prop,
1513
- doc: parent.doc
1514
- };
1515
- }
1516
- /**
1517
- * Segments of a field-path string argument (`'address.city'` → `address`, `city`), with
1518
- * ranges that exclude the quotes. A string spanning several lines is a single segment.
1519
- */ function fieldPathSegments(argToken) {
1520
- const { text, range } = argToken;
1521
- if (range.start.line !== range.end.line) return [{
1522
- path: text,
1523
- range
1524
- }];
1525
- const line = range.start.line;
1526
- const contentStart = range.start.character + 1;
1527
- const segments = [];
1528
- let start = 0;
1529
- for (const part of text.split(".")) {
1530
- const end = start + part.length;
1531
- segments.push({
1532
- path: text.slice(0, end),
1533
- range: {
1534
- start: {
1535
- line,
1536
- character: contentStart + start
1537
- },
1538
- end: {
1539
- line,
1540
- character: contentStart + end
1541
- }
1542
- }
1543
- });
1544
- start = end + 1;
1532
+ get lastNode() {
1533
+ return this.nodes[this.nodes.length - 1];
1545
1534
  }
1546
- return segments;
1547
- }
1548
- /** The segment under `character`, or the last segment when `character` is omitted. */ function fieldPathSegmentAt(argToken, character) {
1549
- const segments = fieldPathSegments(argToken);
1550
- return (character === void 0 ? void 0 : segments.find((s) => s.range.end.character >= character)) ?? segments[segments.length - 1];
1551
- }
1552
- /**
1553
- * Resolve a field reference token to the property it names:
1554
- * - a field ref inside a `query` argument (`amount`, `Customer.name` in backticks);
1555
- * - a `string` argument whose spec declares `fieldScope`: a (dotted) field path of the
1556
- * scope's `unqualifiedTarget`. With `character` (a cursor column), the path resolves
1557
- * only up to the segment under the cursor — `'address.city'` with the cursor on
1558
- * `address` resolves `address` — and `range` is that segment's range.
1559
- *
1560
- * Returns `undefined` for any other token, or when the scope or the path does not resolve.
1561
- */ function resolveFieldRefAt(token, doc, character) {
1562
- if (isQueryFieldRef(token.parentNode)) {
1563
- const { fieldRef, typeRef, queryArgToken } = token.parentNode;
1564
- const scope = token === fieldRef && queryArgToken ? getQueryScope(queryArgToken, doc) : void 0;
1565
- const typeName = scope && (typeRef?.text ?? scope.unqualifiedTarget);
1566
- return typeName ? resolveFieldPath(doc, typeName, {
1567
- path: token.text,
1568
- range: token.range
1569
- }) : void 0;
1535
+ unexpectedEOB() {
1536
+ this.issues.unexpectedEOB = true;
1570
1537
  }
1571
- const typeName = getFieldPathTarget(token, doc);
1572
- return typeName ? resolveFieldPath(doc, typeName, fieldPathSegmentAt(token, character)) : void 0;
1573
- }
1574
- /**
1575
- * Resolve the segments named `fieldName` of a field-path `string` argument
1576
- * (`'address.city'` has the segments `address` and `city`). Supports find-references.
1577
- */ function resolveFieldPathArgSegments(argToken, doc, fieldName) {
1578
- const segments = fieldPathSegments(argToken).filter((s) => s.path === fieldName || s.path.endsWith(`.${fieldName}`));
1579
- const typeName = segments.length > 0 ? getFieldPathTarget(argToken, doc) : void 0;
1580
- if (!typeName) return [];
1581
- const targets = [];
1582
- for (const segment of segments) {
1583
- const target = resolveFieldPath(doc, typeName, segment);
1584
- if (target) targets.push(target);
1538
+ unfork(fork) {
1539
+ this.i = fork.index;
1540
+ this.update();
1585
1541
  }
1586
- return targets;
1587
- }
1588
- /**
1589
- * Resolve a query field ref node to a property definition.
1590
- */ function resolveQueryFieldRef(fieldRefNode, doc, scope) {
1591
- const typeName = fieldRefNode.typeRef?.text ?? scope.unqualifiedTarget;
1592
- const { fieldRef } = fieldRefNode;
1593
- const resolved = typeName ? resolveFieldPath(doc, typeName, {
1594
- path: fieldRef.text,
1595
- range: fieldRef.range
1596
- }) : void 0;
1597
- return resolved && {
1598
- targetUri: resolved.doc.id,
1599
- doc: resolved.doc,
1600
- prop: resolved.prop
1601
- };
1602
- }
1603
- /**
1604
- * Get fields available for a type (resolving extends/intersections).
1605
- * With `chain`, returns the fields of the nested object that field path leads to.
1606
- */ function getFieldsForType(doc, typeName, chain = []) {
1607
- const unwound = doc.unwindType(typeName, chain);
1608
- if (!unwound?.def) return [];
1609
- let def = unwound.doc.mergeIntersection(unwound.def);
1610
- if (isInterface(def)) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
1611
- if (isStructure(def) || isInterface(def)) return Array.from(def.props.values());
1612
- return [];
1613
- }
1614
- /**
1615
- * Completion scope of a field-path `string` argument (spec declares `fieldScope`) at the
1616
- * cursor column `character`: the fields of the level being typed — `'address.ci'` offers
1617
- * the fields of `address` (`chain` = `['address']`).
1618
- */ function getFieldPathCompletionScope(argToken, doc, character) {
1619
- const typeName = getFieldPathTarget(argToken, doc);
1620
- if (!typeName) return;
1621
- const chain = fieldPathSegmentAt(argToken, character).path.split(".").slice(0, -1);
1622
- return {
1542
+ accepted() {
1543
+ if (this.$ && this.$.accepted !== false) {
1544
+ this.$.accepted = true;
1545
+ this.badNodes.delete(this.$);
1546
+ }
1547
+ }
1548
+ toString() {
1549
+ return this.$ ? `[${this.$.type}] ${this.$.text}` : `void`;
1550
+ }
1551
+ update() {
1552
+ this.$ = this.nodes[this.i];
1553
+ return this;
1554
+ }
1555
+ move(v = 1) {
1556
+ this.i += v;
1557
+ this.$ = this.nodes[this.i];
1558
+ return this;
1559
+ }
1560
+ next(skip) {
1561
+ return this.fork().move().skip(skip);
1562
+ }
1563
+ fork(nodes) {
1564
+ return new NodeIterator(nodes || this.nodes, this.messages, this.badNodes, this.issues, nodes ? this.$ : this.parent, nodes ? 0 : this.i).update();
1565
+ }
1566
+ skip(pun) {
1567
+ while (this.$?.type === "comment" || this.$?.type === "punctuation" && pun?.length && pun.includes(this.$.text)) this.move();
1568
+ return this;
1569
+ }
1570
+ skipUntil(pun) {
1571
+ while (this.$ && !this.satisfies({
1572
+ node: "punctuation",
1573
+ text: pun
1574
+ })) this.move();
1575
+ }
1576
+ unexpected(force = false, msg = "Unexpected token") {
1577
+ if (force && this.$) this.$.accepted = false;
1578
+ if (this.$ && !this.badNodes.has(this.$)) this.badNodes.set(this.$, msg);
1579
+ }
1580
+ shouldHaveError(depth) {
1581
+ for (let i = this.i; i <= depth; i++) if (i < this.nodes.length) this.nodes[i].accepted = false;
1582
+ }
1583
+ nodesLeft() {
1584
+ return this.nodes.length > 0 && this.index < this.nodes.length;
1585
+ }
1586
+ satisfies(...rules) {
1587
+ for (const rule of rules) {
1588
+ const passed = Array.isArray(rule.node) ? rule.node.includes(this.$?.type) : this.$?.type === rule.node;
1589
+ if (passed && rule.text === void 0) return true;
1590
+ if (passed && Array.isArray(rule.text) ? rule.text.includes(this.$?.text) : this.$?.text === rule.text) return true;
1591
+ }
1592
+ return false;
1593
+ }
1594
+ confirmIssues() {
1595
+ if (this.issues.unexpectedEOB) {
1596
+ const pos = (this.lastNode || this.parent)?.getRange().end || {
1597
+ character: 1,
1598
+ line: 1
1599
+ };
1600
+ this.messages.push({
1601
+ severity: 1,
1602
+ message: `Unexpected end of block`,
1603
+ range: {
1604
+ start: pos,
1605
+ end: pos
1606
+ }
1607
+ });
1608
+ this.issues.unexpectedEOB = false;
1609
+ }
1610
+ }
1611
+ getErrors() {
1612
+ this.badNodes.forEach((msg, node) => {
1613
+ if (node.accepted) this.badNodes.delete(node);
1614
+ });
1615
+ return Array.from(this.badNodes.entries(), ([node, msg]) => ({
1616
+ severity: 1,
1617
+ message: msg,
1618
+ range: node.getRange?.() || {
1619
+ start: {
1620
+ character: 1,
1621
+ line: 1
1622
+ },
1623
+ end: {
1624
+ character: 1,
1625
+ line: 1
1626
+ }
1627
+ }
1628
+ })).concat(this.messages);
1629
+ }
1630
+ constructor(nodes, messages = [], badNodes = /* @__PURE__ */ new Map(), issues = {}, parent, i = -1) {
1631
+ _define_property$7(this, "nodes", void 0);
1632
+ _define_property$7(this, "messages", void 0);
1633
+ _define_property$7(this, "badNodes", void 0);
1634
+ _define_property$7(this, "issues", void 0);
1635
+ _define_property$7(this, "parent", void 0);
1636
+ _define_property$7(this, "i", void 0);
1637
+ _define_property$7(this, "$", void 0);
1638
+ this.nodes = nodes;
1639
+ this.messages = messages;
1640
+ this.badNodes = badNodes;
1641
+ this.issues = issues;
1642
+ this.parent = parent;
1643
+ this.i = i;
1644
+ }
1645
+ };
1646
+
1647
+ //#endregion
1648
+ //#region packages/core/src/parser/pipes/query.pipe.ts
1649
+ const SYMBOLIC_OPS = new Set([
1650
+ "=",
1651
+ "!=",
1652
+ ">",
1653
+ ">=",
1654
+ "<",
1655
+ "<="
1656
+ ]);
1657
+ const VALUE_KEYWORDS = new Set([
1658
+ "true",
1659
+ "false",
1660
+ "null",
1661
+ "undefined"
1662
+ ]);
1663
+ const ZERO_RANGE = {
1664
+ start: {
1665
+ line: 0,
1666
+ character: 0
1667
+ },
1668
+ end: {
1669
+ line: 0,
1670
+ character: 0
1671
+ }
1672
+ };
1673
+ /**
1674
+ * Parse a backtick-delimited query expression.
1675
+ *
1676
+ * `ni` iterates the query token's children and carries that token as its
1677
+ * `parent` — the range to blame when a diagnostic has no token of its own —
1678
+ * so fork it from the annotation iterator while the query token is current.
1679
+ * Returns a SemanticQueryNode or undefined if the content is empty.
1680
+ */ function parseQueryExpression(ni, sourceToken) {
1681
+ if (!ni.$) return;
1682
+ const expr = parseOrExpr(ni);
1683
+ if (!expr) return;
1684
+ if (ni.$) pushError(ni, `Unexpected token in query expression: "${ni.$.text}"`);
1685
+ const node = new SemanticQueryNode();
1686
+ node.expression = expr;
1687
+ node.sourceToken = sourceToken;
1688
+ return node;
1689
+ }
1690
+ function parseOrExpr(ni) {
1691
+ const left = parseAndExpr(ni);
1692
+ if (!left) return;
1693
+ const operands = [left];
1694
+ while (ni.$?.type === "identifier" && ni.$.text === "or") {
1695
+ ni.move();
1696
+ const right = parseAndExpr(ni);
1697
+ if (!right) {
1698
+ pushError(ni, "Expected expression after \"or\"");
1699
+ break;
1700
+ }
1701
+ operands.push(right);
1702
+ }
1703
+ if (operands.length === 1) return operands[0];
1704
+ const node = new SemanticQueryLogicalNode();
1705
+ node.operator = "or";
1706
+ node.operands = operands;
1707
+ return node;
1708
+ }
1709
+ function parseAndExpr(ni) {
1710
+ const left = parseUnaryExpr(ni);
1711
+ if (!left) return;
1712
+ const operands = [left];
1713
+ while (ni.$?.type === "identifier" && ni.$.text === "and") {
1714
+ ni.move();
1715
+ const right = parseUnaryExpr(ni);
1716
+ if (!right) {
1717
+ pushError(ni, "Expected expression after \"and\"");
1718
+ break;
1719
+ }
1720
+ operands.push(right);
1721
+ }
1722
+ if (operands.length === 1) return operands[0];
1723
+ const node = new SemanticQueryLogicalNode();
1724
+ node.operator = "and";
1725
+ node.operands = operands;
1726
+ return node;
1727
+ }
1728
+ function parseUnaryExpr(ni) {
1729
+ if (ni.$?.type === "identifier" && ni.$.text === "not") {
1730
+ ni.move();
1731
+ const operand = parseUnaryExpr(ni);
1732
+ if (!operand) {
1733
+ pushError(ni, "Expected expression after \"not\"");
1734
+ return;
1735
+ }
1736
+ const node = new SemanticQueryLogicalNode();
1737
+ node.operator = "not";
1738
+ node.operands = [operand];
1739
+ return node;
1740
+ }
1741
+ if (ni.$?.type === "block" && ni.$.text === "(") {
1742
+ const subNi = ni.fork(ni.$.children || []);
1743
+ ni.move();
1744
+ if (!subNi.$) {
1745
+ pushError(subNi, "Empty parenthesized expression");
1746
+ return;
1747
+ }
1748
+ const expr = parseOrExpr(subNi);
1749
+ if (subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
1750
+ return expr;
1751
+ }
1752
+ return parseComparison(ni);
1753
+ }
1754
+ function parseComparison(ni) {
1755
+ const left = parseFieldRef(ni);
1756
+ if (!left) return;
1757
+ if (ni.$?.type === "punctuation" && SYMBOLIC_OPS.has(ni.$.text)) {
1758
+ const opText = ni.$.text;
1759
+ ni.move();
1760
+ const right = parseValueOrFieldRef(ni);
1761
+ if (!right) {
1762
+ pushError(ni, `Expected value or field reference after "${opText}"`);
1763
+ return;
1764
+ }
1765
+ const node = new SemanticQueryComparisonNode();
1766
+ node.left = left;
1767
+ node.operator = opText;
1768
+ node.right = right;
1769
+ return node;
1770
+ }
1771
+ if (ni.$?.type === "identifier") {
1772
+ const opText = ni.$.text;
1773
+ if (opText === "in") {
1774
+ ni.move();
1775
+ const right = parseValueList(ni);
1776
+ if (!right) return;
1777
+ const node = new SemanticQueryComparisonNode();
1778
+ node.left = left;
1779
+ node.operator = "in";
1780
+ node.right = right;
1781
+ return node;
1782
+ }
1783
+ if (opText === "matches") {
1784
+ ni.move();
1785
+ const right = parseValueOrFieldRef(ni);
1786
+ if (!right) {
1787
+ pushError(ni, "Expected value after \"matches\"");
1788
+ return;
1789
+ }
1790
+ const node = new SemanticQueryComparisonNode();
1791
+ node.left = left;
1792
+ node.operator = "matches";
1793
+ node.right = right;
1794
+ return node;
1795
+ }
1796
+ if (opText === "exists") {
1797
+ ni.move();
1798
+ const node = new SemanticQueryComparisonNode();
1799
+ node.left = left;
1800
+ node.operator = "exists";
1801
+ return node;
1802
+ }
1803
+ if (opText === "not") return parseNotComparison(ni, left);
1804
+ pushError(ni, `Unknown operator "${opText}"`);
1805
+ return;
1806
+ }
1807
+ pushError(ni, "Expected operator after field reference");
1808
+ }
1809
+ function parseNotComparison(ni, left) {
1810
+ ni.move();
1811
+ if (ni.$?.type === "identifier" && ni.$.text === "in") {
1812
+ ni.move();
1813
+ const right = parseValueList(ni);
1814
+ if (!right) return;
1815
+ const node = new SemanticQueryComparisonNode();
1816
+ node.left = left;
1817
+ node.operator = "not in";
1818
+ node.right = right;
1819
+ return node;
1820
+ }
1821
+ if (ni.$?.type === "identifier" && ni.$.text === "exists") {
1822
+ ni.move();
1823
+ const node = new SemanticQueryComparisonNode();
1824
+ node.left = left;
1825
+ node.operator = "not exists";
1826
+ return node;
1827
+ }
1828
+ pushError(ni, "Expected \"in\" or \"exists\" after \"not\"");
1829
+ }
1830
+ function parseFieldRef(ni) {
1831
+ if (ni.$?.type !== "identifier") {
1832
+ pushError(ni, "Expected field reference");
1833
+ return;
1834
+ }
1835
+ const firstToken = new Token(ni.$);
1836
+ ni.move();
1837
+ if (ni.$?.type === "punctuation" && ni.$.text === ".") {
1838
+ ni.move();
1839
+ if (ni.$?.type === "identifier") {
1840
+ const secondToken = new Token(ni.$);
1841
+ ni.move();
1842
+ let fieldText = secondToken.text;
1843
+ while (ni.$?.type === "punctuation" && ni.$.text === ".") {
1844
+ ni.move();
1845
+ if (ni.$?.type === "identifier") {
1846
+ fieldText += `.${ni.$.text}`;
1847
+ ni.move();
1848
+ } else {
1849
+ pushError(ni, "Expected identifier after \".\"");
1850
+ break;
1851
+ }
1852
+ }
1853
+ const node = new SemanticQueryFieldRefNode();
1854
+ node.typeRef = firstToken;
1855
+ node.fieldRef = fieldText === secondToken.text ? secondToken : secondToken.clone({ text: fieldText });
1856
+ return node;
1857
+ }
1858
+ pushError(ni, "Expected identifier after \".\"");
1859
+ const node = new SemanticQueryFieldRefNode();
1860
+ node.fieldRef = firstToken;
1861
+ return node;
1862
+ }
1863
+ const node = new SemanticQueryFieldRefNode();
1864
+ node.fieldRef = firstToken;
1865
+ return node;
1866
+ }
1867
+ function parseValueOrFieldRef(ni) {
1868
+ if (!ni.$) return;
1869
+ if (ni.$.type === "text" || ni.$.type === "number" || ni.$.type === "regexp") return parseValue(ni);
1870
+ if (ni.$.type === "identifier") {
1871
+ if (VALUE_KEYWORDS.has(ni.$.text)) return parseValue(ni);
1872
+ return parseFieldRef(ni);
1873
+ }
1874
+ pushError(ni, "Expected value or field reference");
1875
+ }
1876
+ function parseValue(ni) {
1877
+ if (!ni.$) {
1878
+ pushError(ni, "Expected value");
1879
+ return;
1880
+ }
1881
+ const token = ni.$;
1882
+ if (token.type === "text" || token.type === "number" || token.type === "regexp" || token.type === "identifier" && VALUE_KEYWORDS.has(token.text)) {
1883
+ const node = new SemanticQueryValueNode();
1884
+ node.valueToken = new Token(token);
1885
+ ni.move();
1886
+ return node;
1887
+ }
1888
+ pushError(ni, `Unexpected token "${token.text}" where value expected`);
1889
+ }
1890
+ function parseValueList(ni) {
1891
+ if (ni.$?.type === "block" && ni.$.text === "(") {
1892
+ const subNi = ni.fork(ni.$.children || []);
1893
+ ni.move();
1894
+ if (!subNi.$) {
1895
+ pushError(subNi, "Empty value list in \"in\" expression");
1896
+ return;
1897
+ }
1898
+ const values = [];
1899
+ const first = parseValue(subNi);
1900
+ if (first) values.push(first);
1901
+ while (subNi.$?.type === "punctuation" && subNi.$.text === ",") {
1902
+ subNi.move();
1903
+ const v = parseValue(subNi);
1904
+ if (v) values.push(v);
1905
+ }
1906
+ if (subNi.$) pushError(subNi, `Unexpected token in value list: "${subNi.$.text}"`);
1907
+ const node = new SemanticQueryValueListNode();
1908
+ node.values = values;
1909
+ return node;
1910
+ }
1911
+ pushError(ni, "Expected parenthesized value list after \"in\"");
1912
+ }
1913
+ /**
1914
+ * Range to blame for a diagnostic: the current token, else the enclosing
1915
+ * query token / "(...)" block the iterator was forked from.
1916
+ */ function rangeOf(ni) {
1917
+ return ni.$?.getRange?.() ?? ni.parent?.getRange?.() ?? ZERO_RANGE;
1918
+ }
1919
+ function pushError(ni, message) {
1920
+ ni.messages.push({
1921
+ severity: 1,
1922
+ message,
1923
+ range: rangeOf(ni)
1924
+ });
1925
+ }
1926
+
1927
+ //#endregion
1928
+ //#region packages/core/src/parser/pipes/expr.pipe.ts
1929
+ /**
1930
+ * Parse a backtick annotation argument as the given kind and attach the tree to
1931
+ * the token (`queryNode`, `exprNode` or `orderNode`). Returns the diagnostics.
1932
+ */ function parseBacktickArg(argToken, kind) {
1933
+ const messages = [];
1934
+ const ni = new NodeIterator(argToken.children, messages, /* @__PURE__ */ new Map(), {}, argToken.lexicalToken, 0).update();
1935
+ switch (kind) {
1936
+ case "expr":
1937
+ argToken.exprNode = parseExprExpression(ni, argToken);
1938
+ break;
1939
+ case "order":
1940
+ argToken.orderNode = parseOrderList(ni, argToken);
1941
+ break;
1942
+ default: argToken.queryNode = parseQueryExpression(ni, argToken);
1943
+ }
1944
+ return messages;
1945
+ }
1946
+ /** Vocabulary of `expr` / `order` arguments: arithmetic operators, functions, order directions. */ const BACKTICK_ARG_VOCABULARY = {
1947
+ arithmeticOps: [
1948
+ "+",
1949
+ "-",
1950
+ "*",
1951
+ "/"
1952
+ ],
1953
+ functions: ["coalesce"],
1954
+ orderDirections: ["asc", "desc"]
1955
+ };
1956
+ const ORDER_DIRECTIONS = new Set(BACKTICK_ARG_VOCABULARY.orderDirections);
1957
+ /**
1958
+ * Parse a backtick arithmetic expression:
1959
+ *
1960
+ * ```
1961
+ * expr := additive
1962
+ * additive := mult (('+' | '-') mult)*
1963
+ * mult := unary (('*' | '/') unary)*
1964
+ * unary := '-' unary | primary
1965
+ * primary := NUMBER | fieldRef | 'coalesce' '(' expr (',' expr)+ ')' | '(' expr ')'
1966
+ * ```
1967
+ *
1968
+ * A signed number in binary-operator position (`a -5`, `a+1`) is split into the
1969
+ * operator and an unsigned operand. Returns `undefined` when the content is empty.
1970
+ */ function parseExprExpression(ni, sourceToken) {
1971
+ if (!ni.$) {
1972
+ pushError(ni, "Empty expression");
1973
+ return;
1974
+ }
1975
+ const expr = parseAdditive(ni);
1976
+ if (!expr) return;
1977
+ if (ni.$) pushError(ni, `Unexpected token in expression: "${ni.$.text}"`);
1978
+ const node = new SemanticExprNode();
1979
+ node.expression = expr;
1980
+ node.sourceToken = sourceToken;
1981
+ return node;
1982
+ }
1983
+ function isPunct(t, chars) {
1984
+ return t?.type === "punctuation" && t.text.length === 1 && chars.includes(t.text);
1985
+ }
1986
+ function isParenBlock(t) {
1987
+ return t?.type === "block" && t.text === "(";
1988
+ }
1989
+ /** A number token whose text carries a sign (`-5`, `+1`). */ function signedNumber(t) {
1990
+ if (t?.type !== "number") return;
1991
+ const c = t.text.charAt(0);
1992
+ return c === "-" || c === "+" ? c : void 0;
1993
+ }
1994
+ function binary(op, left, right) {
1995
+ const node = new SemanticExprBinaryNode();
1996
+ node.op = op;
1997
+ node.left = left;
1998
+ node.right = right;
1999
+ return node;
2000
+ }
2001
+ function parseAdditive(ni) {
2002
+ let left = parseMult(ni);
2003
+ if (!left) return;
2004
+ for (;;) {
2005
+ const punct = isPunct(ni.$, "+-");
2006
+ const op = punct ? ni.$?.text : signedNumber(ni.$);
2007
+ if (!op) break;
2008
+ if (punct) ni.move();
2009
+ const right = parseMult(ni, !punct);
2010
+ if (!right) {
2011
+ pushError(ni, `Expected operand after "${op}"`);
2012
+ return;
2013
+ }
2014
+ left = binary(op, left, right);
2015
+ }
2016
+ return left;
2017
+ }
2018
+ function parseMult(ni, unsignFirst = false) {
2019
+ let left = parseUnary(ni, unsignFirst);
2020
+ if (!left) return;
2021
+ for (let t = ni.$; isPunct(t, "*/"); t = ni.$) {
2022
+ const op = t.text;
2023
+ ni.move();
2024
+ const right = parseUnary(ni);
2025
+ if (!right) {
2026
+ pushError(ni, `Expected operand after "${op}"`);
2027
+ return;
2028
+ }
2029
+ left = binary(op, left, right);
2030
+ }
2031
+ return left;
2032
+ }
2033
+ function parseUnary(ni, unsign = false) {
2034
+ if (!unsign && isPunct(ni.$, "-")) {
2035
+ ni.move();
2036
+ const operand = parseUnary(ni);
2037
+ if (!operand) {
2038
+ pushError(ni, "Expected operand after \"-\"");
2039
+ return;
2040
+ }
2041
+ const node = new SemanticExprUnaryNode();
2042
+ node.operand = operand;
2043
+ return node;
2044
+ }
2045
+ return parsePrimary(ni, unsign);
2046
+ }
2047
+ function parsePrimary(ni, unsign = false) {
2048
+ const t = ni.$;
2049
+ if (!t) {
2050
+ pushError(ni, "Expected operand");
2051
+ return;
2052
+ }
2053
+ if (t.type === "number") return parseNumber(ni, t, unsign);
2054
+ if (isParenBlock(t)) {
2055
+ const subNi = ni.fork(t.children || []);
2056
+ ni.move();
2057
+ if (!subNi.$) {
2058
+ pushError(subNi, "Empty parenthesized expression");
2059
+ return;
2060
+ }
2061
+ const expr = parseAdditive(subNi);
2062
+ if (expr && subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
2063
+ return expr;
2064
+ }
2065
+ if (t.type === "identifier") {
2066
+ if (VALUE_KEYWORDS.has(t.text)) {
2067
+ pushError(ni, `"${t.text}" is not allowed in an arithmetic expression`);
2068
+ return;
2069
+ }
2070
+ if (t.text === "coalesce" && isParenBlock(ni.next().$)) {
2071
+ ni.move();
2072
+ return parseCoalesce(ni);
2073
+ }
2074
+ return parseFieldRef(ni);
2075
+ }
2076
+ pushError(ni, `Unexpected token in expression: "${t.text}"`);
2077
+ }
2078
+ /** Why a number literal cannot be used in an expression (or `undefined` when it can). */ function numberLiteralProblem(text, value) {
2079
+ if (!Number.isFinite(value)) return "is out of range";
2080
+ if (value === 0 && /[1-9]/.test(text.replace(/[eE].*$/, ""))) return "underflows to 0";
2081
+ if (Math.abs(value) > Number.MAX_SAFE_INTEGER) return "exceeds the safe integer range (±2^53 - 1)";
2082
+ }
2083
+ function parseNumber(ni, lexical, unsign) {
2084
+ const token = new Token(lexical);
2085
+ const text = unsign ? token.text.slice(1) : token.text;
2086
+ const value = Number(text);
2087
+ const problem = numberLiteralProblem(text, value);
2088
+ if (problem) {
2089
+ pushError(ni, `Number literal "${token.text}" ${problem}`);
2090
+ ni.move();
2091
+ return;
2092
+ }
2093
+ ni.move();
2094
+ const node = new SemanticExprNumberNode();
2095
+ node.valueToken = token;
2096
+ node.value = value;
2097
+ return node;
2098
+ }
2099
+ function parseCoalesce(ni) {
2100
+ const subNi = ni.fork(ni.$?.children || []);
2101
+ ni.move();
2102
+ const args = [];
2103
+ if (subNi.$) for (;;) {
2104
+ const arg = parseAdditive(subNi);
2105
+ if (!arg) return;
2106
+ args.push(arg);
2107
+ if (!isPunct(subNi.$, ",")) break;
2108
+ subNi.move();
2109
+ }
2110
+ if (subNi.$) {
2111
+ pushError(subNi, `Unexpected token in coalesce(): "${subNi.$.text}"`);
2112
+ return;
2113
+ }
2114
+ if (args.length < 2) {
2115
+ pushError(subNi, "coalesce() requires at least 2 arguments");
2116
+ return;
2117
+ }
2118
+ const node = new SemanticExprCallNode();
2119
+ node.args = args;
2120
+ return node;
2121
+ }
2122
+ /**
2123
+ * Parse a backtick ordering: `key (asc|desc)? (, key (asc|desc)?)*`.
2124
+ * Returns `undefined` when the content is empty or a key does not parse.
2125
+ */ function parseOrderList(ni, sourceToken) {
2126
+ if (!ni.$) {
2127
+ pushError(ni, "Empty order list");
2128
+ return;
2129
+ }
2130
+ const items = [];
2131
+ for (;;) {
2132
+ const ref = parseFieldRef(ni);
2133
+ if (!ref) return;
2134
+ const item = {
2135
+ ref,
2136
+ desc: false
2137
+ };
2138
+ if (ni.$?.type === "identifier" && ORDER_DIRECTIONS.has(ni.$.text)) {
2139
+ item.desc = ni.$.text === "desc";
2140
+ item.dirToken = new Token(ni.$);
2141
+ ni.move();
2142
+ }
2143
+ items.push(item);
2144
+ if (!ni.$) break;
2145
+ if (isPunct(ni.$, ",")) {
2146
+ ni.move();
2147
+ continue;
2148
+ }
2149
+ pushError(ni, `Unexpected token in order list: "${ni.$.text}" (expected "," or "asc" / "desc")`);
2150
+ return;
2151
+ }
2152
+ const node = new SemanticOrderNode();
2153
+ node.items = items;
2154
+ node.sourceToken = sourceToken;
2155
+ return node;
2156
+ }
2157
+
2158
+ //#endregion
2159
+ //#region packages/core/src/lsp/legacy-db-query-scope.ts
2160
+ /**
2161
+ * @deprecated Built-in editor scopes for the `@db.view.filter`, `@db.view.joins` and
2162
+ * `@db.rel.filter` query arguments. They are a fallback for DB plugin versions whose
2163
+ * argument specs do not declare a `fieldScope` hook yet — the DB plugin owns these
2164
+ * rules now. Scheduled for removal in `@atscript/core` 0.2.0 (next minor).
2165
+ */
2166
+ /**
2167
+ * @deprecated Query scope of a built-in `@db.*` query argument (see the module note);
2168
+ * `undefined` for any other annotation.
2169
+ */ function getLegacyDbQueryScope(queryArgToken) {
2170
+ const owner = queryArgToken.parentNode;
2171
+ if (!owner) return;
2172
+ switch (queryArgToken.annotationRef?.text.slice(1)) {
2173
+ case "db.view.filter": return getViewFilterScope(owner);
2174
+ case "db.view.joins": return getViewJoinsScope(owner, queryArgToken);
2175
+ case "db.rel.filter": return getRelFilterScope(owner);
2176
+ default: return;
2177
+ }
2178
+ }
2179
+ function getViewFilterScope(owner) {
2180
+ const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
2181
+ if (!entryTypeName) return;
2182
+ const allowedTypes = [entryTypeName];
2183
+ const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
2184
+ if (joinsAnnotations) {
2185
+ for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
2186
+ }
2187
+ return {
2188
+ allowedTypes,
2189
+ unqualifiedTarget: entryTypeName
2190
+ };
2191
+ }
2192
+ function getViewJoinsScope(owner, queryArgToken) {
2193
+ const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
2194
+ if (!entryTypeName) return;
2195
+ const joinTargetName = (owner.annotations?.find((a) => a.name === "db.view.joins" && a.args.includes(queryArgToken)))?.args[0]?.text;
2196
+ if (!joinTargetName) return;
2197
+ return {
2198
+ allowedTypes: [joinTargetName, entryTypeName],
2199
+ unqualifiedTarget: entryTypeName
2200
+ };
2201
+ }
2202
+ function getRelFilterScope(owner) {
2203
+ let def = owner.getDefinition();
2204
+ if (isArray(def)) def = def?.getDefinition();
2205
+ if (!isRef(def)) return;
2206
+ const targetTypeName = def.id;
2207
+ const allowedTypes = [targetTypeName];
2208
+ const viaAnnotation = owner.annotations?.find((a) => a.name === "db.rel.via");
2209
+ if (viaAnnotation?.args[0]) allowedTypes.push(viaAnnotation.args[0].text);
2210
+ return {
2211
+ allowedTypes,
2212
+ unqualifiedTarget: targetTypeName
2213
+ };
2214
+ }
2215
+
2216
+ //#endregion
2217
+ //#region packages/core/src/lsp/field-refs.ts
2218
+ function getArgSpecAt(annotationToken, index, doc) {
2219
+ return doc.resolveAnnotation(annotationToken.text.slice(1))?.arguments[index];
2220
+ }
2221
+ function getArgSpec(argToken, doc) {
2222
+ const annotationRef = argToken.annotationRef;
2223
+ if (!annotationRef || typeof argToken.index !== "number") return;
2224
+ return getArgSpecAt(annotationRef, argToken.index, doc);
2225
+ }
2226
+ /**
2227
+ * The annotation an argument token belongs to, found among the annotations of the annotated
2228
+ * node (`argToken.parentNode`, a prop or an annotate entry). For `fieldScope` hooks that scope
2229
+ * an argument by its siblings (`getSiblingAnnotation(arg)?.args[0]?.text`).
2230
+ */ function getSiblingAnnotation(argToken) {
2231
+ return argToken.parentNode?.annotations?.find((a) => a.args.includes(argToken));
2232
+ }
2233
+ /**
2234
+ * The values an annotation argument may take, from the `valueScope` hook of its spec
2235
+ * (`undefined` when the argument declares none or the set cannot be determined).
2236
+ */ function getValueCandidates(annotationToken, argIndex, doc) {
2237
+ return getArgSpecAt(annotationToken, argIndex, doc)?.valueScope?.(annotationToken, doc);
2238
+ }
2239
+ /**
2240
+ * The declared value a value-argument token names (`valueScope`), or `undefined` when the token
2241
+ * is not a value argument or names no candidate.
2242
+ */ function getDeclaredValue(token, doc) {
2243
+ if (!token.annotationRef || typeof token.index !== "number" || token.isReference) return;
2244
+ return getValueCandidates(token.annotationRef, token.index, doc)?.find((c) => c.value === token.text);
2245
+ }
2246
+ /**
2247
+ * Field scope of an annotation argument: the answer of the argument spec's `fieldScope`
2248
+ * hook when it declares one, otherwise the deprecated built-in `@db.*` query rules.
2249
+ */ function getQueryScope(argToken, doc) {
2250
+ const argSpec = getArgSpec(argToken, doc);
2251
+ return argSpec?.fieldScope ? argSpec.fieldScope(argToken, doc) : getLegacyDbQueryScope(argToken);
2252
+ }
2253
+ /**
2254
+ * Type a field-path `string` argument names a field of: the `unqualifiedTarget` of the
2255
+ * argument spec's `fieldScope`. `undefined` for any other token.
2256
+ */ function getFieldPathTarget(argToken, doc) {
2257
+ if (argToken.type !== "text") return;
2258
+ const argSpec = getArgSpec(argToken, doc);
2259
+ if (argSpec?.type !== "string" || !argSpec.fieldScope) return;
2260
+ return argSpec.fieldScope(argToken, doc)?.unqualifiedTarget ?? void 0;
2261
+ }
2262
+ /**
2263
+ * Resolve a (possibly dotted) field path of a type to the property it names and the
2264
+ * document that declares that property.
2265
+ */ function resolveFieldPath(doc, typeName, segment) {
2266
+ const chain = segment.path.split(".");
2267
+ const [name] = chain.splice(-1);
2268
+ const parent = doc.unwindType(typeName, chain);
2269
+ if (!parent || !(isStructure(parent.def) || isInterface(parent.def))) return;
2270
+ const prop = parent.def.props.get(name);
2271
+ return prop && {
2272
+ typeName,
2273
+ range: segment.range,
2274
+ prop,
2275
+ doc: parent.doc
2276
+ };
2277
+ }
2278
+ /**
2279
+ * Segments of a field-path string argument (`'address.city'` → `address`, `city`), with
2280
+ * ranges that exclude the quotes. A string spanning several lines is a single segment.
2281
+ */ function fieldPathSegments(argToken) {
2282
+ const { text, range } = argToken;
2283
+ if (range.start.line !== range.end.line) return [{
2284
+ path: text,
2285
+ range
2286
+ }];
2287
+ const line = range.start.line;
2288
+ const contentStart = range.start.character + 1;
2289
+ const segments = [];
2290
+ let start = 0;
2291
+ for (const part of text.split(".")) {
2292
+ const end = start + part.length;
2293
+ segments.push({
2294
+ path: text.slice(0, end),
2295
+ range: {
2296
+ start: {
2297
+ line,
2298
+ character: contentStart + start
2299
+ },
2300
+ end: {
2301
+ line,
2302
+ character: contentStart + end
2303
+ }
2304
+ }
2305
+ });
2306
+ start = end + 1;
2307
+ }
2308
+ return segments;
2309
+ }
2310
+ /** The segment under `character`, or the last segment when `character` is omitted. */ function fieldPathSegmentAt(argToken, character) {
2311
+ const segments = fieldPathSegments(argToken);
2312
+ return (character === void 0 ? void 0 : segments.find((s) => s.range.end.character >= character)) ?? segments[segments.length - 1];
2313
+ }
2314
+ /**
2315
+ * Resolve a field reference token to the property it names:
2316
+ * - a field ref inside a `query` argument (`amount`, `Customer.name` in backticks);
2317
+ * - a `string` argument whose spec declares `fieldScope`: a (dotted) field path of the
2318
+ * scope's `unqualifiedTarget`. With `character` (a cursor column), the path resolves
2319
+ * only up to the segment under the cursor — `'address.city'` with the cursor on
2320
+ * `address` resolves `address` — and `range` is that segment's range.
2321
+ *
2322
+ * Returns `undefined` for any other token, or when the scope or the path does not resolve.
2323
+ */ function resolveFieldRefAt(token, doc, character) {
2324
+ if (isQueryFieldRef(token.parentNode)) {
2325
+ const { fieldRef, typeRef, queryArgToken } = token.parentNode;
2326
+ const scope = token === fieldRef && queryArgToken ? getQueryScope(queryArgToken, doc) : void 0;
2327
+ const typeName = scope && (typeRef?.text ?? scope.unqualifiedTarget);
2328
+ return typeName ? resolveFieldPath(doc, typeName, {
2329
+ path: token.text,
2330
+ range: token.range
2331
+ }) : void 0;
2332
+ }
2333
+ const typeName = getFieldPathTarget(token, doc);
2334
+ return typeName ? resolveFieldPath(doc, typeName, fieldPathSegmentAt(token, character)) : void 0;
2335
+ }
2336
+ /**
2337
+ * Resolve the segments named `fieldName` of a field-path `string` argument
2338
+ * (`'address.city'` has the segments `address` and `city`). Supports find-references.
2339
+ */ function resolveFieldPathArgSegments(argToken, doc, fieldName) {
2340
+ const segments = fieldPathSegments(argToken).filter((s) => s.path === fieldName || s.path.endsWith(`.${fieldName}`));
2341
+ const typeName = segments.length > 0 ? getFieldPathTarget(argToken, doc) : void 0;
2342
+ if (!typeName) return [];
2343
+ const targets = [];
2344
+ for (const segment of segments) {
2345
+ const target = resolveFieldPath(doc, typeName, segment);
2346
+ if (target) targets.push(target);
2347
+ }
2348
+ return targets;
2349
+ }
2350
+ /**
2351
+ * Resolve a query field ref node to a property definition.
2352
+ */ function resolveQueryFieldRef(fieldRefNode, doc, scope) {
2353
+ const typeName = fieldRefNode.typeRef?.text ?? scope.unqualifiedTarget;
2354
+ const { fieldRef } = fieldRefNode;
2355
+ const resolved = typeName ? resolveFieldPath(doc, typeName, {
2356
+ path: fieldRef.text,
2357
+ range: fieldRef.range
2358
+ }) : void 0;
2359
+ return resolved && {
2360
+ targetUri: resolved.doc.id,
2361
+ doc: resolved.doc,
2362
+ prop: resolved.prop
2363
+ };
2364
+ }
2365
+ /**
2366
+ * Get fields available for a type (resolving extends/intersections).
2367
+ * With `chain`, returns the fields of the nested object that field path leads to.
2368
+ */ function getFieldsForType(doc, typeName, chain = []) {
2369
+ const unwound = doc.unwindType(typeName, chain);
2370
+ if (!unwound?.def) return [];
2371
+ let def = unwound.doc.mergeIntersection(unwound.def);
2372
+ if (isInterface(def)) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
2373
+ if (isStructure(def) || isInterface(def)) return Array.from(def.props.values());
2374
+ return [];
2375
+ }
2376
+ /**
2377
+ * Completion scope of a field-path `string` argument (spec declares `fieldScope`) at the
2378
+ * cursor column `character`: the fields of the level being typed — `'address.ci'` offers
2379
+ * the fields of `address` (`chain` = `['address']`).
2380
+ */ function getFieldPathCompletionScope(argToken, doc, character) {
2381
+ const typeName = getFieldPathTarget(argToken, doc);
2382
+ if (!typeName) return;
2383
+ const chain = fieldPathSegmentAt(argToken, character).path.split(".").slice(0, -1);
2384
+ return {
1623
2385
  typeName,
1624
2386
  chain,
1625
2387
  fields: getFieldsForType(doc, typeName, chain)
@@ -1636,14 +2398,6 @@ function getArgSpec(argToken, doc) {
1636
2398
  getFields: (typeName) => getFieldsForType(doc, typeName)
1637
2399
  };
1638
2400
  }
1639
- const SYMBOLIC_OPS$1 = new Set([
1640
- "=",
1641
- "!=",
1642
- ">",
1643
- ">=",
1644
- "<",
1645
- "<="
1646
- ]);
1647
2401
  const KEYWORD_OPS = new Set([
1648
2402
  "in",
1649
2403
  "matches",
@@ -1654,18 +2408,14 @@ const LOGICAL_KEYWORDS = new Set([
1654
2408
  "or",
1655
2409
  "not"
1656
2410
  ]);
1657
- const VALUE_KEYWORDS$1 = new Set([
1658
- "true",
1659
- "false",
1660
- "null",
1661
- "undefined"
1662
- ]);
1663
2411
  /**
1664
2412
  * Analyze text inside backticks up to cursor position
1665
2413
  * to determine what kind of completions to offer.
1666
2414
  * Uses lightweight text scanning, not full AST parsing,
1667
2415
  * so it works on incomplete/mid-typing input.
1668
- */ function analyzeQueryCursorContext(textBeforeCursor) {
2416
+ *
2417
+ * `mode` selects the grammar of the argument (default `query`).
2418
+ */ function analyzeQueryCursorContext(textBeforeCursor, mode = "query") {
1669
2419
  const trimmed = textBeforeCursor.trimEnd();
1670
2420
  const hasTrailingSpace = textBeforeCursor.length > trimmed.length;
1671
2421
  if (trimmed.length === 0) return { type: "field-start" };
@@ -1678,18 +2428,19 @@ const VALUE_KEYWORDS$1 = new Set([
1678
2428
  };
1679
2429
  return { type: "field-start" };
1680
2430
  }
2431
+ if (mode !== "query") return analyzeArgCursorContext(trimmed, hasTrailingSpace, mode);
1681
2432
  const tokens = tokenizeQueryText(trimmed);
1682
2433
  if (tokens.length === 0) return { type: "field-start" };
1683
2434
  const last = tokens[tokens.length - 1];
1684
2435
  if (LOGICAL_KEYWORDS.has(last) || last === "(") return { type: "field-start" };
1685
- if (SYMBOLIC_OPS$1.has(last)) return { type: "after-operator" };
2436
+ if (SYMBOLIC_OPS.has(last)) return { type: "after-operator" };
1686
2437
  if (last === "in" || last === "matches") return { type: "after-operator" };
1687
2438
  if (last === "exists") return { type: "after-comparison" };
1688
- if (VALUE_KEYWORDS$1.has(last)) return { type: "after-comparison" };
2439
+ if (VALUE_KEYWORDS.has(last)) return { type: "after-comparison" };
1689
2440
  if (/^['"]/.test(last) || /^\d/.test(last)) return { type: "after-comparison" };
1690
2441
  if (tokens.length >= 2) {
1691
2442
  const prev = tokens[tokens.length - 2];
1692
- if (SYMBOLIC_OPS$1.has(prev) || KEYWORD_OPS.has(prev)) return { type: "after-comparison" };
2443
+ if (SYMBOLIC_OPS.has(prev) || KEYWORD_OPS.has(prev)) return { type: "after-comparison" };
1693
2444
  }
1694
2445
  if (/^\w+$/u.test(last)) {
1695
2446
  if (!hasTrailingSpace) return { type: "field-start" };
@@ -1697,10 +2448,30 @@ const VALUE_KEYWORDS$1 = new Set([
1697
2448
  }
1698
2449
  return { type: "field-start" };
1699
2450
  }
2451
+ const ARITHMETIC_OPS = new Set(BACKTICK_ARG_VOCABULARY.arithmeticOps);
2452
+ /** An order key (an identifier other than `asc` / `desc`). */ function isOrderKey(token) {
2453
+ return token !== void 0 && /^\w+$/u.test(token) && !ORDER_DIRECTIONS.has(token);
2454
+ }
2455
+ /**
2456
+ * Cursor context inside an `expr` or `order` argument — `trimmed` is the
2457
+ * non-empty text before the cursor that does not end with `.`.
2458
+ */ function analyzeArgCursorContext(trimmed, hasTrailingSpace, mode) {
2459
+ const tokens = tokenizeQueryText(trimmed, true);
2460
+ const last = tokens[tokens.length - 1];
2461
+ if (last === void 0 || last === "," || last === "(" || ARITHMETIC_OPS.has(last)) return { type: "field-start" };
2462
+ if (mode === "order") {
2463
+ if (!/^\w+$/u.test(last)) return { type: "after-order-direction" };
2464
+ if (!hasTrailingSpace) return isOrderKey(tokens[tokens.length - 2]) ? { type: "after-order-key" } : { type: "field-start" };
2465
+ return isOrderKey(last) ? { type: "after-order-key" } : { type: "after-order-direction" };
2466
+ }
2467
+ if (/^[a-z_$]\w*$/iu.test(last) && !hasTrailingSpace) return { type: "field-start" };
2468
+ return { type: "after-operand" };
2469
+ }
1700
2470
  /**
1701
2471
  * Simple tokenizer for query text — splits into identifiers, operators, and punctuation.
1702
2472
  * Does NOT need to handle all edge cases; just enough for cursor context analysis.
1703
- */ function tokenizeQueryText(text) {
2473
+ * With `arithmetic`, `+ - * /` are tokens too (otherwise they are skipped).
2474
+ */ function tokenizeQueryText(text, arithmetic = false) {
1704
2475
  const tokens = [];
1705
2476
  let i = 0;
1706
2477
  while (i < text.length) {
@@ -1727,7 +2498,7 @@ const VALUE_KEYWORDS$1 = new Set([
1727
2498
  continue;
1728
2499
  }
1729
2500
  }
1730
- if ("=><(),".includes(text[i])) {
2501
+ if ("=><(),".includes(text[i]) || arithmetic && ARITHMETIC_OPS.has(text[i])) {
1731
2502
  tokens.push(text[i]);
1732
2503
  i++;
1733
2504
  continue;
@@ -1751,7 +2522,7 @@ const VALUE_KEYWORDS$1 = new Set([
1751
2522
 
1752
2523
  //#endregion
1753
2524
  //#region packages/core/src/parser/id-registry.ts
1754
- function _define_property$7(obj, key, value) {
2525
+ function _define_property$6(obj, key, value) {
1755
2526
  if (key in obj) Object.defineProperty(obj, key, {
1756
2527
  value,
1757
2528
  enumerable: true,
@@ -1789,11 +2560,11 @@ var IdRegistry = class {
1789
2560
  }))];
1790
2561
  }
1791
2562
  constructor(globalTypes = []) {
1792
- _define_property$7(this, "reserved", void 0);
1793
- _define_property$7(this, "globalTypes", void 0);
1794
- _define_property$7(this, "definitions", /* @__PURE__ */ new Map());
1795
- _define_property$7(this, "duplicates", /* @__PURE__ */ new Set());
1796
- _define_property$7(this, "forbidden", /* @__PURE__ */ new Set());
2563
+ _define_property$6(this, "reserved", void 0);
2564
+ _define_property$6(this, "globalTypes", void 0);
2565
+ _define_property$6(this, "definitions", /* @__PURE__ */ new Map());
2566
+ _define_property$6(this, "duplicates", /* @__PURE__ */ new Set());
2567
+ _define_property$6(this, "forbidden", /* @__PURE__ */ new Set());
1797
2568
  this.reserved = new Set([
1798
2569
  "interface",
1799
2570
  "type",
@@ -1807,137 +2578,6 @@ var IdRegistry = class {
1807
2578
  }
1808
2579
  };
1809
2580
 
1810
- //#endregion
1811
- //#region packages/core/src/parser/iterator.ts
1812
- function _define_property$6(obj, key, value) {
1813
- if (key in obj) Object.defineProperty(obj, key, {
1814
- value,
1815
- enumerable: true,
1816
- configurable: true,
1817
- writable: true
1818
- });
1819
- else obj[key] = value;
1820
- return obj;
1821
- }
1822
- var NodeIterator = class NodeIterator {
1823
- get index() {
1824
- return this.i;
1825
- }
1826
- get lastNode() {
1827
- return this.nodes[this.nodes.length - 1];
1828
- }
1829
- unexpectedEOB() {
1830
- this.issues.unexpectedEOB = true;
1831
- }
1832
- unfork(fork) {
1833
- this.i = fork.index;
1834
- this.update();
1835
- }
1836
- accepted() {
1837
- if (this.$ && this.$.accepted !== false) {
1838
- this.$.accepted = true;
1839
- this.badNodes.delete(this.$);
1840
- }
1841
- }
1842
- toString() {
1843
- return this.$ ? `[${this.$.type}] ${this.$.text}` : `void`;
1844
- }
1845
- update() {
1846
- this.$ = this.nodes[this.i];
1847
- return this;
1848
- }
1849
- move(v = 1) {
1850
- this.i += v;
1851
- this.$ = this.nodes[this.i];
1852
- return this;
1853
- }
1854
- next(skip) {
1855
- return this.fork().move().skip(skip);
1856
- }
1857
- fork(nodes) {
1858
- return new NodeIterator(nodes || this.nodes, this.messages, this.badNodes, this.issues, nodes ? this.$ : this.parent, nodes ? 0 : this.i).update();
1859
- }
1860
- skip(pun) {
1861
- while (this.$?.type === "comment" || this.$?.type === "punctuation" && pun?.length && pun.includes(this.$.text)) this.move();
1862
- return this;
1863
- }
1864
- skipUntil(pun) {
1865
- while (this.$ && !this.satisfies({
1866
- node: "punctuation",
1867
- text: pun
1868
- })) this.move();
1869
- }
1870
- unexpected(force = false, msg = "Unexpected token") {
1871
- if (force && this.$) this.$.accepted = false;
1872
- if (this.$ && !this.badNodes.has(this.$)) this.badNodes.set(this.$, msg);
1873
- }
1874
- shouldHaveError(depth) {
1875
- for (let i = this.i; i <= depth; i++) if (i < this.nodes.length) this.nodes[i].accepted = false;
1876
- }
1877
- nodesLeft() {
1878
- return this.nodes.length > 0 && this.index < this.nodes.length;
1879
- }
1880
- satisfies(...rules) {
1881
- for (const rule of rules) {
1882
- const passed = Array.isArray(rule.node) ? rule.node.includes(this.$?.type) : this.$?.type === rule.node;
1883
- if (passed && rule.text === void 0) return true;
1884
- if (passed && Array.isArray(rule.text) ? rule.text.includes(this.$?.text) : this.$?.text === rule.text) return true;
1885
- }
1886
- return false;
1887
- }
1888
- confirmIssues() {
1889
- if (this.issues.unexpectedEOB) {
1890
- const pos = (this.lastNode || this.parent)?.getRange().end || {
1891
- character: 1,
1892
- line: 1
1893
- };
1894
- this.messages.push({
1895
- severity: 1,
1896
- message: `Unexpected end of block`,
1897
- range: {
1898
- start: pos,
1899
- end: pos
1900
- }
1901
- });
1902
- this.issues.unexpectedEOB = false;
1903
- }
1904
- }
1905
- getErrors() {
1906
- this.badNodes.forEach((msg, node) => {
1907
- if (node.accepted) this.badNodes.delete(node);
1908
- });
1909
- return Array.from(this.badNodes.entries(), ([node, msg]) => ({
1910
- severity: 1,
1911
- message: msg,
1912
- range: node.getRange?.() || {
1913
- start: {
1914
- character: 1,
1915
- line: 1
1916
- },
1917
- end: {
1918
- character: 1,
1919
- line: 1
1920
- }
1921
- }
1922
- })).concat(this.messages);
1923
- }
1924
- constructor(nodes, messages = [], badNodes = /* @__PURE__ */ new Map(), issues = {}, parent, i = -1) {
1925
- _define_property$6(this, "nodes", void 0);
1926
- _define_property$6(this, "messages", void 0);
1927
- _define_property$6(this, "badNodes", void 0);
1928
- _define_property$6(this, "issues", void 0);
1929
- _define_property$6(this, "parent", void 0);
1930
- _define_property$6(this, "i", void 0);
1931
- _define_property$6(this, "$", void 0);
1932
- this.nodes = nodes;
1933
- this.messages = messages;
1934
- this.badNodes = badNodes;
1935
- this.issues = issues;
1936
- this.parent = parent;
1937
- this.i = i;
1938
- }
1939
- };
1940
-
1941
2581
  //#endregion
1942
2582
  //#region packages/core/src/tokenizer/tokens/a-identifier.token.ts
1943
2583
  /**
@@ -2093,6 +2733,33 @@ const block$1 = new _prostojs_parser.Node({
2093
2733
  }
2094
2734
  });
2095
2735
 
2736
+ //#endregion
2737
+ //#region packages/core/src/tokenizer/tokens/query-arith.token.ts
2738
+ /**
2739
+ * Arithmetic operator token — `*` and `-` inside backtick expressions
2740
+ * (`+` and `/` are already generic punctuation).
2741
+ *
2742
+ * Registered after `NumberToken`, so a sign written adjacent to a number
2743
+ * (`-5`, `+1`) still lexes as a signed number; the expression parser splits a
2744
+ * signed number found in binary-operator position (`a -5` → `a - 5`).
2745
+ * Only recognized inside queries — not in root or generic blocks.
2746
+ */ const QueryArithmeticToken = new _prostojs_parser.Node({
2747
+ name: "punctuation",
2748
+ start: {
2749
+ token: RegExp("(?<text>[*-])", "u"),
2750
+ omit: true
2751
+ },
2752
+ end: {
2753
+ token: "",
2754
+ omit: true
2755
+ },
2756
+ eofClose: true,
2757
+ data: {
2758
+ type: "punctuation",
2759
+ text: ""
2760
+ }
2761
+ });
2762
+
2096
2763
  //#endregion
2097
2764
  //#region packages/core/src/tokenizer/tokens/query-block.token.ts
2098
2765
  /**
@@ -2146,43 +2813,54 @@ const block$1 = new _prostojs_parser.Node({
2146
2813
  omit: true
2147
2814
  },
2148
2815
  end: {
2149
- token: /`/u,
2150
- omit: true
2151
- },
2152
- skip: /\s/u,
2153
- eofClose: true,
2154
- data: {
2155
- type: "query",
2156
- text: ""
2157
- }
2158
- });
2159
-
2160
- //#endregion
2161
- //#region packages/core/src/tokenizer/tokens/regexp.token.ts
2162
- const REGEXP_LITERAL_RE = /\/(?![/*])(?:\\.|\[.*?]|[^/\\\n\r[])*\/[dgimsuy]*/;
2163
- /**
2164
- * RegExp literal – `/pattern/flags`
2165
- * • Starts with `/` but *not* `//` or `/*`
2166
- * • Ends with `/` followed by zero-or-more valid flags
2167
- */ const RegExpToken = new _prostojs_parser.Node({
2168
- name: "regexp",
2169
- start: {
2170
- token: REGEXP_LITERAL_RE,
2171
- omit: true
2172
- },
2173
- end: {
2174
- token: "",
2816
+ token: /`/u,
2175
2817
  omit: true
2176
2818
  },
2819
+ skip: /\s/u,
2177
2820
  eofClose: true,
2178
2821
  data: {
2179
- type: "regexp",
2822
+ type: "query",
2180
2823
  text: ""
2181
2824
  }
2182
- }).onOpen((node, match) => {
2183
- node.data.text = match?.text ?? "";
2184
2825
  });
2185
2826
 
2827
+ //#endregion
2828
+ //#region packages/core/src/tokenizer/tokens/regexp.token.ts
2829
+ const REGEXP_LITERAL_RE = /\/(?![/*])(?:\\.|\[.*?]|[^/\\\n\r[])*\/[dgimsuy]*/;
2830
+ /**
2831
+ * Regexp literal inside a backtick expression: only directly after the
2832
+ * `matches` keyword (the one operator that takes a regexp), so `/` elsewhere
2833
+ * stays the division operator (`a / b / c` is not the regexp `/ b /`).
2834
+ * The lookbehind works because the parser scans the full source from the
2835
+ * current position.
2836
+ */ const QUERY_REGEXP_LITERAL_RE = new RegExp(`(?<=\\bmatches\\s*)${REGEXP_LITERAL_RE.source}`);
2837
+ /** A regexp-literal token node starting at `start`. */ function regExpNode(start) {
2838
+ return new _prostojs_parser.Node({
2839
+ name: "regexp",
2840
+ start: {
2841
+ token: start,
2842
+ omit: true
2843
+ },
2844
+ end: {
2845
+ token: "",
2846
+ omit: true
2847
+ },
2848
+ eofClose: true,
2849
+ data: {
2850
+ type: "regexp",
2851
+ text: ""
2852
+ }
2853
+ }).onOpen((node, match) => {
2854
+ node.data.text = match?.text ?? "";
2855
+ });
2856
+ }
2857
+ /**
2858
+ * RegExp literal – `/pattern/flags`
2859
+ * • Starts with `/` but *not* `//` or `/*`
2860
+ * • Ends with `/` followed by zero-or-more valid flags
2861
+ */ const RegExpToken = regExpNode(REGEXP_LITERAL_RE);
2862
+ /** RegExp literal inside backtick expressions — recognized only after `matches`. */ const QueryRegExpToken = regExpNode(QUERY_REGEXP_LITERAL_RE);
2863
+
2186
2864
  //#endregion
2187
2865
  //#region packages/core/src/tokenizer/tokens/text.node.ts
2188
2866
  /**
@@ -2244,8 +2922,8 @@ const root = new _prostojs_parser.Node({
2244
2922
  });
2245
2923
  tokens.root = root;
2246
2924
  BlockToken.recognize(RegExpToken, ...commentNodes.all, BlockToken, QueryToken, AIdentifierToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2247
- QueryToken.recognize(RegExpToken, QueryOperatorToken, QueryBlockToken, BlockToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2248
- QueryBlockToken.recognize(RegExpToken, QueryOperatorToken, QueryBlockToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2925
+ QueryToken.recognize(QueryRegExpToken, QueryOperatorToken, QueryBlockToken, BlockToken, IdentifierToken, TextToken, NumberToken, QueryArithmeticToken, PunctuationToken);
2926
+ QueryBlockToken.recognize(QueryRegExpToken, QueryOperatorToken, QueryBlockToken, IdentifierToken, TextToken, NumberToken, QueryArithmeticToken, PunctuationToken);
2249
2927
  /** 1-based parser position → 0-based VSCode position, shifted by `offset` characters. */ function toPos(p, offset = 0) {
2250
2928
  return {
2251
2929
  line: p.line - 1,
@@ -2457,373 +3135,93 @@ function $pipe(entity, pipe = []) {
2457
3135
  this.stopCondition = sc;
2458
3136
  return this;
2459
3137
  },
2460
- t(node, skip = []) {
2461
- this.pipe.push($token(node).saveAs("identifier").skip(...skip));
2462
- return this;
2463
- }
2464
- };
2465
- }
2466
- function runPipes(pipes, ni, singlePass = false) {
2467
- const nodes = [];
2468
- while (ni.$) {
2469
- let matched = true;
2470
- let depth = ni.index;
2471
- for (const { targetFactory, pipe, skipTokens: skip, stopCondition } of pipes) {
2472
- const target = { node: targetFactory() };
2473
- const fork = ni.fork();
2474
- fork.skip(skip);
2475
- if (!fork.$) {
2476
- ni.unfork(fork);
2477
- break;
2478
- }
2479
- matched = true;
2480
- for (const { handler } of pipe) if (!handler(fork, target)) {
2481
- matched = false;
2482
- break;
2483
- }
2484
- if (fork.index > depth) depth = fork.index;
2485
- if (matched) {
2486
- nodes.push(target.node);
2487
- ni.unfork(fork);
2488
- if (stopCondition && stopCondition(fork)) return nodes;
2489
- ni.move(-1);
2490
- break;
2491
- }
2492
- }
2493
- if (singlePass) return nodes;
2494
- if (!matched) {
2495
- ni.shouldHaveError(depth);
2496
- ni.move(depth - ni.index);
2497
- }
2498
- ni.move();
2499
- if (matched) {} else {
2500
- ni.confirmIssues();
2501
- ni.skipUntil([";", "\n"]);
2502
- }
2503
- }
2504
- return nodes;
2505
- }
2506
- function runPipesOnce(pipes, ni) {
2507
- return runPipes(pipes, ni, true)[0];
2508
- }
2509
-
2510
- //#endregion
2511
- //#region packages/core/src/parser/grouping.ts
2512
- function groupByPriority(nodes, priority) {
2513
- if (nodes.length === 1) return nodes[0];
2514
- if (nodes.length === 0) return;
2515
- if (nodes.length % 2 === 0) throw new Error(`Invalid number of nodes ${nodes.length}. Odd number expected`);
2516
- let currentPass = nodes;
2517
- let temporaryResult = [];
2518
- let groupped = [];
2519
- for (const p of priority) {
2520
- for (const [i, node] of currentPass.entries()) {
2521
- const isOperator = i % 2 === 1;
2522
- if (!isOperator && node instanceof Token) throw new Error(`Unexpected token ${node.toString()} at ${i}`);
2523
- else if (isOperator && !(node instanceof Token)) throw new Error(`Unexpected token ${isGroup(node) ? node.op : node.token.toString()} at ${i}`);
2524
- if (isOperator) {
2525
- if (node.text !== p) temporaryResult.push(node);
2526
- continue;
2527
- }
2528
- const prev = currentPass[i - 1]?.text;
2529
- const next = currentPass[i + 1]?.text;
2530
- if (prev !== p && next !== p) {
2531
- temporaryResult.push(node);
2532
- continue;
2533
- }
2534
- if (prev === p || next === p) {
2535
- groupped.push(node);
2536
- if (next !== p) {
2537
- temporaryResult.push(new $n.SemanticGroup(groupped, p));
2538
- groupped = [];
2539
- }
2540
- }
2541
- }
2542
- currentPass = temporaryResult;
2543
- temporaryResult = [];
2544
- }
2545
- const output = currentPass[0];
2546
- return output.length === 1 ? output.first : output;
2547
- }
2548
-
2549
- //#endregion
2550
- //#region packages/core/src/parser/pipes/query.pipe.ts
2551
- const SYMBOLIC_OPS = new Set([
2552
- "=",
2553
- "!=",
2554
- ">",
2555
- ">=",
2556
- "<",
2557
- "<="
2558
- ]);
2559
- const VALUE_KEYWORDS = new Set([
2560
- "true",
2561
- "false",
2562
- "null",
2563
- "undefined"
2564
- ]);
2565
- const ZERO_RANGE = {
2566
- start: {
2567
- line: 0,
2568
- character: 0
2569
- },
2570
- end: {
2571
- line: 0,
2572
- character: 0
2573
- }
2574
- };
2575
- /**
2576
- * Parse a backtick-delimited query expression.
2577
- *
2578
- * `ni` iterates the query token's children and carries that token as its
2579
- * `parent` — the range to blame when a diagnostic has no token of its own —
2580
- * so fork it from the annotation iterator while the query token is current.
2581
- * Returns a SemanticQueryNode or undefined if the content is empty.
2582
- */ function parseQueryExpression(ni, sourceToken) {
2583
- if (!ni.$) return;
2584
- const expr = parseOrExpr(ni);
2585
- if (!expr) return;
2586
- if (ni.$) pushError(ni, `Unexpected token in query expression: "${ni.$.text}"`);
2587
- const node = new SemanticQueryNode();
2588
- node.expression = expr;
2589
- node.sourceToken = sourceToken;
2590
- return node;
2591
- }
2592
- function parseOrExpr(ni) {
2593
- const left = parseAndExpr(ni);
2594
- if (!left) return;
2595
- const operands = [left];
2596
- while (ni.$?.type === "identifier" && ni.$.text === "or") {
2597
- ni.move();
2598
- const right = parseAndExpr(ni);
2599
- if (!right) {
2600
- pushError(ni, "Expected expression after \"or\"");
2601
- break;
2602
- }
2603
- operands.push(right);
2604
- }
2605
- if (operands.length === 1) return operands[0];
2606
- const node = new SemanticQueryLogicalNode();
2607
- node.operator = "or";
2608
- node.operands = operands;
2609
- return node;
2610
- }
2611
- function parseAndExpr(ni) {
2612
- const left = parseUnaryExpr(ni);
2613
- if (!left) return;
2614
- const operands = [left];
2615
- while (ni.$?.type === "identifier" && ni.$.text === "and") {
2616
- ni.move();
2617
- const right = parseUnaryExpr(ni);
2618
- if (!right) {
2619
- pushError(ni, "Expected expression after \"and\"");
2620
- break;
2621
- }
2622
- operands.push(right);
2623
- }
2624
- if (operands.length === 1) return operands[0];
2625
- const node = new SemanticQueryLogicalNode();
2626
- node.operator = "and";
2627
- node.operands = operands;
2628
- return node;
2629
- }
2630
- function parseUnaryExpr(ni) {
2631
- if (ni.$?.type === "identifier" && ni.$.text === "not") {
2632
- ni.move();
2633
- const operand = parseUnaryExpr(ni);
2634
- if (!operand) {
2635
- pushError(ni, "Expected expression after \"not\"");
2636
- return;
2637
- }
2638
- const node = new SemanticQueryLogicalNode();
2639
- node.operator = "not";
2640
- node.operands = [operand];
2641
- return node;
2642
- }
2643
- if (ni.$?.type === "block" && ni.$.text === "(") {
2644
- const subNi = ni.fork(ni.$.children || []);
2645
- ni.move();
2646
- if (!subNi.$) {
2647
- pushError(subNi, "Empty parenthesized expression");
2648
- return;
2649
- }
2650
- const expr = parseOrExpr(subNi);
2651
- if (subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
2652
- return expr;
2653
- }
2654
- return parseComparison(ni);
2655
- }
2656
- function parseComparison(ni) {
2657
- const left = parseFieldRef(ni);
2658
- if (!left) return;
2659
- if (ni.$?.type === "punctuation" && SYMBOLIC_OPS.has(ni.$.text)) {
2660
- const opText = ni.$.text;
2661
- ni.move();
2662
- const right = parseValueOrFieldRef(ni);
2663
- if (!right) {
2664
- pushError(ni, `Expected value or field reference after "${opText}"`);
2665
- return;
2666
- }
2667
- const node = new SemanticQueryComparisonNode();
2668
- node.left = left;
2669
- node.operator = opText;
2670
- node.right = right;
2671
- return node;
2672
- }
2673
- if (ni.$?.type === "identifier") {
2674
- const opText = ni.$.text;
2675
- if (opText === "in") {
2676
- ni.move();
2677
- const right = parseValueList(ni);
2678
- if (!right) return;
2679
- const node = new SemanticQueryComparisonNode();
2680
- node.left = left;
2681
- node.operator = "in";
2682
- node.right = right;
2683
- return node;
2684
- }
2685
- if (opText === "matches") {
2686
- ni.move();
2687
- const right = parseValueOrFieldRef(ni);
2688
- if (!right) {
2689
- pushError(ni, "Expected value after \"matches\"");
2690
- return;
3138
+ t(node, skip = []) {
3139
+ this.pipe.push($token(node).saveAs("identifier").skip(...skip));
3140
+ return this;
3141
+ }
3142
+ };
3143
+ }
3144
+ function runPipes(pipes, ni, singlePass = false) {
3145
+ const nodes = [];
3146
+ while (ni.$) {
3147
+ let matched = true;
3148
+ let depth = ni.index;
3149
+ for (const { targetFactory, pipe, skipTokens: skip, stopCondition } of pipes) {
3150
+ const target = { node: targetFactory() };
3151
+ const fork = ni.fork();
3152
+ fork.skip(skip);
3153
+ if (!fork.$) {
3154
+ ni.unfork(fork);
3155
+ break;
3156
+ }
3157
+ matched = true;
3158
+ for (const { handler } of pipe) if (!handler(fork, target)) {
3159
+ matched = false;
3160
+ break;
3161
+ }
3162
+ if (fork.index > depth) depth = fork.index;
3163
+ if (matched) {
3164
+ nodes.push(target.node);
3165
+ ni.unfork(fork);
3166
+ if (stopCondition && stopCondition(fork)) return nodes;
3167
+ ni.move(-1);
3168
+ break;
2691
3169
  }
2692
- const node = new SemanticQueryComparisonNode();
2693
- node.left = left;
2694
- node.operator = "matches";
2695
- node.right = right;
2696
- return node;
2697
3170
  }
2698
- if (opText === "exists") {
2699
- ni.move();
2700
- const node = new SemanticQueryComparisonNode();
2701
- node.left = left;
2702
- node.operator = "exists";
2703
- return node;
3171
+ if (singlePass) return nodes;
3172
+ if (!matched) {
3173
+ ni.shouldHaveError(depth);
3174
+ ni.move(depth - ni.index);
2704
3175
  }
2705
- if (opText === "not") return parseNotComparison(ni, left);
2706
- pushError(ni, `Unknown operator "${opText}"`);
2707
- return;
2708
- }
2709
- pushError(ni, "Expected operator after field reference");
2710
- }
2711
- function parseNotComparison(ni, left) {
2712
- ni.move();
2713
- if (ni.$?.type === "identifier" && ni.$.text === "in") {
2714
- ni.move();
2715
- const right = parseValueList(ni);
2716
- if (!right) return;
2717
- const node = new SemanticQueryComparisonNode();
2718
- node.left = left;
2719
- node.operator = "not in";
2720
- node.right = right;
2721
- return node;
2722
- }
2723
- if (ni.$?.type === "identifier" && ni.$.text === "exists") {
2724
- ni.move();
2725
- const node = new SemanticQueryComparisonNode();
2726
- node.left = left;
2727
- node.operator = "not exists";
2728
- return node;
2729
- }
2730
- pushError(ni, "Expected \"in\" or \"exists\" after \"not\"");
2731
- }
2732
- function parseFieldRef(ni) {
2733
- if (ni.$?.type !== "identifier") {
2734
- pushError(ni, "Expected field reference");
2735
- return;
2736
- }
2737
- const firstToken = new Token(ni.$);
2738
- ni.move();
2739
- if (ni.$?.type === "punctuation" && ni.$.text === ".") {
2740
3176
  ni.move();
2741
- if (ni.$?.type === "identifier") {
2742
- const secondToken = new Token(ni.$);
2743
- ni.move();
2744
- let fieldText = secondToken.text;
2745
- while (ni.$?.type === "punctuation" && ni.$.text === ".") {
2746
- ni.move();
2747
- if (ni.$?.type === "identifier") {
2748
- fieldText += `.${ni.$.text}`;
2749
- ni.move();
2750
- } else {
2751
- pushError(ni, "Expected identifier after \".\"");
2752
- break;
2753
- }
2754
- }
2755
- const node = new SemanticQueryFieldRefNode();
2756
- node.typeRef = firstToken;
2757
- node.fieldRef = fieldText === secondToken.text ? secondToken : secondToken.clone({ text: fieldText });
2758
- return node;
3177
+ if (matched) {} else {
3178
+ ni.confirmIssues();
3179
+ ni.skipUntil([";", "\n"]);
2759
3180
  }
2760
- pushError(ni, "Expected identifier after \".\"");
2761
- const node = new SemanticQueryFieldRefNode();
2762
- node.fieldRef = firstToken;
2763
- return node;
2764
- }
2765
- const node = new SemanticQueryFieldRefNode();
2766
- node.fieldRef = firstToken;
2767
- return node;
2768
- }
2769
- function parseValueOrFieldRef(ni) {
2770
- if (!ni.$) return;
2771
- if (ni.$.type === "text" || ni.$.type === "number" || ni.$.type === "regexp") return parseValue(ni);
2772
- if (ni.$.type === "identifier") {
2773
- if (VALUE_KEYWORDS.has(ni.$.text)) return parseValue(ni);
2774
- return parseFieldRef(ni);
2775
3181
  }
2776
- pushError(ni, "Expected value or field reference");
3182
+ return nodes;
2777
3183
  }
2778
- function parseValue(ni) {
2779
- if (!ni.$) {
2780
- pushError(ni, "Expected value");
2781
- return;
2782
- }
2783
- const token = ni.$;
2784
- if (token.type === "text" || token.type === "number" || token.type === "regexp" || token.type === "identifier" && VALUE_KEYWORDS.has(token.text)) {
2785
- const node = new SemanticQueryValueNode();
2786
- node.valueToken = new Token(token);
2787
- ni.move();
2788
- return node;
2789
- }
2790
- pushError(ni, `Unexpected token "${token.text}" where value expected`);
3184
+ function runPipesOnce(pipes, ni) {
3185
+ return runPipes(pipes, ni, true)[0];
2791
3186
  }
2792
- function parseValueList(ni) {
2793
- if (ni.$?.type === "block" && ni.$.text === "(") {
2794
- const subNi = ni.fork(ni.$.children || []);
2795
- ni.move();
2796
- if (!subNi.$) {
2797
- pushError(subNi, "Empty value list in \"in\" expression");
2798
- return;
2799
- }
2800
- const values = [];
2801
- const first = parseValue(subNi);
2802
- if (first) values.push(first);
2803
- while (subNi.$?.type === "punctuation" && subNi.$.text === ",") {
2804
- subNi.move();
2805
- const v = parseValue(subNi);
2806
- if (v) values.push(v);
3187
+
3188
+ //#endregion
3189
+ //#region packages/core/src/parser/grouping.ts
3190
+ function groupByPriority(nodes, priority) {
3191
+ if (nodes.length === 1) return nodes[0];
3192
+ if (nodes.length === 0) return;
3193
+ if (nodes.length % 2 === 0) throw new Error(`Invalid number of nodes ${nodes.length}. Odd number expected`);
3194
+ let currentPass = nodes;
3195
+ let temporaryResult = [];
3196
+ let groupped = [];
3197
+ for (const p of priority) {
3198
+ for (const [i, node] of currentPass.entries()) {
3199
+ const isOperator = i % 2 === 1;
3200
+ if (!isOperator && node instanceof Token) throw new Error(`Unexpected token ${node.toString()} at ${i}`);
3201
+ else if (isOperator && !(node instanceof Token)) throw new Error(`Unexpected token ${isGroup(node) ? node.op : node.token.toString()} at ${i}`);
3202
+ if (isOperator) {
3203
+ if (node.text !== p) temporaryResult.push(node);
3204
+ continue;
3205
+ }
3206
+ const prev = currentPass[i - 1]?.text;
3207
+ const next = currentPass[i + 1]?.text;
3208
+ if (prev !== p && next !== p) {
3209
+ temporaryResult.push(node);
3210
+ continue;
3211
+ }
3212
+ if (prev === p || next === p) {
3213
+ groupped.push(node);
3214
+ if (next !== p) {
3215
+ temporaryResult.push(new $n.SemanticGroup(groupped, p));
3216
+ groupped = [];
3217
+ }
3218
+ }
2807
3219
  }
2808
- if (subNi.$) pushError(subNi, `Unexpected token in value list: "${subNi.$.text}"`);
2809
- const node = new SemanticQueryValueListNode();
2810
- node.values = values;
2811
- return node;
3220
+ currentPass = temporaryResult;
3221
+ temporaryResult = [];
2812
3222
  }
2813
- pushError(ni, "Expected parenthesized value list after \"in\"");
2814
- }
2815
- /**
2816
- * Range to blame for a diagnostic: the current token, else the enclosing
2817
- * query token / "(...)" block the iterator was forked from.
2818
- */ function rangeOf(ni) {
2819
- return ni.$?.getRange?.() ?? ni.parent?.getRange?.() ?? ZERO_RANGE;
2820
- }
2821
- function pushError(ni, message) {
2822
- ni.messages.push({
2823
- severity: 1,
2824
- message,
2825
- range: rangeOf(ni)
2826
- });
3223
+ const output = currentPass[0];
3224
+ return output.length === 1 ? output.first : output;
2827
3225
  }
2828
3226
 
2829
3227
  //#endregion
@@ -2945,10 +3343,6 @@ function annotations() {
2945
3343
  }
2946
3344
  while (ni.satisfies(...opts.argument)) {
2947
3345
  let argToken = new Token(ni.$);
2948
- if (argToken.type === "query") {
2949
- const queryNode = parseQueryExpression(ni.fork(argToken.children), argToken);
2950
- if (queryNode) argToken.queryNode = queryNode;
2951
- }
2952
3346
  ni.accepted();
2953
3347
  ni.move();
2954
3348
  if (argToken.type === "identifier" && ![
@@ -3475,7 +3869,7 @@ function _define_property$3(obj, key, value) {
3475
3869
  else obj[key] = value;
3476
3870
  return obj;
3477
3871
  }
3478
- var AtscriptDoc = class {
3872
+ var AtscriptDoc = class AtscriptDoc {
3479
3873
  get name() {
3480
3874
  return this.id.split("/").pop();
3481
3875
  }
@@ -3529,7 +3923,8 @@ var AtscriptDoc = class {
3529
3923
  update(text, debug = false) {
3530
3924
  this._text = text;
3531
3925
  this.cleanup();
3532
- const ni = new NodeIterator(tokenize(text, debug), []).move();
3926
+ const rawTokens = tokenize(text, debug);
3927
+ const ni = new NodeIterator(rawTokens, []).move();
3533
3928
  this.nodes = runPipes([
3534
3929
  pipes.importPipe,
3535
3930
  pipes.type,
@@ -3539,6 +3934,43 @@ var AtscriptDoc = class {
3539
3934
  if (debug) console.log(this.nodes.map((n) => n.toString()).join("\n"));
3540
3935
  this.semanticMessages = ni.getErrors();
3541
3936
  this.registerNodes(this.nodes);
3937
+ this.parseUnregisteredBacktickArgs(rawTokens);
3938
+ }
3939
+ /**
3940
+ * Backtick arguments of annotations that never get registered (dangling at
3941
+ * EOF, or followed by a syntax error) are still parsed for diagnostics — by
3942
+ * the argument spec of the preceding annotation when it resolves, else as a
3943
+ * query predicate.
3944
+ */ parseUnregisteredBacktickArgs(tokens) {
3945
+ for (let i = 0; i < tokens.length; i++) {
3946
+ const t = tokens[i];
3947
+ if (t.type === "block" && t.children) {
3948
+ this.parseUnregisteredBacktickArgs(t.children);
3949
+ continue;
3950
+ }
3951
+ if (t.type !== "query" || this.parsedBacktickArgs.has(t)) continue;
3952
+ let argIndex = 0;
3953
+ let annotation;
3954
+ for (let j = i - 1; j >= 0; j--) {
3955
+ const p = tokens[j];
3956
+ if (p.type === "annotation") {
3957
+ annotation = p;
3958
+ break;
3959
+ }
3960
+ if (p.type === "block" || p.type === "punctuation" && (p.text === "\n" || p.text === ";")) break;
3961
+ if (p.type === "punctuation" && p.text === ",") argIndex++;
3962
+ }
3963
+ if (!annotation) continue;
3964
+ this.parseBacktickArgAs(new Token(t), this.resolveAnnotation(annotation.text.slice(1))?.arguments[argIndex]?.type);
3965
+ }
3966
+ }
3967
+ /**
3968
+ * Parse a backtick argument by its spec type: `expr` / `order` get their own
3969
+ * grammar; anything else (unknown annotation, position beyond the spec) parses
3970
+ * as a query predicate.
3971
+ */ parseBacktickArgAs(arg, specType) {
3972
+ this.parsedBacktickArgs.add(arg.lexicalToken);
3973
+ this.registerMessages(parseBacktickArg(arg, isBacktickArgType(specType) ? specType : "query"));
3542
3974
  }
3543
3975
  cleanup() {
3544
3976
  this.exports.clear();
@@ -3556,6 +3988,7 @@ var AtscriptDoc = class {
3556
3988
  this.blocksIndex = new BlocksIndex();
3557
3989
  this.resolvedAnnotations = [];
3558
3990
  this.annotations = [];
3991
+ this.parsedBacktickArgs = /* @__PURE__ */ new WeakSet();
3559
3992
  }
3560
3993
  registerNodes(nodes) {
3561
3994
  for (const node of nodes) {
@@ -3567,18 +4000,30 @@ var AtscriptDoc = class {
3567
4000
  });
3568
4001
  }
3569
4002
  }
4003
+ /**
4004
+ * The document in which the given annotation was written (and whose imports
4005
+ * its type-reference arguments resolve against). Annotations inherited into
4006
+ * another document through a chain ref, `extends` or `annotate` keep the
4007
+ * declaring document. `undefined` for annotations never registered on a doc.
4008
+ */ annotationOrigin(annotation) {
4009
+ return AtscriptDoc.annotationOrigins.get(annotation);
4010
+ }
3570
4011
  registerAnnotation(annotationTokens) {
4012
+ AtscriptDoc.annotationOrigins.set(annotationTokens, this);
3571
4013
  this.annotations.push(annotationTokens);
3572
4014
  const mainToken = annotationTokens.token;
3573
4015
  const args = annotationTokens.args;
3574
4016
  this.tokensIndex.add(mainToken);
3575
4017
  args?.forEach((a) => this.tokensIndex.add(a));
3576
4018
  const annotationSpec = this.resolveAnnotation(mainToken.text.slice(1));
4019
+ const specArgs = annotationSpec?.arguments ?? [];
4020
+ args?.forEach((a, i) => {
4021
+ if (a.type === "query") this.parseBacktickArgAs(a, specArgs[i]?.type);
4022
+ });
3577
4023
  if (annotationSpec) {
3578
4024
  this.registerMessages(annotationSpec.validate(mainToken, args || [], this));
3579
4025
  annotationSpec.modify(mainToken, args || [], this);
3580
4026
  this.resolvedAnnotations.push(mainToken);
3581
- const specArgs = annotationSpec.arguments;
3582
4027
  for (let i = 0; i < (args?.length ?? 0); i++) {
3583
4028
  const argSpec = specArgs[i];
3584
4029
  if (argSpec?.type === "ref" && args?.[i]) {
@@ -3586,6 +4031,7 @@ var AtscriptDoc = class {
3586
4031
  const dotIdx = refToken.text.indexOf(".");
3587
4032
  if (dotIdx > 0) {
3588
4033
  const typeToken = refToken.clone({ text: refToken.text.slice(0, dotIdx) });
4034
+ typeToken.annotationRef = refToken.annotationRef;
3589
4035
  typeToken.isReference = true;
3590
4036
  this.referred.push(typeToken);
3591
4037
  } else {
@@ -3593,7 +4039,7 @@ var AtscriptDoc = class {
3593
4039
  this.referred.push(refToken);
3594
4040
  }
3595
4041
  }
3596
- if (argSpec?.type === "query" && args?.[i]?.queryNode) args[i].queryNode.registerAtDocument(this);
4042
+ if (isBacktickArgType(argSpec?.type)) args?.[i]?.backtickNode?.registerAtDocument(this);
3597
4043
  if (argSpec?.type === "string" && argSpec.fieldScope && args?.[i]) this.fieldPathArgs.push(args[i]);
3598
4044
  }
3599
4045
  } else {
@@ -3737,6 +4183,40 @@ var AtscriptDoc = class {
3737
4183
  return block?.blockType === "annotate" && isAnnotate(block.parentNode) ? block.parentNode : void 0;
3738
4184
  }
3739
4185
  /**
4186
+ * The definition an annotated node stands for, with the document that declares it:
4187
+ * a prop / type declaration's own definition, or — for an `annotate` block entry —
4188
+ * the type of the target property the entry names (`annotate Host { name @x.y }`
4189
+ * → the type of `Host.name`). Plugin hooks use it to introspect the field an
4190
+ * annotation sits on, whether it is written inline or in an annotate block.
4191
+ * `undefined` when the node has no definition or the entry does not resolve.
4192
+ */ annotatedDefinition(node) {
4193
+ if (!node) return;
4194
+ if (!isRef(node)) {
4195
+ const def = node.getDefinition();
4196
+ return def ? {
4197
+ def,
4198
+ doc: this
4199
+ } : void 0;
4200
+ }
4201
+ const idToken = node.token("identifier");
4202
+ const block = idToken ? this.annotateBlockAt(idToken.range.start.line, idToken.range.start.character) : void 0;
4203
+ if (!block) return {
4204
+ def: node,
4205
+ doc: this
4206
+ };
4207
+ const chain = [node.id, ...node.chain.map((c) => c.text)];
4208
+ const unwound = this.unwindType(block.targetName, chain);
4209
+ if (unwound?.def && (!isGroup(unwound.def) || unwound.node?.id === chain.at(-1))) return {
4210
+ def: unwound.def,
4211
+ doc: unwound.doc
4212
+ };
4213
+ const merged = this.resolveChainWithMerge(block.targetName, chain);
4214
+ return merged ? {
4215
+ def: merged,
4216
+ doc: this
4217
+ } : void 0;
4218
+ }
4219
+ /**
3740
4220
  * Collects ad-hoc annotations from all `annotate` blocks targeting a given type/interface.
3741
4221
  * Returns a map of property path (dot-joined) → annotations array.
3742
4222
  * For entries without a chain (root-level), the key is the entry identifier.
@@ -4004,22 +4484,51 @@ var AtscriptDoc = class {
4004
4484
  } : void 0;
4005
4485
  }
4006
4486
  }
4487
+ /** Pushes an "Unknown identifier" error when `t` is not defined; returns whether it was. */ reportUnknownIdentifier(t) {
4488
+ if (this.registry.isDefined(t)) return false;
4489
+ this._allMessages.push({
4490
+ severity: 1,
4491
+ message: `Unknown identifier "${t.text}"`,
4492
+ range: t.range
4493
+ });
4494
+ return true;
4495
+ }
4496
+ /** Definition link from `token` to `target`, or to what the token resolves to when omitted. */ definitionLink(token, target) {
4497
+ const resolved = target ?? this.toRangeTarget(this.getDefinitionFor(token));
4498
+ if (!resolved) return;
4499
+ const range = resolved.range ?? zeroRange;
4500
+ return [{
4501
+ targetUri: resolved.uri,
4502
+ targetRange: range,
4503
+ targetSelectionRange: range,
4504
+ originSelectionRange: token.range
4505
+ }];
4506
+ }
4507
+ toRangeTarget(def) {
4508
+ return def && {
4509
+ uri: def.uri,
4510
+ range: def.token?.range
4511
+ };
4512
+ }
4007
4513
  getToDefinitionAt(line, character) {
4008
4514
  const token = this.tokensIndex.at(line, character);
4009
4515
  if (token) {
4516
+ if (token.annotationRef && token.isReference) return this.definitionLink(token);
4517
+ const declared = getDeclaredValue(token, this)?.definition;
4518
+ if (declared) return this.definitionLink(token, {
4519
+ uri: declared.doc.id,
4520
+ range: declared.token.range
4521
+ });
4010
4522
  const annotateBlock = this.annotateBlockAt(line, character);
4011
4523
  if (annotateBlock && isRef(token.parentNode)) {
4012
4524
  const targetName = annotateBlock.targetName;
4013
4525
  const entryRef = token.parentNode;
4014
4526
  const chain = token.isChain && typeof token.index === "number" ? [entryRef.id, ...entryRef.chain.slice(0, token.index).map((c) => c.text)] : [token.text];
4015
4527
  const unwound = this.unwindType(targetName, chain);
4016
- if (unwound?.node) return [{
4017
- targetUri: unwound.doc.id,
4018
- targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
4019
- targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
4020
- originSelectionRange: token.range
4021
- }];
4022
- return;
4528
+ return unwound?.node ? this.definitionLink(token, {
4529
+ uri: unwound.doc.id,
4530
+ range: unwound.node.token("identifier")?.range
4531
+ }) : void 0;
4023
4532
  }
4024
4533
  const fieldRef = resolveFieldRefAt(token, this, character);
4025
4534
  if (fieldRef) {
@@ -4033,41 +4542,21 @@ var AtscriptDoc = class {
4033
4542
  }
4034
4543
  if (isQueryFieldRef(token.parentNode)) {
4035
4544
  const { typeRef, queryArgToken } = token.parentNode;
4036
- if (token === typeRef && queryArgToken && getQueryScope(queryArgToken, this)) {
4037
- const result = this.getDefinitionFor(token);
4038
- return result ? [{
4039
- targetUri: result.uri,
4040
- targetRange: result.token?.range ?? zeroRange,
4041
- targetSelectionRange: result.token?.range ?? zeroRange,
4042
- originSelectionRange: token.range
4043
- }] : void 0;
4044
- }
4545
+ if (token === typeRef && queryArgToken && getQueryScope(queryArgToken, this)) return this.definitionLink(token);
4045
4546
  return;
4046
4547
  }
4047
- if (isProp(token.parentNode)) return [{
4048
- targetUri: this.id,
4049
- targetRange: token.range,
4050
- targetSelectionRange: token.range,
4051
- originSelectionRange: token.range
4052
- }];
4548
+ if (isProp(token.parentNode)) return this.definitionLink(token, {
4549
+ uri: this.id,
4550
+ range: token.range
4551
+ });
4053
4552
  if (token.isChain && isRef(token.parentNode) && typeof token.index === "number") {
4054
4553
  const id = token.parentNode.id;
4055
4554
  const unwound = this.unwindType(id, token.parentNode.chain.slice(0, token.index));
4056
- if (unwound?.node) return [{
4057
- targetUri: unwound.doc.id,
4058
- targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
4059
- targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
4060
- originSelectionRange: token.range
4061
- }];
4062
- } else {
4063
- const result = this.getDefinitionFor(token);
4064
- return result ? [{
4065
- targetUri: result.uri,
4066
- targetRange: result.token?.range ?? zeroRange,
4067
- targetSelectionRange: result.token?.range ?? zeroRange,
4068
- originSelectionRange: token.range
4069
- }] : void 0;
4070
- }
4555
+ if (unwound?.node) return this.definitionLink(token, {
4556
+ uri: unwound.doc.id,
4557
+ range: unwound.node.token("identifier")?.range
4558
+ });
4559
+ } else return this.definitionLink(token);
4071
4560
  }
4072
4561
  }
4073
4562
  registerImport({ from, imports, block }) {
@@ -4262,6 +4751,10 @@ var AtscriptDoc = class {
4262
4751
  }
4263
4752
  }
4264
4753
  for (const t of this.referred) {
4754
+ if (t.annotationRef || isQueryFieldRef(t.parentNode)) {
4755
+ this.reportUnknownIdentifier(t);
4756
+ continue;
4757
+ }
4265
4758
  const annotateBlock = this.annotateBlockAt(t.range.start.line, t.range.start.character);
4266
4759
  if (annotateBlock) {
4267
4760
  const targetName = annotateBlock.targetName;
@@ -4295,14 +4788,7 @@ var AtscriptDoc = class {
4295
4788
  }
4296
4789
  continue;
4297
4790
  }
4298
- if (!this.registry.isDefined(t)) {
4299
- this._allMessages.push({
4300
- severity: 1,
4301
- message: `Unknown identifier "${t.text}"`,
4302
- range: t.range
4303
- });
4304
- continue;
4305
- }
4791
+ if (this.reportUnknownIdentifier(t)) continue;
4306
4792
  if (isRef(t.parentNode)) {
4307
4793
  const def = this.unwindType(t.parentNode.id, t.parentNode.chain)?.def;
4308
4794
  if (isPrimitive(def) && !def.config.type) {
@@ -4350,6 +4836,10 @@ var AtscriptDoc = class {
4350
4836
  let def = this.unwindType(targetName)?.def;
4351
4837
  if (!def) return;
4352
4838
  for (const prop of chain) {
4839
+ if (isRef(def)) {
4840
+ def = this.unwindType(def.id, def.chain)?.def;
4841
+ if (!def) return;
4842
+ }
4353
4843
  def = this.mergeIntersection(def);
4354
4844
  if (isProp(def)) {
4355
4845
  const inner = def.getDefinition();
@@ -4519,6 +5009,7 @@ var AtscriptDoc = class {
4519
5009
  _define_property$3(this, "nodes", void 0);
4520
5010
  _define_property$3(this, "_text", void 0);
4521
5011
  _define_property$3(this, "_annotateNodesByTarget", void 0);
5012
+ /** Lexical backtick tokens already parsed by `registerAnnotation`. */ _define_property$3(this, "parsedBacktickArgs", void 0);
4522
5013
  _define_property$3(this, "resolvedAnnotations", void 0);
4523
5014
  _define_property$3(this, "annotations", void 0);
4524
5015
  _define_property$3(this, "_nextTypeId", void 0);
@@ -4543,6 +5034,7 @@ var AtscriptDoc = class {
4543
5034
  this._annotationSpecCache = /* @__PURE__ */ new Map();
4544
5035
  this.nodes = [];
4545
5036
  this._text = "";
5037
+ this.parsedBacktickArgs = /* @__PURE__ */ new WeakSet();
4546
5038
  this.resolvedAnnotations = [];
4547
5039
  this.annotations = [];
4548
5040
  this._nextTypeId = 0;
@@ -4550,6 +5042,10 @@ var AtscriptDoc = class {
4550
5042
  this.registry = new IdRegistry(Array.from(config.primitives?.keys() || []));
4551
5043
  }
4552
5044
  };
5045
+ /**
5046
+ * Annotation tokens survive merges across refs, chain refs and `extends`
5047
+ * unchanged, so they are keyed by identity to the document that declared them.
5048
+ */ _define_property$3(AtscriptDoc, "annotationOrigins", /* @__PURE__ */ new WeakMap());
4553
5049
  const zeroRange = {
4554
5050
  start: {
4555
5051
  line: 0,
@@ -5267,7 +5763,9 @@ var AtscriptRepo = class {
5267
5763
  async getUsedAnnotations() {
5268
5764
  const ANNOTATION_TYPE_MAP = {
5269
5765
  ref: "import(\"@atscript/typescript/utils\").AtscriptRef",
5270
- query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode"
5766
+ query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode",
5767
+ expr: "import(\"@atscript/typescript/utils\").AtscriptExprNode",
5768
+ order: "import(\"@atscript/typescript/utils\").AtscriptOrderItem[]"
5271
5769
  };
5272
5770
  const mapArgType = (t) => ANNOTATION_TYPE_MAP[t] || t;
5273
5771
  const manager = await this.getSharedPluginManager();
@@ -5931,6 +6429,7 @@ exports.$n = $n;
5931
6429
  exports.AnnotationSpec = AnnotationSpec;
5932
6430
  exports.AtscriptDoc = AtscriptDoc;
5933
6431
  exports.AtscriptRepo = AtscriptRepo;
6432
+ exports.BACKTICK_ARG_VOCABULARY = BACKTICK_ARG_VOCABULARY;
5934
6433
  exports.BuildRepo = BuildRepo;
5935
6434
  exports.DB_ENTITY_ANNOTATIONS = DB_ENTITY_ANNOTATIONS;
5936
6435
  exports.DEFAULT_FORMAT = DEFAULT_FORMAT;
@@ -5938,10 +6437,16 @@ exports.PluginManager = PluginManager;
5938
6437
  exports.SemanticAnnotateNode = SemanticAnnotateNode;
5939
6438
  exports.SemanticArrayNode = SemanticArrayNode;
5940
6439
  exports.SemanticConstNode = SemanticConstNode;
6440
+ exports.SemanticExprBinaryNode = SemanticExprBinaryNode;
6441
+ exports.SemanticExprCallNode = SemanticExprCallNode;
6442
+ exports.SemanticExprNode = SemanticExprNode;
6443
+ exports.SemanticExprNumberNode = SemanticExprNumberNode;
6444
+ exports.SemanticExprUnaryNode = SemanticExprUnaryNode;
5941
6445
  exports.SemanticGroup = SemanticGroup;
5942
6446
  exports.SemanticImportNode = SemanticImportNode;
5943
6447
  exports.SemanticInterfaceNode = SemanticInterfaceNode;
5944
6448
  exports.SemanticNode = SemanticNode;
6449
+ exports.SemanticOrderNode = SemanticOrderNode;
5945
6450
  exports.SemanticPrimitiveNode = SemanticPrimitiveNode;
5946
6451
  exports.SemanticPropNode = SemanticPropNode;
5947
6452
  exports.SemanticQueryComparisonNode = SemanticQueryComparisonNode;
@@ -5962,15 +6467,19 @@ exports.createAtscriptPlugin = createAtscriptPlugin;
5962
6467
  exports.defineConfig = defineConfig;
5963
6468
  exports.fileUriToPath = fileUriToPath;
5964
6469
  exports.flattenInterfaceNode = flattenInterfaceNode;
6470
+ exports.getDeclaredValue = getDeclaredValue;
5965
6471
  exports.getFieldPathCompletionScope = getFieldPathCompletionScope;
5966
6472
  exports.getFieldsForType = getFieldsForType;
5967
6473
  exports.getQueryCompletionScope = getQueryCompletionScope;
5968
6474
  exports.getQueryScope = getQueryScope;
5969
6475
  exports.getRelPath = getRelPath;
6476
+ exports.getSiblingAnnotation = getSiblingAnnotation;
6477
+ exports.getValueCandidates = getValueCandidates;
5970
6478
  exports.hasNavPropAnnotation = hasNavPropAnnotation;
5971
6479
  exports.isAnnotate = isAnnotate;
5972
6480
  exports.isAnnotationSpec = isAnnotationSpec;
5973
6481
  exports.isArray = isArray;
6482
+ exports.isBacktickArgType = isBacktickArgType;
5974
6483
  exports.isBareId = isBareId;
5975
6484
  exports.isBareSpecifier = isBareSpecifier;
5976
6485
  exports.isConst = isConst;