Format C source with pycparser

Clean up dirty C source.

Dirty code

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 pycparser

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

Plastic surgery

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;
}


$ 

Use

--Clean the C source written by beginner students

Recommended Posts

Format C source with pycparser
Container-like # 1 made with C
Debugging C / C ++ with gdb
SQL format with sqlparse
Using X11 with ubuntu18.04 (C)
ABC163 C problem with python3
Try Google Mock with C
Format json with Vim (with python)
ABC188 C problem with python3
String format with Python% operator
ABC187 C problem with python
Solve ABC163 A ~ C with Python
Call C from Python with DragonFFI
Install Python from source with Ansible
Writing C language with Sympy (metaprogramming)
Vector format operation & conversion with arcpy
Solve ABC168 A ~ C with Python
Increase source visibility with type hints
Solved AtCoder ABC 114 C-755 with Python3
Solve ABC162 A ~ C with Python
Solve ABC167 A ~ C with Python
Solve ABC158 A ~ C with Python
Segfault with 16 characters in C language
Merge JSON format data with Ansible
Speed up C / C ++ compilation with ccache
[Python] Format when to_csv with pandas