@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.mjs CHANGED
@@ -369,6 +369,9 @@ var Token = class Token {
369
369
  ...replace
370
370
  });
371
371
  }
372
+ /** The underlying lexical token (for re-iterating its children). */ get lexicalToken() {
373
+ return this._data;
374
+ }
372
375
  get text() {
373
376
  return this._data.text || "";
374
377
  }
@@ -392,6 +395,9 @@ var Token = class Token {
392
395
  get isAnnotation() {
393
396
  return this._data.type === "annotation";
394
397
  }
398
+ /** The parsed tree of a backtick argument — whichever of the three it was parsed as. */ get backtickNode() {
399
+ return this.queryNode ?? this.exprNode ?? this.orderNode;
400
+ }
395
401
  constructor(_data) {
396
402
  _define_property$13(this, "_data", void 0);
397
403
  /**
@@ -426,6 +432,12 @@ var Token = class Token {
426
432
  /**
427
433
  * Parsed query expression tree (for query-type annotation arguments)
428
434
  */ _define_property$13(this, "queryNode", void 0);
435
+ /**
436
+ * Parsed arithmetic expression (for expr-type annotation arguments)
437
+ */ _define_property$13(this, "exprNode", void 0);
438
+ /**
439
+ * Parsed ordering (for order-type annotation arguments)
440
+ */ _define_property$13(this, "orderNode", void 0);
429
441
  this._data = _data;
430
442
  }
431
443
  };
@@ -784,15 +796,20 @@ function _define_property$9(obj, key, value) {
784
796
  }
