@atscript/core 0.0.32 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -157,6 +157,70 @@ else this.annotationsCounter.set(name, 1);
157
157
  }
158
158
  };
159
159
 
160
+ //#endregion
161
+ //#region packages/core/src/parser/nodes/annotate-node.ts
162
+ var SemanticAnnotateNode = class extends SemanticNode {
163
+ get isMutating() {
164
+ return !this.token("identifier");
165
+ }
166
+ get targetName() {
167
+ return this.token("target").text;
168
+ }
169
+ get entries() {
170
+ if (!this.definition) return [];
171
+ if (isGroup(this.definition)) return this.definition.unwrap().filter((n) => isRef(n));
172
+ if (isRef(this.definition)) return [this.definition];
173
+ return [];
174
+ }
175
+ get id() {
176
+ return this.token("identifier")?.text ?? this.targetName;
177
+ }
178
+ registerAtDocument(doc) {
179
+ const targetToken = this.token("target");
180
+ targetToken.isReference = true;
181
+ doc.referred.push(targetToken);
182
+ doc.tokensIndex.add(targetToken);
183
+ const identifierToken = this.token("identifier");
184
+ if (identifierToken) {
185
+ doc.registerDefinition(identifierToken);
186
+ if (this.token("export")) {
187
+ identifierToken.exported = true;
188
+ doc.registerExport(this);
189
+ }
190
+ } else if (this.token("export")) doc.registerMessage(this.token("export"), "Cannot export mutating ad-hoc annotations block");
191
+ const block$2 = this.token("inner");
192
+ if (block$2) {
193
+ block$2.blockType = "annotate";
194
+ doc.blocksIndex.add(block$2);
195
+ }
196
+ const seenEntries = new Set();
197
+ for (const entry of this.entries) {
198
+ const entryPath = entry.hasChain ? `${entry.id}.${entry.chain.map((c) => c.text).join(".")}` : entry.id;
199
+ if (seenEntries.has(entryPath)) {
200
+ const idRange = entry.token("identifier").range;
201
+ const endRange = entry.hasChain ? entry.chain[entry.chain.length - 1].range : idRange;
202
+ doc.messages.push({
203
+ severity: 1,
204
+ message: "Duplicate annotate entry",
205
+ range: {
206
+ start: idRange.start,
207
+ end: endRange.end
208
+ }
209
+ });
210
+ continue;
211
+ }
212
+ seenEntries.add(entryPath);
213
+ }
214
+ if (this.definition) this.definition.registerAtDocument(doc);
215
+ this.annotations?.forEach((val) => {
216
+ doc.registerAnnotation(val);
217
+ });
218
+ }
219
+ constructor() {
220
+ super("annotate");
221
+ }
222
+ };
223
+
160
224
  //#endregion
161
225
  //#region packages/core/src/parser/nodes/array-node.ts
