tokless 0.4.1 → 0.5.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.
@@ -0,0 +1,64 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+
5
+ const LANG_DIR_TO_EXTS = Object.freeze({
6
+ javascript: ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'],
7
+ sfc: ['.vue', '.svelte'],
8
+ java: ['.java'],
9
+ 'c-family': ['.c', '.h', '.cpp', '.hpp', '.cc', '.cs'],
10
+ kotlin: ['.kt', '.kts'],
11
+ go: ['.go'],
12
+ rust: ['.rs'],
13
+ python: ['.py'],
14
+ markdown: ['.md', '.mdx'],
15
+ });
16
+
17
+ const EXT_TO_LANG_DIR = new Map();
18
+ for (const [langDir, exts] of Object.entries(LANG_DIR_TO_EXTS)) {
19
+ for (const ext of exts) {
20
+ EXT_TO_LANG_DIR.set(ext, langDir);
21
+ }
22
+ }
23
+
24
+ const SUPPORTED_EXTS = new Set(EXT_TO_LANG_DIR.keys());
25
+
26
+ const loadedHandlers = new Map();
27
+
28
+ function normalizeExt(extOrPath) {
29
+ if (!extOrPath) return '';
30
+ const str = String(extOrPath).toLowerCase();
31
+ if (str.startsWith('.')) return str;
32
+ return path.extname(str).toLowerCase() || `.${str}`;
33
+ }
34
+
35
+ function getLanguageDir(extOrPath) {
36
+ const ext = normalizeExt(extOrPath);
37
+ return EXT_TO_LANG_DIR.get(ext) || null;
38
+ }
39
+
40
+ function getLanguageHandler(extOrPath) {
41
+ const langDir = getLanguageDir(extOrPath);
42
+ if (!langDir) return null;
43
+ if (loadedHandlers.has(langDir)) {
44
+ return loadedHandlers.get(langDir);
45
+ }
46
+ // 陷阱: 仅在真实扫描到对应后缀时按需惰性 require 语言模块,保持 CLI 冷启动与 SUPPORTED_EXTS 零额外加载开销
47
+ const handler = require(path.join(__dirname, '..', 'langs', langDir));
48
+ loadedHandlers.set(langDir, handler);
49
+ return handler;
50
+ }
51
+
52
+ function clearLanguageCache() {
53
+ loadedHandlers.clear();
54
+ }
55
+
56
+ module.exports = {
57
+ LANG_DIR_TO_EXTS,
58
+ EXT_TO_LANG_DIR,
59
+ SUPPORTED_EXTS,
60
+ normalizeExt,
61
+ getLanguageDir,
62
+ getLanguageHandler,
63
+ clearLanguageCache,
64
+ };
@@ -0,0 +1,177 @@
1
+ 'use strict';
2
+
3
+ const {
4
+ preprocessBraceLines,
5
+ hasTopLevelChar,
6
+ } = require('../../core/lexer');
7
+ const {
8
+ DEFAULT_CONTROL_KEYWORDS,
9
+ stripLeadingAttributesAndAnnotations,
10
+ scanBraceLanguage,
11
+ } = require('../../core/block-anchor');
12
+
13
+ const ID = 'c-family';
14
+ const EXTENSIONS = ['.c', '.h', '.cpp', '.hpp', '.cc', '.cs'];
15
+ const HEADER_EXTS = new Set(['.h', '.hpp']);
16
+ const CPP_CONTAINERS = new Set(['class', 'struct', 'union', 'enum', 'namespace']);
17
+ const CS_CONTAINERS = new Set(['class', 'struct', 'interface', 'enum', 'record', 'namespace']);
18
+
19
+ function parse(lines, ext = '.c', options = {}) {
20
+ if (ext && typeof ext === 'object') {
21
+ options = ext;
22
+ ext = '.c';
23
+ }
24
+ const normalizedExt = String(ext || '.c').toLowerCase();
25
+ const isCs = normalizedExt === '.cs';
26
+ const isHeader = HEADER_EXTS.has(normalizedExt);
27
+ const lineOffset = options.lineOffset || 0;
28
+
29
+ const analyzed = preprocessBraceLines(lines, 'c');
30
+
31
+ return scanBraceLanguage(analyzed, {
32
+ lexer: 'c',
33
+ containers: isCs ? CS_CONTAINERS : CPP_CONTAINERS,
34
+ lineOffset,
35
+ onStatementLine({
36
+ analyzed: rows,
37
+ lineIdx,
38
+ scopeStack,
39
+ items,
40
+ lineOffset: offset,
41
+ findDeclarationRange,
42
+ buildCompactSignature,
43
+ }) {
44
+ const trimmed = rows[lineIdx].clean.trim();
45
+ if (!trimmed || trimmed.startsWith('#')) return null;
46
+
47
+ const core = stripLeadingAttributesAndAnnotations(trimmed);
48
+ if (!core) return null;
49
+
50
+ const activeScope = scopeStack.length > 0 ? scopeStack[scopeStack.length - 1] : null;
51
+ const inTypeScope =
52
+ activeScope !== null && activeScope.kind !== 'namespace' && activeScope.kind !== 'enum';
53
+
54
+ if (isCs && inTypeScope) {
55
+ const propMatch = core.match(
56
+ /^(?:(?:public|private|protected|internal|static|virtual|override|abstract|sealed|readonly|new|required|unsafe)\s+)+[\w.<>,?\[\]\s]+\s+([A-Za-z_]\w*)\s*(?:\{|=>)/
57
+ );
58
+ if (propMatch && !DEFAULT_CONTROL_KEYWORDS.has(propMatch[1])) {
59
+ const beforeBraceOrArrow = core.split(/\{|=>/)[0];
60
+ if (!beforeBraceOrArrow.includes('(') && !hasTopLevelChar(beforeBraceOrArrow, '=')) {
61
+ const range = findDeclarationRange(rows, lineIdx, 'c');
62
+ const signature = buildCompactSignature(
63
+ rows,
64
+ lineIdx,
65
+ range.headerEndIdx,
66
+ range.hasBlock
67
+ );
68
+ items.push({
69
+ kind: 'property',
70
+ name: propMatch[1],
71
+ signature,
72
+ startLine: lineIdx + 1 + offset,
73
+ endLine: range.endIdx + 1 + offset,
74
+ depth: scopeStack.length,
75
+ });
76
+ return { jumpToLine: range.endIdx };
77
+ }
78
+ }
79
+ }
80
+
81
+ if (!isCs && /\boperator\s*(?:<<|>>|\+|-|\*|\/|%|\^|&|\|)=/.test(core)) {
82
+ const range = findDeclarationRange(rows, lineIdx, 'c');
83
+ if (range.hasBlock || isHeader) {
84
+ const opMatch = core.match(/\b(operator\s*(?:<<|>>|\+|-|\*|\/|%|\^|&|\|)=)/);
85
+ if (opMatch) {
86
+ const signature = buildCompactSignature(
87
+ rows,
88
+ lineIdx,
89
+ range.headerEndIdx,
90
+ range.hasBlock
91
+ );
92
+ items.push({
93
+ kind: inTypeScope ? 'method' : 'function',
94
+ name: opMatch[1].replace(/\s+/g, ''),
95
+ signature,
96
+ startLine: lineIdx + 1 + offset,
97
+ endLine: range.endIdx + 1 + offset,
98
+ depth: scopeStack.length,
99
+ });
100
+ return { jumpToLine: range.endIdx };
101
+ }
102
+ }
103
+ }
104
+
105
+ if (isHeader || (isCs && activeScope && activeScope.kind === 'interface')) {
106
+ const range = findDeclarationRange(rows, lineIdx, 'c');
107
+ if (range.hasBlock) return null;
108
+
109
+ const joined = stripLeadingAttributesAndAnnotations(
110
+ rows
111
+ .slice(lineIdx, range.endIdx + 1)
112
+ .map((r) => r.clean)
113
+ .join(' ')
114
+ ).trim();
115
+ if (!joined.endsWith(';')) return null;
116
+ if (/^(?:typedef|using|friend|extern\s+"C"|template\b[^;]*;$)/.test(joined)) return null;
117
+
118
+ const cleanedProto = joined.replace(/^(?:public|private|protected)\s*:\s*/, '').trim();
119
+ const parenIdx = cleanedProto.indexOf('(');
120
+ if (parenIdx <= 0) return null;
121
+ const beforeParen = cleanedProto.slice(0, parenIdx).trim();
122
+ if (hasTopLevelChar(beforeParen, '=')) return null;
123
+
124
+ const firstWordMatch = beforeParen.match(/^([A-Za-z_]\w*)\b/);
125
+ if (firstWordMatch && DEFAULT_CONTROL_KEYWORDS.has(firstWordMatch[1])) return null;
126
+
127
+ let name = '';
128
+ const opProto = beforeParen.match(/\b(operator\s*(?:\(\)|\[\]|[^\s(]+))\s*$/);
129
+ if (opProto) {
130
+ name = opProto[1].replace(/\s+/g, '');
131
+ } else {
132
+ const nm = beforeParen.match(/([~A-Za-z_]\w*)$/);
133
+ if (!nm || DEFAULT_CONTROL_KEYWORDS.has(nm[1])) return null;
134
+ name = nm[1];
135
+ const prefix = beforeParen.slice(0, beforeParen.length - name.length).trim();
136
+ const isCtorOrDtor =
137
+ inTypeScope &&
138
+ activeScope &&
139
+ (name === activeScope.name || name === `~${activeScope.name}`);
140
+ // 陷阱: 头文件宏调用(如 `DECLARE_API(foo);`)无返回类型前缀,必须要求显式返回类型或类构造/析构名才认作函数原型
141
+ if (!prefix && !isCtorOrDtor) return null;
142
+ }
143
+
144
+ const afterCloseIdx = cleanedProto.lastIndexOf(')');
145
+ if (afterCloseIdx === -1) return null;
146
+ const tail = cleanedProto.slice(afterCloseIdx + 1, -1).trim();
147
+ if (
148
+ tail &&
149
+ !/^(?:(?:const|volatile|noexcept(?:\([^)]*\))?|override|final)\s*)*(?:=\s*(?:0|default|delete))?$/.test(
150
+ tail
151
+ )
152
+ ) {
153
+ return null;
154
+ }
155
+
156
+ const signature = buildCompactSignature(rows, lineIdx, range.headerEndIdx, false);
157
+ items.push({
158
+ kind: inTypeScope ? 'method' : 'function',
159
+ name,
160
+ signature,
161
+ startLine: lineIdx + 1 + offset,
162
+ endLine: range.endIdx + 1 + offset,
163
+ depth: scopeStack.length,
164
+ });
165
+ return { jumpToLine: range.endIdx };
166
+ }
167
+
168
+ return null;
169
+ },
170
+ });
171
+ }
172
+
173
+ module.exports = {
174
+ id: ID,
175
+ extensions: EXTENSIONS,
176
+ parse,
177
+ };
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+
3
+ const {
4
+ preprocessBraceLines,
5
+ findMatchingForward,
6
+ } = require('../../core/lexer');
7
+ const {
8
+ findDeclarationRange,
9
+ buildCompactSignature,
10
+ } = require('../../core/block-anchor');
11
+
12
+ const ID = 'go';
13
+ const EXTENSIONS = ['.go'];
14
+
15
+ function extractGoFuncName(analyzed, lineIdx) {
16
+ const clean = analyzed[lineIdx].clean;
17
+ const m = clean.match(/^\s*func\b\s*/);
18
+ if (!m) return null;
19
+ let col = m[0].length;
20
+ if (col < clean.length && clean[col] === '(') {
21
+ const closeRecv = findMatchingForward(analyzed, lineIdx, col, '(', ')');
22
+ if (!closeRecv) return null;
23
+ const afterRecv = analyzed[closeRecv.line].clean.slice(closeRecv.col + 1).trimStart();
24
+ const nm = afterRecv.match(/^([A-Za-z_]\w*)\b/);
25
+ return nm ? nm[1] : null;
26
+ }
27
+ const nm = clean.slice(col).match(/^([A-Za-z_]\w*)\b/);
28
+ return nm ? nm[1] : null;
29
+ }
30
+
31
+ function parse(lines, ext = '.go', options = {}) {
32
+ if (ext && typeof ext === 'object') {
33
+ options = ext;
34
+ ext = '.go';
35
+ }
36
+ const lineOffset = options.lineOffset || 0;
37
+ const analyzed = preprocessBraceLines(lines, 'go');
38
+ const items = [];
39
+ let inTypeGroup = false;
40
+
41
+ for (let i = 0; i < analyzed.length; i++) {
42
+ const info = analyzed[i];
43
+ if (info.braceStart !== 0) continue;
44
+ const trimmed = info.clean.trim();
45
+ if (!trimmed) continue;
46
+
47
+ if (!inTypeGroup && /^type\s*\(\s*$/.test(trimmed)) {
48
+ inTypeGroup = true;
49
+ continue;
50
+ }
51
+ if (inTypeGroup && /^\)\s*$/.test(trimmed)) {
52
+ inTypeGroup = false;
53
+ continue;
54
+ }
55
+
56
+ let kind = null;
57
+ let name = '';
58
+ let m;
59
+
60
+ if (!inTypeGroup && /^func\b/.test(trimmed)) {
61
+ const fnName = extractGoFuncName(analyzed, i);
62
+ if (fnName) {
63
+ kind = 'func';
64
+ name = fnName;
65
+ }
66
+ } else if (
67
+ (m = trimmed.match(/^(?:type\s+)?([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s+struct\b/)) &&
68
+ (inTypeGroup || trimmed.startsWith('type '))
69
+ ) {
70
+ kind = 'struct';
71
+ name = m[1];
72
+ } else if (
73
+ (m = trimmed.match(/^(?:type\s+)?([A-Za-z_]\w*)\s*(?:\[[^\]]*\])?\s+interface\b/)) &&
74
+ (inTypeGroup || trimmed.startsWith('type '))
75
+ ) {
76
+ kind = 'interface';
77
+ name = m[1];
78
+ } else if (!inTypeGroup && (m = trimmed.match(/^type\s+([A-Za-z_]\w*)\b/))) {
79
+ kind = 'type';
80
+ name = m[1];
81
+ } else if (inTypeGroup && (m = trimmed.match(/^([A-Za-z_]\w*)\b/))) {
82
+ kind = 'type';
83
+ name = m[1];
84
+ }
85
+
86
+ if (kind) {
87
+ const range = findDeclarationRange(analyzed, i, 'go');
88
+ const signature = buildCompactSignature(analyzed, i, range.headerEndIdx, range.hasBlock);
89
+ items.push({
90
+ kind,
91
+ name,
92
+ signature,
93
+ startLine: i + 1 + lineOffset,
94
+ endLine: range.endIdx + 1 + lineOffset,
95
+ depth: 0,
96
+ });
97
+ i = range.endIdx;
98
+ }
99
+ }
100
+
101
+ return items;
102
+ }
103
+
104
+ module.exports = {
105
+ id: ID,
106
+ extensions: EXTENSIONS,
107
+ parse,
108
+ };
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+
3
+ const {
4
+ preprocessBraceLines,
5
+ findMatchingForward,
6
+ skipWhitespaceForward,
7
+ stripLeadingAnnotationsOnText,
8
+ hasTopLevelChar,
9
+ } = require('../../core/lexer');
10
+ const { scanBraceLanguage } = require('../../core/block-anchor');
11
+
12
+ const ID = 'java';
13
+ const EXTENSIONS = ['.java'];
14
+ const JAVA_CONTAINERS = new Set(['class', 'interface', '@interface', 'enum', 'record']);
15
+
16
+ function neutralizeAnnotationBraces(lines) {
17
+ const analyzed = preprocessBraceLines(lines, 'java');
18
+ let mutated = false;
19
+
20
+ for (let line = 0; line < analyzed.length; line++) {
21
+ const clean = analyzed[line].clean;
22
+ for (let col = 0; col < clean.length; col++) {
23
+ if (clean[col] !== '@') continue;
24
+ if (/^@interface\b/.test(clean.slice(col))) continue;
25
+ const nameMatch = clean.slice(col + 1).match(/^\s*([A-Za-z_$][\w$.]*)/);
26
+ if (!nameMatch) continue;
27
+ const afterNameCol = col + 1 + nameMatch[0].length;
28
+ const next = skipWhitespaceForward(
29
+ analyzed,
30
+ line,
31
+ afterNameCol,
32
+ Math.min(analyzed.length - 1, line + 1)
33
+ );
34
+ if (!next || next.ch !== '(') continue;
35
+ const closePos = findMatchingForward(analyzed, next.line, next.col, '(', ')');
36
+ if (!closePos) continue;
37
+
38
+ // 陷阱: 注解实参内的数组或 Lambda 花括号(如 `@RequestMapping(value = {"/a", "/b"})`)会扰乱类体 braceStart 深度,需先抹平为空格
39
+ for (let rLine = next.line; rLine <= closePos.line; rLine++) {
40
+ const cStr = analyzed[rLine].clean;
41
+ const cStart = rLine === next.line ? next.col + 1 : 0;
42
+ const cEnd = rLine === closePos.line ? closePos.col - 1 : cStr.length - 1;
43
+ if (cStart > cEnd) continue;
44
+ let chars = null;
45
+ for (let k = cStart; k <= cEnd; k++) {
46
+ if (cStr[k] === '{' || cStr[k] === '}' || cStr[k] === ';') {
47
+ if (!chars) chars = cStr.split('');
48
+ chars[k] = ' ';
49
+ mutated = true;
50
+ }
51
+ }
52
+ if (chars) {
53
+ analyzed[rLine].clean = chars.join('');
54
+ }
55
+ }
56
+
57
+ line = closePos.line;
58
+ col = closePos.col;
59
+ }
60
+ }
61
+
62
+ if (mutated) {
63
+ let brace = 0;
64
+ for (let i = 0; i < analyzed.length; i++) {
65
+ analyzed[i].braceStart = brace;
66
+ const c = analyzed[i].clean;
67
+ for (let k = 0; k < c.length; k++) {
68
+ if (c[k] === '{') brace++;
69
+ else if (c[k] === '}') brace = Math.max(0, brace - 1);
70
+ }
71
+ analyzed[i].braceEnd = brace;
72
+ }
73
+ }
74
+
75
+ return analyzed;
76
+ }
77
+
78
+ function parse(lines, ext = '.java', options = {}) {
79
+ if (ext && typeof ext === 'object') {
80
+ options = ext;
81
+ ext = '.java';
82
+ }
83
+ const lineOffset = options.lineOffset || 0;
84
+ const analyzed = neutralizeAnnotationBraces(lines);
85
+
86
+ return scanBraceLanguage(analyzed, {
87
+ lexer: 'java',
88
+ containers: JAVA_CONTAINERS,
89
+ javaStyleEnum: true,
90
+ javaCompactRecordConstructor: true,
91
+ lineOffset,
92
+ onStatementLine({
93
+ analyzed: rows,
94
+ lineIdx,
95
+ scopeStack,
96
+ items,
97
+ lineOffset: offset,
98
+ findDeclarationRange,
99
+ buildCompactSignature,
100
+ }) {
101
+ const activeScope = scopeStack.length > 0 ? scopeStack[scopeStack.length - 1] : null;
102
+ if (!activeScope || (activeScope.kind !== 'interface' && activeScope.kind !== '@interface')) {
103
+ return null;
104
+ }
105
+ const trimmed = rows[lineIdx].clean.trim();
106
+ if (!trimmed || trimmed.startsWith('@')) {
107
+ const stripped = stripLeadingAnnotationsOnText(trimmed).rest;
108
+ if (!stripped) return null;
109
+ }
110
+ const range = findDeclarationRange(rows, lineIdx, 'java');
111
+ if (range.hasBlock) return null;
112
+
113
+ const joinedClean = rows
114
+ .slice(lineIdx, range.endIdx + 1)
115
+ .map((r) => r.clean)
116
+ .join(' ')
117
+ .trim();
118
+ if (!joinedClean.endsWith(';')) return null;
119
+
120
+ const withoutAnnos = stripLeadingAnnotationsOnText(joinedClean).rest;
121
+ const openParen = withoutAnnos.indexOf('(');
122
+ if (openParen <= 0) return null;
123
+ const beforeParen = withoutAnnos.slice(0, openParen).trim();
124
+ if (hasTopLevelChar(beforeParen, '=')) return null;
125
+
126
+ const nameMatch = beforeParen.match(/([A-Za-z_$][\w$]*)$/);
127
+ if (!nameMatch) return null;
128
+ const prefix = beforeParen.slice(0, beforeParen.length - nameMatch[1].length).trim();
129
+ if (!prefix) return null;
130
+
131
+ const signature = buildCompactSignature(rows, lineIdx, range.headerEndIdx, false);
132
+ items.push({
133
+ kind: 'method',
134
+ name: nameMatch[1],
135
+ signature,
136
+ startLine: lineIdx + 1 + offset,
137
+ endLine: range.endIdx + 1 + offset,
138
+ depth: scopeStack.length,
139
+ });
140
+ return { jumpToLine: range.endIdx };
141
+ },
142
+ });
143
+ }
144
+
145
+ module.exports = {
146
+ id: ID,
147
+ extensions: EXTENSIONS,
148
+ parse,
149
+ };