Abstract Syntax Tree (AST) in Java
Abstract Syntax Tree is a kind of tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code.
There is numerous importance of AST with application in compilers as abstract syntax trees are data structures widely used in compilers to represent the structure of program code. An AST is usually the result of the syntax analysis phase of a compiler. It often serves as an intermediate representation of the program through several stages that the compiler requires, and has a strong impact on the final output of the compiler.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Let us do discuss the use of AST before proceeding further to the implementation part. AST’s are mainly used in compilers to check code for their accuracy. If the generated tree has errors, the compiler prints an error message. Abstract Syntax Tree (AST) is used because some constructs cannot be represented in context-free grammar, such as implicit typing. They are highly specific to programming languages, but research is underway on universal syntax trees.
id + id * id would have the following syntax tree which is as follows:
Abstract syntax tree will be as follows:
Here we will be writing custom java source codes corresponding to which we will be providing the AST for the same java source code as in implementation.
Example 1(A) Java source code
Example 1(B) AST of above source code
Now you must be wondering how to make an AST or how the above code is generated for that geek follow the simple steps as listed in the sequential order.
- Run the Source Code in your local Environment.
- Download the Checkstyle Command line
- Audit the Program with the help of Checkstyle in your Terminal:
java -jar checkstyle-8.43-all.jar -c /google_checks.xml YourFile.java
- After Audit, Run this command in your terminal to get the AST of your preferred Code: java -jar checkstyle-8.43-all.jar -t YourFile.java
- AST is now ready. But wait geeks,
Note: This is not an Updated AST
Remember: To update the AST, we have to do the following two steps
Step 1: We should replace
">" with ">" and "<" with "<"
Step 2: Remove the code lines
Example 1(C) Updated AST Examples of the above code is as follows:
Example 2: Representing 1 + 2 can be represented in AST