Repository navigation
Expand file tree
/
Copy pathjson_ast_parser.js
More file actions
100 lines (90 loc) · 3.99 KB
/
Copy pathjson_ast_parser.js
File metadata and controls
100 lines (90 loc) · 3.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const Parser = require('tree-sitter');
const JSON = require('tree-sitter-json');
const fs = require('fs');
class JsonAstParser {
constructor() {
this.parser = new Parser();
this.parser.setLanguage(JSON);
}
/**
* 解析文件并提取 string 类型的 Value 节点
* @param {string} filePath 文件路径
* @returns {Array} 提取的节点信息列表
*/
parseFile(filePath) {
try {
const sourceCode = fs.readFileSync(filePath, 'utf8');
if (typeof sourceCode !== 'string') {
throw new Error(`Read file result is not a string: ${typeof sourceCode}`);
}
// console.log(`[DEBUG] Parsing ${filePath}, size: ${sourceCode.length}`);
// 使用 input callback 方式解析
// tree-sitter 0.21.x 要求传入一个函数,该函数接收 offset 参数并返回字符串片段
const tree = this.parser.parse((offset) => {
const chunkSize = 1024;
if (offset >= sourceCode.length) {
return null;
}
return sourceCode.slice(offset, offset + chunkSize);
});
const results = [];
this._traverse(tree.rootNode, results, filePath);
return results;
} catch (e) {
console.error(`[AST Parser Error] Failed to parse ${filePath}:`, e);
return []; // 返回空数组避免 crash
}
}
/**
* 递归遍历 AST
* @param {SyntaxNode} node 当前节点
* @param {Array} results 结果收集数组
* @param {string} filePath 文件路径
*/
_traverse(node, results, filePath) {
// 我们只关心 pair 节点中的 value 部分
// 结构通常是: (pair key: (string) value: (string))
// 或者 value 可能是 object/array,需要递归
if (node.type === 'pair') {
const valueNode = node.childForFieldName('value');
if (valueNode) {
if (valueNode.type === 'string') {
// 提取 string 内容 (去除引号)
// valueNode.text 包含引号,如 "你好"
// 我们需要提取内容 你好,并记录位置
const rawText = valueNode.text;
const content = rawText.length >= 2 ? rawText.slice(1, -1) : rawText;
results.push({
filePath: filePath,
content: content,
originalText: rawText, // 用于后续可能的精确替换验证
start: {
row: valueNode.startPosition.row,
column: valueNode.startPosition.column
},
end: {
row: valueNode.endPosition.row,
column: valueNode.endPosition.column
}
});
} else {
// 如果 value 是 object 或 array,继续递归
// 注意:pair 的 value 节点本身可能是复合结构,需要遍历其子节点
// 但 _traverse 设计为遍历任意节点,所以直接对 valueNode 的子节点递归即可
// 或者是直接递归 valueNode 自身?
// 实际上,如果 valueNode 是 object,它会有 children (pair),所以继续遍历 children 即可
this._traverseChildren(valueNode, results, filePath);
}
}
} else {
// 对于非 pair 节点(如 root, object, array),继续遍历子节点
this._traverseChildren(node, results, filePath);
}
}
_traverseChildren(node, results, filePath) {
for (let i = 0; i < node.childCount; i++) {
this._traverse(node.child(i), results, filePath);
}
}
}
module.exports = JsonAstParser;