@repometry/tree-sitter 0.0.0 → 0.1.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.0.0",
3
+ "version": "0.1.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.0.0",
41
+ "@repometry/core": "0.2.0",
42
42
  "web-tree-sitter": "0.27.2"
43
43
  }
44
44
  }
@@ -12,6 +12,7 @@ export declare class Control {
12
12
  private logical;
13
13
  private conditional;
14
14
  private alternative;
15
+ private chainedChild;
15
16
  private sequence;
16
17
  }
17
18
  export {};
@@ -19,7 +19,8 @@ export class Control {
19
19
  flow.cognitive++;
20
20
  break;
21
21
  case 'else':
22
- flow.cognitive++;
22
+ if (rule?.elseCognitive?.(node) !== false)
23
+ flow.cognitive++;
23
24
  return this.walk.children(node, flow, depth + Number(parent !== 'nest'));
24
25
  case 'sequence': return this.sequence(node, flow, depth);
25
26
  case 'nest':
@@ -52,16 +53,23 @@ export class Control {
52
53
  conditional(node, flow, depth, chained) {
53
54
  flow.block(node, depth, chained);
54
55
  const work = [];
56
+ const alternate = this.walk.grammar.rules[node.type]?.alternative?.(node);
55
57
  for (let index = 0; index < node.childCount; index++) {
56
58
  const child = node.child(index);
57
- if (!child.isNamed || this.walk.ignored(child.type))
59
+ const explicitAlternative = child.id === alternate?.id;
60
+ if ((!child.isNamed && !explicitAlternative) || this.walk.ignored(child.type))
58
61
  continue;
59
- work.push(node.fieldNameForChild(index) === 'alternative' ? this.alternative(child, flow, depth) : { node: child, flow, depth: depth + 1 });
62
+ const alternative = explicitAlternative || node.fieldNameForChild(index) === 'alternative';
63
+ work.push(alternative ? this.alternative(child, flow, depth) : { node: child, flow, depth: depth + 1 });
60
64
  }
61
65
  this.walk.next(work);
62
66
  }
63
67
  alternative(node, flow, depth) {
64
- switch (this.walk.grammar.rules[node.type]?.flow) {
68
+ const rule = this.walk.grammar.rules[node.type];
69
+ const chained = rule?.chainedAlternative ? this.chainedChild(node) : undefined;
70
+ if (chained)
71
+ return { node: chained, flow, depth, chained: true };
72
+ switch (rule?.flow) {
65
73
  case 'if': return { node, flow, depth, chained: true };
66
74
  case 'elif': return { node, flow, depth: depth + 1 };
67
75
  case 'else': return { node, flow, depth: depth + 1, parent: 'nest' };
@@ -71,6 +79,10 @@ export class Control {
71
79
  };
72
80
  }
73
81
  }
82
+ chainedChild(node) {
83
+ const [child, sibling] = this.walk.named(node);
84
+ return child && sibling === undefined && this.walk.grammar.rules[child.type]?.flow === 'if' ? child : undefined;
85
+ }
74
86
  sequence(node, flow, depth) {
75
87
  const work = [];
76
88
  const values = [];
@@ -19,6 +19,18 @@ export interface NodeRule {
19
19
  readonly decision?: true | ((node: Node) => number);
20
20
  readonly exit?: 'return' | 'label';
21
21
  readonly order?: readonly number[];
22
+ /** Body members when the grammar does not expose a single body field. */
23
+ readonly body?: (node: Node) => readonly Node[];
24
+ /** Keep a signature without a body outside measured functions. */
25
+ readonly requiresBody?: boolean;
26
+ /** Lexical parameter count when the grammar does not expose a list of formal parameters. */
27
+ readonly parameters?: (node: Node) => number | undefined;
28
+ /** Alternate branch when the grammar does not expose an alternative field. */
29
+ readonly alternative?: (node: Node) => Node | null;
30
+ /** Whether an alternative wrapper contributes its flat cognitive point. */
31
+ readonly elseCognitive?: (node: Node) => boolean;
32
+ /** A wrapper is transparent when its sole named child is a chained conditional. */
33
+ readonly chainedAlternative?: true;
22
34
  }
23
35
  export interface Grammar {
24
36
  readonly language: ProvidedLanguage;
@@ -40,6 +52,8 @@ export interface Grammar {
40
52
  readonly logicalTypes: ReadonlySet<string>;
41
53
  readonly logicalOperators: ReadonlySet<string>;
42
54
  readonly logicalCognitive: 'parent' | 'sequence';
55
+ /** A parameters field with one of these node types is a single parameter. */
56
+ readonly singleParameterTypes?: ReadonlySet<string>;
43
57
  readonly parameterNames?: string;
44
58
  readonly parameterSeparators?: ReadonlySet<string>;
45
59
  readonly requireFirst?: string;
@@ -53,12 +53,18 @@ export class Structure {
53
53
  this.scope({ ...task, node: definition }, this.grammar.rules[definition.type]?.flow === 'class', decorators);
54
54
  }
55
55
  scope({ node, flow, depth }, isClass, decorators = []) {
56
- const body = node.childForFieldName('body');
56
+ const rule = this.grammar.rules[node.type];
57
+ const body = rule?.body?.(node) ?? fieldBody(node);
58
+ if (rule?.requiresBody && body.length === 0) {
59
+ this.walk.children(node, flow, depth);
60
+ return;
61
+ }
57
62
  const header = this.header(node, body, decorators).map(child => ({ node: child, flow, depth }));
58
63
  this.walk.next([...header, () => this.enterScope(node, body, isClass)]);
59
64
  }
60
65
  header(node, body, decorators) {
61
- const header = this.walk.named(node).filter(child => child.id !== body?.id);
66
+ const bodies = new Set(body.map(member => member.id));
67
+ const header = this.walk.named(node).filter(child => !bodies.has(child.id));
62
68
  if (!decorators.length)
63
69
  return header;
64
70
  const annotation = node.childForFieldName('return_type');
@@ -83,8 +89,7 @@ export class Structure {
83
89
  if (simple)
84
90
  this.names.pop();
85
91
  }]);
86
- if (body)
87
- this.walk.next([{ node: body, flow: own, depth: 0 }]);
92
+ this.walk.next(body.map(member => ({ node: member, flow: own, depth: 0 })));
88
93
  }
89
94
  recordFunction(node, own, label, name) {
90
95
  const line = this.lines.line(node.startIndex);
@@ -97,9 +102,14 @@ export class Structure {
97
102
  this.observe('function-complexity', own.cognitive, label + ' · Cognitive complexity', node);
98
103
  }
99
104
  parameters(node) {
105
+ const specified = this.grammar.rules[node.type]?.parameters?.(node);
106
+ if (specified !== undefined)
107
+ return specified;
100
108
  const list = node.childForFieldName('parameters');
101
109
  if (!list)
102
110
  return 0;
111
+ if (this.grammar.singleParameterTypes?.has(list.type))
112
+ return 1;
103
113
  const { parameterNames, parameterSeparators } = this.grammar;
104
114
  const parameters = this.walk.named(list).filter(item => !parameterSeparators?.has(item.type));
105
115
  return parameters.reduce((count, item) => count + (parameterNames ? Math.max(1, item.childrenForFieldName(parameterNames).length) : 1), 0);
@@ -116,4 +126,8 @@ export class Structure {
116
126
  this.observations.push({ rule, value, label, line, endLine: Math.max(line, end ?? line), ...(anchor ? { anchor } : {}) });
117
127
  }
118
128
  }
129
+ function fieldBody(node) {
130
+ const body = node.childForFieldName('body');
131
+ return body ? [body] : [];
132
+ }
119
133
  //# sourceMappingURL=structure.js.map
@@ -1,4 +1,9 @@
1
- import type { Plugin } from '@repometry/core/internal/engine/plugin.js';
1
+ import type { PluginManifest } from '@repometry/core';
2
2
  import type { Grammar } from './language.js';
3
- /** The tree-sitter language plugin for the given language units, which parse in that order of precedence. */
4
- export declare function treeSitter(grammars: readonly Grammar[]): Plugin;
3
+ type NativeManifest = PluginManifest & {
4
+ readonly version: string;
5
+ create(): Awaited<ReturnType<PluginManifest['create']>>;
6
+ };
7
+ /** The public manifest backed by one grammar. */
8
+ export declare function treeSitter(grammar: Grammar): NativeManifest;
9
+ export {};
@@ -1,20 +1,19 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { extname } from 'node:path';
3
- import { pluginApi } from '@repometry/core/internal/engine/plugin.js';
4
- import { codeStructure } from '@repometry/core/internal/model/code-structure.js';
3
+ import { codeStructure, pluginManifestSchema } from '@repometry/core';
4
+ import { readStructure } from '@repometry/core/internal/engine/author-contracts.js';
5
5
  import { sourceFile } from '@repometry/core/internal/model/snapshot.js';
6
- import { duplicationSettings } from '@repometry/core/internal/profile/maintainability.js';
7
6
  import { SourceLines } from './source-lines.js';
8
7
  import { Structure } from './structure.js';
9
8
  import { firstSyntaxIssue } from './syntax-issue.js';
10
9
  import { scanClones } from './tokens.js';
11
10
  const parsers = new Map();
12
11
  let initialized;
13
- /** The tree-sitter language plugin for the given language units, which parse in that order of precedence. */
14
- export function treeSitter(grammars) {
15
- const byExtension = new Map(grammars.flatMap(grammar => grammar.language.extensions.map(extension => [extension, grammar])));
12
+ /** The public manifest backed by one grammar. */
13
+ export function treeSitter(grammar) {
14
+ const byExtension = new Map(grammar.language.extensions.map(extension => [extension, grammar]));
16
15
  // At this depth the emitted `execute` keeps the text it had as a module constant: profiles digest that text.
17
- const operations = [{
16
+ const [parse] = [{
18
17
  id: 'parse', role: 'provider', inputs: { file: sourceFile }, output: codeStructure,
19
18
  async execute(inputs) {
20
19
  const file = inputs.read('file', sourceFile);
@@ -24,13 +23,17 @@ export function treeSitter(grammars) {
24
23
  return inspectFile(file, grammar);
25
24
  },
26
25
  }];
26
+ const { extensions, globs, measures, ...language } = grammar.language;
27
27
  return {
28
- id: 'tree-sitter', version: '1.0.0', api: pluginApi, kinds: ['language'],
29
- providesLanguages: grammars.map(({ language }) => language),
30
- tools: { 'web-tree-sitter': '0.27.2', ...Object.fromEntries(grammars.map(({ tool }) => [tool.package, tool.version])) },
31
- settings: { duplication: { ...duplicationSettings, minTokens: duplicationSettings.minNodes } },
32
- produces: [{ contract: codeStructure.id, persistence: 'transient' }],
33
- operations,
28
+ schema: pluginManifestSchema, id: 'language-' + language.id.replaceAll('-', ''), category: 'language', version: '1.0.0',
29
+ languages: [{ ...language, include: [...(extensions ?? []).map(ext => '**/*' + ext), ...(globs ?? [])],
30
+ ...(measures === undefined ? {} : { measures: measures.map(measure => measure === 'structuralRules' ? 'checks' : measure) }) }],
31
+ tools: { [grammar.tool.package]: grammar.tool.version },
32
+ create: () => ({
33
+ produces: [{ contract: codeStructure.id, persistence: 'transient' }],
34
+ operations: [{ ...parse, implementation: parse.execute.toString(),
35
+ execute: async (inputs) => readStructure(await parse.execute(inputs)) }],
36
+ }),
34
37
  };
35
38
  }
36
39
  async function inspectFile({ path, bytes }, grammar) {