Parsing is the process of analyzing a sequence of tokens to determine their grammatical structure according to the rules of a language. It organizes tokens according to grammar rules and constructs a parse tree or Abstract Syntax Tree (AST) to represent the structure of the input.

- Converts tokens into a structured parse tree
- Helps understand the grammatical structure of text or code
- Ensures the input follows syntax rules
- Used in compilers, interpreters, and NLP applications
- Supports further tasks like semantic analysis and code execution
Role of Parser
A parser performs syntax analysis by checking whether the sequence of tokens follows the grammar rules of a programming language. It constructs a parse tree or AST and reports syntax errors.
- Checks whether code follows grammar and syntax rules
- Constructs parse trees or Abstract Syntax Trees (ASTs).
- Reports syntax errors when the input does not follow grammar rules.
- Detects and reports syntax errors clearly
- Attempts basic error recovery during parsing
- Supports error recovery to continue parsing after certain syntax errors.
Types of Parsing
The parsing is divided into two types:

1. Top-Down Parsing
Top-down Parsing builds the parse tree from the start symbol toward the input symbols.
- Starts from the start symbol.
- Expands non-terminals using production rules.
- Uses leftmost derivation.
- Common techniques include recursive descent parsing and predictive parsing.
- Easier to implement for simple grammars.
Types of Top-Down Parsing
With Backtracking
- Tries alternative production rules when the selected rule fails.
- Backtracks to explore other possible productions.
- Can be slower because it may require repeated attempts.
Without Backtracking
- Uses lookahead symbols to select the appropriate production rule.
- Does not backtrack to try alternative productions.
- Predictive parsing is a common example.
2. Bottom-Up Parsing
Bottom-up Parsing builds the parse tree from input symbols toward the start symbol.
- Starts from the input string.
- Reduces substrings into non-terminals.
- Uses rightmost derivation in reverse.
- Commonly implemented using shift-reduce parsing, which reduces input symbols and substrings into non-terminals.
- Efficient for complex grammars and compiler design.
Types of Bottom-Up Parsing
Bottom-Up vs. Top-Down Parser
Top-Down Parsing | Bottom-Up Parsing |
|---|---|
Builds the parse tree from root to leaves. | Builds the parse tree from leaves to root. |
Uses leftmost derivation. | Uses rightmost derivation in reverse. |
Starts from the start symbol. | Starts from the input string. |
Expands non-terminals using production rules. | Reduces substrings into non-terminals. |
May use backtracking, depending on the technique. | Standard shift-reduce parsers do not use backtracking. |
Generally simpler to implement. | Generally more complex to implement. |
Recursive Descent Parser, LL Parser. | Shift-Reduce Parser, LR Parser. |

