Debian Codegraph @

pycparser223/examples/explore_ast.py

raw symbols SCIP
1 #-----------------------------------------------------------------
2 # pycparser: explore_ast.py
3 #
4 # This example demonstrates how to "explore" the AST created by
5 # pycparser to understand its structure. The AST is a n-nary tree
6 # of nodes, each node having several children, each with a name.
7 # Just read the code, and let the comments guide you. The lines
8 # beginning with #~ can be uncommented to print out useful
9 # information from the AST.
10 # It helps to have the pycparser/_c_ast.cfg file in front of you.
11 #
12 # Eli Bendersky [https://eli.thegreenplace.net/]
13 # License: BSD
14 #-----------------------------------------------------------------
15 import sys
16
17 # This is not required if you've installed pycparser into
18 # your site-packages/ with setup.py
19 sys.path.extend(['.', '..'])
20
21 from pycparser import c_parser
22
23 # This is some C source to parse. Note that pycparser must begin
24 # at the top level of the C file, i.e. with either declarations
25 # or function definitions (this is called "external declarations"
26 # in C grammar lingo)
27 #
28 # Also, a C parser must have all the types declared in order to
29 # build the correct AST. It doesn't matter what they're declared
30 # to, so I've inserted the dummy typedef in the code to let the
31 # parser know Hash and Node are types. You don't need to do it
32 # when parsing real, correct C code.
33
34 text = r"""
35 typedef int Node, Hash;
36
37 void HashPrint(Hash* hash, void (*PrintFunc)(char*, char*))
38 {
39 unsigned int i;
40
41 if (hash == NULL || hash->heads == NULL)
42 return;
43
44 for (i = 0; i < hash->table_size; ++i)
45 {
46 Node* temp = hash->heads[i];
47
48 while (temp != NULL)
49 {
50 PrintFunc(temp->entry->key, temp->entry->value);
51 temp = temp->next;
52 }
53 }
54 }
55 """
56
57 # Create the parser and ask to parse the text. parse() will throw
58 # a ParseError if there's an error in the code
59 #
60 parser = c_parser.CParser()
61 ast = parser.parse(text, filename='<none>')
62
63 # Uncomment the following line to see the AST in a nice, human
64 # readable way. show() is the most useful tool in exploring ASTs
65 # created by pycparser. See the c_ast.py file for the options you
66 # can pass it.
67
68 #ast.show(showcoord=True)
69
70 # OK, we've seen that the top node is FileAST. This is always the
71 # top node of the AST. Its children are "external declarations",
72 # and are stored in a list called ext[] (see _c_ast.cfg for the
73 # names and types of Nodes and their children).
74 # As you see from the printout, our AST has two Typedef children
75 # and one FuncDef child.
76 # Let's explore FuncDef more closely. As I've mentioned, the list
77 # ext[] holds the children of FileAST. Since the function
78 # definition is the third child, it's ext[2]. Uncomment the
79 # following line to show it:
80
81 #ast.ext[2].show()
82
83 # A FuncDef consists of a declaration, a list of parameter
84 # declarations (for K&R style function definitions), and a body.
85 # First, let's examine the declaration.
86
87 function_decl = ast.ext[2].decl
88
89 # function_decl, like any other declaration, is a Decl. Its type child
90 # is a FuncDecl, which has a return type and arguments stored in a
91 # ParamList node
92
93 #function_decl.type.show()
94 #function_decl.type.args.show()
95
96 # The following displays the name and type of each argument:
97
98 #for param_decl in function_decl.type.args.params:
99 #print('Arg name: %s' % param_decl.name)
100 #print('Type:')
101 #param_decl.type.show(offset=6)
102
103 # The body is of FuncDef is a Compound, which is a placeholder for a block
104 # surrounded by {} (You should be reading _c_ast.cfg parallel to this
105 # explanation and seeing these things with your own eyes).
106 # Let's see the block's declarations:
107
108 function_body = ast.ext[2].body
109
110 # The following displays the declarations and statements in the function
111 # body
112
113 #for decl in function_body.block_items:
114 #decl.show()
115
116 # We can see a single variable declaration, i, declared to be a simple type
117 # declaration of type 'unsigned int', followed by statements.
118
119 # block_items is a list, so the third element is the For statement:
120
121 for_stmt = function_body.block_items[2]
122 #for_stmt.show()
123
124 # As you can see in _c_ast.cfg, For's children are 'init, cond,
125 # next' for the respective parts of the 'for' loop specifier,
126 # and stmt, which is either a single stmt or a Compound if there's
127 # a block.
128 #
129 # Let's dig deeper, to the while statement inside the for loop:
130
131 while_stmt = for_stmt.stmt.block_items[1]
132 #while_stmt.show()
133
134 # While is simpler, it only has a condition node and a stmt node.
135 # The condition:
136
137 while_cond = while_stmt.cond
138 #while_cond.show()
139
140 # Note that it's a BinaryOp node - the basic constituent of
141 # expressions in our AST. BinaryOp is the expression tree, with
142 # left and right nodes as children. It also has the op attribute,
143 # which is just the string representation of the operator.
144
145 #print(while_cond.op)
146 #while_cond.left.show()
147 #while_cond.right.show()
148
149
150 # That's it for the example. I hope you now see how easy it is to explore the
151 # AST created by pycparser. Although on the surface it is quite complex and has
152 # a lot of node types, this is the inherent complexity of the C language every
153 # parser/compiler designer has to cope with.
154 # Using the tools provided by the c_ast package it's easy to explore the
155 # structure of AST nodes and write code that processes them.
156 # Specifically, see the cdecl.py example for a non-trivial demonstration of what
157 # you can do by recursively going through the AST.