0% found this document useful (0 votes)
5 views2 pages

PCD

The document presents a Python implementation of a Recursive Descent Parser for parsing mathematical expressions. It defines rules for expressions, terms, and factors, and includes error handling for invalid inputs. The parser processes an input expression and checks for successful parsing completion indicated by a '$' character.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

PCD

The document presents a Python implementation of a Recursive Descent Parser for parsing mathematical expressions. It defines rules for expressions, terms, and factors, and includes error handling for invalid inputs. The parser processes an input expression and checks for successful parsing completion indicated by a '$' character.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import sys

class RecursiveDescentParser:
def __init__(self, input_expr):
self.input = input_expr
self.pos = 0 # Position tracker in input string

def match(self, expected):


"""Matches the expected character and moves the pointer forward."""
if self.pos < len(self.input) and self.input[self.pos] == expected:
self.pos += 1
else:
self.error()

def E(self):
"""Handles the Expression rule: E → T E'"""
self.T()
self.EDash()

def EDash(self):
"""Handles the Expression Dash rule: E' → + T E' | ε"""
if self.pos < len(self.input) and self.input[self.pos] == '+':
self.match('+')
self.T()
self.EDash()

def T(self):
"""Handles the Term rule: T → F T'"""
self.F()
self.TDash()

def TDash(self):
"""Handles the Term Dash rule: T' → * F T' | ε"""
if self.pos < len(self.input) and self.input[self.pos] == '*':
self.match('*')
self.F()
self.TDash()

def F(self):
"""Handles the Factor rule: F → (E) | id"""
if self.pos < len(self.input) and self.input[self.pos] == '(':
self.match('(')
self.E()
self.match(')')
elif self.pos < len(self.input) and self.input[self.pos].isalnum():
self.match(self.input[self.pos]) # Match identifier (e.g., 'a', 'b')
else:
self.error()

def error(self):
"""Prints an error message and exits."""
print(f"Parsing Error at position {self.pos}!")
sys.exit(1)

def parse(self):
"""Initiates parsing and checks if input ends correctly with '$'."""
self.E()
if self.pos < len(self.input) and self.input[self.pos] == '$':
print("Parsing successful!")
else:
self.error()

if __name__ == "__main__":
expr = input("Enter an expression: ")
parser = RecursiveDescentParser(expr)
parser.parse()

output

Enter an expression: s(bic)

Parsing successful!

Program finished with exit code Press ENTER to exit console.

You might also like