7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語ソースをpycparserで整形する

Last updated at Posted at 2016-04-27

汚いC言語ソースを綺麗にする.

汚いコード

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

pycparserを使う

C言語パーサの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()) # 読み込む
	
	parser = c_parser.CParser() # パーサ
	ast = parser.parse(text, filename='<none>') # パースする

	generator = c_generator.CGenerator() # 生成器
	print(generator.visit(ast)) # 単にパースしたものを書き出すだけ

if __name__ =='__main__':
    main()

参考

整形

pycparserは#includeやコメントには対応していないので,

  • grepで#includeを取り除く
  • gcc -Eでコメントを取り除く
    それから整形
実行
$ 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;
}


$ 

用途

  • 初心者の学生が書いたC言語のソースをきれいにする
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?