162
226
  var SemanticArrayNode = class extends SemanticNode {
@@ -692,6 +756,7 @@ var SemanticTypeNode = class extends SemanticNode {
692
756
  //#endregion
693
757
  //#region packages/core/src/parser/nodes/index.ts
694
758
  const $n = {
759
+ SemanticAnnotateNode,
695
760
  SemanticGroup,
696
761
  SemanticInterfaceNode,
697
762
  SemanticTypeNode,
@@ -737,6 +802,9 @@ function isImport(node) {
737
802
  function isPrimitive(node) {
738
803
  return node?.entity === "primitive";
739
804
  }
805
+ function isAnnotate(node) {
806
+ return node?.entity === "annotate";
807
+ }
740
808
 
741
809
  //#endregion
742
810
  //#region packages/core/src/annotations/annotation-spec.ts
@@ -1047,7 +1115,9 @@ else this.definitions.set(token.text, token);
1047
1115
  "type",
1048
1116
  "import",
1049
1117
  "from",
1050
- "export"
1118
+ "export",
1119
+ "annotate",
1120
+ "as"
1051
1121
  ].concat(globalTypes));
1052
1122
  this.globalTypes = new Set(globalTypes);
1053
1123
  }
@@ -1504,6 +1574,7 @@ function $pipe(entity, pipe = []) {
1504
1574
  case "structure": return new $n.SemanticStructureNode();
1505
1575
  case "tuple": return new $n.SemanticTupleNode();
1506
1576
  case "import": return new $n.SemanticImportNode();
1577
+ case "annotate": return new $n.SemanticAnnotateNode();
1507
1578
  case "primitive": throw new Error("Can't create pipe for primitive node");
1508
1579
  default: throw new Error(`Can't create pipe for ${entity} node`);
1509
1580
  }
@@ -1975,11 +2046,32 @@ const importPipe = $pipe("import", [
1975
2046
  text().saveAs("path").skip(";", "\n"),
1976
2047
  definition([$pipe("ref", [identifier().saveAs("identifier").skip("\n")])]).from("inner").separatedBy(",").skip("\n").respectPriority()
1977
2048
  ]).skip("\n", ";");
2049
+ const skipComments = { handler(ni) {
2050
+ ni.skip();
2051
+ return true;
2052
+ } };
2053
+ const annotateEntry = $pipe("ref", [
2054
+ annotations(),
2055
+ refWithChain(),
2056
+ skipComments,
2057
+ pun(";", ",", "\n").orEob().lookBehind()
2058
+ ]).skip("\n", ";", ",");
2059
+ const annotatePipe = $pipe("annotate", [
2060
+ annotations(),
2061
+ identifier("export").saveAs("export").optional().skip("\n"),
2062
+ identifier("annotate").saveAs("type").skip("\n").suppressEobError(),
2063
+ identifier().saveAs("target").skip("\n"),
2064
+ identifier("as").optional().skip("\n"),
2065
+ identifier().saveAs("identifier").optional().skip("\n"),
2066
+ block("{}").saveAs("inner"),
2067
+ unwrap("inner").with([annotateEntry])
2068
+ ]).skip("\n", ";");
1978
2069
  const pipes = {
1979
2070
  type,
1980
2071
  props,
1981
2072
  interfaceType,
1982
2073
  importPipe,
2074
+ annotatePipe,
1983
2075
  tuple
1984
2076
  };
1985
2077
 
@@ -2204,7 +2296,8 @@ var AtscriptDoc = class {
2204
2296
  this.nodes = runPipes([
2205
2297
  pipes.importPipe,
2206
2298
  pipes.type,
2207
- pipes.interfaceType
2299
+ pipes.interfaceType,
2300
+ pipes.annotatePipe
2208
2301
  ], ni);
2209
2302
  if (debug) console.log(this.nodes.map((n) => n.toString()).join("\n"));
2210
2303
  this.semanticMessages = ni.getErrors();
@@ -2313,6 +2406,7 @@ var AtscriptDoc = class {
2313
2406
  };
2314
2407
  resolveType();
2315
2408
  if (!def) return undefined;
2409
+ if (isAnnotate(def)) return doc.unwindType(def.targetName, chain, watchCb, tracked);
2316
2410
  for (const item of chain) {
2317
2411
  const itemText = typeof item === "string" ? item : item.text;
2318
2412
  if (!def) return undefined;
@@ -2359,6 +2453,15 @@ else if (isStructure(def) || isInterface(def) || isPrimitive(def)) def = def.pro
2359
2453
  }
2360
2454
  return right;
2361
2455
  }
2456
+ /**
2457
+ * Collects ad-hoc annotations from all `annotate` blocks targeting a given type/interface.
2458
+ * Returns a map of property path (dot-joined) → annotations array.
2459
+ * For entries without a chain (root-level), the key is the entry identifier.
2460
+ */ getAnnotateNodesFor(targetName) {
2461
+ const result = [];
2462
+ for (const node of this.nodes) if (isAnnotate(node) && node.targetName === targetName) result.push(node);
2463
+ return result;
2464
+ }
2362
2465
  usageListFor(token) {
2363
2466
  if (token.isDefinition) {
2364
2467
  const refs = this.referred.filter((t) => t.text === token.text).map((r) => ({
@@ -2435,23 +2538,39 @@ else if (isStructure(def) || isInterface(def) || isPrimitive(def)) def = def.pro
2435
2538
  }
2436
2539
  getToDefinitionAt(line, character) {
2437
2540
  const token = this.tokensIndex.at(line, character);
2438
- if (token) if (token.isChain && isRef(token.parentNode) && typeof token.index === "number") {
2439
- const id = token.parentNode.id;
2440
- const unwound = this.unwindType(id, token.parentNode.chain.slice(0, token.index));
2441
- if (unwound?.node) return [{
2442
- targetUri: unwound.doc.id,
2443
- targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
2444
- targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
2445
- originSelectionRange: token.range
2446
- }];
2447
- } else {
2448
- const result = this.getDefinitionFor(token);
2449
- return result ? [{
2450
- targetUri: result.uri,
2451
- targetRange: result.token?.range ?? zeroRange,
2452
- targetSelectionRange: result.token?.range ?? zeroRange,
2453
- originSelectionRange: token.range
2454
- }] : undefined;
2541
+ if (token) {
2542
+ const block$2 = this.blocksIndex.at(line, character);
2543
+ if (block$2?.blockType === "annotate" && isAnnotate(block$2.parentNode) && isRef(token.parentNode)) {
2544
+ const targetName = block$2.parentNode.targetName;
2545
+ const entryRef = token.parentNode;
2546
+ const chain = token.isChain && typeof token.index === "number" ? [entryRef.id, ...entryRef.chain.slice(0, token.index).map((c) => c.text)] : [token.text];
2547
+ const unwound = this.unwindType(targetName, chain);
2548
+ if (unwound?.node) return [{
2549
+ targetUri: unwound.doc.id,
2550
+ targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
2551
+ targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
2552
+ originSelectionRange: token.range
2553
+ }];
2554
+ return undefined;
2555
+ }
2556
+ if (token.isChain && isRef(token.parentNode) && typeof token.index === "number") {
2557
+ const id = token.parentNode.id;
2558
+ const unwound = this.unwindType(id, token.parentNode.chain.slice(0, token.index));
2559
+ if (unwound?.node) return [{
2560
+ targetUri: unwound.doc.id,
2561
+ targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
2562
+ targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
2563
+ originSelectionRange: token.range
2564
+ }];
2565
+ } else {
2566
+ const result = this.getDefinitionFor(token);
2567
+ return result ? [{
2568
+ targetUri: result.uri,
2569
+ targetRange: result.token?.range ?? zeroRange,
2570
+ targetSelectionRange: result.token?.range ?? zeroRange,
2571
+ originSelectionRange: token.range
2572
+ }] : undefined;
2573
+ }
2455
2574
  }
2456
2575
  }
2457
2576
  registerImport({ from, imports, block: block$2 }) {
@@ -2604,6 +2723,34 @@ else if (isStructure(def) || isInterface(def) || isPrimitive(def)) def = def.pro
2604
2723
  ...this.messages
2605
2724
  ];
2606
2725
  for (const t of this.referred) {
2726
+ const block$2 = this.blocksIndex.at(t.range.start.line, t.range.start.character);
2727
+ if (block$2?.blockType === "annotate" && isAnnotate(block$2.parentNode)) {
2728
+ const targetName = block$2.parentNode.targetName;
2729
+ if (!this.registry.isDefined(targetName)) continue;
2730
+ const chain = isRef(t.parentNode) && t.parentNode.hasChain ? [t.text, ...t.parentNode.chain.map((c) => c.text)] : [t.text];
2731
+ const unwound = this.unwindType(targetName, chain);
2732
+ if (!unwound?.def) {
2733
+ const lastToken = chain.length > 1 && isRef(t.parentNode) ? t.parentNode.chain[t.parentNode.chain.length - 1] || t : t;
2734
+ this._allMessages.push({
2735
+ severity: 1,
2736
+ message: `Unknown property "${chain.join(".")}" in "${targetName}"`,
2737
+ range: lastToken.range
2738
+ });
2739
+ } else if (isRef(t.parentNode) && t.parentNode.hasChain) {
2740
+ const length = t.parentNode.chain.length - 1;
2741
+ for (let i = length; i >= 0; i--) {
2742
+ const token = t.parentNode.chain[i];
2743
+ const memberChain = [t.text, ...t.parentNode.chain.slice(0, i + 1).map((c) => c.text)];
2744
+ const decl = this.unwindType(targetName, memberChain);
2745
+ if (!decl?.def) this._allMessages.push({
2746
+ severity: 1,
2747
+ message: `Unknown property "${memberChain.join(".")}" in "${targetName}"`,
2748
+ range: token.range
2749
+ });
2750
+ }
2751
+ }
2752
+ continue;
2753
+ }
2607
2754
  if (!this.registry.isDefined(t)) {
2608
2755
  this._allMessages.push({
2609
2756
  severity: 1,
@@ -3451,12 +3598,15 @@ else types.push({ type: "boolean" });
3451
3598
  async checkDoc(atscript) {
3452
3599
  await this.checkImports(atscript);
3453
3600
  }
3454
- async checkImports(atscript) {
3455
- const promise = Promise.all(Array.from(atscript.imports.values(), async ({ from, imports }) => this.checkImport(atscript, from, imports)));
3601
+ async checkImports(atscript, checked) {
3602
+ const _checked = checked || new Set();
3603
+ if (_checked.has(atscript.id)) return;
3604
+ _checked.add(atscript.id);
3605
+ const promise = Promise.all(Array.from(atscript.imports.values(), async ({ from, imports }) => this.checkImport(atscript, from, imports, _checked)));
3456
3606
  const results = await promise;
3457
3607
  atscript.updateDependencies(results.filter(Boolean));
3458
3608
  }
3459
- async checkImport(atscript, from, imports) {
3609
+ async checkImport(atscript, from, imports, checked) {
3460
3610
  const forId = resolveAtscriptFromPath(from.text, atscript.id);
3461
3611
  if (forId === atscript.id) {
3462
3612
  const messages = atscript.getDiagMessages();
@@ -3471,6 +3621,7 @@ else types.push({ type: "boolean" });
3471
3621
  let external;
3472
3622
  try {
3473
3623
  external = await this.openDocument(forId);
3624
+ await this.checkImports(external, checked);
3474
3625
  for (const token of imports) if (!external.exports.has(token.text)) errors.push({
3475
3626
  severity: 1,
3476
3627
  message: `"${from.text}" has no exported member "${token.text}"`,
@@ -3548,6 +3699,9 @@ else {
3548
3699
  return new BuildRepo(rootDir, repo, documents.filter(Boolean));
3549
3700
  }
3550
3701
  var BuildRepo = class {
3702
+ getDoc(id) {
3703
+ return this.docs.find((d) => d.id === id);
3704
+ }
3551
3705
  async diagnostics() {
3552
3706
  const docMessages = new Map();
3553
3707
  for (const document of this.docs) {
@@ -3601,6 +3755,7 @@ exports.AtscriptDoc = AtscriptDoc
3601
3755
  exports.AtscriptRepo = AtscriptRepo
3602
3756
  exports.BuildRepo = BuildRepo
3603
3757
  exports.PluginManager = PluginManager
3758
+ exports.SemanticAnnotateNode = SemanticAnnotateNode
3604
3759
  exports.SemanticArrayNode = SemanticArrayNode
3605
3760
  exports.SemanticConstNode = SemanticConstNode
3606
3761
  exports.SemanticGroup = SemanticGroup
@@ -3618,6 +3773,7 @@ exports.build = build
3618
3773
  exports.createAtscriptPlugin = createAtscriptPlugin
3619
3774
  exports.defineConfig = defineConfig
3620
3775
  exports.getRelPath = getRelPath
3776
+ exports.isAnnotate = isAnnotate
3621
3777
  exports.isAnnotationSpec = isAnnotationSpec
3622
3778
  exports.isArray = isArray
3623
3779
  exports.isConst = isConst
package/dist/index.d.ts CHANGED
@@ -79,7 +79,7 @@ declare class Token {
79
79
  /**
80
80
  * Block type
81
81
  */
82
- blockType?: 'structure' | 'type' | 'import';
82
+ blockType?: 'structure' | 'type' | 'import' | 'annotate';
83
83
  }
84
84
 
85
85
  interface TPluginManagers {
@@ -127,8 +127,8 @@ declare class AtscriptRepo {
127
127
  openDocument(id: string, text?: string): Promise<AtscriptDoc>;
128
128
  protected _openDocument(id: string, text?: string): Promise<AtscriptDoc>;
129
129
  checkDoc(atscript: AtscriptDoc): Promise<void>;
130
- checkImports(atscript: AtscriptDoc): Promise<void>;
131
- checkImport(atscript: AtscriptDoc, from: Token, imports: Token[]): Promise<AtscriptDoc | undefined>;
130
+ checkImports(atscript: AtscriptDoc, checked?: Set<string>): Promise<void>;
131
+ checkImport(atscript: AtscriptDoc, from: Token, imports: Token[], checked?: Set<string>): Promise<AtscriptDoc | undefined>;
132
132
  }
133
133
 
134
134
  type TPunctuation = '\n' | '&' | '+' | ',' | '\\' | '.' | '/' | ':' | '=' | '?' | '|' | ';';
@@ -164,6 +164,7 @@ declare class BuildRepo {
164
164
  private readonly repo;
165
165
  private readonly docs;
166
166
  constructor(rootDir: string, repo: AtscriptRepo, docs: AtscriptDoc[]);
167
+ getDoc(id: string): AtscriptDoc | undefined;
167
168
  diagnostics(): Promise<Map<string, TMessages>>;
168
169
  generate(config: TAtscriptConfigOutput, docs?: AtscriptDoc[]): Promise<TOutput[]>;
169
170
  write(config: TAtscriptConfigOutput, docs?: AtscriptDoc[]): Promise<TOutput[]>;
@@ -219,8 +220,8 @@ declare class IdRegistry {
219
220
  getErrors(): TMessages;
220
221
  }
221
222
 
222
- type TSemanticToken = 'type' | 'identifier' | 'array' | 'export' | 'optional' | 'inner' | 'path' | 'from';
223
- type TNodeEntity = 'interface' | 'type' | 'ref' | 'const' | 'prop' | 'structure' | 'tuple' | 'group' | 'array' | 'import' | 'primitive';
223
+ type TSemanticToken = 'type' | 'identifier' | 'array' | 'export' | 'optional' | 'inner' | 'path' | 'from' | 'target';
224
+ type TNodeEntity = 'interface' | 'type' | 'ref' | 'const' | 'prop' | 'structure' | 'tuple' | 'group' | 'array' | 'import' | 'primitive' | 'annotate';
224
225
  interface TAnnotationTokens {
225
226
  name: string;
226
227
  token: Token;
@@ -269,6 +270,37 @@ type TPrimitiveTypeFinalOptional = {
269
270
  };
270
271
  type TPrimitiveTypeDef = TPrimitiveTypeComplex | TPrimitiveTypeArray | TPrimitiveTypeObject | TPrimitiveTypeFinal | TPrimitiveTypeFinalOptional;
271
272
 
273
+ declare class SemanticNode {
274
+ entity: TNodeEntity;
275
+ constructor(entity: TNodeEntity);
276
+ protected tokens?: Map<TSemanticToken, Token>;
277
+ protected isGroup: boolean;
278
+ protected definition?: SemanticNode;
279
+ annotations?: TAnnotationTokens[];
280
+ annotationsCounter?: Map<string, number>;
281
+ registerAtDocument(doc: AtscriptDoc): void;
282
+ protected _documentation?: string;
283
+ setDocumentation(s: string): void;
284
+ get documentation(): string | undefined;
285
+ get id(): string | undefined;
286
+ get referredIdentifiers(): Token[];
287
+ getIdentifiersRecursive(node: SemanticNode): Token[];
288
+ countAnnotations(name: string): number;
289
+ annotate(name: string, token: Token): (arg: Token) => void;
290
+ get length(): number;
291
+ define(node: SemanticNode): this;
292
+ get def(): SemanticNode | undefined;
293
+ get identifier(): string | undefined;
294
+ saveToken(token: Token, semantic: TSemanticToken): this;
295
+ wrap(node: SemanticNode, token: Token): this;
296
+ token(s: TSemanticToken): Token | undefined;
297
+ has(s: TSemanticToken): boolean | undefined;
298
+ toString(level?: number, prefix?: string): string;
299
+ renderAnnotations(): string;
300
+ protected renderChildren(): string;
301
+ getDefinition(): SemanticNode | undefined;
302
+ }
303
+
272
304
  declare class SemanticPrimitiveNode extends SemanticNode {
273
305
  private readonly _id;
274
306
  readonly config: TPrimitiveConfig;
@@ -409,6 +441,12 @@ declare class AtscriptDoc {
409
441
  token: Token;
410
442
  }[] | undefined;
411
443
  evalAnnotationsForNode(givenNode: SemanticNode): TAnnotationTokens[] | undefined;
444
+ /**
445
+ * Collects ad-hoc annotations from all `annotate` blocks targeting a given type/interface.
446
+ * Returns a map of property path (dot-joined) → annotations array.
447
+ * For entries without a chain (root-level), the key is the entry identifier.
448
+ */
449
+ getAnnotateNodesFor(targetName: string): SemanticAnnotateNode[];
412
450
  usageListFor(token: Token): Array<{
413
451
  uri: string;
414
452
  range: Token['range'];
@@ -523,35 +561,26 @@ declare class AtscriptDoc {
523
561
  mergeNodesAnnotations(left?: TAnnotationTokens[], right?: TAnnotationTokens[]): TAnnotationTokens[];
524
562
  }
525
563
 
526
- declare class SemanticNode {
527
- entity: TNodeEntity;
528
- constructor(entity: TNodeEntity);
529
- protected tokens?: Map<TSemanticToken, Token>;
530
- protected isGroup: boolean;
531
- protected definition?: SemanticNode;
532
- annotations?: TAnnotationTokens[];
533
- annotationsCounter?: Map<string, number>;
534
- registerAtDocument(doc: AtscriptDoc): void;
535
- protected _documentation?: string;
536
- setDocumentation(s: string): void;
537
- get documentation(): string | undefined;
538
- get id(): string | undefined;
564
+ declare class SemanticRefNode extends SemanticNode {
565
+ constructor();
539
566
  get referredIdentifiers(): Token[];
540
- getIdentifiersRecursive(node: SemanticNode): Token[];
541
- countAnnotations(name: string): number;
542
- annotate(name: string, token: Token): (arg: Token) => void;
543
- get length(): number;
544
- define(node: SemanticNode): this;
545
- get def(): SemanticNode | undefined;
546
- get identifier(): string | undefined;
547
- saveToken(token: Token, semantic: TSemanticToken): this;
548
- wrap(node: SemanticNode, token: Token): this;
549
- token(s: TSemanticToken): Token | undefined;
550
- has(s: TSemanticToken): boolean | undefined;
567
+ protected _chain: Token[];
568
+ protected _dots: Token[];
569
+ registerAtDocument(doc: AtscriptDoc): void;
570
+ addChain(token: Token): void;
571
+ addDot(token: Token): void;
572
+ get chain(): Token[];
573
+ get hasChain(): boolean;
551
574
  toString(level?: number, prefix?: string): string;
552
- renderAnnotations(): string;
553
- protected renderChildren(): string;
554
- getDefinition(): SemanticNode | undefined;
575
+ }
576
+
577
+ declare class SemanticAnnotateNode extends SemanticNode {
578
+ constructor();
579
+ get isMutating(): boolean;
580
+ get targetName(): string;
581
+ get entries(): SemanticRefNode[];
582
+ get id(): string;
583
+ registerAtDocument(doc: AtscriptDoc): void;
555
584
  }
556
585
 
557
586
  declare class SemanticArrayNode extends SemanticNode {
@@ -584,19 +613,6 @@ declare class SemanticImportNode extends SemanticNode {
584
613
  registerAtDocument(doc: AtscriptDoc): void;
585
614
  }
586
615
 
587
- declare class SemanticRefNode extends SemanticNode {
588
- constructor();
589
- get referredIdentifiers(): Token[];
590
- protected _chain: Token[];
591
- protected _dots: Token[];
592
- registerAtDocument(doc: AtscriptDoc): void;
593
- addChain(token: Token): void;
594
- addDot(token: Token): void;
595
- get chain(): Token[];
596
- get hasChain(): boolean;
597
- toString(level?: number, prefix?: string): string;
598
- }
599
-
600
616
  declare class SemanticPropNode extends SemanticNode {
601
617
  constructor();
602
618
  registerAtDocument(doc: AtscriptDoc): void;
@@ -637,6 +653,7 @@ declare class SemanticTypeNode extends SemanticNode {
637
653
  }
638
654
 
639
655
  declare const $n: {
656
+ SemanticAnnotateNode: typeof SemanticAnnotateNode;
640
657
  SemanticGroup: typeof SemanticGroup;
641
658
  SemanticInterfaceNode: typeof SemanticInterfaceNode;
642
659
  SemanticTypeNode: typeof SemanticTypeNode;
@@ -661,6 +678,7 @@ declare function isTuple(node?: SemanticNode): node is SemanticTupleNode;
661
678
  declare function isArray(node?: SemanticNode): node is SemanticArrayNode;
662
679
  declare function isImport(node?: SemanticNode): node is SemanticImportNode;
663
680
  declare function isPrimitive(node?: SemanticNode): node is SemanticPrimitiveNode;
681
+ declare function isAnnotate(node?: SemanticNode): node is SemanticAnnotateNode;
664
682
 
665
683
  interface TAtscriptConfigInput {
666
684
  rootDir: string;
@@ -728,4 +746,4 @@ declare function resolveAnnotation(name: string, annotationsTree?: TAnnotationsT
728
746
  declare function resolveAtscriptFromPath(from: string, id: string): string;
729
747
  declare function getRelPath(fromUri: string, toUri: string): string;
730
748
 
731
- export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, PluginManager, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, type TAnnotationArgument, type TAnnotationSpecConfig, type TAnnotationTokens, type TAnnotationsTree, type TAtscriptConfig, type TAtscriptConfigInput, type TAtscriptConfigOutput, type TAtscriptDocConfig, type TAtscriptPlugin, type TAtscriptRenderFormat, type TMessages, type TNodeEntity, type TOutput, type TOutputWithSource, type TPluginOutput, type TPrimitiveBaseConfig, type TPrimitiveConfig, type TPrimitiveTypeArray, type TPrimitiveTypeComplex, type TPrimitiveTypeDef, type TPrimitiveTypeFinal, type TPrimitiveTypeFinalOptional, type TPrimitiveTypeObject, type TSemanticToken, Token, build, createAtscriptPlugin, defineConfig, getRelPath, isAnnotationSpec, isArray, isConst, isGroup, isImport, isInterface, isPrimitive, isProp, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, resolveAnnotation, resolveAtscriptFromPath, resolveConfigFile };
749
+ export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, type TAnnotationArgument, type TAnnotationSpecConfig, type TAnnotationTokens, type TAnnotationsTree, type TAtscriptConfig, type TAtscriptConfigInput, type TAtscriptConfigOutput, type TAtscriptDocConfig, type TAtscriptPlugin, type TAtscriptRenderFormat, type TMessages, type TNodeEntity, type TOutput, type TOutputWithSource, type TPluginOutput, type TPrimitiveBaseConfig, type TPrimitiveConfig, type TPrimitiveTypeArray, type TPrimitiveTypeComplex, type TPrimitiveTypeDef, type TPrimitiveTypeFinal, type TPrimitiveTypeFinalOptional, type TPrimitiveTypeObject, type TSemanticToken, Token, build, createAtscriptPlugin, defineConfig, getRelPath, isAnnotate, isAnnotationSpec, isArray, isConst, isGroup, isImport, isInterface, isPrimitive, isProp, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, resolveAnnotation, resolveAtscriptFromPath, resolveConfigFile };
package/dist/index.mjs CHANGED
@@ -133,6 +133,70 @@ else this.annotationsCounter.set(name, 1);
133
133
  }
134
134
  };
135
135
 
136
+ //#endregion
137
+ //#region packages/core/src/parser/nodes/annotate-node.ts
138
+ var SemanticAnnotateNode = class extends SemanticNode {
139
+ get isMutating() {
140
+ return !this.token("identifier");
141
+ }
142
+ get targetName() {
143
+ return this.token("target").text;
144
+ }
145
+ get entries() {
146
+ if (!this.definition) return [];
147
+ if (isGroup(this.definition)) return this.definition.unwrap().filter((n) => isRef(n));
148
+ if (isRef(this.definition)) return [this.definition];
149
+ return [];
150
+ }
151
+ get id() {
152
+ return this.token("identifier")?.text ?? this.targetName;
153
+ }
154
+ registerAtDocument(doc) {
155
+ const targetToken = this.token("target");
156
+ targetToken.isReference = true;
157
+ doc.referred.push(targetToken);
158
+ doc.tokensIndex.add(targetToken);
159
+ const identifierToken = this.token("identifier");
160
+ if (identifierToken) {
161
+ doc.registerDefinition(identifierToken);
162
+ if (this.token("export")) {
163
+ identifierToken.exported = true;
164
+ doc.registerExport(this);
165
+ }
166
+ } else if (this.token("export")) doc.registerMessage(this.token("export"), "Cannot export mutating ad-hoc annotations block");
167
+ const block$2 = this.token("inner");
168
+ if (block$2) {
169
+ block$2.blockType = "annotate";
170
+ doc.blocksIndex.add(block$2);
171
+ }
172
+ const seenEntries = new Set();
173
+ for (const entry of this.entries) {
174
+ const entryPath = entry.hasChain ? `${entry.id}.${entry.chain.map((c) => c.text).join(".")}` : entry.id;
175
+ if (seenEntries.has(entryPath)) {
176
+ const idRange = entry.token("identifier").range;
177
+ const endRange = entry.hasChain ? entry.chain[entry.chain.length - 1].range : idRange;
178
+ doc.messages.push({
179
+ severity: 1,
180
+ message: "Duplicate annotate entry",
181
+ range: {
182
+ start: idRange.start,
183
+ end: endRange.end
184
+ }
185
+ });
186
+ continue;
187
+ }
188
+ seenEntries.add(entryPath);
189
+ }
190
+ if (this.definition) this.definition.registerAtDocument(doc);
191
+ this.annotations?.forEach((val) => {
192
+ doc.registerAnnotation(val);
193
+ });
194
+ }
195
+ constructor() {
196
+ super("annotate");
197
+ }
198
+ };
199
+
136
200
  //#endregion
137
201
  //#region packages/core/src/parser/nodes/array-node.ts
138
202
  var SemanticArrayNode = class extends SemanticNode {
@@ -668,6 +732,7 @@ var SemanticTypeNode = class extends SemanticNode {
668
732
  //#endregion
669
733
  //#region packages/core/src/parser/nodes/index.ts
670
734
  const $n = {
735
+ SemanticAnnotateNode,
671
736
  SemanticGroup,
672
737
  SemanticInterfaceNode,
673
738
  SemanticTypeNode,
@@ -713,6 +778,9 @@ function isImport(node) {
713
778
  function isPrimitive(node) {
714
779
  return node?.entity === "primitive";
715
780
  }
781
+ function isAnnotate(node) {
782
+ return node?.entity === "annotate";
783
+ }
716
784
 
717
785
  //#endregion
718
786
  //#region packages/core/src/annotations/annotation-spec.ts
@@ -1023,7 +1091,9 @@ else this.definitions.set(token.text, token);
1023
1091
  "type",
1024
1092
  "import",
1025
1093
  "from",
1026
- "export"
1094
+ "export",
1095
+ "annotate",
1096
+ "as"
1027
1097
  ].concat(globalTypes));
1028
1098
  this.globalTypes = new Set(globalTypes);
1029
1099
  }
@@ -1480,6 +1550,7 @@ function $pipe(entity, pipe = []) {
1480
1550
  case "structure": return new $n.SemanticStructureNode();
1481
1551
  case "tuple": return new $n.SemanticTupleNode();
1482
1552
  case "import": return new $n.SemanticImportNode();
1553
+ case "annotate": return new $n.SemanticAnnotateNode();
1483
1554
  case "primitive": throw new Error("Can't create pipe for primitive node");
1484
1555
  default: throw new Error(`Can't create pipe for ${entity} node`);
1485
1556
  }
@@ -1951,11 +2022,32 @@ const importPipe = $pipe("import", [
1951
2022
  text().saveAs("path").skip(";", "\n"),
1952
2023
  definition([$pipe("ref", [identifier().saveAs("identifier").skip("\n")])]).from("inner").separatedBy(",").skip("\n").respectPriority()
1953
2024
  ]).skip("\n", ";");
2025
+ const skipComments = { handler(ni) {
2026
+ ni.skip();
2027
+ return true;
2028
+ } };
2029
+ const annotateEntry = $pipe("ref", [
2030
+ annotations(),
2031
+ refWithChain(),
2032
+ skipComments,
2033
+ pun(";", ",", "\n").orEob().lookBehind()
2034
+ ]).skip("\n", ";", ",");
2035
+ const annotatePipe = $pipe("annotate", [
2036
+ annotations(),
2037
+ identifier("export").saveAs("export").optional().skip("\n"),
2038
+ identifier("annotate").saveAs("type").skip("\n").suppressEobError(),
2039
+ identifier().saveAs("target").skip("\n"),
2040
+ identifier("as").optional().skip("\n"),
2041
+ identifier().saveAs("identifier").optional().skip("\n"),
2042
+ block("{}").saveAs("inner"),
2043
+ unwrap("inner").with([annotateEntry])
2044
+ ]).skip("\n", ";");
1954
2045
  const pipes = {
1955
2046
  type,
1956
2047
  props,
1957
2048
  interfaceType,
1958
2049
  importPipe,
2050
+ annotatePipe,
1959
2051
  tuple
1960
2052
  };
1961
2053
 
@@ -2180,7 +2272,8 @@ var AtscriptDoc = class {
2180
2272
  this.nodes = runPipes([
2181
2273
  pipes.importPipe,
2182
2274
  pipes.type,
2183
- pipes.interfaceType
2275
+ pipes.interfaceType,
2276
+ pipes.annotatePipe
2184
2277
  ], ni);
2185
2278
  if (debug) console.log(this.nodes.map((n) => n.toString()).join("\n"));
2186
2279
  this.semanticMessages = ni.getErrors();
@@ -2289,6 +2382,7 @@ var AtscriptDoc = class {
2289
2382
  };
2290
2383
  resolveType();
2291
2384
  if (!def) return undefined;
2385
+ if (isAnnotate(def)) return doc.unwindType(def.targetName, chain, watchCb, tracked);
2292
2386
  for (const item of chain) {
2293
2387
  const itemText = typeof item === "string" ? item : item.text;
2294
2388
  if (!def) return undefined;
@@ -2335,6 +2429,15 @@ else if (isStructure(def) || isInterface(def) || isPrimitive(def)) def = def.pro
2335
2429
  }
2336
2430
  return right;
2337
2431
  }
2432
+ /**
2433
+ * Collects ad-hoc annotations from all `annotate` blocks targeting a given type/interface.
2434
+ * Returns a map of property path (dot-joined) → annotations array.
2435
+ * For entries without a chain (root-level), the key is the entry identifier.
2436
+ */ getAnnotateNodesFor(targetName) {
2437
+ const result = [];
2438
+ for (const node of this.nodes) if (isAnnotate(node) && node.targetName === targetName) result.push(node);
2439
+ return result;
2440
+ }
2338
2441
  usageListFor(token) {
2339
2442
  if (token.isDefinition) {
2340
2443
  const refs = this.referred.filter((t) => t.text === token.text).map((r) => ({
@@ -2411,23 +2514,39 @@ else if (isStructure(def) || isInterface(def) || isPrimitive(def)) def = def.pro
2411
2514
  }
2412
2515
  getToDefinitionAt(line, character) {
2413
2516
  const token = this.tokensIndex.at(line, character);
2414
- if (token) if (token.isChain && isRef(token.parentNode) && typeof token.index === "number") {
2415
- const id = token.parentNode.id;
2416
- const unwound = this.unwindType(id, token.parentNode.chain.slice(0, token.index));
2417
- if (unwound?.node) return [{
2418
- targetUri: unwound.doc.id,
2419
- targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
2420
- targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
2421
- originSelectionRange: token.range
2422
- }];
2423
- } else {
2424
- const result = this.getDefinitionFor(token);
2425
- return result ? [{
2426
- targetUri: result.uri,
2427
- targetRange: result.token?.range ?? zeroRange,
2428
- targetSelectionRange: result.token?.range ?? zeroRange,
2429
- originSelectionRange: token.range
2430
- }] : undefined;
2517
+ if (token) {
2518
+ const block$2 = this.blocksIndex.at(line, character);
2519
+ if (block$2?.blockType === "annotate" && isAnnotate(block$2.parentNode) && isRef(token.parentNode)) {
2520
+ const targetName = block$2.parentNode.targetName;
2521
+ const entryRef = token.parentNode;
2522
+ const chain = token.isChain && typeof token.index === "number" ? [entryRef.id, ...entryRef.chain.slice(0, token.index).map((c) => c.text)] : [token.text];
2523
+ const unwound = this.unwindType(targetName, chain);
2524
+ if (unwound?.node) return [{
2525
+ targetUri: unwound.doc.id,
2526
+ targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
2527
+ targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
2528
+ originSelectionRange: token.range
2529
+ }];
2530
+ return undefined;
2531
+ }
2532
+ if (token.isChain && isRef(token.parentNode) && typeof token.index === "number") {
2533
+ const id = token.parentNode.id;
2534
+ const unwound = this.unwindType(id, token.parentNode.chain.slice(0, token.index));
2535
+ if (unwound?.node) return [{
2536
+ targetUri: unwound.doc.id,
2537
+ targetRange: unwound.node.token("identifier")?.range ?? zeroRange,
2538
+ targetSelectionRange: unwound.node.token("identifier")?.range ?? zeroRange,
2539
+ originSelectionRange: token.range
2540
+ }];
2541
+ } else {
2542
+ const result = this.getDefinitionFor(token);
2543
+ return result ? [{
2544
+ targetUri: result.uri,
2545
+ targetRange: result.token?.range ?? zeroRange,
2546
+ targetSelectionRange: result.token?.range ?? zeroRange,
2547
+ originSelectionRange: token.range
2548
+ }] : undefined;
2549
+ }
2431
2550
  }
2432
2551
  }
2433
2552
  registerImport({ from, imports, block: block$2 }) {
@@ -2580,6 +2699,34 @@ else if (isStructure(def) || isInterface(def) || isPrimitive(def)) def = def.pro
2580
2699
  ...this.messages
2581
2700
  ];
2582
2701
  for (const t of this.referred) {
2702
+ const block$2 = this.blocksIndex.at(t.range.start.line, t.range.start.character);
2703
+ if (block$2?.blockType === "annotate" && isAnnotate(block$2.parentNode)) {
2704
+ const targetName = block$2.parentNode.targetName;
2705
+ if (!this.registry.isDefined(targetName)) continue;
2706
+ const chain = isRef(t.parentNode) && t.parentNode.hasChain ? [t.text, ...t.parentNode.chain.map((c) => c.text)] : [t.text];
2707
+ const unwound = this.unwindType(targetName, chain);
2708
+ if (!unwound?.def) {
2709
+ const lastToken = chain.length > 1 && isRef(t.parentNode) ? t.parentNode.chain[t.parentNode.chain.length - 1] || t : t;
2710
+ this._allMessages.push({
2711
+ severity: 1,
2712
+ message: `Unknown property "${chain.join(".")}" in "${targetName}"`,
2713
+ range: lastToken.range
2714
+ });
2715
+ } else if (isRef(t.parentNode) && t.parentNode.hasChain) {
2716
+ const length = t.parentNode.chain.length - 1;
2717
+ for (let i = length; i >= 0; i--) {
2718
+ const token = t.parentNode.chain[i];
2719
+ const memberChain = [t.text, ...t.parentNode.chain.slice(0, i + 1).map((c) => c.text)];
2720
+ const decl = this.unwindType(targetName, memberChain);
2721
+ if (!decl?.def) this._allMessages.push({
2722
+ severity: 1,
2723
+ message: `Unknown property "${memberChain.join(".")}" in "${targetName}"`,
2724
+ range: token.range
2725
+ });
2726
+ }
2727
+ }
2728
+ continue;
2729
+ }
2583
2730
  if (!this.registry.isDefined(t)) {
2584
2731
  this._allMessages.push({
2585
2732
  severity: 1,
@@ -3427,12 +3574,15 @@ else types.push({ type: "boolean" });
3427
3574
  async checkDoc(atscript) {
3428
3575
  await this.checkImports(atscript);
3429
3576
  }
3430
- async checkImports(atscript) {
3431
- const promise = Promise.all(Array.from(atscript.imports.values(), async ({ from, imports }) => this.checkImport(atscript, from, imports)));
3577
+ async checkImports(atscript, checked) {
3578
+ const _checked = checked || new Set();
3579
+ if (_checked.has(atscript.id)) return;
3580
+ _checked.add(atscript.id);
3581
+ const promise = Promise.all(Array.from(atscript.imports.values(), async ({ from, imports }) => this.checkImport(atscript, from, imports, _checked)));
3432
3582
  const results = await promise;
3433
3583
  atscript.updateDependencies(results.filter(Boolean));
3434
3584
  }
3435
- async checkImport(atscript, from, imports) {
3585
+ async checkImport(atscript, from, imports, checked) {
3436
3586
  const forId = resolveAtscriptFromPath(from.text, atscript.id);
3437
3587
  if (forId === atscript.id) {
3438
3588
  const messages = atscript.getDiagMessages();
@@ -3447,6 +3597,7 @@ else types.push({ type: "boolean" });
3447
3597
  let external;
3448
3598
  try {
3449
3599
  external = await this.openDocument(forId);
3600
+ await this.checkImports(external, checked);
3450
3601
  for (const token of imports) if (!external.exports.has(token.text)) errors.push({
3451
3602
  severity: 1,
3452
3603
  message: `"${from.text}" has no exported member "${token.text}"`,
@@ -3524,6 +3675,9 @@ else {
3524
3675
  return new BuildRepo(rootDir, repo, documents.filter(Boolean));
3525
3676
  }
3526
3677
  var BuildRepo = class {
3678
+ getDoc(id) {
3679
+ return this.docs.find((d) => d.id === id);
3680
+ }
3527
3681
  async diagnostics() {
3528
3682
  const docMessages = new Map();
3529
3683
  for (const document of this.docs) {
@@ -3571,4 +3725,4 @@ var BuildRepo = class {
3571
3725
  };
3572
3726
 
3573
3727
  //#endregion
3574
- export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, PluginManager, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, build, createAtscriptPlugin, defineConfig, getRelPath, isAnnotationSpec, isArray, isConst, isGroup, isImport, isInterface, isPrimitive, isProp, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, resolveAnnotation, resolveAtscriptFromPath, resolveConfigFile };
3728
+ export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, build, createAtscriptPlugin, defineConfig, getRelPath, isAnnotate, isAnnotationSpec, isArray, isConst, isGroup, isImport, isInterface, isPrimitive, isProp, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, resolveAnnotation, resolveAtscriptFromPath, resolveConfigFile };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/core",
3
- "version": "0.0.32",
3
+ "version": "0.1.1",
4
4
  "description": "Core library for Atscript parsing and file generation.",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",