SLR(1) Parsing: Constructing Parsing Tables for Compiler Design

Learn about SLR(1) parsing, a bottom-up parsing technique used in compiler construction. This guide explains how to construct SLR(1) parsing tables using DFA states and FOLLOW sets, and how these tables are used to parse input strings according to a given grammar.



SLR(1) Parsing: A Step-by-Step Guide

What is SLR(1) Parsing?

SLR(1) parsing (Simple LR(1) parsing) is a method used to create a parsing table for a given context-free grammar. This table is then used by a compiler to analyze code and build a parse tree. SLR(1) is a bottom-up parsing technique, meaning it starts by analyzing the individual tokens of the input and works its way up to the complete grammatical structure. It's a simpler variation of LR(1) parsing, but it cannot handle all grammars that LR(1) can.

Steps in SLR(1) Parsing

  1. Define Grammar: Specify the context-free grammar for the language.
  2. Check for Ambiguity: Ensure that the grammar is unambiguous (each input sentence has only one possible parse tree).
  3. Augmented Production: Add an augmented production rule (e.g., `S' → S`, where `S'` is a new start symbol).
  4. Canonical Collection of LR(0) Items: Compute the canonical collection of LR(0) items (sets of production rules with a marker indicating parsing progress).
  5. DFA Construction: Create a deterministic finite automaton (DFA) representing the states and transitions of the parsing process.
  6. SLR(1) Parsing Table Construction: Build the SLR(1) parsing table (action and goto tables) from the DFA and FOLLOW sets.

Constructing the SLR(1) Parsing Table

The SLR(1) parsing table is populated based on the DFA and FOLLOW sets (sets of terminals that can appear after a non-terminal in a valid sentence). The actions are:

  • Shift: Add the current terminal symbol to the stack.
  • Reduce: Replace a sequence of symbols on the stack with a non-terminal, according to a production rule.
  • Accept: The parse is successful.

(Example SLR(1) table would be shown here)

Example: SLR(1) Parsing

Let's illustrate with this grammar:

Grammar

S → E
E → E + T | T
T → T * F | F
F → id

The steps would involve creating the augmented grammar, constructing the LR(0) items, building the DFA, determining the FOLLOW sets, and finally populating the SLR(1) parsing table. The resulting table would guide the parsing of an input string according to the grammar's rules. (Example of state construction, final states and transitions, and explanation of First and Follow sets would be given here)