-
Notifications
You must be signed in to change notification settings - Fork 609
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New example to generate AST from scratch #507
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
# ----------------------------------------------------------------- | ||
# pycparser: generate_ast.py | ||
# | ||
# Tiny example of writing an AST from scratch to C code. | ||
# | ||
# Andre Ribeiro [https://github.com/Andree37] | ||
# License: BSD | ||
# ----------------------------------------------------------------- | ||
from __future__ import print_function | ||
|
||
from pycparser import c_ast, c_generator | ||
|
||
|
||
# target C code: | ||
# int main() { | ||
# return 0; | ||
# } | ||
|
||
|
||
def create_your_ast(): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. More descriptive name: maybe something like "empty_main_function_ast" |
||
constant_zero = c_ast.Constant(type='int', value='0') | ||
return_node = c_ast.Return(expr=constant_zero) | ||
compound_node = c_ast.Compound(block_items=[return_node]) | ||
type_decl_node = c_ast.TypeDecl(declname='main', quals=[], type=c_ast.IdentifierType(names=['int']), align=[]) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. pycparser code typically tries to wrap at 80 columns |
||
func_decl_node = c_ast.FuncDecl(args=c_ast.ParamList([]), type=type_decl_node) | ||
func_def_node = c_ast.Decl(name='main', quals=[], storage=[], funcspec=[], type=func_decl_node, init=None, | ||
bitsize=None, align=[]) | ||
main_func_node = c_ast.FuncDef(decl=func_def_node, param_decls=None, body=compound_node) | ||
|
||
return main_func_node | ||
|
||
|
||
def generate_c_code(my_ast): | ||
generator = c_generator.CGenerator() | ||
return generator.visit(my_ast) | ||
|
||
|
||
if __name__ == '__main__': | ||
ast = create_your_ast() | ||
print("|----------------------------------------|") | ||
ast.show(offset=2) | ||
print("|----------------------------------------|") | ||
c_code = generate_c_code(ast) | ||
print("C code: \n%s" % c_code) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is unnecessary now -- I also just removed it from other examples for consistency