@repometry/tree-sitter 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/package.json +42 -4
- package/target/main/ts/control.d.ts +17 -0
- package/target/main/ts/control.js +94 -0
- package/target/main/ts/flow.d.ts +37 -0
- package/target/main/ts/flow.js +115 -0
- package/target/main/ts/index.d.ts +3 -0
- package/target/main/ts/index.js +3 -0
- package/target/main/ts/language.d.ts +52 -0
- package/target/main/ts/language.js +3 -0
- package/target/main/ts/logic.d.ts +4 -0
- package/target/main/ts/logic.js +31 -0
- package/target/main/ts/source-lines.d.ts +22 -0
- package/target/main/ts/source-lines.js +62 -0
- package/target/main/ts/structure.d.ts +37 -0
- package/target/main/ts/structure.js +119 -0
- package/target/main/ts/syntax-issue.d.ts +6 -0
- package/target/main/ts/syntax-issue.js +81 -0
- package/target/main/ts/tokens.d.ts +9 -0
- package/target/main/ts/tokens.js +137 -0
- package/target/main/ts/tree-sitter.d.ts +4 -0
- package/target/main/ts/tree-sitter.js +88 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Idleware
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@repometry/tree-sitter",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "The tree-sitter language plugin engine for Repometry",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/idleware/repometry.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/idleware/repometry#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/idleware/repometry/issues"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"repometry",
|
|
16
|
+
"tree-sitter",
|
|
17
|
+
"plugin"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=24"
|
|
22
|
+
},
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./target/main/ts/index.d.ts",
|
|
26
|
+
"default": "./target/main/ts/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"target/main",
|
|
31
|
+
"!target/main/**/*.map"
|
|
32
|
+
],
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "node -e \"require('node:fs').rmSync('target/main', { recursive: true, force: true })\" && tsc -p tsconfig.json && node -e \"require('node:fs').cpSync('../../LICENSE', 'LICENSE')\"",
|
|
38
|
+
"prepack": "npm run build"
|
|
39
|
+
},
|
|
40
|
+
"dependencies": {
|
|
41
|
+
"@repometry/core": "0.0.0",
|
|
42
|
+
"web-tree-sitter": "0.27.2"
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Node } from 'web-tree-sitter';
|
|
2
|
+
import type { StructuralCheck } from '@repometry/core/internal/model/code-structure.js';
|
|
3
|
+
import type { Traversal, Visit } from './flow.js';
|
|
4
|
+
import type { NodeRule } from './language.js';
|
|
5
|
+
type Observe = (rule: StructuralCheck, value: number, label: string, node: Node) => void;
|
|
6
|
+
export declare class Control {
|
|
7
|
+
private readonly walk;
|
|
8
|
+
private readonly observe;
|
|
9
|
+
constructor(walk: Traversal, observe: Observe);
|
|
10
|
+
visit(task: Visit, rule?: NodeRule): void;
|
|
11
|
+
private decisions;
|
|
12
|
+
private logical;
|
|
13
|
+
private conditional;
|
|
14
|
+
private alternative;
|
|
15
|
+
private sequence;
|
|
16
|
+
}
|
|
17
|
+
export {};
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { expressionOperators, logicalOperator } from './logic.js';
|
|
2
|
+
export class Control {
|
|
3
|
+
walk;
|
|
4
|
+
observe;
|
|
5
|
+
constructor(walk, observe) {
|
|
6
|
+
this.walk = walk;
|
|
7
|
+
this.observe = observe;
|
|
8
|
+
}
|
|
9
|
+
visit(task, rule) {
|
|
10
|
+
const { node, flow, depth, parent, logical } = task;
|
|
11
|
+
const kind = rule?.flow;
|
|
12
|
+
const operation = logicalOperator(node, this.walk.grammar);
|
|
13
|
+
this.decisions(node, flow, rule);
|
|
14
|
+
if (operation !== undefined)
|
|
15
|
+
this.logical(node, flow, operation, logical);
|
|
16
|
+
switch (kind) {
|
|
17
|
+
case 'if': return this.conditional(node, flow, depth, task.chained);
|
|
18
|
+
case 'elif':
|
|
19
|
+
flow.cognitive++;
|
|
20
|
+
break;
|
|
21
|
+
case 'else':
|
|
22
|
+
flow.cognitive++;
|
|
23
|
+
return this.walk.children(node, flow, depth + Number(parent !== 'nest'));
|
|
24
|
+
case 'sequence': return this.sequence(node, flow, depth);
|
|
25
|
+
case 'nest':
|
|
26
|
+
flow.block(node, depth);
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
const carried = this.walk.grammar.parens.has(node.type) ? logical : operation;
|
|
30
|
+
this.walk.children(node, flow, depth + Number(kind === 'nest'), kind, carried);
|
|
31
|
+
}
|
|
32
|
+
decisions(node, flow, rule) {
|
|
33
|
+
if (rule?.decision)
|
|
34
|
+
flow.cyclomatic += rule.decision === true ? 1 : rule.decision(node);
|
|
35
|
+
if (rule?.exit === 'return')
|
|
36
|
+
flow.returns++;
|
|
37
|
+
if (rule?.exit === 'label' && this.walk.named(node).length)
|
|
38
|
+
flow.cognitive++;
|
|
39
|
+
}
|
|
40
|
+
logical(node, flow, operator, parent) {
|
|
41
|
+
flow.cyclomatic++;
|
|
42
|
+
const parentMode = this.walk.grammar.logicalCognitive === 'parent';
|
|
43
|
+
if (parentMode && parent !== operator)
|
|
44
|
+
flow.cognitive++;
|
|
45
|
+
if (parent !== undefined)
|
|
46
|
+
return;
|
|
47
|
+
const sequence = expressionOperators(node, this.walk.grammar);
|
|
48
|
+
if (!parentMode)
|
|
49
|
+
flow.cognitive += sequence.filter((item, index) => item !== sequence[index - 1]).length;
|
|
50
|
+
this.observe('boolean-logic', sequence.length, 'Logical operators in one expression', node);
|
|
51
|
+
}
|
|
52
|
+
conditional(node, flow, depth, chained) {
|
|
53
|
+
flow.block(node, depth, chained);
|
|
54
|
+
const work = [];
|
|
55
|
+
for (let index = 0; index < node.childCount; index++) {
|
|
56
|
+
const child = node.child(index);
|
|
57
|
+
if (!child.isNamed || this.walk.ignored(child.type))
|
|
58
|
+
continue;
|
|
59
|
+
work.push(node.fieldNameForChild(index) === 'alternative' ? this.alternative(child, flow, depth) : { node: child, flow, depth: depth + 1 });
|
|
60
|
+
}
|
|
61
|
+
this.walk.next(work);
|
|
62
|
+
}
|
|
63
|
+
alternative(node, flow, depth) {
|
|
64
|
+
switch (this.walk.grammar.rules[node.type]?.flow) {
|
|
65
|
+
case 'if': return { node, flow, depth, chained: true };
|
|
66
|
+
case 'elif': return { node, flow, depth: depth + 1 };
|
|
67
|
+
case 'else': return { node, flow, depth: depth + 1, parent: 'nest' };
|
|
68
|
+
default: return () => {
|
|
69
|
+
flow.cognitive++;
|
|
70
|
+
this.walk.next([{ node, flow, depth: depth + 1 }]);
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
sequence(node, flow, depth) {
|
|
75
|
+
const work = [];
|
|
76
|
+
const values = [];
|
|
77
|
+
for (const child of this.walk.named(node)) {
|
|
78
|
+
const kind = this.walk.grammar.rules[child.type]?.flow;
|
|
79
|
+
if (kind === 'clause' || kind === 'filter') {
|
|
80
|
+
const at = depth++;
|
|
81
|
+
work.push(() => {
|
|
82
|
+
flow.cyclomatic++;
|
|
83
|
+
const position = kind === 'filter' ? this.walk.condition(child) : node;
|
|
84
|
+
flow.block(position, at);
|
|
85
|
+
this.walk.children(child, flow, at + 1);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
else
|
|
89
|
+
values.push(child);
|
|
90
|
+
}
|
|
91
|
+
this.walk.next([...work, ...values.map(value => ({ node: value, flow, depth }))]);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=control.js.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Node } from 'web-tree-sitter';
|
|
2
|
+
import type { Grammar, NodeRule } from './language.js';
|
|
3
|
+
import type { SourceLines } from './source-lines.js';
|
|
4
|
+
export declare class Flow {
|
|
5
|
+
cyclomatic: number;
|
|
6
|
+
cognitive: number;
|
|
7
|
+
returns: number;
|
|
8
|
+
depth: number;
|
|
9
|
+
deepest?: Node;
|
|
10
|
+
block(node: Node, depth: number, chained?: boolean): void;
|
|
11
|
+
}
|
|
12
|
+
export interface Visit {
|
|
13
|
+
readonly node: Node;
|
|
14
|
+
readonly flow: Flow;
|
|
15
|
+
readonly depth: number;
|
|
16
|
+
readonly parent?: NodeRule['flow'];
|
|
17
|
+
readonly logical?: string;
|
|
18
|
+
readonly chained?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export type Work = Visit | (() => void);
|
|
21
|
+
export declare class Traversal {
|
|
22
|
+
readonly grammar: Grammar;
|
|
23
|
+
private readonly source;
|
|
24
|
+
private readonly pending;
|
|
25
|
+
private readonly cursors;
|
|
26
|
+
private readonly batchChildren;
|
|
27
|
+
constructor(grammar: Grammar, source: SourceLines);
|
|
28
|
+
run(root: Node, module: Flow, visit: (task: Visit) => void): void;
|
|
29
|
+
next(items: readonly Work[]): void;
|
|
30
|
+
named(node: Node): Node[];
|
|
31
|
+
ignored(type: string): boolean;
|
|
32
|
+
children(node: Node, flow: Flow, depth: number, parent?: NodeRule['flow'], logical?: string): void;
|
|
33
|
+
private checkEmptyBlock;
|
|
34
|
+
/** Wide subtrees are visited in source order without caching an array of all child wrappers on their parent. */
|
|
35
|
+
private batches;
|
|
36
|
+
condition(node: Node): Node;
|
|
37
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
export class Flow {
|
|
2
|
+
cyclomatic = 1;
|
|
3
|
+
cognitive = 0;
|
|
4
|
+
returns = 0;
|
|
5
|
+
depth = 0;
|
|
6
|
+
deepest;
|
|
7
|
+
block(node, depth, chained = false) {
|
|
8
|
+
this.cognitive += chained ? 1 : 1 + depth;
|
|
9
|
+
if (depth + 1 <= this.depth)
|
|
10
|
+
return;
|
|
11
|
+
this.depth = depth + 1;
|
|
12
|
+
this.deepest = node;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const childBatchSize = 128;
|
|
16
|
+
export class Traversal {
|
|
17
|
+
grammar;
|
|
18
|
+
source;
|
|
19
|
+
pending = [];
|
|
20
|
+
cursors = new Set();
|
|
21
|
+
batchChildren;
|
|
22
|
+
constructor(grammar, source) {
|
|
23
|
+
this.grammar = grammar;
|
|
24
|
+
this.source = source;
|
|
25
|
+
this.batchChildren = source.text.length >= 256 * 1024;
|
|
26
|
+
}
|
|
27
|
+
run(root, module, visit) {
|
|
28
|
+
try {
|
|
29
|
+
this.children(root, module, 0);
|
|
30
|
+
while (this.pending.length) {
|
|
31
|
+
const item = this.pending.pop();
|
|
32
|
+
if (typeof item === 'function')
|
|
33
|
+
item();
|
|
34
|
+
else
|
|
35
|
+
visit(item);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
for (const cursor of this.cursors)
|
|
40
|
+
cursor.delete();
|
|
41
|
+
this.cursors.clear();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
next(items) {
|
|
45
|
+
for (let index = items.length - 1; index >= 0; index--)
|
|
46
|
+
this.pending.push(items[index]);
|
|
47
|
+
}
|
|
48
|
+
named(node) {
|
|
49
|
+
return node.namedChildren.filter(child => !this.ignored(child.type));
|
|
50
|
+
}
|
|
51
|
+
ignored(type) {
|
|
52
|
+
return this.grammar.comments.has(type) || this.grammar.extras.has(type);
|
|
53
|
+
}
|
|
54
|
+
children(node, flow, depth, parent, logical) {
|
|
55
|
+
const ordered = this.grammar.rules[node.type]?.order;
|
|
56
|
+
const prepare = (child) => {
|
|
57
|
+
if (this.grammar.rules[child.type]?.flow !== 'filter')
|
|
58
|
+
return { node: child, flow, depth, parent, logical };
|
|
59
|
+
const at = depth++;
|
|
60
|
+
return () => {
|
|
61
|
+
flow.block(this.condition(child), at);
|
|
62
|
+
this.children(child, flow, at + 1);
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
if (this.batchChildren && !ordered && node.namedChildCount > childBatchSize)
|
|
66
|
+
return this.batches(node, prepare);
|
|
67
|
+
const names = this.named(node);
|
|
68
|
+
const children = ordered ? ordered.flatMap(index => names[index] ?? []) : names;
|
|
69
|
+
if (!children.length)
|
|
70
|
+
this.checkEmptyBlock(node);
|
|
71
|
+
this.next(children.map(prepare));
|
|
72
|
+
}
|
|
73
|
+
checkEmptyBlock(node) {
|
|
74
|
+
if (node.type === this.grammar.requireNonemptyBlock) {
|
|
75
|
+
throw new SyntaxError('Expected a statement in the block at ' + this.source.location(node.startIndex, this.grammar.columns));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Wide subtrees are visited in source order without caching an array of all child wrappers on their parent. */
|
|
79
|
+
batches(node, prepare) {
|
|
80
|
+
const cursor = node.walk();
|
|
81
|
+
this.cursors.add(cursor);
|
|
82
|
+
cursor.gotoFirstChild();
|
|
83
|
+
let hasChildren = false;
|
|
84
|
+
const resume = () => {
|
|
85
|
+
const work = [];
|
|
86
|
+
do {
|
|
87
|
+
if (cursor.nodeIsNamed && !this.ignored(cursor.nodeType))
|
|
88
|
+
work.push(prepare(cursor.currentNode));
|
|
89
|
+
if (cursor.gotoNextSibling())
|
|
90
|
+
continue;
|
|
91
|
+
this.cursors.delete(cursor);
|
|
92
|
+
cursor.delete();
|
|
93
|
+
if (!hasChildren && !work.length)
|
|
94
|
+
this.checkEmptyBlock(node);
|
|
95
|
+
this.next(work);
|
|
96
|
+
return;
|
|
97
|
+
} while (work.length < childBatchSize);
|
|
98
|
+
hasChildren = true;
|
|
99
|
+
this.pending.push(resume);
|
|
100
|
+
this.next(work);
|
|
101
|
+
};
|
|
102
|
+
resume();
|
|
103
|
+
}
|
|
104
|
+
condition(node) {
|
|
105
|
+
let expression = this.named(node)[0] ?? node;
|
|
106
|
+
while (this.grammar.parens.has(expression.type)) {
|
|
107
|
+
const child = this.named(expression)[0];
|
|
108
|
+
if (!child)
|
|
109
|
+
break;
|
|
110
|
+
expression = child;
|
|
111
|
+
}
|
|
112
|
+
return expression;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=flow.js.map
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Node } from 'web-tree-sitter';
|
|
2
|
+
import type { ProvidedLanguage } from '@repometry/core/internal/model/language.js';
|
|
3
|
+
declare global {
|
|
4
|
+
interface EmscriptenModule {
|
|
5
|
+
locateFile?: (filename: string, directory: string) => string;
|
|
6
|
+
}
|
|
7
|
+
namespace WebAssembly {
|
|
8
|
+
interface Module {
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export interface TokenRules {
|
|
13
|
+
readonly candidates: ReadonlySet<string>;
|
|
14
|
+
readonly kinds: ReadonlyMap<string, string>;
|
|
15
|
+
readonly normalize?: (type: string, text: string, kind: string | undefined) => readonly [string, string | undefined];
|
|
16
|
+
}
|
|
17
|
+
export interface NodeRule {
|
|
18
|
+
readonly flow?: 'function' | 'class' | 'decorated' | 'if' | 'elif' | 'else' | 'nest' | 'sequence' | 'clause' | 'filter';
|
|
19
|
+
readonly decision?: true | ((node: Node) => number);
|
|
20
|
+
readonly exit?: 'return' | 'label';
|
|
21
|
+
readonly order?: readonly number[];
|
|
22
|
+
}
|
|
23
|
+
export interface Grammar {
|
|
24
|
+
readonly language: ProvidedLanguage;
|
|
25
|
+
/** The grammar package the WASM file was built from, recorded in the plugin's tools. */
|
|
26
|
+
readonly tool: {
|
|
27
|
+
readonly package: string;
|
|
28
|
+
readonly version: string;
|
|
29
|
+
};
|
|
30
|
+
readonly asset: URL;
|
|
31
|
+
readonly decode?: (bytes: Uint8Array) => string;
|
|
32
|
+
readonly prepareSource: (text: string) => string;
|
|
33
|
+
readonly lineBreaks?: RegExp;
|
|
34
|
+
readonly columns: 'bytes' | 'codepoints';
|
|
35
|
+
readonly name: (node: Node) => string | undefined;
|
|
36
|
+
readonly rules: Readonly<Record<string, NodeRule>>;
|
|
37
|
+
readonly parens: ReadonlySet<string>;
|
|
38
|
+
readonly comments: ReadonlySet<string>;
|
|
39
|
+
readonly extras: ReadonlySet<string>;
|
|
40
|
+
readonly logicalTypes: ReadonlySet<string>;
|
|
41
|
+
readonly logicalOperators: ReadonlySet<string>;
|
|
42
|
+
readonly logicalCognitive: 'parent' | 'sequence';
|
|
43
|
+
readonly parameterNames?: string;
|
|
44
|
+
readonly parameterSeparators?: ReadonlySet<string>;
|
|
45
|
+
readonly requireFirst?: string;
|
|
46
|
+
readonly requireNonemptyBlock?: string;
|
|
47
|
+
readonly reportFileRange?: boolean;
|
|
48
|
+
readonly trimObservationComments?: boolean;
|
|
49
|
+
readonly moduleDepthLabel: string;
|
|
50
|
+
readonly tokens: TokenRules;
|
|
51
|
+
}
|
|
52
|
+
export declare const measures: readonly ['functions', 'cyclomaticComplexity', 'cognitiveComplexity', 'commentLines', 'codeLines', 'structuralRules', 'duplication'];
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export function logicalOperator(node, grammar) {
|
|
2
|
+
if (!grammar.logicalTypes.has(node.type))
|
|
3
|
+
return undefined;
|
|
4
|
+
const operator = node.childForFieldName('operator') ?? node.children.find(child => !child.isNamed);
|
|
5
|
+
return operator && grammar.logicalOperators.has(operator.type) ? operator.type : undefined;
|
|
6
|
+
}
|
|
7
|
+
export function expressionOperators(root, grammar) {
|
|
8
|
+
const sequence = [];
|
|
9
|
+
const pending = [root];
|
|
10
|
+
while (pending.length) {
|
|
11
|
+
const node = pending.pop();
|
|
12
|
+
if (typeof node === 'string')
|
|
13
|
+
sequence.push(node);
|
|
14
|
+
else
|
|
15
|
+
for (const item of operatorWork(node, grammar))
|
|
16
|
+
pending.push(item);
|
|
17
|
+
}
|
|
18
|
+
return sequence;
|
|
19
|
+
}
|
|
20
|
+
function operatorWork(node, grammar) {
|
|
21
|
+
if (grammar.parens.has(node.type))
|
|
22
|
+
return node.namedChildren.reverse();
|
|
23
|
+
const operator = logicalOperator(node, grammar);
|
|
24
|
+
if (operator === undefined)
|
|
25
|
+
return [];
|
|
26
|
+
const children = node.namedChildren.filter(child => !grammar.comments.has(child.type) && !grammar.extras.has(child.type));
|
|
27
|
+
const first = node.childForFieldName('left') ?? children[0];
|
|
28
|
+
const second = node.childForFieldName('right') ?? children[1];
|
|
29
|
+
return [...(second ? [second] : []), operator, ...(first ? [first] : [])];
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=logic.js.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface Span {
|
|
2
|
+
readonly start: number;
|
|
3
|
+
readonly end: number;
|
|
4
|
+
}
|
|
5
|
+
export declare function lowerBound(values: readonly number[], value: number): number;
|
|
6
|
+
export declare class SourceLines {
|
|
7
|
+
readonly text: string;
|
|
8
|
+
readonly starts: number[];
|
|
9
|
+
readonly count: number;
|
|
10
|
+
constructor(text: string, lineBreaks?: RegExp);
|
|
11
|
+
line(offset: number): number;
|
|
12
|
+
position(span: Span): {
|
|
13
|
+
line: number;
|
|
14
|
+
endLine: number;
|
|
15
|
+
};
|
|
16
|
+
column(offset: number, columns: 'bytes' | 'codepoints'): number;
|
|
17
|
+
location(offset: number, columns: 'bytes' | 'codepoints'): string;
|
|
18
|
+
classify(comments: readonly Span[]): {
|
|
19
|
+
codeLines: number[];
|
|
20
|
+
commentLines: number;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
export function lowerBound(values, value) {
|
|
2
|
+
let start = 0;
|
|
3
|
+
let end = values.length;
|
|
4
|
+
while (start < end) {
|
|
5
|
+
const middle = (start + end) >>> 1;
|
|
6
|
+
if (values[middle] < value)
|
|
7
|
+
start = middle + 1;
|
|
8
|
+
else
|
|
9
|
+
end = middle;
|
|
10
|
+
}
|
|
11
|
+
return start;
|
|
12
|
+
}
|
|
13
|
+
export class SourceLines {
|
|
14
|
+
text;
|
|
15
|
+
starts = [0];
|
|
16
|
+
count;
|
|
17
|
+
constructor(text, lineBreaks = /\r\n|[\n\r]/g) {
|
|
18
|
+
this.text = text;
|
|
19
|
+
for (const match of text.matchAll(lineBreaks))
|
|
20
|
+
this.starts.push(match.index + match[0].length);
|
|
21
|
+
this.count = this.starts.length - Number(this.starts.at(-1) === text.length);
|
|
22
|
+
}
|
|
23
|
+
line(offset) {
|
|
24
|
+
return lowerBound(this.starts, offset + 1);
|
|
25
|
+
}
|
|
26
|
+
position(span) {
|
|
27
|
+
return { line: this.line(span.start), endLine: this.line(Math.max(span.start, span.end - 1)) };
|
|
28
|
+
}
|
|
29
|
+
column(offset, columns) {
|
|
30
|
+
const prefix = this.text.slice(this.starts[this.line(offset) - 1], offset);
|
|
31
|
+
return 1 + (columns === 'bytes' ? Buffer.byteLength(prefix) : [...prefix].length);
|
|
32
|
+
}
|
|
33
|
+
location(offset, columns) {
|
|
34
|
+
const index = Math.min(offset, this.text.length);
|
|
35
|
+
return 'line ' + this.line(index) + ', column ' + this.column(index, columns);
|
|
36
|
+
}
|
|
37
|
+
classify(comments) {
|
|
38
|
+
const codeLines = [];
|
|
39
|
+
let commentLines = 0;
|
|
40
|
+
let next = 0;
|
|
41
|
+
for (let row = 0; row < this.count; row++) {
|
|
42
|
+
const start = this.starts[row];
|
|
43
|
+
const end = this.starts[row + 1] ?? this.text.length;
|
|
44
|
+
while (comments[next] && comments[next].end <= start)
|
|
45
|
+
next++;
|
|
46
|
+
const first = next;
|
|
47
|
+
let offset = start;
|
|
48
|
+
let code = false;
|
|
49
|
+
for (let index = first; comments[index] && comments[index].start < end; index++) {
|
|
50
|
+
const comment = comments[index];
|
|
51
|
+
code ||= this.text.slice(offset, comment.start).trim() !== '';
|
|
52
|
+
offset = comment.end;
|
|
53
|
+
}
|
|
54
|
+
if (code || this.text.slice(offset, end).trim())
|
|
55
|
+
codeLines.push(row + 1);
|
|
56
|
+
else if (comments[first] && comments[first].start < end)
|
|
57
|
+
commentLines++;
|
|
58
|
+
}
|
|
59
|
+
return { codeLines, commentLines };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=source-lines.js.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Node } from 'web-tree-sitter';
|
|
2
|
+
import type { FunctionComplexity, StructuralObservation } from '@repometry/core/internal/model/code-structure.js';
|
|
3
|
+
import type { Grammar } from './language.js';
|
|
4
|
+
import type { SourceLines } from './source-lines.js';
|
|
5
|
+
export declare class Structure {
|
|
6
|
+
private readonly grammar;
|
|
7
|
+
private readonly lines;
|
|
8
|
+
private readonly codeLines;
|
|
9
|
+
private readonly cyclomaticFunctions;
|
|
10
|
+
private readonly cognitiveFunctions;
|
|
11
|
+
private readonly observations;
|
|
12
|
+
private readonly names;
|
|
13
|
+
private readonly anchors;
|
|
14
|
+
private readonly walk;
|
|
15
|
+
private readonly control;
|
|
16
|
+
private classes;
|
|
17
|
+
private cognitive;
|
|
18
|
+
constructor(grammar: Grammar, lines: SourceLines, codeLines: readonly number[]);
|
|
19
|
+
measure(root: Node): {
|
|
20
|
+
lines: number;
|
|
21
|
+
functions: number;
|
|
22
|
+
cognitiveComplexity: number;
|
|
23
|
+
cyclomaticFunctions: FunctionComplexity[];
|
|
24
|
+
cognitiveFunctions: FunctionComplexity[];
|
|
25
|
+
observations: StructuralObservation[];
|
|
26
|
+
classes?: number | undefined;
|
|
27
|
+
};
|
|
28
|
+
private visit;
|
|
29
|
+
private decorated;
|
|
30
|
+
private scope;
|
|
31
|
+
private header;
|
|
32
|
+
private enterScope;
|
|
33
|
+
private recordFunction;
|
|
34
|
+
private parameters;
|
|
35
|
+
private finish;
|
|
36
|
+
private observe;
|
|
37
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { Control } from './control.js';
|
|
2
|
+
import { Flow, Traversal } from './flow.js';
|
|
3
|
+
import { lowerBound } from './source-lines.js';
|
|
4
|
+
export class Structure {
|
|
5
|
+
grammar;
|
|
6
|
+
lines;
|
|
7
|
+
codeLines;
|
|
8
|
+
cyclomaticFunctions = [];
|
|
9
|
+
cognitiveFunctions = [];
|
|
10
|
+
observations = [];
|
|
11
|
+
names = [];
|
|
12
|
+
anchors = [];
|
|
13
|
+
walk;
|
|
14
|
+
control;
|
|
15
|
+
classes = 0;
|
|
16
|
+
cognitive = 0;
|
|
17
|
+
constructor(grammar, lines, codeLines) {
|
|
18
|
+
this.grammar = grammar;
|
|
19
|
+
this.lines = lines;
|
|
20
|
+
this.codeLines = codeLines;
|
|
21
|
+
this.walk = new Traversal(grammar, lines);
|
|
22
|
+
this.control = new Control(this.walk, this.observe.bind(this));
|
|
23
|
+
}
|
|
24
|
+
measure(root) {
|
|
25
|
+
const module = new Flow();
|
|
26
|
+
this.walk.run(root, module, task => this.visit(task));
|
|
27
|
+
this.finish(module, this.grammar.moduleDepthLabel);
|
|
28
|
+
const position = this.grammar.reportFileRange ? { line: 1, endLine: this.lines.count } : {};
|
|
29
|
+
this.observations.push({ rule: 'file-complexity', value: this.cognitive, label: 'File cognitive complexity', ...position });
|
|
30
|
+
const byPosition = (left, right) => left.line - right.line || left.column - right.column;
|
|
31
|
+
this.cyclomaticFunctions.sort(byPosition);
|
|
32
|
+
this.cognitiveFunctions.sort(byPosition);
|
|
33
|
+
return { lines: this.lines.count, functions: this.cyclomaticFunctions.length,
|
|
34
|
+
cognitiveComplexity: this.cognitive, cyclomaticFunctions: this.cyclomaticFunctions, cognitiveFunctions: this.cognitiveFunctions,
|
|
35
|
+
observations: this.observations, ...(this.grammar.language.measures?.includes('classes') ? { classes: this.classes } : {}) };
|
|
36
|
+
}
|
|
37
|
+
visit(task) {
|
|
38
|
+
const rule = this.grammar.rules[task.node.type];
|
|
39
|
+
if (rule?.flow === 'function')
|
|
40
|
+
this.scope(task, false);
|
|
41
|
+
else if (rule?.flow === 'class')
|
|
42
|
+
this.scope(task, true);
|
|
43
|
+
else if (rule?.flow === 'decorated')
|
|
44
|
+
this.decorated(task);
|
|
45
|
+
else
|
|
46
|
+
this.control.visit(task, rule);
|
|
47
|
+
}
|
|
48
|
+
decorated(task) {
|
|
49
|
+
const definition = task.node.childForFieldName('definition');
|
|
50
|
+
if (!definition)
|
|
51
|
+
return;
|
|
52
|
+
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);
|
|
54
|
+
}
|
|
55
|
+
scope({ node, flow, depth }, isClass, decorators = []) {
|
|
56
|
+
const body = node.childForFieldName('body');
|
|
57
|
+
const header = this.header(node, body, decorators).map(child => ({ node: child, flow, depth }));
|
|
58
|
+
this.walk.next([...header, () => this.enterScope(node, body, isClass)]);
|
|
59
|
+
}
|
|
60
|
+
header(node, body, decorators) {
|
|
61
|
+
const header = this.walk.named(node).filter(child => child.id !== body?.id);
|
|
62
|
+
if (!decorators.length)
|
|
63
|
+
return header;
|
|
64
|
+
const annotation = node.childForFieldName('return_type');
|
|
65
|
+
const index = header.findIndex(child => child.id === annotation?.id);
|
|
66
|
+
return index === -1 ? [...header, ...decorators] : [...header.slice(0, index), ...decorators, ...header.slice(index)];
|
|
67
|
+
}
|
|
68
|
+
enterScope(node, body, isClass) {
|
|
69
|
+
const simple = this.grammar.name(node);
|
|
70
|
+
const name = simple && [...this.names, simple].join('.');
|
|
71
|
+
const label = name ?? '(anonymous)';
|
|
72
|
+
if (simple)
|
|
73
|
+
this.names.push(simple);
|
|
74
|
+
this.anchors.push(name ?? [...this.anchors.slice(-1), label].join('.'));
|
|
75
|
+
const own = new Flow();
|
|
76
|
+
this.walk.next([() => {
|
|
77
|
+
if (isClass)
|
|
78
|
+
this.classes++;
|
|
79
|
+
else
|
|
80
|
+
this.recordFunction(node, own, label, name);
|
|
81
|
+
this.finish(own, label + ' · Control-flow depth');
|
|
82
|
+
this.anchors.pop();
|
|
83
|
+
if (simple)
|
|
84
|
+
this.names.pop();
|
|
85
|
+
}]);
|
|
86
|
+
if (body)
|
|
87
|
+
this.walk.next([{ node: body, flow: own, depth: 0 }]);
|
|
88
|
+
}
|
|
89
|
+
recordFunction(node, own, label, name) {
|
|
90
|
+
const line = this.lines.line(node.startIndex);
|
|
91
|
+
const column = this.lines.column(node.startIndex, this.grammar.columns);
|
|
92
|
+
const position = { ...(name ? { name } : {}), line, column };
|
|
93
|
+
this.cyclomaticFunctions.push({ ...position, value: own.cyclomatic });
|
|
94
|
+
this.cognitiveFunctions.push({ ...position, value: own.cognitive });
|
|
95
|
+
this.observe('function-parameters', this.parameters(node), label + ' · Parameters', node);
|
|
96
|
+
this.observe('return-statements', own.returns, label + ' · Return statements', node);
|
|
97
|
+
this.observe('function-complexity', own.cognitive, label + ' · Cognitive complexity', node);
|
|
98
|
+
}
|
|
99
|
+
parameters(node) {
|
|
100
|
+
const list = node.childForFieldName('parameters');
|
|
101
|
+
if (!list)
|
|
102
|
+
return 0;
|
|
103
|
+
const { parameterNames, parameterSeparators } = this.grammar;
|
|
104
|
+
const parameters = this.walk.named(list).filter(item => !parameterSeparators?.has(item.type));
|
|
105
|
+
return parameters.reduce((count, item) => count + (parameterNames ? Math.max(1, item.childrenForFieldName(parameterNames).length) : 1), 0);
|
|
106
|
+
}
|
|
107
|
+
finish(flow, label) {
|
|
108
|
+
this.cognitive += flow.cognitive;
|
|
109
|
+
if (flow.deepest)
|
|
110
|
+
this.observe('nested-control-flow', flow.depth, label, flow.deepest);
|
|
111
|
+
}
|
|
112
|
+
observe(rule, value, label, node) {
|
|
113
|
+
const anchor = this.anchors.at(-1);
|
|
114
|
+
const { line, endLine } = this.lines.position({ start: node.startIndex, end: node.endIndex });
|
|
115
|
+
const end = this.grammar.trimObservationComments ? this.codeLines[lowerBound(this.codeLines, endLine + 1) - 1] : endLine;
|
|
116
|
+
this.observations.push({ rule, value, label, line, endLine: Math.max(line, end ?? line), ...(anchor ? { anchor } : {}) });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=structure.js.map
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export function firstSyntaxIssue(node, grammar) {
|
|
2
|
+
while (!node.isError && !node.isMissing) {
|
|
3
|
+
const child = node.children.find(child => child.hasError);
|
|
4
|
+
if (!child)
|
|
5
|
+
break;
|
|
6
|
+
node = child;
|
|
7
|
+
}
|
|
8
|
+
if (node.isMissing)
|
|
9
|
+
return missing(node);
|
|
10
|
+
if (node.childCount === 1 && node.firstChild?.type === 'string_start') {
|
|
11
|
+
return { offset: node.startIndex, reason: 'Unterminated string' };
|
|
12
|
+
}
|
|
13
|
+
return errorToken(node, grammar);
|
|
14
|
+
}
|
|
15
|
+
function missing(node) {
|
|
16
|
+
return { offset: node.startIndex, reason: 'Expected ' + JSON.stringify(node.type) };
|
|
17
|
+
}
|
|
18
|
+
function errorToken(error, grammar) {
|
|
19
|
+
let previous;
|
|
20
|
+
for (const node of errorLeaves(error)) {
|
|
21
|
+
if (node.isMissing)
|
|
22
|
+
return missing(node);
|
|
23
|
+
if (node.isError)
|
|
24
|
+
return unexpected(node.startIndex);
|
|
25
|
+
if (node.isExtra)
|
|
26
|
+
continue;
|
|
27
|
+
if (!node.parseState)
|
|
28
|
+
return expectedAfter(previous, grammar) ?? unexpected(node.startIndex);
|
|
29
|
+
if (!symbols(node, node.parseState).includes(node.grammarType))
|
|
30
|
+
return unexpectedAfter(error, previous, node, grammar);
|
|
31
|
+
previous = node;
|
|
32
|
+
}
|
|
33
|
+
return expectedAfter(previous, grammar) ?? missingHeaderColon(error, previous, grammar)
|
|
34
|
+
?? unexpected(previous?.endIndex ?? error.startIndex);
|
|
35
|
+
}
|
|
36
|
+
function unexpectedAfter(error, previous, node, grammar) {
|
|
37
|
+
const nextLine = previous && node.startPosition.row > previous.endPosition.row;
|
|
38
|
+
return (nextLine ? missingHeaderColon(error, previous, grammar) : undefined) ?? unexpected(node.startIndex);
|
|
39
|
+
}
|
|
40
|
+
function missingHeaderColon(error, previous, grammar) {
|
|
41
|
+
if (grammar.language.id !== 'python' || !previous || error.firstChild?.type !== 'if')
|
|
42
|
+
return undefined;
|
|
43
|
+
if (!symbols(previous, previous.nextParseState).includes(':'))
|
|
44
|
+
return undefined;
|
|
45
|
+
return { offset: previous.endIndex, reason: 'Expected ":"' };
|
|
46
|
+
}
|
|
47
|
+
function* errorLeaves(root) {
|
|
48
|
+
const pending = [root];
|
|
49
|
+
while (pending.length) {
|
|
50
|
+
const node = pending.pop();
|
|
51
|
+
if (!node.childCount || node.isMissing)
|
|
52
|
+
yield node;
|
|
53
|
+
else
|
|
54
|
+
for (const child of node.children.toReversed())
|
|
55
|
+
pending.push(child);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function expectedAfter(previous, grammar) {
|
|
59
|
+
if (!previous?.nextParseState)
|
|
60
|
+
return undefined;
|
|
61
|
+
const expected = symbols(previous, previous.nextParseState)
|
|
62
|
+
.filter(name => !grammar.comments.has(name) && !grammar.extras.has(name));
|
|
63
|
+
if (!expected.length || expected.length > 2 || !expected.every(name => /^[^\w\s]+$/u.test(name)))
|
|
64
|
+
return undefined;
|
|
65
|
+
return { offset: previous.endIndex, reason: 'Expected ' + expected.map(name => JSON.stringify(name)).join(' or ') };
|
|
66
|
+
}
|
|
67
|
+
function unexpected(offset) {
|
|
68
|
+
return { offset, reason: 'Unexpected syntax' };
|
|
69
|
+
}
|
|
70
|
+
function symbols(node, state) {
|
|
71
|
+
const iterator = node.tree.language.lookaheadIterator(state);
|
|
72
|
+
if (!iterator)
|
|
73
|
+
return [];
|
|
74
|
+
try {
|
|
75
|
+
return [...iterator];
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
iterator.delete();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=syntax-issue.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Tree } from 'web-tree-sitter';
|
|
2
|
+
import type { CloneSource } from '@repometry/core/internal/model/clone-source.js';
|
|
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): {
|
|
6
|
+
codeLines: number[];
|
|
7
|
+
commentLines: number;
|
|
8
|
+
clones: CloneSource;
|
|
9
|
+
};
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { hash } from 'node:crypto';
|
|
2
|
+
import { duplicationSettings as limits } from '@repometry/core/internal/profile/maintainability.js';
|
|
3
|
+
import { lowerBound } from './source-lines.js';
|
|
4
|
+
export function scanClones(path, tree, source, grammar) {
|
|
5
|
+
const cursor = tree.walk();
|
|
6
|
+
try {
|
|
7
|
+
return new TokenScanner(cursor, source, grammar).scan(path);
|
|
8
|
+
}
|
|
9
|
+
finally {
|
|
10
|
+
cursor.delete();
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
class FingerprintInput {
|
|
14
|
+
bytes = Buffer.allocUnsafe(256);
|
|
15
|
+
offsets = [0];
|
|
16
|
+
append(spelling) {
|
|
17
|
+
const start = this.offsets.at(-1);
|
|
18
|
+
// UTF-8 needs at most three bytes per UTF-16 code unit. Only measure near the buffer boundary.
|
|
19
|
+
if (start + spelling.length * 3 > this.bytes.length)
|
|
20
|
+
this.reserve(start, Buffer.byteLength(spelling));
|
|
21
|
+
this.offsets.push(start + this.bytes.write(spelling, start));
|
|
22
|
+
}
|
|
23
|
+
reserve(start, needed) {
|
|
24
|
+
if (start + needed <= this.bytes.length)
|
|
25
|
+
return;
|
|
26
|
+
const bytes = Buffer.allocUnsafe(Math.max(start + needed, this.bytes.length * 2));
|
|
27
|
+
this.bytes.copy(bytes, 0, 0, start);
|
|
28
|
+
this.bytes = bytes;
|
|
29
|
+
}
|
|
30
|
+
fingerprint(start, end) {
|
|
31
|
+
return hash('sha256', this.bytes.subarray(this.offsets[start], this.offsets[end]), 'base64url');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
class TokenScanner {
|
|
35
|
+
cursor;
|
|
36
|
+
source;
|
|
37
|
+
grammar;
|
|
38
|
+
comments = [];
|
|
39
|
+
ranges = [];
|
|
40
|
+
starts = [];
|
|
41
|
+
ends = [];
|
|
42
|
+
exact = new FingerprintInput();
|
|
43
|
+
similar = new FingerprintInput();
|
|
44
|
+
collect;
|
|
45
|
+
candidateEnd = 0;
|
|
46
|
+
constructor(cursor, source, grammar) {
|
|
47
|
+
this.cursor = cursor;
|
|
48
|
+
this.source = source;
|
|
49
|
+
this.grammar = grammar;
|
|
50
|
+
this.collect = source.count >= limits.minCodeLines;
|
|
51
|
+
}
|
|
52
|
+
scan(path) {
|
|
53
|
+
do {
|
|
54
|
+
if (this.read(this.cursor.nodeType))
|
|
55
|
+
continue;
|
|
56
|
+
if (!this.advance())
|
|
57
|
+
break;
|
|
58
|
+
} while (true);
|
|
59
|
+
const lines = this.source.classify(this.comments);
|
|
60
|
+
return { ...lines, clones: this.cloneSource(path, lines.codeLines) };
|
|
61
|
+
}
|
|
62
|
+
advance() {
|
|
63
|
+
while (!this.cursor.gotoNextSibling()) {
|
|
64
|
+
if (!this.cursor.gotoParent())
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
read(type) {
|
|
70
|
+
if (this.grammar.comments.has(type)) {
|
|
71
|
+
this.comments.push(span(this.cursor));
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
if (this.grammar.extras.has(type))
|
|
75
|
+
return false;
|
|
76
|
+
if (this.collect && this.grammar.tokens.candidates.has(type))
|
|
77
|
+
this.candidate();
|
|
78
|
+
const kind = this.collect ? this.grammar.tokens.kinds.get(type) : undefined;
|
|
79
|
+
if (!kind && this.cursor.gotoFirstChild())
|
|
80
|
+
return true;
|
|
81
|
+
if (this.candidateEnd) {
|
|
82
|
+
const start = this.cursor.startIndex;
|
|
83
|
+
if (start < this.candidateEnd)
|
|
84
|
+
this.record(start, type, kind);
|
|
85
|
+
}
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
candidate() {
|
|
89
|
+
const range = span(this.cursor);
|
|
90
|
+
if (range.end - range.start < limits.minNodes)
|
|
91
|
+
return;
|
|
92
|
+
if (this.source.line(range.end - 1) - this.source.line(range.start) + 1 < limits.minCodeLines)
|
|
93
|
+
return;
|
|
94
|
+
// Only tokens inside ranges that could meet both minima can be part of a fingerprint.
|
|
95
|
+
this.ranges.push(range);
|
|
96
|
+
this.candidateEnd = Math.max(this.candidateEnd, range.end);
|
|
97
|
+
}
|
|
98
|
+
record(start, type, literal) {
|
|
99
|
+
const end = this.cursor.endIndex;
|
|
100
|
+
const value = this.source.text.slice(start, end);
|
|
101
|
+
if (!value.trim())
|
|
102
|
+
return;
|
|
103
|
+
const [spelling, kind] = this.grammar.tokens.normalize?.(type, value, literal) ?? [value, literal];
|
|
104
|
+
// Each spelling is its UTF-16 length, a colon, then the text. A kind is !kind:.
|
|
105
|
+
const exact = spelling.length + ':' + spelling;
|
|
106
|
+
this.starts.push(start);
|
|
107
|
+
this.ends.push(end);
|
|
108
|
+
this.exact.append(exact);
|
|
109
|
+
this.similar.append(kind === undefined ? exact : '!' + kind + ':');
|
|
110
|
+
}
|
|
111
|
+
cloneSource(path, lines) {
|
|
112
|
+
const candidates = [];
|
|
113
|
+
const seen = new Set();
|
|
114
|
+
for (const range of this.ranges) {
|
|
115
|
+
const start = lowerBound(this.starts, range.start);
|
|
116
|
+
const end = lowerBound(this.starts, range.end);
|
|
117
|
+
const nodes = end - start; // Existing ranking field holds the significant token count.
|
|
118
|
+
if (nodes < limits.minNodes)
|
|
119
|
+
continue;
|
|
120
|
+
const key = start + ':' + end;
|
|
121
|
+
if (seen.has(key))
|
|
122
|
+
continue;
|
|
123
|
+
seen.add(key);
|
|
124
|
+
const span = { start: this.starts[start], end: this.ends[end - 1] };
|
|
125
|
+
const { line, endLine } = this.source.position(span);
|
|
126
|
+
const codeLines = lowerBound(lines, endLine + 1) - lowerBound(lines, line);
|
|
127
|
+
if (codeLines >= limits.minCodeLines)
|
|
128
|
+
candidates.push({ ...span, line, endLine, nodes, codeLines,
|
|
129
|
+
exact: this.exact.fingerprint(start, end), similar: this.similar.fingerprint(start, end) });
|
|
130
|
+
}
|
|
131
|
+
return { path, scheme: this.grammar.language.id + '-tokens/v1', codeLines: lines, candidates };
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function span({ startIndex: start, endIndex: end }) {
|
|
135
|
+
return { start, end };
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=tokens.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Plugin } from '@repometry/core/internal/engine/plugin.js';
|
|
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;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
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';
|
|
5
|
+
import { sourceFile } from '@repometry/core/internal/model/snapshot.js';
|
|
6
|
+
import { duplicationSettings } from '@repometry/core/internal/profile/maintainability.js';
|
|
7
|
+
import { SourceLines } from './source-lines.js';
|
|
8
|
+
import { Structure } from './structure.js';
|
|
9
|
+
import { firstSyntaxIssue } from './syntax-issue.js';
|
|
10
|
+
import { scanClones } from './tokens.js';
|
|
11
|
+
const parsers = new Map();
|
|
12
|
+
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])));
|
|
16
|
+
// At this depth the emitted `execute` keeps the text it had as a module constant: profiles digest that text.
|
|
17
|
+
const operations = [{
|
|
18
|
+
id: 'parse', role: 'provider', inputs: { file: sourceFile }, output: codeStructure,
|
|
19
|
+
async execute(inputs) {
|
|
20
|
+
const file = inputs.read('file', sourceFile);
|
|
21
|
+
const grammar = byExtension.get(extname(file.path));
|
|
22
|
+
if (!grammar)
|
|
23
|
+
throw new Error('No grammar for ' + file.path);
|
|
24
|
+
return inspectFile(file, grammar);
|
|
25
|
+
},
|
|
26
|
+
}];
|
|
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,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
async function inspectFile({ path, bytes }, grammar) {
|
|
37
|
+
const text = grammar.decode?.(bytes) ?? new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
38
|
+
const source = new SourceLines(text, grammar.lineBreaks);
|
|
39
|
+
const input = grammar.prepareSource(text);
|
|
40
|
+
const parser = await parserFor(grammar);
|
|
41
|
+
const tree = parser.parse(input);
|
|
42
|
+
try {
|
|
43
|
+
return extract(path, grammar, source, tree);
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
tree?.delete();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function extract(path, grammar, source, tree) {
|
|
50
|
+
if (!tree)
|
|
51
|
+
throw new SyntaxError('No syntax tree at ' + source.location(0, grammar.columns));
|
|
52
|
+
const root = tree.rootNode;
|
|
53
|
+
if (root.hasError) {
|
|
54
|
+
const { offset, reason } = firstSyntaxIssue(root, grammar);
|
|
55
|
+
throw new SyntaxError(reason + ' at ' + source.location(offset, grammar.columns));
|
|
56
|
+
}
|
|
57
|
+
const header = grammar.requireFirst && firstHeader(root, grammar);
|
|
58
|
+
if (grammar.requireFirst && (!header || header.type !== grammar.requireFirst)) {
|
|
59
|
+
throw new SyntaxError('Expected a ' + grammar.requireFirst.replaceAll('_', ' ') +
|
|
60
|
+
' at ' + source.location(header ? header.startIndex : 0, grammar.columns));
|
|
61
|
+
}
|
|
62
|
+
const facts = scanClones(path, tree, source, grammar);
|
|
63
|
+
return { path, ...new Structure(grammar, source, facts.codeLines).measure(root), ...facts };
|
|
64
|
+
}
|
|
65
|
+
function firstHeader(root, grammar) {
|
|
66
|
+
let node = root.firstNamedChild;
|
|
67
|
+
while (node && grammar.comments.has(node.type))
|
|
68
|
+
node = node.nextNamedSibling;
|
|
69
|
+
return node;
|
|
70
|
+
}
|
|
71
|
+
function parserFor(grammar) {
|
|
72
|
+
const existing = parsers.get(grammar);
|
|
73
|
+
if (existing)
|
|
74
|
+
return existing;
|
|
75
|
+
const parser = makeParser(grammar);
|
|
76
|
+
parsers.set(grammar, parser);
|
|
77
|
+
void parser.catch(() => parsers.delete(grammar));
|
|
78
|
+
return parser;
|
|
79
|
+
}
|
|
80
|
+
async function makeParser({ asset }) {
|
|
81
|
+
const { Language, Parser } = await import('web-tree-sitter');
|
|
82
|
+
await (initialized ??= Parser.init());
|
|
83
|
+
const language = await Language.load(await readFile(asset));
|
|
84
|
+
const parser = new Parser();
|
|
85
|
+
parser.setLanguage(language);
|
|
86
|
+
return parser;
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=tree-sitter.js.map
|
package/README.md
DELETED