import random
import os
from tree_sitter import Language, Parser

# 加载 C 语言解析器
C_LANGUAGE = Language('build/my-languages.so', 'c')
parser = Parser()
parser.set_language(C_LANGUAGE)

# 读取存储路径的 .txt 文件
path_file = "./data/testThree-paths.txt"  # 存储 C 代码文件路径的文件

with open(path_file, "r", encoding="utf-8") as f:
    c_files = [line.strip() for line in f.readlines() if line.strip()]

# 解析函数体 { ... }
def find_function_body(node):
    if node.type == "function_definition":
        for child in node.children:
            if child.type == "compound_statement":
                return child
    for child in node.children:
        result = find_function_body(child)
        if result:
            return result
    return None

for c_file in c_files:
    if not os.path.exists(c_file):
        print(f"文件不存在: {c_file}")
        continue

    # 读取 C 代码
    with open(c_file, "r", encoding="utf-8") as f:
        code = f.read()

    code_bytes = bytes(code, "utf-8")
    tree = parser.parse(code_bytes)
    root_node = tree.root_node

    function_body = find_function_body(root_node)

    if function_body:
        # 生成未使用变量
        unused_var = '\n    char unusedstr[] = "This is an unused string";'

        # 在 `{` 之后插入变量
        insert_pos = function_body.start_byte + 1  # `{` 之后插入
        new_code = code_bytes[:insert_pos].decode() + unused_var + code_bytes[insert_pos:].decode()

        # 保存修改后的 C 代码
        with open(c_file, "w", encoding="utf-8") as f:
            f.write(new_code)

        print(f"修改完成: {c_file}")
    else:
        print(f"未找到函数体: {c_file}")

