gpt4 book ai didi

python - 无法修改 pycparser AST |将 AST 转换为 C 代码

转载 作者:行者123 更新时间:2023-11-28 18:52:09 34 4
gpt4 key购买 nike

我正在尝试修改/重构输入的 C 源代码。我试图在输入代码的每一行之后添加一个 printf 语句。

例如如果我的输入是 -

void foo(){
// Sample input code
int a = 0, b = 0;
a++;
if(a<5)
b++;
b--;
}

我想添加语句 printf('Hi');,导致 -

void foo(){
int a = 0, b = 0;
printf('Hi');
a++;
printf('Hi');
if(a<5){
b++;
printf('Hi');
}
printf('Hi');
b--;
printf('Hi');
}

作为第一步,我只是尝试声明一个变量 test 并尝试将其插入到由随机源代码生成的 AST 的开头。这是我参与的 python 代码,在将 AST 提取到对象 ast -

之后
for i in range(0,len(ast.ext)):
## Look for a function named 'foo'
if(type(ast.ext[i]) == c_ast.FuncDef and ast.ext[i].decl.name == 'foo'):
## Store the list of AST node objects in functionBody
functionBody = ast.ext[i].body

## Create a Decl object for the variable test
id_obj = c_ast.ID('test')
identifier_obj = c_ast.IdentifierType(['int'])
typedecl_obj = c_ast.TypeDecl(id_obj.name,[],identifier_obj)
decl_obj = c_ast.Decl(id_obj.name,[],[],[],typedecl_obj,[],[])

## Append the object to a list.
## Concatenate to a copy of existing list of AST objects
lst1 = []
lst1.append(decl_obj)
lst2 = []
lst2 = copy.deepcopy(functionBody.block_items)
lst3 = []
lst3 = lst1+lst2

## Create a modified AST and print content
functionBody1 = c_ast.Compound(lst3)
functionBody1.show()

我发现生成的结构 functionBody1 没有变化,并且每当我尝试使用它的 show( ) 方法时也会收到以下错误。

'list' object has no attribute 'show'

知道我要偏离轨道的地方吗?

谢谢

最佳答案

我发现三个地方你传递了一个你应该传递 None 的列表。

## Create a Decl object for the variable test
id_obj = c_ast.ID('test')
identifier_obj = c_ast.IdentifierType(['int'])
typedecl_obj = c_ast.TypeDecl(id_obj.name,None,identifier_obj)
decl_obj = c_ast.Decl(id_obj.name,[],[],[],typedecl_obj,None,None)

我不太熟悉这个,因为我也在学习 pycparser,但是这个更改为我修复了你的回溯。

关于python - 无法修改 pycparser AST |将 AST 转换为 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10936782/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com