Tuesday 11 February 2014

Python AST(Abstract Syntax Tree) and Abstract Syntax Description Language Tutorial 1

Hello guys this is after long time after which I am writing a blog. I am going to write about Abstract Syntax Tree implementation, their view and nomenclature in python. So first of all what is Abstract Syntax Tree? When we compile a program in a compiler, Compiler do many checks that your program is correct with respect to language grammar. So AST is representation of a program in a grammar of that particular language with removal of delimeter(like braces,Colons,spaces). Abstract Syntax Description Lanuguage (ASDL) is a language designed to describe the tree-like data structures in compilers. Its main goal is to provide a method for compiler components written in different languages to interoperate. ASDL makes it easier for applications written in a variety of programming languages to communicate complex recursive data structures. Python AST is tree where every node is specific to ASDL. Link to this documentation is as follows: 


You can get more information about AST from wikpedia or any online materials but here I will be more specific to python AST as I have worked upon for two week. 

Here is the more specific documentation of python AST:

Creation
---------
if you want to create python AST of a code you can do that by to ways.Which are as follows:

Method 1 (Python code)
--------

import ast
ast_tree=ast.parse("""
#code of which you want to create AST.
""")

Method 2 (Python code)
--------

import _ast
ast_tree=compile("""
#code of which you want to create AST.
""","<string>","exec",_ast.PyCF_ONLY_AST)

Method 1 is very straight forward. It uses ast class of python and parses python Code. 

Method 2 uses _ast class and use compile function with "exec" for module, "single" for single interactive statement and "eval" for expression.

Here the root of the AST will be any one of these three based of what values of flags you are using in compile function mentioned above.If you are using parse function then it will automatically take it as a module.

You can use ast.dump(ast_tree) method to print all nodes of generated AST. You can also use astmonkey library to see pictorial form of AST. Link of that is as follows :https://pypi.python.org/pypi/astmonkey.

Ok friend that's it for now, I will publish tutorial 2 which will include in deep details regarding AST in coming days so stay tuned and don't forget to subscribe!

No comments:

Post a Comment