我将尝试修改/重构输入的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开头。
在提取了AST对象ast
后,我参与了以下Python代码-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'
你有没有想法,我在哪里偏离了轨道?
谢谢