785
797
  var SemanticQueryNode = class extends SemanticNode {
786
798
  registerAtDocument(doc) {
787
- this.propagateQueryArgToken(this.expression);
799
+ for (const ref of this.fieldRefs()) ref.queryArgToken = this.sourceToken;
788
800
  this.expression.registerAtDocument(doc);
789
801
  }
790
- propagateQueryArgToken(expr) {
791
- if ("left" in expr) {
792
- expr.left.queryArgToken = this.sourceToken;
793
- const right = expr.right;
794
- if (right && "fieldRef" in right) right.queryArgToken = this.sourceToken;
795
- } else if ("operands" in expr) for (const operand of expr.operands) this.propagateQueryArgToken(operand);
802
+ /** Every field ref of the predicate (both sides of comparisons), in source order. */ fieldRefs() {
803
+ const refs = [];
804
+ const walk = (expr) => {
805
+ if ("left" in expr) {
806
+ refs.push(expr.left);
807
+ const right = expr.right;
808
+ if (right && "fieldRef" in right) refs.push(right);
809
+ } else if ("operands" in expr) for (const operand of expr.operands) walk(operand);
810
+ };
811
+ walk(this.expression);
812
+ return refs;
796
813
  }
797
814
  constructor() {
798
815
  super("query"), _define_property$9(this, "expression", void 0), _define_property$9(this, "sourceToken", void 0);
@@ -847,6 +864,74 @@ var SemanticQueryValueListNode = class extends SemanticNode {
847
864
  super("query-value-list"), _define_property$9(this, "values", void 0);
848
865
  }
849
866
  };
867
+ /** Set `queryArgToken` on every field-ref leaf and register the leaves at the document. */ function registerFieldRefs(refs, sourceToken, doc) {
868
+ for (const ref of refs) {
869
+ ref.queryArgToken = sourceToken;
870
+ ref.registerAtDocument(doc);
871
+ }
872
+ }
873
+ /** Root of a parsed `expr` argument (closed arithmetic over field refs). */ var SemanticExprNode = class extends SemanticNode {
874
+ /** Every field-ref leaf of the expression, in source order. */ fieldRefs() {
875
+ const refs = [];
876
+ collectExprFieldRefs(this.expression, refs);
877
+ return refs;
878
+ }
879
+ registerAtDocument(doc) {
880
+ registerFieldRefs(this.fieldRefs(), this.sourceToken, doc);
881
+ }
882
+ constructor() {
883
+ super("query-expr"), _define_property$9(this, "expression", void 0), _define_property$9(this, "sourceToken", void 0);
884
+ }
885
+ };
886
+ function collectExprFieldRefs(node, out) {
887
+ switch (node.entity) {
888
+ case "query-field-ref":
889
+ out.push(node);
890
+ break;
891
+ case "query-expr-binary":
892
+ collectExprFieldRefs(node.left, out);
893
+ collectExprFieldRefs(node.right, out);
894
+ break;
895
+ case "query-expr-unary":
896
+ collectExprFieldRefs(node.operand, out);
897
+ break;
898
+ case "query-expr-call":
899
+ for (const arg of node.args) collectExprFieldRefs(arg, out);
900
+ break;
901
+ default:
902
+ }
903
+ }
904
+ var SemanticExprBinaryNode = class extends SemanticNode {
905
+ constructor() {
906
+ super("query-expr-binary"), _define_property$9(this, "op", void 0), _define_property$9(this, "left", void 0), _define_property$9(this, "right", void 0);
907
+ }
908
+ };
909
+ var SemanticExprUnaryNode = class extends SemanticNode {
910
+ constructor() {
911
+ super("query-expr-unary"), _define_property$9(this, "op", "neg"), _define_property$9(this, "operand", void 0);
912
+ }
913
+ };
914
+ var SemanticExprCallNode = class extends SemanticNode {
915
+ constructor() {
916
+ super("query-expr-call"), _define_property$9(this, "fn", "coalesce"), _define_property$9(this, "args", void 0);
917
+ }
918
+ };
919
+ var SemanticExprNumberNode = class extends SemanticNode {
920
+ constructor() {
921
+ super("query-expr-number"), _define_property$9(this, "valueToken", void 0), _define_property$9(this, "value", void 0);
922
+ }
923
+ };
924
+ /** Root of a parsed `order` argument: `key (asc|desc)?, …`. */ var SemanticOrderNode = class extends SemanticNode {
925
+ /** Every order key, in source order. */ fieldRefs() {
926
+ return this.items.map((i) => i.ref);
927
+ }
928
+ registerAtDocument(doc) {
929
+ registerFieldRefs(this.fieldRefs(), this.sourceToken, doc);
930
+ }
931
+ constructor() {
932
+ super("query-order"), _define_property$9(this, "items", void 0), _define_property$9(this, "sourceToken", void 0);
933
+ }
934
+ };
850
935
 
851
936
  //#endregion
852
937
  //#region packages/core/src/parser/nodes/index.ts
@@ -922,6 +1007,14 @@ function _define_property$8(obj, key, value) {
922
1007
  else obj[key] = value;
923
1008
  return obj;
924
1009
  }
1010
+ /** Whether an annotation argument type is written in backticks (`query`, `expr`, `order`). */ function isBacktickArgType(type) {
1011
+ return type === "query" || type === "expr" || type === "order";
1012
+ }
1013
+ const BACKTICK_TYPE_MESSAGES = {
1014
+ query: "query expression expected (use backticks).",
1015
+ expr: "expression expected (use backticks).",
1016
+ order: "order list expected (use backticks)."
1017
+ };
925
1018
  var AnnotationSpec = class {
926
1019
  get arguments() {
927
1020
  if (!this.config.argument) return [];
@@ -932,7 +1025,7 @@ var AnnotationSpec = class {
932
1025
  return this.arguments.map((arg, index) => {
933
1026
  const placeholderIndex = index + 1;
934
1027
  const defaultValue = this.getDefaultValueForType(arg.name, arg.type);
935
- const quote = arg.type === "string" ? `'` : arg.type === "query" ? "`" : "";
1028
+ const quote = arg.type === "string" ? `'` : isBacktickArgType(arg.type) ? "`" : "";
936
1029
  return `${quote}\${${placeholderIndex}:${defaultValue}}${quote}`;
937
1030
  }).join(", ");
938
1031
  }
@@ -942,7 +1035,9 @@ var AnnotationSpec = class {
942
1035
  case "number": return tokenType === "number" ? void 0 : "number expected.";
943
1036
  case "boolean": return tokenType === "identifier" ? void 0 : "boolean expected.";
944
1037
  case "ref": return tokenType === "identifier" ? void 0 : "type reference expected.";
945
- case "query": return tokenType === "query" ? void 0 : "query expression expected (use backticks).";
1038
+ case "query":
1039
+ case "expr":
1040
+ case "order": return tokenType === "query" ? void 0 : BACKTICK_TYPE_MESSAGES[type];
946
1041
  default: return `unknown type "${type}".`;
947
1042
  }
948
1043
  }
@@ -1064,6 +1159,8 @@ var AnnotationSpec = class {
1064
1159
  case "boolean": return "true";
1065
1160
  case "ref": return "TypeName";
1066
1161
  case "query": return "field = value";
1162
+ case "expr": return "field + 1";
1163
+ case "order": return "field asc";
1067
1164
  default: return "";
1068
1165
  }
1069
1166
  }
@@ -1386,209 +1483,874 @@ async function loadConfig(configPath, forceFormat) {
1386
1483
  }
1387
1484
 
1388
1485
  //#endregion
1389
- //#region packages/core/src/lsp/legacy-db-query-scope.ts
1390
- /**
1391
- * @deprecated Built-in editor scopes for the `@db.view.filter`, `@db.view.joins` and
1392
- * `@db.rel.filter` query arguments. They are a fallback for DB plugin versions whose
1393
- * argument specs do not declare a `fieldScope` hook yet — the DB plugin owns these
1394
- * rules now. Scheduled for removal in `@atscript/core` 0.2.0 (next minor).
1395
- */
1396
- /**
1397
- * @deprecated Query scope of a built-in `@db.*` query argument (see the module note);
1398
- * `undefined` for any other annotation.
1399
- */ function getLegacyDbQueryScope(queryArgToken) {
1400
- const owner = queryArgToken.parentNode;
1401
- if (!owner) return;
1402
- switch (queryArgToken.annotationRef?.text.slice(1)) {
1403
- case "db.view.filter": return getViewFilterScope(owner);
1404
- case "db.view.joins": return getViewJoinsScope(owner, queryArgToken);
1405
- case "db.rel.filter": return getRelFilterScope(owner);
1406
- default: return;
1407
- }
1486
+ //#region packages/core/src/parser/iterator.ts
1487
+ function _define_property$7(obj, key, value) {
1488
+ if (key in obj) Object.defineProperty(obj, key, {
1489
+ value,
1490
+ enumerable: true,
1491
+ configurable: true,
1492
+ writable: true
1493
+ });
1494
+ else obj[key] = value;
1495
+ return obj;
1408
1496
  }
1409
- function getViewFilterScope(owner) {
1410
- const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
1411
- if (!entryTypeName) return;
1412
- const allowedTypes = [entryTypeName];
1413
- const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
1414
- if (joinsAnnotations) {
1415
- for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
1497
+ var NodeIterator = class NodeIterator {
1498
+ get index() {
1499
+ return this.i;
1416
1500
  }
1417
- return {
1418
- allowedTypes,
1419
- unqualifiedTarget: entryTypeName
1420
- };
1421
- }
1422
- function getViewJoinsScope(owner, queryArgToken) {
1423
- const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
1424
- if (!entryTypeName) return;
1425
- const joinTargetName = (owner.annotations?.find((a) => a.name === "db.view.joins" && a.args.includes(queryArgToken)))?.args[0]?.text;
1426
- if (!joinTargetName) return;
1427
- return {
1428
- allowedTypes: [joinTargetName, entryTypeName],
1429
- unqualifiedTarget: entryTypeName
1430
- };
1431
- }
1432
- function getRelFilterScope(owner) {
1433
- let def = owner.getDefinition();
1434
- if (isArray(def)) def = def?.getDefinition();
1435
- if (!isRef(def)) return;
1436
- const targetTypeName = def.id;
1437
- const allowedTypes = [targetTypeName];
1438
- const viaAnnotation = owner.annotations?.find((a) => a.name === "db.rel.via");
1439
- if (viaAnnotation?.args[0]) allowedTypes.push(viaAnnotation.args[0].text);
1440
- return {
1441
- allowedTypes,
1442
- unqualifiedTarget: targetTypeName
1443
- };
1444
- }
1445
-
1446
- //#endregion
1447
- //#region packages/core/src/lsp/field-refs.ts
1448
- function getArgSpec(argToken, doc) {
1449
- const annotationRef = argToken.annotationRef;
1450
- if (!annotationRef || typeof argToken.index !== "number") return;
1451
- return doc.resolveAnnotation(annotationRef.text.slice(1))?.arguments[argToken.index];
1452
- }
1453
- /**
1454
- * Field scope of an annotation argument: the answer of the argument spec's `fieldScope`
1455
- * hook when it declares one, otherwise the deprecated built-in `@db.*` query rules.
1456
- */ function getQueryScope(argToken, doc) {
1457
- const argSpec = getArgSpec(argToken, doc);
1458
- return argSpec?.fieldScope ? argSpec.fieldScope(argToken, doc) : getLegacyDbQueryScope(argToken);
1459
- }
1460
- /**
1461
- * Type a field-path `string` argument names a field of: the `unqualifiedTarget` of the
1462
- * argument spec's `fieldScope`. `undefined` for any other token.
1463
- */ function getFieldPathTarget(argToken, doc) {
1464
- if (argToken.type !== "text") return;
1465
- const argSpec = getArgSpec(argToken, doc);
1466
- if (argSpec?.type !== "string" || !argSpec.fieldScope) return;
1467
- return argSpec.fieldScope(argToken, doc)?.unqualifiedTarget ?? void 0;
1468
- }
1469
- /**
1470
- * Resolve a (possibly dotted) field path of a type to the property it names and the
1471
- * document that declares that property.
1472
- */ function resolveFieldPath(doc, typeName, segment) {
1473
- const chain = segment.path.split(".");
1474
- const [name] = chain.splice(-1);
1475
- const parent = doc.unwindType(typeName, chain);
1476
- if (!parent || !(isStructure(parent.def) || isInterface(parent.def))) return;
1477
- const prop = parent.def.props.get(name);
1478
- return prop && {
1479
- typeName,
1480
- range: segment.range,
1481
- prop,
1482
- doc: parent.doc
1483
- };
1484
- }
1485
- /**
1486
- * Segments of a field-path string argument (`'address.city'` → `address`, `city`), with
1487
- * ranges that exclude the quotes. A string spanning several lines is a single segment.
1488
- */ function fieldPathSegments(argToken) {
1489
- const { text, range } = argToken;
1490
- if (range.start.line !== range.end.line) return [{
1491
- path: text,
1492
- range
1493
- }];
1494
- const line = range.start.line;
1495
- const contentStart = range.start.character + 1;
1496
- const segments = [];
1497
- let start = 0;
1498
- for (const part of text.split(".")) {
1499
- const end = start + part.length;
1500
- segments.push({
1501
- path: text.slice(0, end),
1502
- range: {
1503
- start: {
1504
- line,
1505
- character: contentStart + start
1506
- },
1507
- end: {
1508
- line,
1509
- character: contentStart + end
1510
- }
1511
- }
1512
- });
1513
- start = end + 1;
1501
+ get lastNode() {
1502
+ return this.nodes[this.nodes.length - 1];
1514
1503
  }
1515
- return segments;
1516
- }
1517
- /** The segment under `character`, or the last segment when `character` is omitted. */ function fieldPathSegmentAt(argToken, character) {
1518
- const segments = fieldPathSegments(argToken);
1519
- return (character === void 0 ? void 0 : segments.find((s) => s.range.end.character >= character)) ?? segments[segments.length - 1];
1520
- }
1521
- /**
1522
- * Resolve a field reference token to the property it names:
1523
- * - a field ref inside a `query` argument (`amount`, `Customer.name` in backticks);
1524
- * - a `string` argument whose spec declares `fieldScope`: a (dotted) field path of the
1525
- * scope's `unqualifiedTarget`. With `character` (a cursor column), the path resolves
1526
- * only up to the segment under the cursor — `'address.city'` with the cursor on
1527
- * `address` resolves `address` — and `range` is that segment's range.
1528
- *
1529
- * Returns `undefined` for any other token, or when the scope or the path does not resolve.
1530
- */ function resolveFieldRefAt(token, doc, character) {
1531
- if (isQueryFieldRef(token.parentNode)) {
1532
- const { fieldRef, typeRef, queryArgToken } = token.parentNode;
1533
- const scope = token === fieldRef && queryArgToken ? getQueryScope(queryArgToken, doc) : void 0;
1534
- const typeName = scope && (typeRef?.text ?? scope.unqualifiedTarget);
1535
- return typeName ? resolveFieldPath(doc, typeName, {
1536
- path: token.text,
1537
- range: token.range
1538
- }) : void 0;
1504
+ unexpectedEOB() {
1505
+ this.issues.unexpectedEOB = true;
1539
1506
  }
1540
- const typeName = getFieldPathTarget(token, doc);
1541
- return typeName ? resolveFieldPath(doc, typeName, fieldPathSegmentAt(token, character)) : void 0;
1542
- }
1543
- /**
1544
- * Resolve the segments named `fieldName` of a field-path `string` argument
1545
- * (`'address.city'` has the segments `address` and `city`). Supports find-references.
1546
- */ function resolveFieldPathArgSegments(argToken, doc, fieldName) {
1547
- const segments = fieldPathSegments(argToken).filter((s) => s.path === fieldName || s.path.endsWith(`.${fieldName}`));
1548
- const typeName = segments.length > 0 ? getFieldPathTarget(argToken, doc) : void 0;
1549
- if (!typeName) return [];
1550
- const targets = [];
1551
- for (const segment of segments) {
1552
- const target = resolveFieldPath(doc, typeName, segment);
1553
- if (target) targets.push(target);
1507
+ unfork(fork) {
1508
+ this.i = fork.index;
1509
+ this.update();
1554
1510
  }
1555
- return targets;
1556
- }
1557
- /**
1558
- * Resolve a query field ref node to a property definition.
1559
- */ function resolveQueryFieldRef(fieldRefNode, doc, scope) {
1560
- const typeName = fieldRefNode.typeRef?.text ?? scope.unqualifiedTarget;
1561
- const { fieldRef } = fieldRefNode;
1562
- const resolved = typeName ? resolveFieldPath(doc, typeName, {
1563
- path: fieldRef.text,
1564
- range: fieldRef.range
1565
- }) : void 0;
1566
- return resolved && {
1567
- targetUri: resolved.doc.id,
1568
- doc: resolved.doc,
1569
- prop: resolved.prop
1570
- };
1571
- }
1572
- /**
1573
- * Get fields available for a type (resolving extends/intersections).
1574
- * With `chain`, returns the fields of the nested object that field path leads to.
1575
- */ function getFieldsForType(doc, typeName, chain = []) {
1576
- const unwound = doc.unwindType(typeName, chain);
1577
- if (!unwound?.def) return [];
1578
- let def = unwound.doc.mergeIntersection(unwound.def);
1579
- if (isInterface(def)) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
1580
- if (isStructure(def) || isInterface(def)) return Array.from(def.props.values());
1581
- return [];
1582
- }
1583
- /**
1584
- * Completion scope of a field-path `string` argument (spec declares `fieldScope`) at the
1585
- * cursor column `character`: the fields of the level being typed — `'address.ci'` offers
1586
- * the fields of `address` (`chain` = `['address']`).
1587
- */ function getFieldPathCompletionScope(argToken, doc, character) {
1588
- const typeName = getFieldPathTarget(argToken, doc);
1589
- if (!typeName) return;
1590
- const chain = fieldPathSegmentAt(argToken, character).path.split(".").slice(0, -1);
1591
- return {
1511
+ accepted() {
1512
+ if (this.$ && this.$.accepted !== false) {
1513
+ this.$.accepted = true;
1514
+ this.badNodes.delete(this.$);
1515
+ }
1516
+ }
1517
+ toString() {
1518
+ return this.$ ? `[${this.$.type}] ${this.$.text}` : `void`;
1519
+ }
1520
+ update() {
1521
+ this.$ = this.nodes[this.i];
1522
+ return this;
1523
+ }
1524
+ move(v = 1) {
1525
+ this.i += v;
1526
+ this.$ = this.nodes[this.i];
1527
+ return this;
1528
+ }
1529
+ next(skip) {
1530
+ return this.fork().move().skip(skip);
1531
+ }
1532
+ fork(nodes) {
1533
+ return new NodeIterator(nodes || this.nodes, this.messages, this.badNodes, this.issues, nodes ? this.$ : this.parent, nodes ? 0 : this.i).update();
1534
+ }
1535
+ skip(pun) {
1536
+ while (this.$?.type === "comment" || this.$?.type === "punctuation" && pun?.length && pun.includes(this.$.text)) this.move();
1537
+ return this;
1538
+ }
1539
+ skipUntil(pun) {
1540
+ while (this.$ && !this.satisfies({
1541
+ node: "punctuation",
1542
+ text: pun
1543
+ })) this.move();
1544
+ }
1545
+ unexpected(force = false, msg = "Unexpected token") {
1546
+ if (force && this.$) this.$.accepted = false;
1547
+ if (this.$ && !this.badNodes.has(this.$)) this.badNodes.set(this.$, msg);
1548
+ }
1549
+ shouldHaveError(depth) {
1550
+ for (let i = this.i; i <= depth; i++) if (i < this.nodes.length) this.nodes[i].accepted = false;
1551
+ }
1552
+ nodesLeft() {
1553
+ return this.nodes.length > 0 && this.index < this.nodes.length;
1554
+ }
1555
+ satisfies(...rules) {
1556
+ for (const rule of rules) {
1557
+ const passed = Array.isArray(rule.node) ? rule.node.includes(this.$?.type) : this.$?.type === rule.node;
1558
+ if (passed && rule.text === void 0) return true;
1559
+ if (passed && Array.isArray(rule.text) ? rule.text.includes(this.$?.text) : this.$?.text === rule.text) return true;
1560
+ }
1561
+ return false;
1562
+ }
1563
+ confirmIssues() {
1564
+ if (this.issues.unexpectedEOB) {
1565
+ const pos = (this.lastNode || this.parent)?.getRange().end || {
1566
+ character: 1,
1567
+ line: 1
1568
+ };
1569
+ this.messages.push({
1570
+ severity: 1,
1571
+ message: `Unexpected end of block`,
1572
+ range: {
1573
+ start: pos,
1574
+ end: pos
1575
+ }
1576
+ });
1577
+ this.issues.unexpectedEOB = false;
1578
+ }
1579
+ }
1580
+ getErrors() {
1581
+ this.badNodes.forEach((msg, node) => {
1582
+ if (node.accepted) this.badNodes.delete(node);
1583
+ });
1584
+ return Array.from(this.badNodes.entries(), ([node, msg]) => ({
1585
+ severity: 1,
1586
+ message: msg,
1587
+ range: node.getRange?.() || {
1588
+ start: {
1589
+ character: 1,
1590
+ line: 1
1591
+ },
1592
+ end: {
1593
+ character: 1,
1594
+ line: 1
1595
+ }
1596
+ }
1597
+ })).concat(this.messages);
1598
+ }
1599
+ constructor(nodes, messages = [], badNodes = /* @__PURE__ */ new Map(), issues = {}, parent, i = -1) {
1600
+ _define_property$7(this, "nodes", void 0);
1601
+ _define_property$7(this, "messages", void 0);
1602
+ _define_property$7(this, "badNodes", void 0);
1603
+ _define_property$7(this, "issues", void 0);
1604
+ _define_property$7(this, "parent", void 0);
1605
+ _define_property$7(this, "i", void 0);
1606
+ _define_property$7(this, "$", void 0);
1607
+ this.nodes = nodes;
1608
+ this.messages = messages;
1609
+ this.badNodes = badNodes;
1610
+ this.issues = issues;
1611
+ this.parent = parent;
1612
+ this.i = i;
1613
+ }
1614
+ };
1615
+
1616
+ //#endregion
1617
+ //#region packages/core/src/parser/pipes/query.pipe.ts
1618
+ const SYMBOLIC_OPS = new Set([
1619
+ "=",
1620
+ "!=",
1621
+ ">",
1622
+ ">=",
1623
+ "<",
1624
+ "<="
1625
+ ]);
1626
+ const VALUE_KEYWORDS = new Set([
1627
+ "true",
1628
+ "false",
1629
+ "null",
1630
+ "undefined"
1631
+ ]);
1632
+ const ZERO_RANGE = {
1633
+ start: {
1634
+ line: 0,
1635
+ character: 0
1636
+ },
1637
+ end: {
1638
+ line: 0,
1639
+ character: 0
1640
+ }
1641
+ };
1642
+ /**
1643
+ * Parse a backtick-delimited query expression.
1644
+ *
1645
+ * `ni` iterates the query token's children and carries that token as its
1646
+ * `parent` — the range to blame when a diagnostic has no token of its own —
1647
+ * so fork it from the annotation iterator while the query token is current.
1648
+ * Returns a SemanticQueryNode or undefined if the content is empty.
1649
+ */ function parseQueryExpression(ni, sourceToken) {
1650
+ if (!ni.$) return;
1651
+ const expr = parseOrExpr(ni);
1652
+ if (!expr) return;
1653
+ if (ni.$) pushError(ni, `Unexpected token in query expression: "${ni.$.text}"`);
1654
+ const node = new SemanticQueryNode();
1655
+ node.expression = expr;
1656
+ node.sourceToken = sourceToken;
1657
+ return node;
1658
+ }
1659
+ function parseOrExpr(ni) {
1660
+ const left = parseAndExpr(ni);
1661
+ if (!left) return;
1662
+ const operands = [left];
1663
+ while (ni.$?.type === "identifier" && ni.$.text === "or") {
1664
+ ni.move();
1665
+ const right = parseAndExpr(ni);
1666
+ if (!right) {
1667
+ pushError(ni, "Expected expression after \"or\"");
1668
+ break;
1669
+ }
1670
+ operands.push(right);
1671
+ }
1672
+ if (operands.length === 1) return operands[0];
1673
+ const node = new SemanticQueryLogicalNode();
1674
+ node.operator = "or";
1675
+ node.operands = operands;
1676
+ return node;
1677
+ }
1678
+ function parseAndExpr(ni) {
1679
+ const left = parseUnaryExpr(ni);
1680
+ if (!left) return;
1681
+ const operands = [left];
1682
+ while (ni.$?.type === "identifier" && ni.$.text === "and") {
1683
+ ni.move();
1684
+ const right = parseUnaryExpr(ni);
1685
+ if (!right) {
1686
+ pushError(ni, "Expected expression after \"and\"");
1687
+ break;
1688
+ }
1689
+ operands.push(right);
1690
+ }
1691
+ if (operands.length === 1) return operands[0];
1692
+ const node = new SemanticQueryLogicalNode();
1693
+ node.operator = "and";
1694
+ node.operands = operands;
1695
+ return node;
1696
+ }
1697
+ function parseUnaryExpr(ni) {
1698
+ if (ni.$?.type === "identifier" && ni.$.text === "not") {
1699
+ ni.move();
1700
+ const operand = parseUnaryExpr(ni);
1701
+ if (!operand) {
1702
+ pushError(ni, "Expected expression after \"not\"");
1703
+ return;
1704
+ }
1705
+ const node = new SemanticQueryLogicalNode();
1706
+ node.operator = "not";
1707
+ node.operands = [operand];
1708
+ return node;
1709
+ }
1710
+ if (ni.$?.type === "block" && ni.$.text === "(") {
1711
+ const subNi = ni.fork(ni.$.children || []);
1712
+ ni.move();
1713
+ if (!subNi.$) {
1714
+ pushError(subNi, "Empty parenthesized expression");
1715
+ return;
1716
+ }
1717
+ const expr = parseOrExpr(subNi);
1718
+ if (subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
1719
+ return expr;
1720
+ }
1721
+ return parseComparison(ni);
1722
+ }
1723
+ function parseComparison(ni) {
1724
+ const left = parseFieldRef(ni);
1725
+ if (!left) return;
1726
+ if (ni.$?.type === "punctuation" && SYMBOLIC_OPS.has(ni.$.text)) {
1727
+ const opText = ni.$.text;
1728
+ ni.move();
1729
+ const right = parseValueOrFieldRef(ni);
1730
+ if (!right) {
1731
+ pushError(ni, `Expected value or field reference after "${opText}"`);
1732
+ return;
1733
+ }
1734
+ const node = new SemanticQueryComparisonNode();
1735
+ node.left = left;
1736
+ node.operator = opText;
1737
+ node.right = right;
1738
+ return node;
1739
+ }
1740
+ if (ni.$?.type === "identifier") {
1741
+ const opText = ni.$.text;
1742
+ if (opText === "in") {
1743
+ ni.move();
1744
+ const right = parseValueList(ni);
1745
+ if (!right) return;
1746
+ const node = new SemanticQueryComparisonNode();
1747
+ node.left = left;
1748
+ node.operator = "in";
1749
+ node.right = right;
1750
+ return node;
1751
+ }
1752
+ if (opText === "matches") {
1753
+ ni.move();
1754
+ const right = parseValueOrFieldRef(ni);
1755
+ if (!right) {
1756
+ pushError(ni, "Expected value after \"matches\"");
1757
+ return;
1758
+ }
1759
+ const node = new SemanticQueryComparisonNode();
1760
+ node.left = left;
1761
+ node.operator = "matches";
1762
+ node.right = right;
1763
+ return node;
1764
+ }
1765
+ if (opText === "exists") {
1766
+ ni.move();
1767
+ const node = new SemanticQueryComparisonNode();
1768
+ node.left = left;
1769
+ node.operator = "exists";
1770
+ return node;
1771
+ }
1772
+ if (opText === "not") return parseNotComparison(ni, left);
1773
+ pushError(ni, `Unknown operator "${opText}"`);
1774
+ return;
1775
+ }
1776
+ pushError(ni, "Expected operator after field reference");
1777
+ }
1778
+ function parseNotComparison(ni, left) {
1779
+ ni.move();
1780
+ if (ni.$?.type === "identifier" && ni.$.text === "in") {
1781
+ ni.move();
1782
+ const right = parseValueList(ni);
1783
+ if (!right) return;
1784
+ const node = new SemanticQueryComparisonNode();
1785
+ node.left = left;
1786
+ node.operator = "not in";
1787
+ node.right = right;
1788
+ return node;
1789
+ }
1790
+ if (ni.$?.type === "identifier" && ni.$.text === "exists") {
1791
+ ni.move();
1792
+ const node = new SemanticQueryComparisonNode();
1793
+ node.left = left;
1794
+ node.operator = "not exists";
1795
+ return node;
1796
+ }
1797
+ pushError(ni, "Expected \"in\" or \"exists\" after \"not\"");
1798
+ }
1799
+ function parseFieldRef(ni) {
1800
+ if (ni.$?.type !== "identifier") {
1801
+ pushError(ni, "Expected field reference");
1802
+ return;
1803
+ }
1804
+ const firstToken = new Token(ni.$);
1805
+ ni.move();
1806
+ if (ni.$?.type === "punctuation" && ni.$.text === ".") {
1807
+ ni.move();
1808
+ if (ni.$?.type === "identifier") {
1809
+ const secondToken = new Token(ni.$);
1810
+ ni.move();
1811
+ let fieldText = secondToken.text;
1812
+ while (ni.$?.type === "punctuation" && ni.$.text === ".") {
1813
+ ni.move();
1814
+ if (ni.$?.type === "identifier") {
1815
+ fieldText += `.${ni.$.text}`;
1816
+ ni.move();
1817
+ } else {
1818
+ pushError(ni, "Expected identifier after \".\"");
1819
+ break;
1820
+ }
1821
+ }
1822
+ const node = new SemanticQueryFieldRefNode();
1823
+ node.typeRef = firstToken;
1824
+ node.fieldRef = fieldText === secondToken.text ? secondToken : secondToken.clone({ text: fieldText });
1825
+ return node;
1826
+ }
1827
+ pushError(ni, "Expected identifier after \".\"");
1828
+ const node = new SemanticQueryFieldRefNode();
1829
+ node.fieldRef = firstToken;
1830
+ return node;
1831
+ }
1832
+ const node = new SemanticQueryFieldRefNode();
1833
+ node.fieldRef = firstToken;
1834
+ return node;
1835
+ }
1836
+ function parseValueOrFieldRef(ni) {
1837
+ if (!ni.$) return;
1838
+ if (ni.$.type === "text" || ni.$.type === "number" || ni.$.type === "regexp") return parseValue(ni);
1839
+ if (ni.$.type === "identifier") {
1840
+ if (VALUE_KEYWORDS.has(ni.$.text)) return parseValue(ni);
1841
+ return parseFieldRef(ni);
1842
+ }
1843
+ pushError(ni, "Expected value or field reference");
1844
+ }
1845
+ function parseValue(ni) {
1846
+ if (!ni.$) {
1847
+ pushError(ni, "Expected value");
1848
+ return;
1849
+ }
1850
+ const token = ni.$;
1851
+ if (token.type === "text" || token.type === "number" || token.type === "regexp" || token.type === "identifier" && VALUE_KEYWORDS.has(token.text)) {
1852
+ const node = new SemanticQueryValueNode();
1853
+ node.valueToken = new Token(token);
1854
+ ni.move();
1855
+ return node;
1856
+ }
1857
+ pushError(ni, `Unexpected token "${token.text}" where value expected`);
1858
+ }
1859
+ function parseValueList(ni) {
1860
+ if (ni.$?.type === "block" && ni.$.text === "(") {
1861
+ const subNi = ni.fork(ni.$.children || []);
1862
+ ni.move();
1863
+ if (!subNi.$) {
1864
+ pushError(subNi, "Empty value list in \"in\" expression");
1865
+ return;
1866
+ }
1867
+ const values = [];
1868
+ const first = parseValue(subNi);
1869
+ if (first) values.push(first);
1870
+ while (subNi.$?.type === "punctuation" && subNi.$.text === ",") {
1871
+ subNi.move();
1872
+ const v = parseValue(subNi);
1873
+ if (v) values.push(v);
1874
+ }
1875
+ if (subNi.$) pushError(subNi, `Unexpected token in value list: "${subNi.$.text}"`);
1876
+ const node = new SemanticQueryValueListNode();
1877
+ node.values = values;
1878
+ return node;
1879
+ }
1880
+ pushError(ni, "Expected parenthesized value list after \"in\"");
1881
+ }
1882
+ /**
1883
+ * Range to blame for a diagnostic: the current token, else the enclosing
1884
+ * query token / "(...)" block the iterator was forked from.
1885
+ */ function rangeOf(ni) {
1886
+ return ni.$?.getRange?.() ?? ni.parent?.getRange?.() ?? ZERO_RANGE;
1887
+ }
1888
+ function pushError(ni, message) {
1889
+ ni.messages.push({
1890
+ severity: 1,
1891
+ message,
1892
+ range: rangeOf(ni)
1893
+ });
1894
+ }
1895
+
1896
+ //#endregion
1897
+ //#region packages/core/src/parser/pipes/expr.pipe.ts
1898
+ /**
1899
+ * Parse a backtick annotation argument as the given kind and attach the tree to
1900
+ * the token (`queryNode`, `exprNode` or `orderNode`). Returns the diagnostics.
1901
+ */ function parseBacktickArg(argToken, kind) {
1902
+ const messages = [];
1903
+ const ni = new NodeIterator(argToken.children, messages, /* @__PURE__ */ new Map(), {}, argToken.lexicalToken, 0).update();
1904
+ switch (kind) {
1905
+ case "expr":
1906
+ argToken.exprNode = parseExprExpression(ni, argToken);
1907
+ break;
1908
+ case "order":
1909
+ argToken.orderNode = parseOrderList(ni, argToken);
1910
+ break;
1911
+ default: argToken.queryNode = parseQueryExpression(ni, argToken);
1912
+ }
1913
+ return messages;
1914
+ }
1915
+ /** Vocabulary of `expr` / `order` arguments: arithmetic operators, functions, order directions. */ const BACKTICK_ARG_VOCABULARY = {
1916
+ arithmeticOps: [
1917
+ "+",
1918
+ "-",
1919
+ "*",
1920
+ "/"
1921
+ ],
1922
+ functions: ["coalesce"],
1923
+ orderDirections: ["asc", "desc"]
1924
+ };
1925
+ const ORDER_DIRECTIONS = new Set(BACKTICK_ARG_VOCABULARY.orderDirections);
1926
+ /**
1927
+ * Parse a backtick arithmetic expression:
1928
+ *
1929
+ * ```
1930
+ * expr := additive
1931
+ * additive := mult (('+' | '-') mult)*
1932
+ * mult := unary (('*' | '/') unary)*
1933
+ * unary := '-' unary | primary
1934
+ * primary := NUMBER | fieldRef | 'coalesce' '(' expr (',' expr)+ ')' | '(' expr ')'
1935
+ * ```
1936
+ *
1937
+ * A signed number in binary-operator position (`a -5`, `a+1`) is split into the
1938
+ * operator and an unsigned operand. Returns `undefined` when the content is empty.
1939
+ */ function parseExprExpression(ni, sourceToken) {
1940
+ if (!ni.$) {
1941
+ pushError(ni, "Empty expression");
1942
+ return;
1943
+ }
1944
+ const expr = parseAdditive(ni);
1945
+ if (!expr) return;
1946
+ if (ni.$) pushError(ni, `Unexpected token in expression: "${ni.$.text}"`);
1947
+ const node = new SemanticExprNode();
1948
+ node.expression = expr;
1949
+ node.sourceToken = sourceToken;
1950
+ return node;
1951
+ }
1952
+ function isPunct(t, chars) {
1953
+ return t?.type === "punctuation" && t.text.length === 1 && chars.includes(t.text);
1954
+ }
1955
+ function isParenBlock(t) {
1956
+ return t?.type === "block" && t.text === "(";
1957
+ }
1958
+ /** A number token whose text carries a sign (`-5`, `+1`). */ function signedNumber(t) {
1959
+ if (t?.type !== "number") return;
1960
+ const c = t.text.charAt(0);
1961
+ return c === "-" || c === "+" ? c : void 0;
1962
+ }
1963
+ function binary(op, left, right) {
1964
+ const node = new SemanticExprBinaryNode();
1965
+ node.op = op;
1966
+ node.left = left;
1967
+ node.right = right;
1968
+ return node;
1969
+ }
1970
+ function parseAdditive(ni) {
1971
+ let left = parseMult(ni);
1972
+ if (!left) return;
1973
+ for (;;) {
1974
+ const punct = isPunct(ni.$, "+-");
1975
+ const op = punct ? ni.$?.text : signedNumber(ni.$);
1976
+ if (!op) break;
1977
+ if (punct) ni.move();
1978
+ const right = parseMult(ni, !punct);
1979
+ if (!right) {
1980
+ pushError(ni, `Expected operand after "${op}"`);
1981
+ return;
1982
+ }
1983
+ left = binary(op, left, right);
1984
+ }
1985
+ return left;
1986
+ }
1987
+ function parseMult(ni, unsignFirst = false) {
1988
+ let left = parseUnary(ni, unsignFirst);
1989
+ if (!left) return;
1990
+ for (let t = ni.$; isPunct(t, "*/"); t = ni.$) {
1991
+ const op = t.text;
1992
+ ni.move();
1993
+ const right = parseUnary(ni);
1994
+ if (!right) {
1995
+ pushError(ni, `Expected operand after "${op}"`);
1996
+ return;
1997
+ }
1998
+ left = binary(op, left, right);
1999
+ }
2000
+ return left;
2001
+ }
2002
+ function parseUnary(ni, unsign = false) {
2003
+ if (!unsign && isPunct(ni.$, "-")) {
2004
+ ni.move();
2005
+ const operand = parseUnary(ni);
2006
+ if (!operand) {
2007
+ pushError(ni, "Expected operand after \"-\"");
2008
+ return;
2009
+ }
2010
+ const node = new SemanticExprUnaryNode();
2011
+ node.operand = operand;
2012
+ return node;
2013
+ }
2014
+ return parsePrimary(ni, unsign);
2015
+ }
2016
+ function parsePrimary(ni, unsign = false) {
2017
+ const t = ni.$;
2018
+ if (!t) {
2019
+ pushError(ni, "Expected operand");
2020
+ return;
2021
+ }
2022
+ if (t.type === "number") return parseNumber(ni, t, unsign);
2023
+ if (isParenBlock(t)) {
2024
+ const subNi = ni.fork(t.children || []);
2025
+ ni.move();
2026
+ if (!subNi.$) {
2027
+ pushError(subNi, "Empty parenthesized expression");
2028
+ return;
2029
+ }
2030
+ const expr = parseAdditive(subNi);
2031
+ if (expr && subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
2032
+ return expr;
2033
+ }
2034
+ if (t.type === "identifier") {
2035
+ if (VALUE_KEYWORDS.has(t.text)) {
2036
+ pushError(ni, `"${t.text}" is not allowed in an arithmetic expression`);
2037
+ return;
2038
+ }
2039
+ if (t.text === "coalesce" && isParenBlock(ni.next().$)) {
2040
+ ni.move();
2041
+ return parseCoalesce(ni);
2042
+ }
2043
+ return parseFieldRef(ni);
2044
+ }
2045
+ pushError(ni, `Unexpected token in expression: "${t.text}"`);
2046
+ }
2047
+ /** Why a number literal cannot be used in an expression (or `undefined` when it can). */ function numberLiteralProblem(text, value) {
2048
+ if (!Number.isFinite(value)) return "is out of range";
2049
+ if (value === 0 && /[1-9]/.test(text.replace(/[eE].*$/, ""))) return "underflows to 0";
2050
+ if (Math.abs(value) > Number.MAX_SAFE_INTEGER) return "exceeds the safe integer range (±2^53 - 1)";
2051
+ }
2052
+ function parseNumber(ni, lexical, unsign) {
2053
+ const token = new Token(lexical);
2054
+ const text = unsign ? token.text.slice(1) : token.text;
2055
+ const value = Number(text);
2056
+ const problem = numberLiteralProblem(text, value);
2057
+ if (problem) {
2058
+ pushError(ni, `Number literal "${token.text}" ${problem}`);
2059
+ ni.move();
2060
+ return;
2061
+ }
2062
+ ni.move();
2063
+ const node = new SemanticExprNumberNode();
2064
+ node.valueToken = token;
2065
+ node.value = value;
2066
+ return node;
2067
+ }
2068
+ function parseCoalesce(ni) {
2069
+ const subNi = ni.fork(ni.$?.children || []);
2070
+ ni.move();
2071
+ const args = [];
2072
+ if (subNi.$) for (;;) {
2073
+ const arg = parseAdditive(subNi);
2074
+ if (!arg) return;
2075
+ args.push(arg);
2076
+ if (!isPunct(subNi.$, ",")) break;
2077
+ subNi.move();
2078
+ }
2079
+ if (subNi.$) {
2080
+ pushError(subNi, `Unexpected token in coalesce(): "${subNi.$.text}"`);
2081
+ return;
2082
+ }
2083
+ if (args.length < 2) {
2084
+ pushError(subNi, "coalesce() requires at least 2 arguments");
2085
+ return;
2086
+ }
2087
+ const node = new SemanticExprCallNode();
2088
+ node.args = args;
2089
+ return node;
2090
+ }
2091
+ /**
2092
+ * Parse a backtick ordering: `key (asc|desc)? (, key (asc|desc)?)*`.
2093
+ * Returns `undefined` when the content is empty or a key does not parse.
2094
+ */ function parseOrderList(ni, sourceToken) {
2095
+ if (!ni.$) {
2096
+ pushError(ni, "Empty order list");
2097
+ return;
2098
+ }
2099
+ const items = [];
2100
+ for (;;) {
2101
+ const ref = parseFieldRef(ni);
2102
+ if (!ref) return;
2103
+ const item = {
2104
+ ref,
2105
+ desc: false
2106
+ };
2107
+ if (ni.$?.type === "identifier" && ORDER_DIRECTIONS.has(ni.$.text)) {
2108
+ item.desc = ni.$.text === "desc";
2109
+ item.dirToken = new Token(ni.$);
2110
+ ni.move();
2111
+ }
2112
+ items.push(item);
2113
+ if (!ni.$) break;
2114
+ if (isPunct(ni.$, ",")) {
2115
+ ni.move();
2116
+ continue;
2117
+ }
2118
+ pushError(ni, `Unexpected token in order list: "${ni.$.text}" (expected "," or "asc" / "desc")`);
2119
+ return;
2120
+ }
2121
+ const node = new SemanticOrderNode();
2122
+ node.items = items;
2123
+ node.sourceToken = sourceToken;
2124
+ return node;
2125
+ }
2126
+
2127
+ //#endregion
2128
+ //#region packages/core/src/lsp/legacy-db-query-scope.ts
2129
+ /**
2130
+ * @deprecated Built-in editor scopes for the `@db.view.filter`, `@db.view.joins` and
2131
+ * `@db.rel.filter` query arguments. They are a fallback for DB plugin versions whose
2132
+ * argument specs do not declare a `fieldScope` hook yet — the DB plugin owns these
2133
+ * rules now. Scheduled for removal in `@atscript/core` 0.2.0 (next minor).
2134
+ */
2135
+ /**
2136
+ * @deprecated Query scope of a built-in `@db.*` query argument (see the module note);
2137
+ * `undefined` for any other annotation.
2138
+ */ function getLegacyDbQueryScope(queryArgToken) {
2139
+ const owner = queryArgToken.parentNode;
2140
+ if (!owner) return;
2141
+ switch (queryArgToken.annotationRef?.text.slice(1)) {
2142
+ case "db.view.filter": return getViewFilterScope(owner);
2143
+ case "db.view.joins": return getViewJoinsScope(owner, queryArgToken);
2144
+ case "db.rel.filter": return getRelFilterScope(owner);
2145
+ default: return;
2146
+ }
2147
+ }
2148
+ function getViewFilterScope(owner) {
2149
+ const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
2150
+ if (!entryTypeName) return;
2151
+ const allowedTypes = [entryTypeName];
2152
+ const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
2153
+ if (joinsAnnotations) {
2154
+ for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
2155
+ }
2156
+ return {
2157
+ allowedTypes,
2158
+ unqualifiedTarget: entryTypeName
2159
+ };
2160
+ }
2161
+ function getViewJoinsScope(owner, queryArgToken) {
2162
+ const entryTypeName = (owner.annotations?.filter((a) => a.name === "db.view.for"))?.[0]?.args[0]?.text;
2163
+ if (!entryTypeName) return;
2164
+ const joinTargetName = (owner.annotations?.find((a) => a.name === "db.view.joins" && a.args.includes(queryArgToken)))?.args[0]?.text;
2165
+ if (!joinTargetName) return;
2166
+ return {
2167
+ allowedTypes: [joinTargetName, entryTypeName],
2168
+ unqualifiedTarget: entryTypeName
2169
+ };
2170
+ }
2171
+ function getRelFilterScope(owner) {
2172
+ let def = owner.getDefinition();
2173
+ if (isArray(def)) def = def?.getDefinition();
2174
+ if (!isRef(def)) return;
2175
+ const targetTypeName = def.id;
2176
+ const allowedTypes = [targetTypeName];
2177
+ const viaAnnotation = owner.annotations?.find((a) => a.name === "db.rel.via");
2178
+ if (viaAnnotation?.args[0]) allowedTypes.push(viaAnnotation.args[0].text);
2179
+ return {
2180
+ allowedTypes,
2181
+ unqualifiedTarget: targetTypeName
2182
+ };
2183
+ }
2184
+
2185
+ //#endregion
2186
+ //#region packages/core/src/lsp/field-refs.ts
2187
+ function getArgSpecAt(annotationToken, index, doc) {
2188
+ return doc.resolveAnnotation(annotationToken.text.slice(1))?.arguments[index];
2189
+ }
2190
+ function getArgSpec(argToken, doc) {
2191
+ const annotationRef = argToken.annotationRef;
2192
+ if (!annotationRef || typeof argToken.index !== "number") return;
2193
+ return getArgSpecAt(annotationRef, argToken.index, doc);
2194
+ }
2195
+ /**
2196
+ * The annotation an argument token belongs to, found among the annotations of the annotated
2197
+ * node (`argToken.parentNode`, a prop or an annotate entry). For `fieldScope` hooks that scope
2198
+ * an argument by its siblings (`getSiblingAnnotation(arg)?.args[0]?.text`).
2199
+ */ function getSiblingAnnotation(argToken) {
2200
+ return argToken.parentNode?.annotations?.find((a) => a.args.includes(argToken));
2201
+ }
2202
+ /**
2203
+ * The values an annotation argument may take, from the `valueScope` hook of its spec
2204
+ * (`undefined` when the argument declares none or the set cannot be determined).
2205
+ */ function getValueCandidates(annotationToken, argIndex, doc) {
2206
+ return getArgSpecAt(annotationToken, argIndex, doc)?.valueScope?.(annotationToken, doc);
2207
+ }
2208
+ /**
2209
+ * The declared value a value-argument token names (`valueScope`), or `undefined` when the token
2210
+ * is not a value argument or names no candidate.
2211
+ */ function getDeclaredValue(token, doc) {
2212
+ if (!token.annotationRef || typeof token.index !== "number" || token.isReference) return;
2213
+ return getValueCandidates(token.annotationRef, token.index, doc)?.find((c) => c.value === token.text);
2214
+ }
2215
+ /**
2216
+ * Field scope of an annotation argument: the answer of the argument spec's `fieldScope`
2217
+ * hook when it declares one, otherwise the deprecated built-in `@db.*` query rules.
2218
+ */ function getQueryScope(argToken, doc) {
2219
+ const argSpec = getArgSpec(argToken, doc);
2220
+ return argSpec?.fieldScope ? argSpec.fieldScope(argToken, doc) : getLegacyDbQueryScope(argToken);
2221
+ }
2222
+ /**
2223
+ * Type a field-path `string` argument names a field of: the `unqualifiedTarget` of the
2224
+ * argument spec's `fieldScope`. `undefined` for any other token.
2225
+ */ function getFieldPathTarget(argToken, doc) {
2226
+ if (argToken.type !== "text") return;
2227
+ const argSpec = getArgSpec(argToken, doc);
2228
+ if (argSpec?.type !== "string" || !argSpec.fieldScope) return;
2229
+ return argSpec.fieldScope(argToken, doc)?.unqualifiedTarget ?? void 0;
2230
+ }
2231
+ /**
2232
+ * Resolve a (possibly dotted) field path of a type to the property it names and the
2233
+ * document that declares that property.
2234
+ */ function resolveFieldPath(doc, typeName, segment) {
2235
+ const chain = segment.path.split(".");
2236
+ const [name] = chain.splice(-1);
2237
+ const parent = doc.unwindType(typeName, chain);
2238
+ if (!parent || !(isStructure(parent.def) || isInterface(parent.def))) return;
2239
+ const prop = parent.def.props.get(name);
2240
+ return prop && {
2241
+ typeName,
2242
+ range: segment.range,
2243
+ prop,
2244
+ doc: parent.doc
2245
+ };
2246
+ }
2247
+ /**
2248
+ * Segments of a field-path string argument (`'address.city'` → `address`, `city`), with
2249
+ * ranges that exclude the quotes. A string spanning several lines is a single segment.
2250
+ */ function fieldPathSegments(argToken) {
2251
+ const { text, range } = argToken;
2252
+ if (range.start.line !== range.end.line) return [{
2253
+ path: text,
2254
+ range
2255
+ }];
2256
+ const line = range.start.line;
2257
+ const contentStart = range.start.character + 1;
2258
+ const segments = [];
2259
+ let start = 0;
2260
+ for (const part of text.split(".")) {
2261
+ const end = start + part.length;
2262
+ segments.push({
2263
+ path: text.slice(0, end),
2264
+ range: {
2265
+ start: {
2266
+ line,
2267
+ character: contentStart + start
2268
+ },
2269
+ end: {
2270
+ line,
2271
+ character: contentStart + end
2272
+ }
2273
+ }
2274
+ });
2275
+ start = end + 1;
2276
+ }
2277
+ return segments;
2278
+ }
2279
+ /** The segment under `character`, or the last segment when `character` is omitted. */ function fieldPathSegmentAt(argToken, character) {
2280
+ const segments = fieldPathSegments(argToken);
2281
+ return (character === void 0 ? void 0 : segments.find((s) => s.range.end.character >= character)) ?? segments[segments.length - 1];
2282
+ }
2283
+ /**
2284
+ * Resolve a field reference token to the property it names:
2285
+ * - a field ref inside a `query` argument (`amount`, `Customer.name` in backticks);
2286
+ * - a `string` argument whose spec declares `fieldScope`: a (dotted) field path of the
2287
+ * scope's `unqualifiedTarget`. With `character` (a cursor column), the path resolves
2288
+ * only up to the segment under the cursor — `'address.city'` with the cursor on
2289
+ * `address` resolves `address` — and `range` is that segment's range.
2290
+ *
2291
+ * Returns `undefined` for any other token, or when the scope or the path does not resolve.
2292
+ */ function resolveFieldRefAt(token, doc, character) {
2293
+ if (isQueryFieldRef(token.parentNode)) {
2294
+ const { fieldRef, typeRef, queryArgToken } = token.parentNode;
2295
+ const scope = token === fieldRef && queryArgToken ? getQueryScope(queryArgToken, doc) : void 0;
2296
+ const typeName = scope && (typeRef?.text ?? scope.unqualifiedTarget);
2297
+ return typeName ? resolveFieldPath(doc, typeName, {
2298
+ path: token.text,
2299
+ range: token.range
2300
+ }) : void 0;
2301
+ }
2302
+ const typeName = getFieldPathTarget(token, doc);
2303
+ return typeName ? resolveFieldPath(doc, typeName, fieldPathSegmentAt(token, character)) : void 0;
2304
+ }
2305
+ /**
2306
+ * Resolve the segments named `fieldName` of a field-path `string` argument
2307
+ * (`'address.city'` has the segments `address` and `city`). Supports find-references.
2308
+ */ function resolveFieldPathArgSegments(argToken, doc, fieldName) {
2309
+ const segments = fieldPathSegments(argToken).filter((s) => s.path === fieldName || s.path.endsWith(`.${fieldName}`));
2310
+ const typeName = segments.length > 0 ? getFieldPathTarget(argToken, doc) : void 0;
2311
+ if (!typeName) return [];
2312
+ const targets = [];
2313
+ for (const segment of segments) {
2314
+ const target = resolveFieldPath(doc, typeName, segment);
2315
+ if (target) targets.push(target);
2316
+ }
2317
+ return targets;
2318
+ }
2319
+ /**
2320
+ * Resolve a query field ref node to a property definition.
2321
+ */ function resolveQueryFieldRef(fieldRefNode, doc, scope) {
2322
+ const typeName = fieldRefNode.typeRef?.text ?? scope.unqualifiedTarget;
2323
+ const { fieldRef } = fieldRefNode;
2324
+ const resolved = typeName ? resolveFieldPath(doc, typeName, {
2325
+ path: fieldRef.text,
2326
+ range: fieldRef.range
2327
+ }) : void 0;
2328
+ return resolved && {
2329
+ targetUri: resolved.doc.id,
2330
+ doc: resolved.doc,
2331
+ prop: resolved.prop
2332
+ };
2333
+ }
2334
+ /**
2335
+ * Get fields available for a type (resolving extends/intersections).
2336
+ * With `chain`, returns the fields of the nested object that field path leads to.
2337
+ */ function getFieldsForType(doc, typeName, chain = []) {
2338
+ const unwound = doc.unwindType(typeName, chain);
2339
+ if (!unwound?.def) return [];
2340
+ let def = unwound.doc.mergeIntersection(unwound.def);
2341
+ if (isInterface(def)) def = unwound.doc.resolveInterfaceExtends(def) || def.getDefinition() || def;
2342
+ if (isStructure(def) || isInterface(def)) return Array.from(def.props.values());
2343
+ return [];
2344
+ }
2345
+ /**
2346
+ * Completion scope of a field-path `string` argument (spec declares `fieldScope`) at the
2347
+ * cursor column `character`: the fields of the level being typed — `'address.ci'` offers
2348
+ * the fields of `address` (`chain` = `['address']`).
2349
+ */ function getFieldPathCompletionScope(argToken, doc, character) {
2350
+ const typeName = getFieldPathTarget(argToken, doc);
2351
+ if (!typeName) return;
2352
+ const chain = fieldPathSegmentAt(argToken, character).path.split(".").slice(0, -1);
2353
+ return {
1592
2354
  typeName,
1593
2355
  chain,
1594
2356
  fields: getFieldsForType(doc, typeName, chain)
@@ -1605,14 +2367,6 @@ function getArgSpec(argToken, doc) {
1605
2367
  getFields: (typeName) => getFieldsForType(doc, typeName)
1606
2368
  };
1607
2369
  }
1608
- const SYMBOLIC_OPS$1 = new Set([
1609
- "=",
1610
- "!=",
1611
- ">",
1612
- ">=",
1613
- "<",
1614
- "<="
1615
- ]);
1616
2370
  const KEYWORD_OPS = new Set([
1617
2371
  "in",
1618
2372
  "matches",
@@ -1623,18 +2377,14 @@ const LOGICAL_KEYWORDS = new Set([
1623
2377
  "or",
1624
2378
  "not"
1625
2379
  ]);
1626
- const VALUE_KEYWORDS$1 = new Set([
1627
- "true",
1628
- "false",
1629
- "null",
1630
- "undefined"
1631
- ]);
1632
2380
  /**
1633
2381
  * Analyze text inside backticks up to cursor position
1634
2382
  * to determine what kind of completions to offer.
1635
2383
  * Uses lightweight text scanning, not full AST parsing,
1636
2384
  * so it works on incomplete/mid-typing input.
1637
- */ function analyzeQueryCursorContext(textBeforeCursor) {
2385
+ *
2386
+ * `mode` selects the grammar of the argument (default `query`).
2387
+ */ function analyzeQueryCursorContext(textBeforeCursor, mode = "query") {
1638
2388
  const trimmed = textBeforeCursor.trimEnd();
1639
2389
  const hasTrailingSpace = textBeforeCursor.length > trimmed.length;
1640
2390
  if (trimmed.length === 0) return { type: "field-start" };
@@ -1647,18 +2397,19 @@ const VALUE_KEYWORDS$1 = new Set([
1647
2397
  };
1648
2398
  return { type: "field-start" };
1649
2399
  }
2400
+ if (mode !== "query") return analyzeArgCursorContext(trimmed, hasTrailingSpace, mode);
1650
2401
  const tokens = tokenizeQueryText(trimmed);
1651
2402
  if (tokens.length === 0) return { type: "field-start" };
1652
2403
  const last = tokens[tokens.length - 1];
1653
2404
  if (LOGICAL_KEYWORDS.has(last) || last === "(") return { type: "field-start" };
1654
- if (SYMBOLIC_OPS$1.has(last)) return { type: "after-operator" };
2405
+ if (SYMBOLIC_OPS.has(last)) return { type: "after-operator" };
1655
2406
  if (last === "in" || last === "matches") return { type: "after-operator" };
1656
2407
  if (last === "exists") return { type: "after-comparison" };
1657
- if (VALUE_KEYWORDS$1.has(last)) return { type: "after-comparison" };
2408
+ if (VALUE_KEYWORDS.has(last)) return { type: "after-comparison" };
1658
2409
  if (/^['"]/.test(last) || /^\d/.test(last)) return { type: "after-comparison" };
1659
2410
  if (tokens.length >= 2) {
1660
2411
  const prev = tokens[tokens.length - 2];
1661
- if (SYMBOLIC_OPS$1.has(prev) || KEYWORD_OPS.has(prev)) return { type: "after-comparison" };
2412
+ if (SYMBOLIC_OPS.has(prev) || KEYWORD_OPS.has(prev)) return { type: "after-comparison" };
1662
2413
  }
1663
2414
  if (/^\w+$/u.test(last)) {
1664
2415
  if (!hasTrailingSpace) return { type: "field-start" };
@@ -1666,10 +2417,30 @@ const VALUE_KEYWORDS$1 = new Set([
1666
2417
  }
1667
2418
  return { type: "field-start" };
1668
2419
  }
2420
+ const ARITHMETIC_OPS = new Set(BACKTICK_ARG_VOCABULARY.arithmeticOps);
2421
+ /** An order key (an identifier other than `asc` / `desc`). */ function isOrderKey(token) {
2422
+ return token !== void 0 && /^\w+$/u.test(token) && !ORDER_DIRECTIONS.has(token);
2423
+ }
2424
+ /**
2425
+ * Cursor context inside an `expr` or `order` argument — `trimmed` is the
2426
+ * non-empty text before the cursor that does not end with `.`.
2427
+ */ function analyzeArgCursorContext(trimmed, hasTrailingSpace, mode) {
2428
+ const tokens = tokenizeQueryText(trimmed, true);
2429
+ const last = tokens[tokens.length - 1];
2430
+ if (last === void 0 || last === "," || last === "(" || ARITHMETIC_OPS.has(last)) return { type: "field-start" };
2431
+ if (mode === "order") {
2432
+ if (!/^\w+$/u.test(last)) return { type: "after-order-direction" };
2433
+ if (!hasTrailingSpace) return isOrderKey(tokens[tokens.length - 2]) ? { type: "after-order-key" } : { type: "field-start" };
2434
+ return isOrderKey(last) ? { type: "after-order-key" } : { type: "after-order-direction" };
2435
+ }
2436
+ if (/^[a-z_$]\w*$/iu.test(last) && !hasTrailingSpace) return { type: "field-start" };
2437
+ return { type: "after-operand" };
2438
+ }
1669
2439
  /**
1670
2440
  * Simple tokenizer for query text — splits into identifiers, operators, and punctuation.
1671
2441
  * Does NOT need to handle all edge cases; just enough for cursor context analysis.
1672
- */ function tokenizeQueryText(text) {
2442
+ * With `arithmetic`, `+ - * /` are tokens too (otherwise they are skipped).
2443
+ */ function tokenizeQueryText(text, arithmetic = false) {
1673
2444
  const tokens = [];
1674
2445
  let i = 0;
1675
2446
  while (i < text.length) {
@@ -1696,7 +2467,7 @@ const VALUE_KEYWORDS$1 = new Set([
1696
2467
  continue;
1697
2468
  }
1698
2469
  }
1699
- if ("=><(),".includes(text[i])) {
2470
+ if ("=><(),".includes(text[i]) || arithmetic && ARITHMETIC_OPS.has(text[i])) {
1700
2471
  tokens.push(text[i]);
1701
2472
  i++;
1702
2473
  continue;
@@ -1720,7 +2491,7 @@ const VALUE_KEYWORDS$1 = new Set([
1720
2491
 
1721
2492
  //#endregion
1722
2493
  //#region packages/core/src/parser/id-registry.ts
1723
- function _define_property$7(obj, key, value) {
2494
+ function _define_property$6(obj, key, value) {
1724
2495
  if (key in obj) Object.defineProperty(obj, key, {
1725
2496
  value,
1726
2497
  enumerable: true,
@@ -1758,11 +2529,11 @@ var IdRegistry = class {
1758
2529
  }))];
1759
2530
  }
1760
2531
  constructor(globalTypes = []) {
1761
- _define_property$7(this, "reserved", void 0);
1762
- _define_property$7(this, "globalTypes", void 0);
1763
- _define_property$7(this, "definitions", /* @__PURE__ */ new Map());
1764
- _define_property$7(this, "duplicates", /* @__PURE__ */ new Set());
1765
- _define_property$7(this, "forbidden", /* @__PURE__ */ new Set());
2532
+ _define_property$6(this, "reserved", void 0);
2533
+ _define_property$6(this, "globalTypes", void 0);
2534
+ _define_property$6(this, "definitions", /* @__PURE__ */ new Map());
2535
+ _define_property$6(this, "duplicates", /* @__PURE__ */ new Set());
2536
+ _define_property$6(this, "forbidden", /* @__PURE__ */ new Set());
1766
2537
  this.reserved = new Set([
1767
2538
  "interface",
1768
2539
  "type",
@@ -1776,137 +2547,6 @@ var IdRegistry = class {
1776
2547
  }
1777
2548
  };
1778
2549
 
1779
- //#endregion
1780
- //#region packages/core/src/parser/iterator.ts
1781
- function _define_property$6(obj, key, value) {
1782
- if (key in obj) Object.defineProperty(obj, key, {
1783
- value,
1784
- enumerable: true,
1785
- configurable: true,
1786
- writable: true
1787
- });
1788
- else obj[key] = value;
1789
- return obj;
1790
- }
1791
- var NodeIterator = class NodeIterator {
1792
- get index() {
1793
- return this.i;
1794
- }
1795
- get lastNode() {
1796
- return this.nodes[this.nodes.length - 1];
1797
- }
1798
- unexpectedEOB() {
1799
- this.issues.unexpectedEOB = true;
1800
- }
1801
- unfork(fork) {
1802
- this.i = fork.index;
1803
- this.update();
1804
- }
1805
- accepted() {
1806
- if (this.$ && this.$.accepted !== false) {
1807
- this.$.accepted = true;
1808
- this.badNodes.delete(this.$);
1809
- }
1810
- }
1811
- toString() {
1812
- return this.$ ? `[${this.$.type}] ${this.$.text}` : `void`;
1813
- }
1814
- update() {
1815
- this.$ = this.nodes[this.i];
1816
- return this;
1817
- }
1818
- move(v = 1) {
1819
- this.i += v;
1820
- this.$ = this.nodes[this.i];
1821
- return this;
1822
- }
1823
- next(skip) {
1824
- return this.fork().move().skip(skip);
1825
- }
1826
- fork(nodes) {
1827
- return new NodeIterator(nodes || this.nodes, this.messages, this.badNodes, this.issues, nodes ? this.$ : this.parent, nodes ? 0 : this.i).update();
1828
- }
1829
- skip(pun) {
1830
- while (this.$?.type === "comment" || this.$?.type === "punctuation" && pun?.length && pun.includes(this.$.text)) this.move();
1831
- return this;
1832
- }
1833
- skipUntil(pun) {
1834
- while (this.$ && !this.satisfies({
1835
- node: "punctuation",
1836
- text: pun
1837
- })) this.move();
1838
- }
1839
- unexpected(force = false, msg = "Unexpected token") {
1840
- if (force && this.$) this.$.accepted = false;
1841
- if (this.$ && !this.badNodes.has(this.$)) this.badNodes.set(this.$, msg);
1842
- }
1843
- shouldHaveError(depth) {
1844
- for (let i = this.i; i <= depth; i++) if (i < this.nodes.length) this.nodes[i].accepted = false;
1845
- }
1846
- nodesLeft() {
1847
- return this.nodes.length > 0 && this.index < this.nodes.length;
1848
- }
1849
- satisfies(...rules) {
1850
- for (const rule of rules) {
1851
- const passed = Array.isArray(rule.node) ? rule.node.includes(this.$?.type) : this.$?.type === rule.node;
1852
- if (passed && rule.text === void 0) return true;
1853
- if (passed && Array.isArray(rule.text) ? rule.text.includes(this.$?.text) : this.$?.text === rule.text) return true;
1854
- }
1855
- return false;
1856
- }
1857
- confirmIssues() {
1858
- if (this.issues.unexpectedEOB) {
1859
- const pos = (this.lastNode || this.parent)?.getRange().end || {
1860
- character: 1,
1861
- line: 1
1862
- };
1863
- this.messages.push({
1864
- severity: 1,
1865
- message: `Unexpected end of block`,
1866
- range: {
1867
- start: pos,
1868
- end: pos
1869
- }
1870
- });
1871
- this.issues.unexpectedEOB = false;
1872
- }
1873
- }
1874
- getErrors() {
1875
- this.badNodes.forEach((msg, node) => {
1876
- if (node.accepted) this.badNodes.delete(node);
1877
- });
1878
- return Array.from(this.badNodes.entries(), ([node, msg]) => ({
1879
- severity: 1,
1880
- message: msg,
1881
- range: node.getRange?.() || {
1882
- start: {
1883
- character: 1,
1884
- line: 1
1885
- },
1886
- end: {
1887
- character: 1,
1888
- line: 1
1889
- }
1890
- }
1891
- })).concat(this.messages);
1892
- }
1893
- constructor(nodes, messages = [], badNodes = /* @__PURE__ */ new Map(), issues = {}, parent, i = -1) {
1894
- _define_property$6(this, "nodes", void 0);
1895
- _define_property$6(this, "messages", void 0);
1896
- _define_property$6(this, "badNodes", void 0);
1897
- _define_property$6(this, "issues", void 0);
1898
- _define_property$6(this, "parent", void 0);
1899
- _define_property$6(this, "i", void 0);
1900
- _define_property$6(this, "$", void 0);
1901
- this.nodes = nodes;
1902
- this.messages = messages;
1903
- this.badNodes = badNodes;
1904
- this.issues = issues;
1905
- this.parent = parent;
1906
- this.i = i;
1907
- }
1908
- };
1909
-
1910
2550
  //#endregion
1911
2551
  //#region packages/core/src/tokenizer/tokens/a-identifier.token.ts
1912
2552
  /**
@@ -2062,6 +2702,33 @@ const block$1 = new Node({
2062
2702
  }
2063
2703
  });
2064
2704
 
2705
+ //#endregion
2706
+ //#region packages/core/src/tokenizer/tokens/query-arith.token.ts
2707
+ /**
2708
+ * Arithmetic operator token — `*` and `-` inside backtick expressions
2709
+ * (`+` and `/` are already generic punctuation).
2710
+ *
2711
+ * Registered after `NumberToken`, so a sign written adjacent to a number
2712
+ * (`-5`, `+1`) still lexes as a signed number; the expression parser splits a
2713
+ * signed number found in binary-operator position (`a -5` → `a - 5`).
2714
+ * Only recognized inside queries — not in root or generic blocks.
2715
+ */ const QueryArithmeticToken = new Node({
2716
+ name: "punctuation",
2717
+ start: {
2718
+ token: RegExp("(?<text>[*-])", "u"),
2719
+ omit: true
2720
+ },
2721
+ end: {
2722
+ token: "",
2723
+ omit: true
2724
+ },
2725
+ eofClose: true,
2726
+ data: {
2727
+ type: "punctuation",
2728
+ text: ""
2729
+ }
2730
+ });
2731
+
2065
2732
  //#endregion
2066
2733
  //#region packages/core/src/tokenizer/tokens/query-block.token.ts
2067
2734
  /**
@@ -2115,43 +2782,54 @@ const block$1 = new Node({
2115
2782
  omit: true
2116
2783
  },
2117
2784
  end: {
2118
- token: /`/u,
2119
- omit: true
2120
- },
2121
- skip: /\s/u,
2122
- eofClose: true,
2123
- data: {
2124
- type: "query",
2125
- text: ""
2126
- }
2127
- });
2128
-
2129
- //#endregion
2130
- //#region packages/core/src/tokenizer/tokens/regexp.token.ts
2131
- const REGEXP_LITERAL_RE = /\/(?![/*])(?:\\.|\[.*?]|[^/\\\n\r[])*\/[dgimsuy]*/;
2132
- /**
2133
- * RegExp literal – `/pattern/flags`
2134
- * • Starts with `/` but *not* `//` or `/*`
2135
- * • Ends with `/` followed by zero-or-more valid flags
2136
- */ const RegExpToken = new Node({
2137
- name: "regexp",
2138
- start: {
2139
- token: REGEXP_LITERAL_RE,
2140
- omit: true
2141
- },
2142
- end: {
2143
- token: "",
2785
+ token: /`/u,
2144
2786
  omit: true
2145
2787
  },
2788
+ skip: /\s/u,
2146
2789
  eofClose: true,
2147
2790
  data: {
2148
- type: "regexp",
2791
+ type: "query",
2149
2792
  text: ""
2150
2793
  }
2151
- }).onOpen((node, match) => {
2152
- node.data.text = match?.text ?? "";
2153
2794
  });
2154
2795
 
2796
+ //#endregion
2797
+ //#region packages/core/src/tokenizer/tokens/regexp.token.ts
2798
+ const REGEXP_LITERAL_RE = /\/(?![/*])(?:\\.|\[.*?]|[^/\\\n\r[])*\/[dgimsuy]*/;
2799
+ /**
2800
+ * Regexp literal inside a backtick expression: only directly after the
2801
+ * `matches` keyword (the one operator that takes a regexp), so `/` elsewhere
2802
+ * stays the division operator (`a / b / c` is not the regexp `/ b /`).
2803
+ * The lookbehind works because the parser scans the full source from the
2804
+ * current position.
2805
+ */ const QUERY_REGEXP_LITERAL_RE = new RegExp(`(?<=\\bmatches\\s*)${REGEXP_LITERAL_RE.source}`);
2806
+ /** A regexp-literal token node starting at `start`. */ function regExpNode(start) {
2807
+ return new Node({
2808
+ name: "regexp",
2809
+ start: {
2810
+ token: start,
2811
+ omit: true
2812
+ },
2813
+ end: {
2814
+ token: "",
2815
+ omit: true
2816
+ },
2817
+ eofClose: true,
2818
+ data: {
2819
+ type: "regexp",
2820
+ text: ""
2821
+ }
2822
+ }).onOpen((node, match) => {
2823
+ node.data.text = match?.text ?? "";
2824
+ });
2825
+ }
2826
+ /**
2827
+ * RegExp literal – `/pattern/flags`
2828
+ * • Starts with `/` but *not* `//` or `/*`
2829
+ * • Ends with `/` followed by zero-or-more valid flags
2830
+ */ const RegExpToken = regExpNode(REGEXP_LITERAL_RE);
2831
+ /** RegExp literal inside backtick expressions — recognized only after `matches`. */ const QueryRegExpToken = regExpNode(QUERY_REGEXP_LITERAL_RE);
2832
+
2155
2833
  //#endregion
2156
2834
  //#region packages/core/src/tokenizer/tokens/text.node.ts
2157
2835
  /**
@@ -2213,8 +2891,8 @@ const root = new Node({
2213
2891
  });
2214
2892
  tokens.root = root;
2215
2893
  BlockToken.recognize(RegExpToken, ...commentNodes.all, BlockToken, QueryToken, AIdentifierToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2216
- QueryToken.recognize(RegExpToken, QueryOperatorToken, QueryBlockToken, BlockToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2217
- QueryBlockToken.recognize(RegExpToken, QueryOperatorToken, QueryBlockToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
2894
+ QueryToken.recognize(QueryRegExpToken, QueryOperatorToken, QueryBlockToken, BlockToken, IdentifierToken, TextToken, NumberToken, QueryArithmeticToken, PunctuationToken);
2895
+ QueryBlockToken.recognize(QueryRegExpToken, QueryOperatorToken, QueryBlockToken, IdentifierToken, TextToken, NumberToken, QueryArithmeticToken, PunctuationToken);
2218
2896
  /** 1-based parser position → 0-based VSCode position, shifted by `offset` characters. */ function toPos(p, offset = 0) {
2219
2897
  return {
2220
2898
  line: p.line - 1,
@@ -2426,373 +3104,93 @@ function $pipe(entity, pipe = []) {
2426
3104
  this.stopCondition = sc;
2427
3105
  return this;
2428
3106
  },
2429
- t(node, skip = []) {
2430
- this.pipe.push($token(node).saveAs("identifier").skip(...skip));
2431
- return this;
2432
- }
2433
- };
2434
- }
2435
- function runPipes(pipes, ni, singlePass = false) {
2436
- const nodes = [];
2437
- while (ni.$) {
2438
- let matched = true;
2439
- let depth = ni.index;
2440
- for (const { targetFactory, pipe, skipTokens: skip, stopCondition } of pipes) {
2441
- const target = { node: targetFactory() };
2442
- const fork = ni.fork();
2443
- fork.skip(skip);
2444
- if (!fork.$) {
2445
- ni.unfork(fork);
2446
- break;
2447
- }
2448
- matched = true;
2449
- for (const { handler } of pipe) if (!handler(fork, target)) {
2450
- matched = false;
2451
- break;
2452
- }
2453
- if (fork.index > depth) depth = fork.index;
2454
- if (matched) {
2455
- nodes.push(target.node);
2456
- ni.unfork(fork);
2457
- if (stopCondition && stopCondition(fork)) return nodes;
2458
- ni.move(-1);
2459
- break;
2460
- }
2461
- }
2462
- if (singlePass) return nodes;
2463
- if (!matched) {
2464
- ni.shouldHaveError(depth);
2465
- ni.move(depth - ni.index);
2466
- }
2467
- ni.move();
2468
- if (matched) {} else {
2469
- ni.confirmIssues();
2470
- ni.skipUntil([";", "\n"]);
2471
- }
2472
- }
2473
- return nodes;
2474
- }
2475
- function runPipesOnce(pipes, ni) {
2476
- return runPipes(pipes, ni, true)[0];
2477
- }
2478
-
2479
- //#endregion
2480
- //#region packages/core/src/parser/grouping.ts
2481
- function groupByPriority(nodes, priority) {
2482
- if (nodes.length === 1) return nodes[0];
2483
- if (nodes.length === 0) return;
2484
- if (nodes.length % 2 === 0) throw new Error(`Invalid number of nodes ${nodes.length}. Odd number expected`);
2485
- let currentPass = nodes;
2486
- let temporaryResult = [];
2487
- let groupped = [];
2488
- for (const p of priority) {
2489
- for (const [i, node] of currentPass.entries()) {
2490
- const isOperator = i % 2 === 1;
2491
- if (!isOperator && node instanceof Token) throw new Error(`Unexpected token ${node.toString()} at ${i}`);
2492
- else if (isOperator && !(node instanceof Token)) throw new Error(`Unexpected token ${isGroup(node) ? node.op : node.token.toString()} at ${i}`);
2493
- if (isOperator) {
2494
- if (node.text !== p) temporaryResult.push(node);
2495
- continue;
2496
- }
2497
- const prev = currentPass[i - 1]?.text;
2498
- const next = currentPass[i + 1]?.text;
2499
- if (prev !== p && next !== p) {
2500
- temporaryResult.push(node);
2501
- continue;
2502
- }
2503
- if (prev === p || next === p) {
2504
- groupped.push(node);
2505
- if (next !== p) {
2506
- temporaryResult.push(new $n.SemanticGroup(groupped, p));
2507
- groupped = [];
2508
- }
2509
- }
2510
- }
2511
- currentPass = temporaryResult;
2512
- temporaryResult = [];
2513
- }
2514
- const output = currentPass[0];
2515
- return output.length === 1 ? output.first : output;
2516
- }
2517
-
2518
- //#endregion
2519
- //#region packages/core/src/parser/pipes/query.pipe.ts
2520
- const SYMBOLIC_OPS = new Set([
2521
- "=",
2522
- "!=",
2523
- ">",
2524
- ">=",
2525
- "<",
2526
- "<="
2527
- ]);
2528
- const VALUE_KEYWORDS = new Set([
2529
- "true",
2530
- "false",
2531
- "null",
2532
- "undefined"
2533
- ]);
2534
- const ZERO_RANGE = {
2535
- start: {
2536
- line: 0,
2537
- character: 0
2538
- },
2539
- end: {
2540
- line: 0,
2541
- character: 0
2542
- }
2543
- };
2544
- /**
2545
- * Parse a backtick-delimited query expression.
2546
- *
2547
- * `ni` iterates the query token's children and carries that token as its
2548
- * `parent` — the range to blame when a diagnostic has no token of its own —
2549
- * so fork it from the annotation iterator while the query token is current.
2550
- * Returns a SemanticQueryNode or undefined if the content is empty.
2551
- */ function parseQueryExpression(ni, sourceToken) {
2552
- if (!ni.$) return;
2553
- const expr = parseOrExpr(ni);
2554
- if (!expr) return;
2555
- if (ni.$) pushError(ni, `Unexpected token in query expression: "${ni.$.text}"`);
2556
- const node = new SemanticQueryNode();
2557
- node.expression = expr;
2558
- node.sourceToken = sourceToken;
2559
- return node;
2560
- }
2561
- function parseOrExpr(ni) {
2562
- const left = parseAndExpr(ni);
2563
- if (!left) return;
2564
- const operands = [left];
2565
- while (ni.$?.type === "identifier" && ni.$.text === "or") {
2566
- ni.move();
2567
- const right = parseAndExpr(ni);
2568
- if (!right) {
2569
- pushError(ni, "Expected expression after \"or\"");
2570
- break;
2571
- }
2572
- operands.push(right);
2573
- }
2574
- if (operands.length === 1) return operands[0];
2575
- const node = new SemanticQueryLogicalNode();
2576
- node.operator = "or";
2577
- node.operands = operands;
2578
- return node;
2579
- }
2580
- function parseAndExpr(ni) {
2581
- const left = parseUnaryExpr(ni);
2582
- if (!left) return;
2583
- const operands = [left];
2584
- while (ni.$?.type === "identifier" && ni.$.text === "and") {
2585
- ni.move();
2586
- const right = parseUnaryExpr(ni);
2587
- if (!right) {
2588
- pushError(ni, "Expected expression after \"and\"");
2589
- break;
2590
- }
2591
- operands.push(right);
2592
- }
2593
- if (operands.length === 1) return operands[0];
2594
- const node = new SemanticQueryLogicalNode();
2595
- node.operator = "and";
2596
- node.operands = operands;
2597
- return node;
2598
- }
2599
- function parseUnaryExpr(ni) {
2600
- if (ni.$?.type === "identifier" && ni.$.text === "not") {
2601
- ni.move();
2602
- const operand = parseUnaryExpr(ni);
2603
- if (!operand) {
2604
- pushError(ni, "Expected expression after \"not\"");
2605
- return;
2606
- }
2607
- const node = new SemanticQueryLogicalNode();
2608
- node.operator = "not";
2609
- node.operands = [operand];
2610
- return node;
2611
- }
2612
- if (ni.$?.type === "block" && ni.$.text === "(") {
2613
- const subNi = ni.fork(ni.$.children || []);
2614
- ni.move();
2615
- if (!subNi.$) {
2616
- pushError(subNi, "Empty parenthesized expression");
2617
- return;
2618
- }
2619
- const expr = parseOrExpr(subNi);
2620
- if (subNi.$) pushError(subNi, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
2621
- return expr;
2622
- }
2623
- return parseComparison(ni);
2624
- }
2625
- function parseComparison(ni) {
2626
- const left = parseFieldRef(ni);
2627
- if (!left) return;
2628
- if (ni.$?.type === "punctuation" && SYMBOLIC_OPS.has(ni.$.text)) {
2629
- const opText = ni.$.text;
2630
- ni.move();
2631
- const right = parseValueOrFieldRef(ni);
2632
- if (!right) {
2633
- pushError(ni, `Expected value or field reference after "${opText}"`);
2634
- return;
2635
- }
2636
- const node = new SemanticQueryComparisonNode();
2637
- node.left = left;
2638
- node.operator = opText;
2639
- node.right = right;
2640
- return node;
2641
- }
2642
- if (ni.$?.type === "identifier") {
2643
- const opText = ni.$.text;
2644
- if (opText === "in") {
2645
- ni.move();
2646
- const right = parseValueList(ni);
2647
- if (!right) return;
2648
- const node = new SemanticQueryComparisonNode();
2649
- node.left = left;
2650
- node.operator = "in";
2651
- node.right = right;
2652
- return node;
2653
- }
2654
- if (opText === "matches") {
2655
- ni.move();
2656
- const right = parseValueOrFieldRef(ni);
2657
- if (!right) {
2658
- pushError(ni, "Expected value after \"matches\"");
2659
- return;
3107
+ t(node, skip = []) {
3108
+ this.pipe.push($token(node).saveAs("identifier").skip(...skip));
3109
+ return this;
3110
+ }
3111
+ };
3112
+ }
3113
+ function runPipes(pipes, ni, singlePass = false) {
3114
+ const nodes = [];
3115
+ while (ni.$) {
3116
+ let matched = true;
3117
+ let depth = ni.index;
3118
+ for (const { targetFactory, pipe, skipTokens: skip, stopCondition } of pipes) {
3119
+ const target = { node: targetFactory() };
3120
+ const fork = ni.fork();
3121
+ fork.skip(skip);
3122
+ if (!fork.$) {
3123
+ ni.unfork(fork);
3124
+ break;
3125
+ }
3126
+ matched = true;
3127
+ for (const { handler } of pipe) if (!handler(fork, target)) {
3128
+ matched = false;
3129
+ break;
3130
+ }
3131
+ if (fork.index > depth) depth = fork.index;
3132
+ if (matched) {
3133
+ nodes.push(target.node);
3134
+ ni.unfork(fork);
3135
+ if (stopCondition && stopCondition(fork)) return nodes;
3136
+ ni.move(-1);
3137
+ break;
2660
3138
  }
2661
- const node = new SemanticQueryComparisonNode();
2662
- node.left = left;
2663
- node.operator = "matches";
2664
- node.right = right;
2665
- return node;
2666
3139
  }
2667
- if (opText === "exists") {
2668
- ni.move();
2669
- const node = new SemanticQueryComparisonNode();
2670
- node.left = left;
2671
- node.operator = "exists";
2672
- return node;
3140
+ if (singlePass) return nodes;
3141
+ if (!matched) {
3142
+ ni.shouldHaveError(depth);
3143
+ ni.move(depth - ni.index);
2673
3144
  }
2674
- if (opText === "not") return parseNotComparison(ni, left);
2675
- pushError(ni, `Unknown operator "${opText}"`);
2676
- return;
2677
- }
2678
- pushError(ni, "Expected operator after field reference");
2679
- }
2680
- function parseNotComparison(ni, left) {
2681
- ni.move();
2682
- if (ni.$?.type === "identifier" && ni.$.text === "in") {
2683
- ni.move();
2684
- const right = parseValueList(ni);
2685
- if (!right) return;
2686
- const node = new SemanticQueryComparisonNode();
2687
- node.left = left;
2688
- node.operator = "not in";
2689
- node.right = right;
2690
- return node;
2691
- }
2692
- if (ni.$?.type === "identifier" && ni.$.text === "exists") {
2693
- ni.move();
2694
- const node = new SemanticQueryComparisonNode();
2695
- node.left = left;
2696
- node.operator = "not exists";
2697
- return node;
2698
- }
2699
- pushError(ni, "Expected \"in\" or \"exists\" after \"not\"");
2700
- }
2701
- function parseFieldRef(ni) {
2702
- if (ni.$?.type !== "identifier") {
2703
- pushError(ni, "Expected field reference");
2704
- return;
2705
- }
2706
- const firstToken = new Token(ni.$);
2707
- ni.move();
2708
- if (ni.$?.type === "punctuation" && ni.$.text === ".") {
2709
3145
  ni.move();
2710
- if (ni.$?.type === "identifier") {
2711
- const secondToken = new Token(ni.$);
2712
- ni.move();
2713
- let fieldText = secondToken.text;
2714
- while (ni.$?.type === "punctuation" && ni.$.text === ".") {
2715
- ni.move();
2716
- if (ni.$?.type === "identifier") {
2717
- fieldText += `.${ni.$.text}`;
2718
- ni.move();
2719
- } else {
2720
- pushError(ni, "Expected identifier after \".\"");
2721
- break;
2722
- }
2723
- }
2724
- const node = new SemanticQueryFieldRefNode();
2725
- node.typeRef = firstToken;
2726
- node.fieldRef = fieldText === secondToken.text ? secondToken : secondToken.clone({ text: fieldText });
2727
- return node;
3146
+ if (matched) {} else {
3147
+ ni.confirmIssues();
3148
+ ni.skipUntil([";", "\n"]);
2728
3149
  }
2729
- pushError(ni, "Expected identifier after \".\"");
2730
- const node = new SemanticQueryFieldRefNode();
2731
- node.fieldRef = firstToken;
2732
- return node;
2733
- }
2734
- const node = new SemanticQueryFieldRefNode();
2735
- node.fieldRef = firstToken;
2736
- return node;
2737
- }
2738
- function parseValueOrFieldRef(ni) {
2739
- if (!ni.$) return;
2740
- if (ni.$.type === "text" || ni.$.type === "number" || ni.$.type === "regexp") return parseValue(ni);
2741
- if (ni.$.type === "identifier") {
2742
- if (VALUE_KEYWORDS.has(ni.$.text)) return parseValue(ni);
2743
- return parseFieldRef(ni);
2744
3150
  }
2745
- pushError(ni, "Expected value or field reference");
3151
+ return nodes;
2746
3152
  }
2747
- function parseValue(ni) {
2748
- if (!ni.$) {
2749
- pushError(ni, "Expected value");
2750
- return;
2751
- }
2752
- const token = ni.$;
2753
- if (token.type === "text" || token.type === "number" || token.type === "regexp" || token.type === "identifier" && VALUE_KEYWORDS.has(token.text)) {
2754
- const node = new SemanticQueryValueNode();
2755
- node.valueToken = new Token(token);
2756
- ni.move();
2757
- return node;
2758
- }
2759
- pushError(ni, `Unexpected token "${token.text}" where value expected`);
3153
+ function runPipesOnce(pipes, ni) {
3154
+ return runPipes(pipes, ni, true)[0];
2760
3155
  }
2761
- function parseValueList(ni) {
2762
- if (ni.$?.type === "block" && ni.$.text === "(") {
2763
- const subNi = ni.fork(ni.$.children || []);
2764
- ni.move();
2765
- if (!subNi.$) {
2766
- pushError(subNi, "Empty value list in \"in\" expression");
2767
- return;
2768
- }
2769
- const values = [];
2770
- const first = parseValue(subNi);
2771
- if (first) values.push(first);
2772
- while (subNi.$?.type === "punctuation" && subNi.$.text === ",") {
2773
- subNi.move();
2774
- const v = parseValue(subNi);
2775
- if (v) values.push(v);
3156
+
3157
+ //#endregion
3158
+ //#region packages/core/src/parser/grouping.ts
3159
+ function groupByPriority(nodes, priority) {
3160
+ if (nodes.length === 1) return nodes[0];
3161
+ if (nodes.length === 0) return;
3162
+ if (nodes.length % 2 === 0) throw new Error(`Invalid number of nodes ${nodes.length}. Odd number expected`);
3163
+ let currentPass = nodes;
3164
+ let temporaryResult = [];
3165
+ let groupped = [];
3166
+ for (const p of priority) {
3167
+ for (const [i, node] of currentPass.entries()) {
3168
+ const isOperator = i % 2 === 1;
3169
+ if (!isOperator && node instanceof Token) throw new Error(`Unexpected token ${node.toString()} at ${i}`);
3170
+ else if (isOperator && !(node instanceof Token)) throw new Error(`Unexpected token ${isGroup(node) ? node.op : node.token.toString()} at ${i}`);
3171
+ if (isOperator) {
3172
+ if (node.text !== p) temporaryResult.push(node);
3173
+ continue;
3174
+ }
3175
+ const prev = currentPass[i - 1]?.text;
3176
+ const next = currentPass[i + 1]?.text;
3177
+ if (prev !== p && next !== p) {
3178
+ temporaryResult.push(node);
3179
+ continue;
3180
+ }
3181
+ if (prev === p || next === p) {
3182
+ groupped.push(node);
3183
+ if (next !== p) {
3184
+ temporaryResult.push(new $n.SemanticGroup(groupped, p));
3185
+ groupped = [];
3186
+ }
3187
+ }
2776
3188
  }
2777
- if (subNi.$) pushError(subNi, `Unexpected token in value list: "${subNi.$.text}"`);
2778
- const node = new SemanticQueryValueListNode();
2779
- node.values = values;
2780
- return node;
3189
+ currentPass = temporaryResult;
3190
+ temporaryResult = [];
2781
3191
  }
2782
- pushError(ni, "Expected parenthesized value list after \"in\"");
2783
- }
2784
- /**
2785
- * Range to blame for a diagnostic: the current token, else the enclosing
2786
- * query token / "(...)" block the iterator was forked from.
2787
- */ function rangeOf(ni) {
2788
- return ni.$?.getRange?.() ?? ni.parent?.getRange?.() ?? ZERO_RANGE;
2789
- }
2790
- function pushError(ni, message) {
2791
- ni.messages.push({
2792
- severity: 1,
2793
- message,
2794
- range: rangeOf(ni)
2795
- });
3192
+ const output = currentPass[0];
3193
+ return output.length === 1 ? output.first : output;
2796
3194
  }
2797
3195
 
2798
3196
  //#endregion
@@ -2914,10 +3312,6 @@ function annotations() {
2914
3312
  }
2915
3313
  while (ni.satisfies(...opts.argument)) {
2916
3314
  let argToken = new Token(ni.$);
2917
- if (argToken.type === "query") {
2918
- const queryNode = parseQueryExpression(ni.fork(argToken.children), argToken);
2919
- if (queryNode) argToken.queryNode = queryNode;
2920
- }
2921
3315
  ni.accepted();
2922
3316
  ni.move();
2923
3317
  if (argToken.type === "identifier" && ![
@@ -3444,7 +3838,7 @@ function _define_property$3(obj, key, value) {
3444
3838
  else obj[key] = value;
3445
3839
  return obj;
3446
3840
  }
3447
- var AtscriptDoc = class {
3841
+ var AtscriptDoc = class AtscriptDoc {
3448
3842
  get name() {
3449
3843
  return this.id.split("/").pop();
3450
3844
  }
@@ -3498,7 +3892,8 @@ var AtscriptDoc = class {
3498
3892
  update(text, debug = false) {
3499
3893
  this._text = text;
3500
3894
  this.cleanup();
3501
- const ni = new NodeIterator(tokenize(text, debug), []).move();
3895
+ const rawTokens = tokenize(text, debug);
3896
+ const ni = new NodeIterator(rawTokens, []).move();
3502
3897
  this.nodes = runPipes([
3503
3898
  pipes.importPipe,
3504
3899
  pipes.type,
@@ -3508,6 +3903,43 @@ var AtscriptDoc = class {
3508
3903
  if (debug) console.log(this.nodes.map((n) => n.toString()).join("\n"));
3509
3904
  this.semanticMessages = ni.getErrors();
3510
3905
  this.registerNodes(this.nodes);
3906
+ this.parseUnregisteredBacktickArgs(rawTokens);
3907
+ }
3908
+ /**
3909
+ * Backtick arguments of annotations that never get registered (dangling at
3910
+ * EOF, or followed by a syntax error) are still parsed for diagnostics — by
3911
+ * the argument spec of the preceding annotation when it resolves, else as a
3912
+ * query predicate.
3913
+ */ parseUnregisteredBacktickArgs(tokens) {
3914
+ for (let i = 0; i < tokens.length; i++) {
3915
+ const t = tokens[i];
3916
+ if (t.type === "block" && t.children) {
3917
+ this.parseUnregisteredBacktickArgs(t.children);
3918
+ continue;
3919
+ }
3920
+ if (t.type !== "query" || this.parsedBacktickArgs.has(t)) continue;
3921
+ let argIndex = 0;
3922
+ let annotation;
3923
+ for (let j = i - 1; j >= 0; j--) {
3924
+ const p = tokens[j];
3925
+ if (p.type === "annotation") {
3926
+ annotation = p;
3927
+ break;
3928
+ }
3929
+ if (p.type === "block" || p.type === "punctuation" && (p.text === "\n" || p.text === ";")) break;
3930
+ if (p.type === "punctuation" && p.text === ",") argIndex++;
3931
+ }
3932
+ if (!annotation) continue;
3933
+ this.parseBacktickArgAs(new Token(t), this.resolveAnnotation(annotation.text.slice(1))?.arguments[argIndex]?.type);
3934
+ }
3935
+ }
3936
+ /**
3937
+ * Parse a backtick argument by its spec type: `expr` / `order` get their own
3938
+ * grammar; anything else (unknown annotation, position beyond the spec) parses
3939
+ * as a query predicate.
3940
+ */ parseBacktickArgAs(arg, specType) {
3941
+ this.parsedBacktickArgs.add(arg.lexicalToken);
3942
+ this.registerMessages(parseBacktickArg(arg, isBacktickArgType(specType) ? specType : "query"));
3511
3943
  }
3512
3944
  cleanup() {
3513
3945
  this.exports.clear();
@@ -3525,6 +3957,7 @@ var AtscriptDoc = class {
3525
3957
  this.blocksIndex = new BlocksIndex();
3526
3958
  this.resolvedAnnotations = [];
3527
3959
  this.annotations = [];
3960
+ this.parsedBacktickArgs = /* @__PURE__ */ new WeakSet();
3528
3961
  }
3529
3962
  registerNodes(nodes) {
3530
3963
  for (const node of nodes) {
@@ -3536,18 +3969,30 @@ var AtscriptDoc = class {
3536
3969
  });
3537
3970
  }
3538
3971
  }
3972
+ /**
3973
+ * The document in which the given annotation was written (and whose imports
3974
+ * its type-reference arguments resolve against). Annotations inherited into
3975
+ * another document through a chain ref, `extends` or `annotate` keep the
3976
+ * declaring document. `undefined` for annotations never registered on a doc.
3977
+ */ annotationOrigin(annotation) {
3978
+ return AtscriptDoc.annotationOrigins.get(annotation);
3979
+ }
3539
3980
  registerAnnotation(annotationTokens) {
3981
+ AtscriptDoc.annotationOrigins.set(annotationTokens, this);
3540
3982
  this.annotations.push(annotationTokens);
3541
3983
  const mainToken = annotationTokens.token;
3542
3984
  const args = annotationTokens.args;
3543
3985
  this.tokensIndex.add(mainToken);
3544
3986
  args?.forEach((a) => this.tokensIndex.add(a));
3545
3987
  const annotationSpec = this.resolveAnnotation(mainToken.text.slice(1));
3988
+ const specArgs = annotationSpec?.arguments ?? [];
3989
+ args?.forEach((a, i) => {
3990
+ if (a.type === "query") this.parseBacktickArgAs(a, specArgs[i]?.type);
3991
+ });
3546
3992
  if (annotationSpec) {
3547
3993
  this.registerMessages(annotationSpec.validate(mainToken, args || [], this));
3548
3994
  annotationSpec.modify(mainToken, args || [], this);
3549
3995
  this.resolvedAnnotations.push(mainToken);
3550
- const specArgs = annotationSpec.arguments;
3551
3996
  for (let i = 0; i < (args?.length ?? 0); i++) {
3552
3997
  const argSpec = specArgs[i];
3553
3998
  if (argSpec?.type === "ref" && args?.[i]) {
@@ -3555,6 +4000,7 @@ var AtscriptDoc = class {
3555
4000
  const dotIdx = refToken.text.indexOf(".");
3556
4001
  if (dotIdx > 0) {
3557
4002
  const typeToken = refToken.clone({ text: refToken.text.slice(0, dotIdx) });
4003
+ typeToken.annotationRef = refToken.annotationRef;
3558
4004
  typeToken.isReference = true;
3559
4005
  this.referred.push(typeToken);
3560
4006
  } else {
@@ -3562,7 +4008,7 @@ var AtscriptDoc = class {
3562
4008
  this.referred.push(refToken);
3563
4009
  }
3564
4010
  }
3565
- if (argSpec?.type === "query" && args?.[i]?.queryNode) args[i].queryNode.registerAtDocument(this);
4011
+ if (isBacktickArgType(argSpec?.type)) args?.[i]?.backtickNode?.registerAtDocument(this);
3566
4012
  if (argSpec?.type === "string" && argSpec.fieldScope && args?.[i]) this.fieldPathArgs.push(args[i]);
3567
4013
  }
3568
4014
  } else {
@@ -3706,6 +4152,40 @@ var AtscriptDoc = class {
3706
4152
  return block?.blockType === "annotate" && isAnnotate(block.parentNode) ? block.parentNode : void 0;
3707
4153
  }
3708
4154
  /**
4155
+ * The definition an annotated node stands for, with the document that declares it:
4156
+ * a prop / type declaration's own definition, or — for an `annotate` block entry —
4157
+ * the type of the target property the entry names (`annotate Host { name @x.y }`
4158
+ * → the type of `Host.name`). Plugin hooks use it to introspect the field an
4159
+ * annotation sits on, whether it is written inline or in an annotate block.
4160
+ * `undefined` when the node has no definition or the entry does not resolve.
4161
+ */ annotatedDefinition(node) {
4162
+ if (!node) return;
4163
+ if (!isRef(node)) {
4164
+ const def = node.getDefinition();
4165
+ return def ? {
4166
+ def,
4167
+ doc: this
4168
+ } : void 0;
4169
+ }
4170
+ const idToken = node.token("identifier");
4171
+ const block = idToken ? this.annotateBlockAt(idToken.range.start.line, idToken.range.start.character) : void 0;
4172
+ if (!block) return {
4173
+ def: node,
4174
+ doc: this
4175
+ };
4176
+ const chain = [node.id, ...node.chain.map((c) => c.text)];
4177
+ const unwound = this.unwindType(block.targetName, chain);
4178
+ if (unwound?.def && (!isGroup(unwound.def) || unwound.node?.id === chain.at(-1))) return {
4179
+ def: unwound.def,
4180
+ doc: unwound.doc
4181
+ };
4182
+ const merged = this.resolveChainWithMerge(block.targetName, chain);
4183
+ return merged ? {
4184
+ def: merged,
4185
+ doc: this
4186
+ } : void 0;
4187
+ }
4188
+ /**
3709
4189
  * Collects ad-hoc annotations from all `annotate` blocks targeting a given type/interface.
3710
4190
  * Returns a map of property path (dot-joined) → annotations array.
3711
4191
  * For entries without a chain (root-level), the key is the entry identifier.
@@ -3973,22 +4453,51 @@ var AtscriptDoc = class {
3973
4453
  } : void 0;
3974
4454
  }
3975
4455
  }
4456
+ /** Pushes an "Unknown identifier" error when `t` is not defined; returns whether it was. */ reportUnknownIdentifier(t) {
4457
+ if (this.registry.isDefined(t)) return false;
4458
+ this._allMessages.push({
4459
+ severity: 1,
4460
+ message: `Unknown identifier "${t.text}"`,
4461
+ range: t.range
4462
+ });
4463
+ return true;
4464
+ }
4465
+ /** Definition link from `token` to `target`, or to what the token resolves to when omitted. */ definitionLink(token, target) {
4466
+ const resolved = target ?? this.toRangeTarget(this.getDefinitionFor(token));
4467
+ if (!resolved) return;
4468
+ const range = resolved.range ?? zeroRange;
4469
+ return [{
4470
+ targetUri: resolved.uri,
4471
+ targetRange: range,
4472
+ targetSelectionRange: range,
4473
+ originSelectionRange: token.range
4474
+ }];
4475
+ }
4476
+ toRangeTarget(def) {
4477
+ return def && {
4478
+ uri: def.uri,
4479
+ range: def.token?.range
4480
+ };
4481
+ }
3976
4482
  getToDefinitionAt(line, character) {
3977
4483
  const token = this.tokensIndex.at(line, character);
3978
4484
  if (token) {
4485
+ if (token.annotationRef && token.isReference) return this.definitionLink(token);
4486
+ const declared = getDeclaredValue(token, this)?.definition;
4487
+ if (declared) return this.definitionLink(token, {
4488
+ uri: declared.doc.id,
4489
+ range: declared.token.range
4490
+ });
3979
4491
  const annotateBlock = this.annotateBlockAt(line, character);
3980
4492
  if (annotateBlock && isRef(token.parentNode)) {
3981
4493
  const targetName = annotateBlock.targetName;
3982
4494
  const entryRef = token.parentNode;
3983
4495
  const chain = token.isChain && typeof token.index === "number" ? [entryRef.id, ...entryRef.chain.slice(0, token.index).map((c) => c.text)] : [token.text];
3984
4496
  const unwound = this.unwindType(targetName, chain);
3985
- if (unwound?.node) return [{
3986
- targetUri: unwound.doc.id,
3987
- targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
3988
- targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
3989
- originSelectionRange: token.range
3990
- }];
3991
- return;
4497
+ return unwound?.node ? this.definitionLink(token, {
4498
+ uri: unwound.doc.id,
4499
+ range: unwound.node.token("identifier")?.range
4500
+ }) : void 0;
3992
4501
  }
3993
4502
  const fieldRef = resolveFieldRefAt(token, this, character);
3994
4503
  if (fieldRef) {
@@ -4002,41 +4511,21 @@ var AtscriptDoc = class {
4002
4511
  }
4003
4512
  if (isQueryFieldRef(token.parentNode)) {
4004
4513
  const { typeRef, queryArgToken } = token.parentNode;
4005
- if (token === typeRef && queryArgToken && getQueryScope(queryArgToken, this)) {
4006
- const result = this.getDefinitionFor(token);
4007
- return result ? [{
4008
- targetUri: result.uri,
4009
- targetRange: result.token?.range ?? zeroRange,
4010
- targetSelectionRange: result.token?.range ?? zeroRange,
4011
- originSelectionRange: token.range
4012
- }] : void 0;
4013
- }
4514
+ if (token === typeRef && queryArgToken && getQueryScope(queryArgToken, this)) return this.definitionLink(token);
4014
4515
  return;
4015
4516
  }
4016
- if (isProp(token.parentNode)) return [{
4017
- targetUri: this.id,
4018
- targetRange: token.range,
4019
- targetSelectionRange: token.range,
4020
- originSelectionRange: token.range
4021
- }];
4517
+ if (isProp(token.parentNode)) return this.definitionLink(token, {
4518
+ uri: this.id,
4519
+ range: token.range
4520
+ });
4022
4521
  if (token.isChain && isRef(token.parentNode) && typeof token.index === "number") {
4023
4522
  const id = token.parentNode.id;
4024
4523
  const unwound = this.unwindType(id, token.parentNode.chain.slice(0, token.index));
4025
- if (unwound?.node) return [{
4026
- targetUri: unwound.doc.id,
4027
- targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
4028
- targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
4029
- originSelectionRange: token.range
4030
- }];
4031
- } else {
4032
- const result = this.getDefinitionFor(token);
4033
- return result ? [{
4034
- targetUri: result.uri,
4035
- targetRange: result.token?.range ?? zeroRange,
4036
- targetSelectionRange: result.token?.range ?? zeroRange,
4037
- originSelectionRange: token.range
4038
- }] : void 0;
4039
- }
4524
+ if (unwound?.node) return this.definitionLink(token, {
4525
+ uri: unwound.doc.id,
4526
+ range: unwound.node.token("identifier")?.range
4527
+ });
4528
+ } else return this.definitionLink(token);
4040
4529
  }
4041
4530
  }
4042
4531
  registerImport({ from, imports, block }) {
@@ -4231,6 +4720,10 @@ var AtscriptDoc = class {
4231
4720
  }
4232
4721
  }
4233
4722
  for (const t of this.referred) {
4723
+ if (t.annotationRef || isQueryFieldRef(t.parentNode)) {
4724
+ this.reportUnknownIdentifier(t);
4725
+ continue;
4726
+ }
4234
4727
  const annotateBlock = this.annotateBlockAt(t.range.start.line, t.range.start.character);
4235
4728
  if (annotateBlock) {
4236
4729
  const targetName = annotateBlock.targetName;
@@ -4264,14 +4757,7 @@ var AtscriptDoc = class {
4264
4757
  }
4265
4758
  continue;
4266
4759
  }
4267
- if (!this.registry.isDefined(t)) {
4268
- this._allMessages.push({
4269
- severity: 1,
4270
- message: `Unknown identifier "${t.text}"`,
4271
- range: t.range
4272
- });
4273
- continue;
4274
- }
4760
+ if (this.reportUnknownIdentifier(t)) continue;
4275
4761
  if (isRef(t.parentNode)) {
4276
4762
  const def = this.unwindType(t.parentNode.id, t.parentNode.chain)?.def;
4277
4763
  if (isPrimitive(def) && !def.config.type) {
@@ -4319,6 +4805,10 @@ var AtscriptDoc = class {
4319
4805
  let def = this.unwindType(targetName)?.def;
4320
4806
  if (!def) return;
4321
4807
  for (const prop of chain) {
4808
+ if (isRef(def)) {
4809
+ def = this.unwindType(def.id, def.chain)?.def;
4810
+ if (!def) return;
4811
+ }
4322
4812
  def = this.mergeIntersection(def);
4323
4813
  if (isProp(def)) {
4324
4814
  const inner = def.getDefinition();
@@ -4488,6 +4978,7 @@ var AtscriptDoc = class {
4488
4978
  _define_property$3(this, "nodes", void 0);
4489
4979
  _define_property$3(this, "_text", void 0);
4490
4980
  _define_property$3(this, "_annotateNodesByTarget", void 0);
4981
+ /** Lexical backtick tokens already parsed by `registerAnnotation`. */ _define_property$3(this, "parsedBacktickArgs", void 0);
4491
4982
  _define_property$3(this, "resolvedAnnotations", void 0);
4492
4983
  _define_property$3(this, "annotations", void 0);
4493
4984
  _define_property$3(this, "_nextTypeId", void 0);
@@ -4512,6 +5003,7 @@ var AtscriptDoc = class {
4512
5003
  this._annotationSpecCache = /* @__PURE__ */ new Map();
4513
5004
  this.nodes = [];
4514
5005
  this._text = "";
5006
+ this.parsedBacktickArgs = /* @__PURE__ */ new WeakSet();
4515
5007
  this.resolvedAnnotations = [];
4516
5008
  this.annotations = [];
4517
5009
  this._nextTypeId = 0;
@@ -4519,6 +5011,10 @@ var AtscriptDoc = class {
4519
5011
  this.registry = new IdRegistry(Array.from(config.primitives?.keys() || []));
4520
5012
  }
4521
5013
  };
5014
+ /**
5015
+ * Annotation tokens survive merges across refs, chain refs and `extends`
5016
+ * unchanged, so they are keyed by identity to the document that declared them.
5017
+ */ _define_property$3(AtscriptDoc, "annotationOrigins", /* @__PURE__ */ new WeakMap());
4522
5018
  const zeroRange = {
4523
5019
  start: {
4524
5020
  line: 0,
@@ -5236,7 +5732,9 @@ var AtscriptRepo = class {
5236
5732
  async getUsedAnnotations() {
5237
5733
  const ANNOTATION_TYPE_MAP = {
5238
5734
  ref: "import(\"@atscript/typescript/utils\").AtscriptRef",
5239
- query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode"
5735
+ query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode",
5736
+ expr: "import(\"@atscript/typescript/utils\").AtscriptExprNode",
5737
+ order: "import(\"@atscript/typescript/utils\").AtscriptOrderItem[]"
5240
5738
  };
5241
5739
  const mapArgType = (t) => ANNOTATION_TYPE_MAP[t] || t;
5242
5740
  const manager = await this.getSharedPluginManager();
@@ -5896,4 +6394,4 @@ function walkArrayElement(doc, arrayNode, prefix, parentOptional, flatMap, stack
5896
6394
  }
5897
6395
 
5898
6396
  //#endregion
5899
- export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticQueryComparisonNode, SemanticQueryFieldRefNode, SemanticQueryLogicalNode, SemanticQueryNode, SemanticQueryValueListNode, SemanticQueryValueNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, analyzeQueryCursorContext, build, clearResolveBareCache, createAtscriptPlugin, defineConfig, fileUriToPath, flattenInterfaceNode, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, parseBareSpecifier, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveQueryFieldRef };
6397
+ export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BACKTICK_ARG_VOCABULARY, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticExprBinaryNode, SemanticExprCallNode, SemanticExprNode, SemanticExprNumberNode, SemanticExprUnaryNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticOrderNode, SemanticPrimitiveNode, SemanticPropNode, SemanticQueryComparisonNode, SemanticQueryFieldRefNode, SemanticQueryLogicalNode, SemanticQueryNode, SemanticQueryValueListNode, SemanticQueryValueNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, analyzeQueryCursorContext, build, clearResolveBareCache, createAtscriptPlugin, defineConfig, fileUriToPath, flattenInterfaceNode, getDeclaredValue, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, getSiblingAnnotation, getValueCandidates, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isBacktickArgType, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, parseBareSpecifier, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveQueryFieldRef };