@repometry/tree-sitter 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@repometry/tree-sitter",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "The tree-sitter language plugin engine for Repometry",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -38,7 +38,7 @@
38
38
  "prepack": "npm run build"
39
39
  },
40
40
  "dependencies": {
41
- "@repometry/core": "0.3.0",
41
+ "@repometry/core": "0.5.0",
42
42
  "web-tree-sitter": "0.27.2"
43
43
  }
44
44
  }
@@ -1,3 +1,4 @@
1
+ import { ruleFor } from './language.js';
1
2
  import { expressionOperators, logicalOperator } from './logic.js';
2
3
  export class Control {
3
4
  walk;
@@ -53,19 +54,29 @@ export class Control {
53
54
  conditional(node, flow, depth, chained) {
54
55
  flow.block(node, depth, chained);
55
56
  const work = [];
56
- const alternate = this.walk.grammar.rules[node.type]?.alternative?.(node);
57
+ const rule = ruleFor(this.walk.grammar, node);
58
+ const alternate = rule?.alternative?.(node);
59
+ const children = rule?.conditionalChildren?.(node);
60
+ if (children) {
61
+ return this.walk.next(children.filter(child => !this.walk.ignored(child.type)).map(child => child.id === alternate?.id ? this.alternative(child, flow, depth) : { node: child, flow, depth: depth + 1 }));
62
+ }
57
63
  for (let index = 0; index < node.childCount; index++) {
58
64
  const child = node.child(index);
59
65
  const explicitAlternative = child.id === alternate?.id;
60
66
  if ((!child.isNamed && !explicitAlternative) || this.walk.ignored(child.type))
61
67
  continue;
68
+ const branches = rule?.alternativeBranches?.(child);
69
+ if (branches) {
70
+ work.push(...branches.map(branch => this.alternative(branch, flow, depth)));
71
+ continue;
72
+ }
62
73
  const alternative = explicitAlternative || node.fieldNameForChild(index) === 'alternative';
63
74
  work.push(alternative ? this.alternative(child, flow, depth) : { node: child, flow, depth: depth + 1 });
64
75
  }
65
76
  this.walk.next(work);
66
77
  }
67
78
  alternative(node, flow, depth) {
68
- const rule = this.walk.grammar.rules[node.type];
79
+ const rule = ruleFor(this.walk.grammar, node);
69
80
  const chained = rule?.chainedAlternative ? this.chainedChild(node) : undefined;
70
81
  if (chained)
71
82
  return { node: chained, flow, depth, chained: true };
@@ -81,13 +92,13 @@ export class Control {
81
92
  }
82
93
  chainedChild(node) {
83
94
  const [child, sibling] = this.walk.named(node);
84
- return child && sibling === undefined && this.walk.grammar.rules[child.type]?.flow === 'if' ? child : undefined;
95
+ return child && sibling === undefined && ruleFor(this.walk.grammar, child)?.flow === 'if' ? child : undefined;
85
96
  }
86
97
  sequence(node, flow, depth) {
87
98
  const work = [];
88
99
  const values = [];
89
100
  for (const child of this.walk.named(node)) {
90
- const kind = this.walk.grammar.rules[child.type]?.flow;
101
+ const kind = ruleFor(this.walk.grammar, child)?.flow;
91
102
  if (kind === 'clause' || kind === 'filter') {
92
103
  const at = depth++;
93
104
  work.push(() => {
@@ -26,6 +26,8 @@ export declare class Traversal {
26
26
  private readonly batchChildren;
27
27
  constructor(grammar: Grammar, source: SourceLines);
28
28
  run(root: Node, module: Flow, visit: (task: Visit) => void): void;
29
+ runScope(node: Node, visit: (task: Visit) => void): void;
30
+ private runWork;
29
31
  next(items: readonly Work[]): void;
30
32
  named(node: Node): Node[];
31
33
  ignored(type: string): boolean;
@@ -1,3 +1,4 @@
1
+ import { ruleFor } from './language.js';
1
2
  export class Flow {
2
3
  cyclomatic = 1;
3
4
  cognitive = 0;
@@ -25,8 +26,14 @@ export class Traversal {
25
26
  this.batchChildren = source.text.length >= 256 * 1024;
26
27
  }
27
28
  run(root, module, visit) {
29
+ this.runWork(() => this.children(root, module, 0), visit);
30
+ }
31
+ runScope(node, visit) {
32
+ this.runWork(() => this.next([{ node, flow: new Flow(), depth: 0 }]), visit);
33
+ }
34
+ runWork(schedule, visit) {
28
35
  try {
29
- this.children(root, module, 0);
36
+ schedule();
30
37
  while (this.pending.length) {
31
38
  const item = this.pending.pop();
32
39
  if (typeof item === 'function')
@@ -46,15 +53,17 @@ export class Traversal {
46
53
  this.pending.push(items[index]);
47
54
  }
48
55
  named(node) {
49
- return node.namedChildren.filter(child => !this.ignored(child.type));
56
+ const field = this.grammar.ignoredFields?.[node.type];
57
+ const excluded = field === undefined ? undefined : node.childForFieldName(field)?.id;
58
+ return node.namedChildren.filter(child => child.id !== excluded && !this.ignored(child.type));
50
59
  }
51
60
  ignored(type) {
52
61
  return this.grammar.comments.has(type) || this.grammar.extras.has(type);
53
62
  }
54
63
  children(node, flow, depth, parent, logical) {
55
- const ordered = this.grammar.rules[node.type]?.order;
64
+ const ordered = ruleFor(this.grammar, node)?.order;
56
65
  const prepare = (child) => {
57
- if (this.grammar.rules[child.type]?.flow !== 'filter')
66
+ if (ruleFor(this.grammar, child)?.flow !== 'filter')
58
67
  return { node: child, flow, depth, parent, logical };
59
68
  const at = depth++;
60
69
  return () => {
@@ -62,8 +71,9 @@ export class Traversal {
62
71
  this.children(child, flow, at + 1);
63
72
  };
64
73
  };
65
- if (this.batchChildren && !ordered && node.namedChildCount > childBatchSize)
74
+ if (this.batchChildren && !ordered && !this.grammar.ignoredFields?.[node.type] && node.namedChildCount > childBatchSize) {
66
75
  return this.batches(node, prepare);
76
+ }
67
77
  const names = this.named(node);
68
78
  const children = ordered ? ordered.flatMap(index => names[index] ?? []) : names;
69
79
  if (!children.length)
@@ -12,9 +12,13 @@ declare global {
12
12
  export interface TokenRules {
13
13
  readonly candidates: ReadonlySet<string>;
14
14
  readonly kinds: ReadonlyMap<string, string>;
15
+ /** Opaque literal tokens whose descendants may contain source comments. */
16
+ readonly literalsWithComments?: ReadonlySet<string>;
15
17
  readonly normalize?: (type: string, text: string, kind: string | undefined) => readonly [string, string | undefined];
16
18
  }
17
19
  export interface NodeRule {
20
+ /** Resolve a semantic rule when multiple constructs share a syntax node type. */
21
+ readonly select?: (node: Node) => NodeRule | undefined;
18
22
  readonly flow?: 'function' | 'class' | 'decorated' | 'if' | 'elif' | 'else' | 'nest' | 'sequence' | 'clause' | 'filter';
19
23
  readonly decision?: true | ((node: Node) => number);
20
24
  readonly exit?: 'return' | 'label';
@@ -25,8 +29,12 @@ export interface NodeRule {
25
29
  readonly requiresBody?: boolean;
26
30
  /** Lexical parameter count when the grammar does not expose a list of formal parameters. */
27
31
  readonly parameters?: (node: Node) => number | undefined;
32
+ /** Conditional members in source order when an ordinary child wraps both branches. */
33
+ readonly conditionalChildren?: (node: Node) => readonly Node[];
28
34
  /** Alternate branch when the grammar does not expose an alternative field. */
29
35
  readonly alternative?: (node: Node) => Node | null;
36
+ /** Authored alternatives stored in one transparent conditional child. */
37
+ readonly alternativeBranches?: (child: Node) => readonly Node[] | undefined;
30
38
  /** Whether an alternative wrapper contributes its flat cognitive point. */
31
39
  readonly elseCognitive?: (node: Node) => boolean;
32
40
  /** A wrapper is transparent when its sole named child is a chained conditional. */
@@ -47,11 +55,16 @@ export interface Grammar {
47
55
  readonly name: (node: Node) => string | undefined;
48
56
  readonly countDeclarations?: (root: Node) => number;
49
57
  readonly rules: Readonly<Record<string, NodeRule>>;
58
+ /** A named field carrying syntax outside the executable source, such as a preprocessor condition. */
59
+ readonly ignoredFields?: Readonly<Record<string, string>>;
60
+ readonly recoverDeclarations?: true;
50
61
  readonly parens: ReadonlySet<string>;
51
62
  readonly comments: ReadonlySet<string>;
52
63
  readonly extras: ReadonlySet<string>;
53
64
  readonly logicalTypes: ReadonlySet<string>;
54
65
  readonly logicalOperators: ReadonlySet<string>;
66
+ /** Match named operator tokens by source spelling. */
67
+ readonly logicalOperatorSpelling?: true;
55
68
  readonly logicalCognitive: 'parent' | 'sequence';
56
69
  /** A parameters field with one of these node types is a single parameter. */
57
70
  readonly singleParameterTypes?: ReadonlySet<string>;
@@ -65,3 +78,4 @@ export interface Grammar {
65
78
  readonly tokens: TokenRules;
66
79
  }
67
80
  export declare const measures: readonly ['functions', 'cyclomaticComplexity', 'cognitiveComplexity', 'commentLines', 'codeLines', 'structuralRules', 'duplication'];
81
+ export declare function ruleFor(grammar: Grammar, node: Node): NodeRule | undefined;
@@ -1,3 +1,7 @@
1
1
  export const measures = ['functions', 'cyclomaticComplexity', 'cognitiveComplexity', 'commentLines', 'codeLines',
2
2
  'structuralRules', 'duplication'];
3
+ export function ruleFor(grammar, node) {
4
+ const rule = grammar.rules[node.type];
5
+ return rule?.select ? rule.select(node) : rule;
6
+ }
3
7
  //# sourceMappingURL=language.js.map
@@ -2,7 +2,10 @@ export function logicalOperator(node, grammar) {
2
2
  if (!grammar.logicalTypes.has(node.type))
3
3
  return undefined;
4
4
  const operator = node.childForFieldName('operator') ?? node.children.find(child => !child.isNamed);
5
- return operator && grammar.logicalOperators.has(operator.type) ? operator.type : undefined;
5
+ if (!operator)
6
+ return undefined;
7
+ const spelling = grammar.logicalOperatorSpelling ? operator.text : operator.type;
8
+ return grammar.logicalOperators.has(spelling) ? spelling : undefined;
6
9
  }
7
10
  export function expressionOperators(root, grammar) {
8
11
  const sequence = [];
@@ -0,0 +1,27 @@
1
+ import type { Tree } from 'web-tree-sitter';
2
+ import type { Grammar } from './language.js';
3
+ import type { SourceLines } from './source-lines.js';
4
+ /** Whole-file line facts plus measurable declarations from a syntax-error tree. */
5
+ export declare function extractRecovered(path: string, tree: Tree, source: SourceLines, grammar: Grammar): {
6
+ structure: {
7
+ codeLines: number[];
8
+ commentLines: number;
9
+ lines: number;
10
+ functions: number;
11
+ cognitiveComplexity: number;
12
+ cyclomaticFunctions: import("@repometry/core").FunctionComplexity[];
13
+ cognitiveFunctions: import("@repometry/core").FunctionComplexity[];
14
+ observations: import("@repometry/core/internal/model/code-structure.js").StructuralObservation[];
15
+ classes?: number | undefined;
16
+ clones: import("@repometry/core").CloneSource;
17
+ path: string;
18
+ } | {
19
+ path: string;
20
+ lines: number;
21
+ codeLines: number[];
22
+ commentLines: number;
23
+ };
24
+ omitted: number;
25
+ reason: string;
26
+ location: string;
27
+ };
@@ -0,0 +1,18 @@
1
+ import { damagedSyntax, recoveredScopes } from './recovery.js';
2
+ import { Structure } from './structure.js';
3
+ import { firstSyntaxIssue } from './syntax-issue.js';
4
+ import { scanClones } from './tokens.js';
5
+ /** Whole-file line facts plus measurable declarations from a syntax-error tree. */
6
+ export function extractRecovered(path, tree, source, grammar) {
7
+ const root = tree.rootNode;
8
+ const damaged = damagedSyntax(root);
9
+ const { scopes, omitted } = recoveredScopes(root, grammar, damaged);
10
+ const facts = scanClones(path, tree, source, grammar, scopes.length ? damaged : false);
11
+ const measured = scopes.length ? new Structure(grammar, source, facts.codeLines).measureRecovered(scopes) : undefined;
12
+ const structure = measured && (measured.functions || measured.classes)
13
+ ? { path, ...measured, ...facts }
14
+ : { path, lines: source.count, codeLines: facts.codeLines, commentLines: facts.commentLines };
15
+ const { reason, offset } = firstSyntaxIssue(root, grammar);
16
+ return { structure, omitted, reason, location: source.location(offset, grammar.columns) };
17
+ }
18
+ //# sourceMappingURL=recovered-file.js.map
@@ -0,0 +1,14 @@
1
+ import type { Node } from 'web-tree-sitter';
2
+ import type { Grammar } from './language.js';
3
+ import type { Span } from './source-lines.js';
4
+ export interface RecoveredScope {
5
+ readonly node: Node;
6
+ readonly parents: readonly string[];
7
+ }
8
+ /** Distinguish missing tokens from error intervals because a missing token can sit on a node boundary. */
9
+ export declare function damagedSyntax(root: Node): (span: Span) => boolean;
10
+ /** Select maximal intact declarations. Their nested declarations are measured by the normal structure traversal. */
11
+ export declare function recoveredScopes(root: Node, grammar: Grammar, damaged: (span: Span) => boolean): {
12
+ scopes: RecoveredScope[];
13
+ omitted: number;
14
+ };
@@ -0,0 +1,60 @@
1
+ import { ruleFor } from './language.js';
2
+ import { lowerBound } from './source-lines.js';
3
+ /** Distinguish missing tokens from error intervals because a missing token can sit on a node boundary. */
4
+ export function damagedSyntax(root) {
5
+ const intervals = [];
6
+ const missing = [];
7
+ const pending = [root];
8
+ while (pending.length) {
9
+ const node = pending.pop();
10
+ const children = node.children.filter(child => child.hasError || child.isError || child.isMissing);
11
+ if (node.isMissing)
12
+ missing.push(node.startIndex);
13
+ else if (node.isError || !children.length)
14
+ intervals.push({ start: node.startIndex, end: node.endIndex });
15
+ pending.push(...children);
16
+ }
17
+ intervals.sort((left, right) => left.start - right.start);
18
+ missing.sort((left, right) => left - right);
19
+ const starts = intervals.map(interval => interval.start);
20
+ let lastEnd = 0;
21
+ const ends = intervals.map(interval => lastEnd = Math.max(lastEnd, interval.end));
22
+ return ({ start, end }) => {
23
+ const previous = lowerBound(starts, end) - 1;
24
+ const point = missing[lowerBound(missing, start)];
25
+ // An error can swallow a modifier immediately before the declaration.
26
+ return (ends[previous] ?? -1) >= start || (point !== undefined && point <= end);
27
+ };
28
+ }
29
+ function isDeclaration(node, grammar) {
30
+ const rule = ruleFor(grammar, node);
31
+ if (rule?.flow !== 'function' && rule?.flow !== 'class')
32
+ return false;
33
+ return !rule.requiresBody || (rule.body?.(node).length ?? Number(node.childForFieldName('body') !== null)) > 0;
34
+ }
35
+ /** Select maximal intact declarations. Their nested declarations are measured by the normal structure traversal. */
36
+ export function recoveredScopes(root, grammar, damaged) {
37
+ const scopes = [];
38
+ const pending = [{ node: root, parents: [] }];
39
+ let omitted = 0;
40
+ while (pending.length) {
41
+ const scope = pending.pop();
42
+ const { node, parents } = scope;
43
+ let context = parents;
44
+ if (isDeclaration(node, grammar)) {
45
+ if (!damaged({ start: node.startIndex, end: node.endIndex })) {
46
+ scopes.push(scope);
47
+ continue;
48
+ }
49
+ omitted++;
50
+ const name = grammar.name(node);
51
+ if (name)
52
+ context = [...parents, name];
53
+ }
54
+ const children = node.namedChildren;
55
+ for (let index = children.length - 1; index >= 0; index--)
56
+ pending.push({ node: children[index], parents: context });
57
+ }
58
+ return { scopes, omitted };
59
+ }
60
+ //# sourceMappingURL=recovery.js.map
@@ -1,6 +1,7 @@
1
1
  import type { Node } from 'web-tree-sitter';
2
2
  import type { FunctionComplexity, StructuralObservation } from '@repometry/core/internal/model/code-structure.js';
3
3
  import type { Grammar } from './language.js';
4
+ import type { RecoveredScope } from './recovery.js';
4
5
  import type { SourceLines } from './source-lines.js';
5
6
  export declare class Structure {
6
7
  private readonly grammar;
@@ -25,6 +26,16 @@ export declare class Structure {
25
26
  observations: StructuralObservation[];
26
27
  classes?: number | undefined;
27
28
  };
29
+ measureRecovered(scopes: readonly RecoveredScope[]): {
30
+ lines: number;
31
+ functions: number;
32
+ cognitiveComplexity: number;
33
+ cyclomaticFunctions: FunctionComplexity[];
34
+ cognitiveFunctions: FunctionComplexity[];
35
+ observations: StructuralObservation[];
36
+ classes?: number | undefined;
37
+ };
38
+ private result;
28
39
  private visit;
29
40
  private decorated;
30
41
  private scope;
@@ -1,3 +1,4 @@
1
+ import { ruleFor } from './language.js';
1
2
  import { Control } from './control.js';
2
3
  import { Flow, Traversal } from './flow.js';
3
4
  import { lowerBound } from './source-lines.js';
@@ -27,6 +28,17 @@ export class Structure {
27
28
  this.finish(module, this.grammar.moduleDepthLabel);
28
29
  const position = this.grammar.reportFileRange ? { line: 1, endLine: this.lines.count } : {};
29
30
  this.observations.push({ rule: 'file-complexity', value: this.cognitive, label: 'File cognitive complexity', ...position });
31
+ return this.result();
32
+ }
33
+ measureRecovered(scopes) {
34
+ for (const { node, parents } of scopes) {
35
+ this.names.push(...parents);
36
+ this.walk.runScope(node, task => this.visit(task));
37
+ this.names.length = 0;
38
+ }
39
+ return this.result();
40
+ }
41
+ result() {
30
42
  const byPosition = (left, right) => left.line - right.line || left.column - right.column;
31
43
  this.cyclomaticFunctions.sort(byPosition);
32
44
  this.cognitiveFunctions.sort(byPosition);
@@ -35,7 +47,7 @@ export class Structure {
35
47
  observations: this.observations, ...(this.grammar.language.measures?.includes('classes') ? { classes: this.classes } : {}) };
36
48
  }
37
49
  visit(task) {
38
- const rule = this.grammar.rules[task.node.type];
50
+ const rule = ruleFor(this.grammar, task.node);
39
51
  if (rule?.flow === 'function')
40
52
  this.scope(task, false);
41
53
  else if (rule?.flow === 'class')
@@ -50,10 +62,10 @@ export class Structure {
50
62
  if (!definition)
51
63
  return;
52
64
  const decorators = this.walk.named(task.node).filter(child => child.id !== definition.id);
53
- this.scope({ ...task, node: definition }, this.grammar.rules[definition.type]?.flow === 'class', decorators);
65
+ this.scope({ ...task, node: definition }, ruleFor(this.grammar, definition)?.flow === 'class', decorators);
54
66
  }
55
67
  scope({ node, flow, depth }, isClass, decorators = []) {
56
- const rule = this.grammar.rules[node.type];
68
+ const rule = ruleFor(this.grammar, node);
57
69
  const body = rule?.body?.(node) ?? fieldBody(node);
58
70
  if (rule?.requiresBody && body.length === 0) {
59
71
  this.walk.children(node, flow, depth);
@@ -102,7 +114,7 @@ export class Structure {
102
114
  this.observe('function-complexity', own.cognitive, label + ' · Cognitive complexity', node);
103
115
  }
104
116
  parameters(node) {
105
- const specified = this.grammar.rules[node.type]?.parameters?.(node);
117
+ const specified = ruleFor(this.grammar, node)?.parameters?.(node);
106
118
  if (specified !== undefined)
107
119
  return specified;
108
120
  const list = node.childForFieldName('parameters');
@@ -1,8 +1,8 @@
1
1
  import type { Tree } from 'web-tree-sitter';
2
2
  import type { CloneSource } from '@repometry/core/internal/model/clone-source.js';
3
3
  import type { Grammar } from './language.js';
4
- import type { SourceLines } from './source-lines.js';
5
- export declare function scanClones(path: string, tree: Tree, source: SourceLines, grammar: Grammar): {
4
+ import type { SourceLines, Span } from './source-lines.js';
5
+ export declare function scanClones(path: string, tree: Tree, source: SourceLines, grammar: Grammar, damaged?: false | ((span: Span) => boolean)): {
6
6
  codeLines: number[];
7
7
  commentLines: number;
8
8
  clones: CloneSource;
@@ -1,10 +1,10 @@
1
1
  import { hash } from 'node:crypto';
2
2
  import { duplicationSettings as limits } from '@repometry/core/internal/profile/maintainability.js';
3
3
  import { lowerBound } from './source-lines.js';
4
- export function scanClones(path, tree, source, grammar) {
4
+ export function scanClones(path, tree, source, grammar, damaged) {
5
5
  const cursor = tree.walk();
6
6
  try {
7
- return new TokenScanner(cursor, source, grammar).scan(path);
7
+ return new TokenScanner(cursor, source, grammar, damaged).scan(path);
8
8
  }
9
9
  finally {
10
10
  cursor.delete();
@@ -35,6 +35,7 @@ class TokenScanner {
35
35
  cursor;
36
36
  source;
37
37
  grammar;
38
+ damaged;
38
39
  comments = [];
39
40
  ranges = [];
40
41
  starts = [];
@@ -43,11 +44,12 @@ class TokenScanner {
43
44
  similar = new FingerprintInput();
44
45
  collect;
45
46
  candidateEnd = 0;
46
- constructor(cursor, source, grammar) {
47
+ constructor(cursor, source, grammar, damaged) {
47
48
  this.cursor = cursor;
48
49
  this.source = source;
49
50
  this.grammar = grammar;
50
- this.collect = source.count >= limits.minCodeLines;
51
+ this.damaged = damaged;
52
+ this.collect = damaged !== false && source.count >= limits.minCodeLines;
51
53
  }
52
54
  scan(path) {
53
55
  do {
@@ -59,9 +61,9 @@ class TokenScanner {
59
61
  const lines = this.source.classify(this.comments);
60
62
  return { ...lines, clones: this.cloneSource(path, lines.codeLines) };
61
63
  }
62
- advance() {
63
- while (!this.cursor.gotoNextSibling()) {
64
- if (!this.cursor.gotoParent())
64
+ advance(cursor = this.cursor) {
65
+ while (!cursor.gotoNextSibling()) {
66
+ if (!cursor.gotoParent())
65
67
  return false;
66
68
  }
67
69
  return true;
@@ -78,6 +80,8 @@ class TokenScanner {
78
80
  const kind = this.collect ? this.grammar.tokens.kinds.get(type) : undefined;
79
81
  if (!kind && this.cursor.gotoFirstChild())
80
82
  return true;
83
+ if (kind && this.grammar.tokens.literalsWithComments?.has(type))
84
+ this.literalComments();
81
85
  if (this.candidateEnd) {
82
86
  const start = this.cursor.startIndex;
83
87
  if (start < this.candidateEnd)
@@ -85,8 +89,29 @@ class TokenScanner {
85
89
  }
86
90
  return false;
87
91
  }
92
+ literalComments() {
93
+ const cursor = this.cursor.currentNode.walk();
94
+ try {
95
+ if (!cursor.gotoFirstChild())
96
+ return;
97
+ do {
98
+ const type = cursor.nodeType;
99
+ if (this.grammar.comments.has(type))
100
+ this.comments.push(span(cursor));
101
+ else if (!this.grammar.extras.has(type) && cursor.gotoFirstChild())
102
+ continue;
103
+ if (!this.advance(cursor))
104
+ break;
105
+ } while (true);
106
+ }
107
+ finally {
108
+ cursor.delete();
109
+ }
110
+ }
88
111
  candidate() {
89
112
  const range = span(this.cursor);
113
+ if (this.damaged && this.damaged(range))
114
+ return;
90
115
  if (range.end - range.start < limits.minNodes)
91
116
  return;
92
117
  if (this.source.line(range.end - 1) - this.source.line(range.start) + 1 < limits.minCodeLines)
@@ -2,7 +2,9 @@ import { readFile } from 'node:fs/promises';
2
2
  import { extname } from 'node:path';
3
3
  import { codeStructure, pluginManifestSchema } from '@repometry/core';
4
4
  import { readStructure } from '@repometry/core/internal/engine/author-contracts.js';
5
+ import { recoveredSyntax } from '@repometry/core/internal/model/code-structure.js';
5
6
  import { sourceFile } from '@repometry/core/internal/model/snapshot.js';
7
+ import { extractRecovered } from './recovered-file.js';
6
8
  import { SourceLines } from './source-lines.js';
7
9
  import { Structure } from './structure.js';
8
10
  import { firstSyntaxIssue } from './syntax-issue.js';
@@ -56,10 +58,8 @@ function extract(path, grammar, source, tree) {
56
58
  if (!tree)
57
59
  throw new SyntaxError('No syntax tree at ' + source.location(0, grammar.columns));
58
60
  const root = tree.rootNode;
59
- if (root.hasError) {
60
- const { offset, reason } = firstSyntaxIssue(root, grammar);
61
- throw new SyntaxError(reason + ' at ' + source.location(offset, grammar.columns));
62
- }
61
+ if (root.hasError)
62
+ return recoverOrReject(path, grammar, source, tree);
63
63
  const header = grammar.requireFirst && firstHeader(root, grammar);
64
64
  if (grammar.requireFirst && (!header || header.type !== grammar.requireFirst)) {
65
65
  throw new SyntaxError('Expected a ' + grammar.requireFirst.replaceAll('_', ' ') +
@@ -71,6 +71,14 @@ function extract(path, grammar, source, tree) {
71
71
  const declarations = grammar.countDeclarations?.(root);
72
72
  return { path, ...structure, ...facts, ...(declarations === undefined ? {} : { declarations }) };
73
73
  }
74
+ function recoverOrReject(path, grammar, source, tree) {
75
+ if (grammar.recoverDeclarations) {
76
+ const { structure, ...details } = extractRecovered(path, tree, source, grammar);
77
+ return { ...structure, [recoveredSyntax]: details };
78
+ }
79
+ const { offset, reason } = firstSyntaxIssue(tree.rootNode, grammar);
80
+ throw new SyntaxError(reason + ' at ' + source.location(offset, grammar.columns));
81
+ }
74
82
  function firstHeader(root, grammar) {
75
83
  let node = root.firstNamedChild;
76
84
  while (node && grammar.comments.has(node.type))