Sure, let's continue your Lean4 code by adding functionality to compute the First Sets for your grammar rules. The First Set of a nonterminal is the set of terminals that begin the strings derivable from that nonterminal. This is particularly useful in parsing algorithms like LL and LR parsers.
Given your current RulePart inductive type, we'll enhance the code to include:
Support for Nonterminals: To make First Sets meaningful across multiple rules, we need to reference nonterminals within rule definitions. We'll add a nonterminal constructor to RulePart.
Helper Functions: We'll create utility functions to handle set operations like union without duplicates.
First Set Computation: We'll implement a recursive function that computes the First Set for any given RulePart.
Example Usage: Finally, we'll demonstrate how to compute the First Set for your sample grammar and an extended example with multiple rules.
Here's the extended code:
lean
import Data.List
import Std
open List Std
-- Extend RulePart to include nonterminals
inductive RulePart
| terminal : Char -> RulePart
| nonterminal : String -> RulePart
| seq : RulePart -> RulePart -> RulePart
| alt : RulePart -> RulePart -> RulePart
| rep : RulePart -> RulePart
-- Define the Rule structure
structure Rule : Type where
lhs : String
rhs : RulePart
-- Sample grammar input in EBNF:
-- digit = '0' | '1' | '2' | '3'
-- number = digit { digit }
def input : List Rule :=
[
{ lhs := "digit",
rhs := RulePart.alt (RulePart.terminal '0')
(RulePart.alt (RulePart.terminal '1')
(RulePart.alt (RulePart.terminal '2') (RulePart.terminal '3'))) },
{ lhs := "number",
rhs := RulePart.seq (RulePart.nonterminal "digit")
(RulePart.rep (RulePart.nonterminal "digit")) }
]
-- Helper function to compute the union of two lists without duplicates
def union (s1 s2 : List Char) : List Char :=
s1 ++ (s2.filter fun c => !(c ∈ s1))
-- Function to compute the First Set of a RulePart
def firstSet (rules : List Rule) : RulePart → List Char
| RulePart.terminal c => [c]
| RulePart.nonterminal name =>
match rules.find? (fun r => r.lhs = name) with
| some rule => firstSet rules rule.rhs
| none => [] -- Undefined nonterminal; return empty set
| RulePart.alt rp1 rp2 => union (firstSet rules rp1) (firstSet rules rp2)
| RulePart.seq rp1 rp2 =>
-- Since we don't handle epsilon (empty string), the First Set is just the First Set of rp1
firstSet rules rp1
| RulePart.rep rp1 => firstSet rules rp1 -- Repetition behaves like the inner part
-- Function to compute the First Set for a rule by its name
def getFirstSet (rules : List Rule) (name : String) : List Char :=
match rules.find? (fun r => r.lhs = name) with
| some rule => firstSet rules rule.rhs
| none => []
-- Example usage: Compute First Sets for "digit" and "number"
def digitFirstSet : List Char := getFirstSet input "digit"
def numberFirstSet : List Char := getFirstSet input "number"
-- Display the First Sets
#eval digitFirstSet -- Output: ['0', '1', '2', '3']
#eval numberFirstSet -- Output: ['0', '1', '2', '3']
Explanation of the Added Components
Nonterminal Support:
lean
| nonterminal : String -> RulePart
This allows you to reference other rules within the grammar, making the First Set computation across multiple rules feasible.
Helper Function union:
lean
def union (s1 s2 : List Char) : List Char :=
s1 ++ (s2.filter fun c => !(c ∈ s1))
Combines two lists of characters, ensuring no duplicates. This is essential when computing the union of First Sets from different alternatives.
firstSet Function:
lean
def firstSet (rules : List Rule) : RulePart → List Char
Recursively computes the First Set for any RulePart. It handles terminals, nonterminals, alternations, sequences, and repetitions:
Terminal: The First Set is the terminal itself.
Nonterminal: Recursively fetches the First Set of the referenced rule.
Alternation (alt): Union of the First Sets of both alternatives.
Sequence (seq): Since we're not handling epsilon (empty strings), the First Set is just that of the first part.
Repetition (rep): Behaves like the inner part's First Set.
getFirstSet Function:
lean
def getFirstSet (rules : List Rule) (name : String) : List Char
Retrieves and computes the First Set for a rule given its name.
Example Usage:
First Set for "digit": As defined, it's ['0', '1', '2', '3'].
First Set for "number": Since "number" starts with "digit", its First Set is the same as that of "digit".
Extending the Grammar
To further illustrate the utility of First Set computation, consider adding more complex rules with sequences and nonterminals. For example:
exprFirstSet: Includes digits and '(' since an expression can start with a term (which starts with a digit or '(') or another expression followed by '+'.
termFirstSet: Similarly includes digits and '(' because a term can start with a factor or another term followed by '*'.
factorFirstSet: Can start with '(' or a number (digits).
Considerations and Enhancements
Handling Epsilon (Empty String):
Currently, the implementation assumes there are no productions that can derive an empty string. To handle such cases, you'll need to extend the RulePart inductive type and modify the firstSet function to account for empty derivations.
Left Recursion and Infinite Loops:
Be cautious with grammars that have left recursion (e.g., expr = expr '+' term) as naive recursive implementations might enter infinite loops. Implement memoization or keep track of visited nonterminals to prevent this.
Error Handling:
The current implementation returns an empty list for undefined nonterminals. Depending on your use case, you might want to handle this more gracefully, such as by reporting an error.
Performance Considerations:
For large grammars, consider using more efficient data structures for sets (like HashSet from Lean's standard library) to optimize the union and membership operations.
Extending to Other Sets:
Beyond First Sets, you might also want to compute Follow Sets, Nullable Sets, and others depending on your parsing requirements.
Feel free to extend this framework further based on your specific needs!