Certainly! Below is a Python file named grammar_classes.py that implements a basic arithmetic grammar using class structures. This simple grammar is designed to parse expressions containing addition and multiplication of integers. The grammar is implemented without any third-party library.
Here is the structure of the grammar:
- Integer: Represents a numerical value.
- Operator: Represents either an addition or a multiplication operator.
- Expression: Can be a single Integer, or a compound expression with an Integer, Operator, and another Expression.
Save this to grammar_classes.py:
import re
# Define the grammar using classes
class Integer:
def __init__(self, value):
self.value = int(value)
def evaluate(self):
return self.value
def __repr__(self):
return f"Integer({self.value})"
class Operator:
def __init__(self, op):
self.op = op
def evaluate(self, left, right):
if self.op == '+':
return left + right
elif self.op == '*':
return left * right
def __repr__(self):
return f"Operator('{self.op}')"
class Expression:
def __init__(self, left, operator, right):
self.left = left
self.operator = operator
self.right = right
def evaluate(self):
left_val = self.left.evaluate()
right_val = self.right.evaluate()
return self.operator.evaluate(left_val, right_val)
def __repr__(self):
return f"Expression({self.left}, {self.operator}, {self.right})"
def parse(tokens):
if len(tokens) == 1:
return Integer(tokens[0])
for i in reversed(range(len(tokens))):
if tokens[i] in ('+', '*'):
left = parse(tokens[:i])
right = parse(tokens[i+1:])
operator = Operator(tokens[i])
return Expression(left, operator, right)
return None
# Tokenizer function
def tokenize(expression):
tokens = re.findall(r'\d+|[+*]', expression)
return tokens
# A simple test function
def test_expression():
test_data = "3 + 5 * 2"
tokens = tokenize(test_data)
parsed_expr = parse(tokens)
if parsed_expr is not None:
print(f"Original expression: {test_data}")
print(f"Parsed expression: {parsed_expr}")
print(f"Evaluated result: {parsed_expr.evaluate()}")
else:
print("Failed to parse expression.")
if __name__ == "__main__":
test_expression()
To use this script, save it and run it with Python:
python grammar_classes.py
This will parse the test expression "3 + 5 * 2", create an in-memory structure representing the parsed expression, and then evaluate the expression to produce the result. The current implementation is simplistic and does not handle parentheses or operator precedence beyond right-to-left evaluation. Extending the grammar to handle more complex scenarios would require further development, such as implementing a more robust parser and precedence handling.