File size: 7,091 Bytes
15d17be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244



import traceback
import os
import json
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from tree_sitter import Language, Parser
import tree_sitter_c
import tree_sitter_cpp
import tree_sitter_java
import tree_sitter_go
import tree_sitter_rust
import tree_sitter_julia
import tree_sitter_python

########################################
# 配置区
########################################

LANG_SO = "build/my-languages.so"
OUTPUT_DIR = "/home/weifengsun/tangou1/step2/step22/dataset"

EXCLUDE_DIRS = {
    ".git", "node_modules", "vendor", "third_party",
    "build", "dist", "target", "__pycache__"
}

LANGUAGE_CONFIG = {
    "python": {
        "ext": [".py"],
        "function_nodes": ["function_definition"],
        "class_nodes": ["class_definition"],
        "name_field": "name",
    },
    "c": {
        "ext": [".c", ".h"],
        "function_nodes": ["function_definition"],
        "name_field": "declarator",
    },
    "cpp": {
        "ext": [".cpp", ".cc", ".cxx", ".hpp", ".hh"],
        "function_nodes": ["function_definition"],
        "name_field": "declarator",
    },
    "java": {
        "ext": [".java"],
        "function_nodes": ["method_declaration", "constructor_declaration"],
        "class_nodes": ["class_declaration"],
        "name_field": "name",
    },
    "go": {
        "ext": [".go"],
        "function_nodes": ["function_declaration", "method_declaration"],
        "name_field": "name",
        "receiver_field": "receiver",
    },
    "rust": {
        "ext": [".rs"],
        "function_nodes": ["function_item"],
        "class_nodes": ["impl_item", "trait_item"],
        "name_field": "name",
    },
    "julia": {
        "ext": [".jl"],
        "function_nodes": ["function_definition"],
        "name_field": "name",
    },
}

EXT_TO_LANG = {}
for lang, cfg in LANGUAGE_CONFIG.items():
    for e in cfg["ext"]:
        EXT_TO_LANG[e] = lang

########################################
# worker 初始化
########################################

LANGUAGES = {
    "python": Language(tree_sitter_python.language()),
    "go": Language(tree_sitter_go.language()),
    "rust": Language(tree_sitter_rust.language()),
    "julia": Language(tree_sitter_julia.language()),
    "c": Language(tree_sitter_c.language()),
    "cpp": Language(tree_sitter_cpp.language()),
    "java": Language(tree_sitter_java.language()),
}

def init_worker():
    global PARSERS
    PARSERS = {}

    for lang in LANGUAGE_CONFIG:
        try:
            # LANGUAGE=Language(LANG_SO, lang)
            parser = Parser(LANGUAGES[lang])
            PARSERS[lang] = parser
        except Exception:
            print(f"Failed to load parser for {lang}")
            print(traceback.format_exc())
            pass


########################################
# 函数提取逻辑
########################################

def extract_functions(tree, file_path, language):
    cfg = LANGUAGE_CONFIG[language]
    results = []

    def walk(node, scope):
        # class / impl 作用域
        if node.type in cfg.get("class_nodes", []):
            name_node = node.child_by_field_name("name") or \
                        node.child_by_field_name("type")
            if name_node:
                scope.append(name_node.text.decode())

        # Go receiver
        if language == "go" and node.type in cfg["function_nodes"]:
            recv = node.child_by_field_name("receiver")
            if recv:
                scope.append(recv.text.decode())

        # 函数定义
        if node.type in cfg["function_nodes"]:
            name_node = node.child_by_field_name(cfg["name_field"])
            if name_node:
                name = name_node.text.decode()
                qual = ".".join(scope + [name])
                results.append({
                    "language": language,
                    "name": name,
                    "qualified_name": qual,
                    "file": file_path,
                    "start_line": node.start_point[0] + 1,
                    "end_line": node.end_point[0] + 1,
                })

        # Julia 简写函数 foo(x)=...
        if language == "julia" and node.type == "assignment":
            left = node.child(0)
            if left and left.type == "call_expression":
                fn = left.child_by_field_name("function")
                if fn:
                    name = fn.text.decode()
                    results.append({
                        "language": language,
                        "name": name,
                        "qualified_name": name,
                        "file": file_path,
                        "start_line": node.start_point[0] + 1,
                        "end_line": node.end_point[0] + 1,
                    })

        for c in node.children:
            walk(c, scope)

        if node.type in cfg.get("class_nodes", []):
            scope.pop()

    walk(tree.root_node, [])
    return results


########################################
# 项目处理
########################################

def process_project(project_path):
    project_name = os.path.basename(project_path.rstrip("/"))
    output_path = os.path.join(OUTPUT_DIR, project_name, "functions.jsonl")

    with open(output_path, "w", encoding="utf-8") as out:
        for root, dirs, files in os.walk(project_path):
            dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS]

            for f in files:
                ext = os.path.splitext(f)[1]
                lang = EXT_TO_LANG.get(ext)
                if not lang:
                    continue

                path = os.path.join(root, f)
                try:
                    code = open(path, "rb").read()
                    tree = PARSERS[lang].parse(code)
                    funcs = extract_functions(tree, path, lang)

                    for fn in funcs:
                        out.write(json.dumps(fn, ensure_ascii=False) + "\n")

                except Exception:
                    continue


########################################
# 主入口
########################################

def load_projects(root):
    return [
        os.path.join(root, d)
        for d in os.listdir(root)
        if os.path.isdir(os.path.join(root, d))
    ]


def main():
    # if len(sys.argv) != 2:
    #     print("Usage: python extract_functions.py <projects_root>")
    #     sys.exit(1)

    # projects_root = sys.argv[1]
    projects_root = "/home/weifengsun/tangou1/domain_code/src/workdir/repos_filtered"
    os.makedirs(OUTPUT_DIR, exist_ok=True)

    projects = load_projects(projects_root)

    with ProcessPoolExecutor(
        max_workers=min(os.cpu_count(), 32),
        initializer=init_worker
    ) as pool:
        futures = {
            pool.submit(process_project, p): p
            for p in projects
        }

        for f in as_completed(futures):
            proj = futures[f]
            try:
                f.result()
                print(f"[OK] {proj}")

            except Exception as e:
                print(f"[FAIL] {proj}: {e}")


if __name__ == "__main__":
    main()