CuriouSTEM

View Original

Compiler Design

As we saw in the previous article, compilers work as translators converting the program written in higher programming languages into lower level programming language, which the computer can easily execute. For the transformation of source code to object code, the compiler passes through multiple phases. Every phase takes output from the previous phase and feeds into the next phase after performing some transformations. The phases followed are: 

  • Lexical Analysis - This is the first phase, the compiler goes through the source code, grouping characters, identifiers, operators, numbers. It ignores any comments present. A symbol table is created which keeps track of the identifiers, their properties and values.

  • Syntax Analysis - This phase takes the tokens/groupings created by the previous phase and checks if the statements in the program follow the correct syntax of the programming language. It creates a parse tree based on the statements in the program. 

  • Semantic Analysis - This phase takes the parse tree created and checks if it is logically correct. It also checks if the variables types declared are compatible. 

  • Intermediate Code Generation - As the name suggests intermediate is between the higher and lower level language. The compiler takes the output from the semantic phase and converts into code that can be easily converted into object code. 

  • Code Optimization - This phase removes unused code, variables, reduces the number of steps and makes the code efficient in that it uses a lower amount of resources and runs faster. 

  • Code Generator - This last phase generates the object code and allocates memory. The symbol table is updated in all the phases.

 During compilation, if any errors are encountered, the compiler stops the process and notifies the programmer. 

Picture Source: geeksforgeeks.org