main.c
#include <stdio.h>
int main
()
{ int // how to
a=0; // comment ?
if(a)printf("hello world\n"
) ;else{ printf /* is this ?*/
("good by\n"); } return
0;}
Use the C language parser pycparser.
c2c.py
#!/usr/bin/env python
import sys
from pycparser import parse_file, c_parser, c_generator, c_ast
def main():
text = ''.join(sys.stdin.readlines()) #Read
parser = c_parser.CParser() #Parser
ast = parser.parse(text, filename='<none>') #To parse
generator = c_generator.CGenerator() #Generator
print(generator.visit(ast)) #Just export what you parsed
if __name__ =='__main__':
main()
reference
Since pycparser does not support #include and comments,
--Remove #include with grep
--Remove comments with gcc -E
Then plastic surgery
Run
$ cat main.c | grep -v "#include" | gcc -E - | python c2c.py
int main()
{
int a = 0;
if (a)
printf("hello world\n");
else
{
printf("good by\n");
}
return 0;
}
$
--Clean the C source written by beginner students
Recommended Posts