0
0

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 3 years have passed since last update.

pycparserでCプログラムのASTを出力してみた

Last updated at Posted at 2020-01-09

研究でCプログラムのASTを取得する必要ができたので、勉強した内容のメモ代わりとして残す。

pycparserをpipでインストール

実際にサンプルプログラムを動かしてみた。

sample.py
from __future__ import print_function
import sys
import json
from pycparser import c_parser, c_ast

text=r'''
int mian(void){
int i,j;
printf("test");
return 0;
}
'''

sys.path.extend(['.', '..'])
parser = c_parser.CParser()
ast = parser.parse(text, filename='<none>')
ast.show(attrnames=True,nodenames=True)
実行結果
FileAST:
  FuncDef <ext[0]>:
    Decl <decl>: name=mian, quals=[], storage=[], funcspec=[]
      FuncDecl <type>:
        ParamList <args>:
          Typename <params[0]>: name=None, quals=[]
            TypeDecl <type>: declname=None, quals=[]
              IdentifierType <type>: names=['void']
        TypeDecl <type>: declname=mian, quals=[]
          IdentifierType <type>: names=['int']
    Compound <body>:
      Decl <block_items[0]>: name=i, quals=[], storage=[], funcspec=[]
        TypeDecl <type>: declname=i, quals=[]
          IdentifierType <type>: names=['int']
      Decl <block_items[1]>: name=j, quals=[], storage=[], funcspec=[]
        TypeDecl <type>: declname=j, quals=[]
          IdentifierType <type>: names=['int']
      FuncCall <block_items[2]>:
        ID <name>: name=printf
        ExprList <args>:
          Constant <exprs[0]>: type=string, value="test"
      Return <block_items[3]>:
        Constant <expr>: type=int, value=0

無事にCのプログラムからASTが出力されました(どうやって保存するんだろう…)。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?