I have a simple C program in test.c
, and I want to get the members of sample_enum
and sample_struct
using python with the help of pycparser.
#include <stdio.h>
typedef enum sample_enum
{
board1 = 0,
board2 = 1,
board3 = 2,
board4 = 3,
board5 = 4,
board6 = 5,
} sample_enum_t;
typedef struct sample_struct {
uint32_t pd_type1;
uint32_t pd_type2;
uint32_t pd_type3;
} sample_struct_t;
int main() {
return 0;
}
I get the preprocessing output and save it into test.txt
.
gcc -E -I/path/to/pycparser/utils/fake_libc_include test.c > test.txt
Here is my python program:
from pycparser import parse_file, c_parser, c_ast
if __name__ == "__main__":
ast = parse_file(filename='test.txt')
ast.show(showcoord=True)
The ast.show prints a bunch of output, including these:
Typedef: sample_enum_t, [], ['typedef'] (at test.c:11:3)
TypeDecl: sample_enum_t, [] (at test.c:11:3)
Enum: sample_enum (at test.c:3:9)
EnumeratorList: (at test.c:5:5)
Enumerator: board1 (at test.c:5:5)
Constant: int, 0 (at test.c:5:14)
Enumerator: board2 (at test.c:6:5)
Constant: int, 1 (at test.c:6:14)
Enumerator: board3 (at test.c:7:5)
Constant: int, 2 (at test.c:7:14)
Enumerator: board4 (at test.c:8:5)
Constant: int, 3 (at test.c:8:14)
Enumerator: board5 (at test.c:9:5)
Constant: int, 4 (at test.c:9:14)
Enumerator: board6 (at test.c:10:5)
Constant: int, 5 (at test.c:10:14)
Typedef: sample_struct_t, [], ['typedef'] (at test.c:17:3)
TypeDecl: sample_struct_t, [] (at test.c:17:3)
Struct: sample_struct (at test.c:13:16)
Decl: pd_type1, [], [], [] (at test.c:14:14)
TypeDecl: pd_type1, [] (at test.c:14:14)
IdentifierType: ['uint32_t'] (at test.c:14:5)
Decl: pd_type2, [], [], [] (at test.c:15:14)
TypeDecl: pd_type2, [] (at test.c:15:14)
IdentifierType: ['uint32_t'] (at test.c:15:5)
Decl: pd_type3, [], [], [] (at test.c:16:14)
TypeDecl: pd_type3, [] (at test.c:16:14)
IdentifierType: ['uint32_t'] (at test.c:16:5)
FuncDef: (at test.c:20:5)
Decl: main, [], [], [] (at test.c:20:5)
FuncDecl: (at test.c:20:5)
TypeDecl: main, [] (at test.c:20:5)
IdentifierType: ['int'] (at test.c:20:1)
Compound: (at test.c:20:1)
Return: (at test.c:22:5)
Constant: int, 0 (at test.c:22:12)
So my question is, do I need to parse the output and extract the members of enum and struct individually? or there is a built-in method/mechanism inside pycparser
that could potentially makes my life easier.