Okay, this is a fun challenge! A Pratt parser is a great choice for this. Here's a Python 3 implementation.
We'll break it down into:
- Tokenization (Lexer): To convert the input string into a stream of tokens.
- Pratt Parser: The core logic with
nud (null denotation) and led (left denotation) functions.
- Evaluation: The
nud and led functions will perform the actual computations.
import re
import math
# --- Tokenizer (Lexer) ---
class Token:
def __init__(self, type, value, position):
self.type = type
self.value = value
self.position = position
def __repr__(self):
return f"Token({self.type!r}, {self.value!r}, {self.position})"
TOKEN_SPECIFICATION = [
('SKIP', r'[ \t]+'), # Skip whitespace
('BOOLEAN', r'true|false'), # Boolean literals
('INTEGER', r'-?\d+'), # Integer literals (allow negative)
('VARIABLE', r'[a-zA-Z_][a-zA-Z0-9_]*'), # Variables (must come after keywords)
('LPAREN', r'\('), # Left parenthesis
('RPAREN', r'\)'), # Right parenthesis
# Operators - order matters for multi-char ops (e.g., == before =)
('OP_EQ', r'=='),
('OP_NEQ', r'!='),
('OP_LTE', r'<='),
('OP_GTE', r'>='),
('OP_LT', r'<'),
('OP_GT', r'>'),
('OP_AND', r'AND'),
('OP_OR', r'OR'),
('OP_NOT', r'NOT'),
('OP_PLUS', r'\+'),
('OP_MINUS', r'-'),
('OP_MUL', r'×|\*'), # Allow both × and * for multiplication
('OP_DIV', r'div'),
('OP_POW', r'\^'),
('OP_MOD', r'mod'),
('MISMATCH', r'.'), # Any other character
]
# Pre-compile token regexes
TOKEN_REGEX = '|'.join('(?P<%s>%s)' % pair for pair in TOKEN_SPECIFICATION)
# Keywords (to distinguish from variables)
KEYWORDS = {'true', 'false', 'AND', 'OR', 'NOT', 'div', 'mod'}
def tokenize(code):
tokens = []
for mo in re.finditer(TOKEN_REGEX, code):
kind = mo.lastgroup
value = mo.group()
position = mo.start()
if kind == 'SKIP':
continue
elif kind == 'MISMATCH':
raise SyntaxError(f"Unexpected character: '{value}' at position {position}")
# Handle keywords that might be captured by VARIABLE regex
if kind == 'VARIABLE' and value in KEYWORDS:
if value in ['true', 'false']:
kind = 'BOOLEAN'
elif value == 'AND':
kind = 'OP_AND'
elif value == 'OR':
kind = 'OP_OR'
elif value == 'NOT':
kind = 'OP_NOT'
elif value == 'div':
kind = 'OP_DIV'
elif value == 'mod':
kind = 'OP_MOD'
if kind == 'INTEGER':
value = int(value)
elif kind == 'BOOLEAN':
value = (value == 'true')
elif kind == 'OP_MUL' and value == '×': # Normalize multiplication operator
value = '*'
tokens.append(Token(kind, value, position))
tokens.append(Token('EOF', None, len(code))) # End Of File token
return tokens
# --- Pratt Parser ---
class PrattParser:
def __init__(self, tokens, variables=None):
self.tokens = tokens
self.pos = 0
self.current_token = self.tokens[self.pos]
self.variables = variables if variables is not None else {}
# Operator precedence (binding power) and handlers
# bp: binding power, nud: null denotation, led: left denotation
self.token_rules = {}
self._register_tokens()
def _advance(self):
self.pos += 1
if self.pos < len(self.tokens):
self.current_token = self.tokens[self.pos]
else:
# Should ideally be caught by EOF check before advancing past it
self.current_token = Token('EOF', None, self.tokens[-1].position + 1 if self.tokens else 0)
def _register_token(self, token_type_or_value, bp=0, nud_fn=None, led_fn=None):
"""Registers rules for a token type or a specific token value (for operators)."""
key = token_type_or_value
if key in self.token_rules:
# Update existing entry if needed, useful for tokens like '-' (unary and binary)
# Though for this setup, we use distinct nud/led for operators
self.token_rules[key] = (
bp if bp != 0 else self.token_rules[key][0],
nud_fn if nud_fn else self.token_rules[key][1],
led_fn if led_fn else self.token_rules[key][2]
)
else:
self.token_rules[key] = (bp, nud_fn, led_fn)
def _get_rule(self, token):
# Prioritize specific operator values over generic token types
rule = self.token_rules.get(token.value) # e.g. '+', 'AND'
if rule is None:
rule = self.token_rules.get(token.type) # e.g. 'INTEGER', 'VARIABLE'
if rule is None:
raise SyntaxError(f"No parsing rule for token {token} (value: {token.value}, type: {token.type})")
return rule
def _get_binding_power(self, token):
return self._get_rule(token)[0]
def _nud(self, token):
nud_fn = self._get_rule(token)[1]
if not nud_fn:
raise SyntaxError(f"Token {token} cannot start an expression (no nud).")
return nud_fn(token)
def _led(self, token, left):
led_fn = self._get_rule(token)[2]
if not led_fn:
raise SyntaxError(f"Token {token} cannot follow an expression (no led).")
return led_fn(token, left)
def _register_tokens(self):
# Literals and Variables
self._register_token('INTEGER', nud_fn=self._nud_literal)
self._register_token('BOOLEAN', nud_fn=self._nud_literal)
self._register_token('VARIABLE', nud_fn=self._nud_variable)
# Parentheses
self._register_token('LPAREN', bp=0, nud_fn=self._nud_lparen) # bp 0, nud handles precedence
self._register_token('RPAREN', bp=0) # bp 0, error if encountered unexpectedly
# Prefix Operator
self._register_token('OP_NOT', bp=70, nud_fn=self._nud_prefix) # NOT has high precedence
self._register_token('OP_MINUS', bp=70, nud_fn=self._nud_prefix) # For unary minus
# Infix Operators (binding power determines precedence)
# Associativity: Left by default. Right-associative needs special handling in led.
# Lower bp binds less tightly
self._register_token('OP_OR', bp=10, led_fn=self._led_infix)
self._register_token('OP_AND', bp=20, led_fn=self._led_infix)
self._register_token('OP_EQ', bp=30, led_fn=self._led_infix)
self._register_token('OP_NEQ', bp=30, led_fn=self._led_infix)
self._register_token('OP_LT', bp=30, led_fn=self._led_infix)
self._register_token('OP_GT', bp=30, led_fn=self._led_infix)
self._register_token('OP_LTE', bp=30, led_fn=self._led_infix)
self._register_token('OP_GTE', bp=30, led_fn=self._led_infix)
self._register_token('OP_PLUS', bp=40, led_fn=self._led_infix)
self._register_token('OP_MINUS', bp=40, led_fn=self._led_infix) # Binary minus
self._register_token('OP_MUL', bp=50, led_fn=self._led_infix)
self._register_token('OP_DIV', bp=50, led_fn=self._led_infix)
self._register_token('OP_MOD', bp=50, led_fn=self._led_infix)
self._register_token('OP_POW', bp=60, led_fn=self._led_infix_right_associative) # ^ is right-associative
self._register_token('EOF', bp=0)
# --- NUD Handlers ---
def _nud_literal(self, token):
return token.value
def _nud_variable(self, token):
if token.value not in self.variables:
raise NameError(f"Undefined variable '{token.value}' at position {token.position}")
return self.variables[token.value]
def _nud_lparen(self, token):
# Consume LPAREN
expr = self.parse_expression(0) # Parse expression inside with lowest precedence
if self.current_token.type != 'RPAREN':
raise SyntaxError(f"Expected ')' but found {self.current_token} at position {self.current_token.position}")
self._advance() # Consume RPAREN
return expr
def _nud_prefix(self, token):
# Consume prefix operator
op_bp = self._get_binding_power(token)
right = self.parse_expression(op_bp) # Parse operand with operator's precedence
if token.type == 'OP_NOT':
if not isinstance(right, bool):
raise TypeError(f"Operand for NOT must be boolean, got {type(right)} ({right}) at pos {token.position}")
return not right
elif token.type == 'OP_MINUS': # Unary minus
if not isinstance(right, (int, float)): # float if we were to add them
raise TypeError(f"Operand for unary '-' must be numeric, got {type(right)} ({right}) at pos {token.position}")
return -right
else:
# Should not happen if registration is correct
raise SyntaxError(f"Unknown prefix operator {token.value} at pos {token.position}")
# --- LED Handlers ---
def _led_infix(self, token, left):
# Consume infix operator
op_bp = self._get_binding_power(token)
right = self.parse_expression(op_bp) # Parse right operand with operator's precedence
op = token.value # For operators, value is the operator symbol/keyword
# Type checking and operation
if op in ['+', '-', '*', 'div', 'mod', '^']:
if not (isinstance(left, int) and isinstance(right, int)):
raise TypeError(f"Operands for '{op}' must be integers. Got {type(left)} and {type(right)} at pos {token.position}")
if op == '+': return left + right
if op == '-': return left - right
if op == '*': return left * right
if op == 'div':
if right == 0: raise ZeroDivisionError(f"Integer division by zero at pos {token.position}")
return left // right
if op == 'mod':
if right == 0: raise ZeroDivisionError(f"Modulo by zero at pos {token.position}")
return left % right
if op == '^': # Already handled by right-associative, but for completeness
return int(math.pow(left, right)) # Result should be int for toy language
elif op in ['==', '!=', '<', '>', '<=', '>=']:
# Allow comparison between two integers or two booleans
if not ((isinstance(left, int) and isinstance(right, int)) or \
(isinstance(left, bool) and isinstance(right, bool))):
raise TypeError(f"Operands for '{op}' must be both integers or both booleans. Got {type(left)} and {type(right)} at pos {token.position}")
if op == '==': return left == right
if op == '!=': return left != right
if op == '<': return left < right
if op == '>': return left > right
if op == '<=': return left <= right
if op == '>=': return left >= right
elif op in ['AND', 'OR']:
if not (isinstance(left, bool) and isinstance(right, bool)):
raise TypeError(f"Operands for '{op}' must be booleans. Got {type(left)} and {type(right)} at pos {token.position}")
if op == 'AND': return left and right
if op == 'OR': return left or right
else:
# Should not happen
raise SyntaxError(f"Unknown infix operator {token.value} at pos {token.position}")
def _led_infix_right_associative(self, token, left):
# For right-associative operators like '^'
op_bp = self._get_binding_power(token)
# Parse right operand with precedence one less than operator's own to achieve right-associativity
right = self.parse_expression(op_bp - 1)
op = token.value
if op == '^':
if not (isinstance(left, int) and isinstance(right, int)):
raise TypeError(f"Operands for '^' must be integers. Got {type(left)} and {type(right)} at pos {token.position}")
if right < 0: # Simplification: no fractional exponents for integers
raise ValueError(f"Negative exponent for integer power not supported simply. Got {right} at pos {token.position}")
return int(math.pow(left, right))
else:
# Should not happen
raise SyntaxError(f"Unknown right-associative infix operator {token.value} at pos {token.position}")
# --- Main Parsing Loop ---
def parse_expression(self, rbp): # rbp: right binding power
# Get the nud for the current token
t = self.current_token
self._advance() # Consume the token handled by nud
left = self._nud(t)
# While the next token has higher precedence, process it as an infix/postfix operator
while rbp < self._get_binding_power(self.current_token):
t = self.current_token
self._advance() # Consume the token handled by led
left = self._led(t, left)
return left
def evaluate(self):
if not self.tokens or self.tokens[0].type == 'EOF':
raise ValueError("Cannot evaluate an empty expression.")
result = self.parse_expression(0) # Start with lowest precedence (0)
# After parsing, we should be at EOF if the whole expression was consumed
if self.current_token.type != 'EOF':
raise SyntaxError(f"Unexpected token {self.current_token} after expression. Position {self.current_token.position}")
return result
# --- Helper Function to Evaluate ---
def evaluate_condition(condition_string, variables=None):
"""
Tokenizes, parses, and evaluates a condition string.
Variables is a dictionary like {'x': 10, 'isValid': True}
"""
try:
tokens = tokenize(condition_string)
parser = PrattParser(tokens, variables)
result = parser.evaluate()
if not isinstance(result, bool):
# For an `if` condition, the final result *must* be boolean.
# The language might allow non-boolean intermediate results though.
raise TypeError(f"Condition evaluated to non-boolean value: {result} (type: {type(result)})")
return result
except (SyntaxError, NameError, TypeError, ZeroDivisionError, ValueError) as e:
print(f"Evaluation Error: {e}")
return None # Or re-raise e
# --- Examples ---
if __name__ == "__main__":
variables = {
"x": 10,
"y": 5,
"isValid": True,
"count": 0
}
print("--- Basic Tests ---")
print(f"'true' -> {evaluate_condition('true', variables)}")
print(f"'10 == x' -> {evaluate_condition('10 == x', variables)}")
print(f"'x > y AND isValid' -> {evaluate_condition('x > y AND isValid', variables)}")
print(f"'NOT (count > 0 OR y < x)' -> {evaluate_condition('NOT (count > 0 OR y < x)', variables)}")
print(f"'1 + 2 * 3' -> {evaluate_condition('1 + 2 * 3 == 7', variables)}") # Should be 1 + (2*3) == 7 -> true
print(f"'(1 + 2) * 3' -> {evaluate_condition('(1 + 2) * 3 == 9', variables)}") # (1+2)*3 == 9 -> true
print("\n--- Mathematical Operations ---")
print(f"'x + y * 2' -> {evaluate_condition('x + y * 2 == 20', variables)}") # 10 + 5*2 = 20
print(f"'(x + y) * 2' -> {evaluate_condition('(x + y) * 2 == 30', variables)}") # (10+5)*2 = 30
print(f"'x div y' -> {evaluate_condition('x div y == 2', variables)}") # 10 div 5 = 2
print(f"'10 div 3' -> {evaluate_condition('10 div 3 == 3', variables)}")
print(f"'x mod 3' -> {evaluate_condition('x mod 3 == 1', variables)}") # 10 mod 3 = 1
print(f"'2 ^ 3 ^ 2' -> {evaluate_condition('2 ^ 3 ^ 2 == 512', variables)}") # 2 ^ (3^2) = 2^9 = 512
print(f"'(2 ^ 3) ^ 2' -> {evaluate_condition('(2 ^ 3) ^ 2 == 64', variables)}") # (2^3)^2 = 8^2 = 64
print(f"'10 - 3 - 2' -> {evaluate_condition('10 - 3 - 2 == 5', variables)}") # (10-3)-2 = 5
print(f"'-5 + x == 5' -> {evaluate_condition('-5 + x == 5', variables)}") # Unary minus
print("\n--- Boolean Logic ---")
print(f"'true AND false OR true' -> {evaluate_condition('true AND false OR true', variables)}") # false OR true -> true
print(f"'true OR false AND true' -> {evaluate_condition('true OR false AND true', variables)}") # true OR false -> true (AND binds tighter)
print(f"'NOT false' -> {evaluate_condition('NOT false', variables)}")
print(f"'NOT (x == 10)' -> {evaluate_condition('NOT (x == 10)', variables)}")
print("\n--- Type Errors and Other Errors ---")
print(f"'10 AND true' -> {evaluate_condition('10 AND true', variables)}")
print(f"'x + isValid' -> {evaluate_condition('x + isValid', variables)}")
print(f"'10 div 0' -> {evaluate_condition('10 div 0', variables)}")
print(f"'z > 10' -> {evaluate_condition('z > 10', variables)}") # Undefined variable
print(f"'(1 + 2' -> {evaluate_condition('(1 + 2', variables)}") # Mismatched paren
print(f"'1 + * 2' -> {evaluate_condition('1 + * 2', variables)}") # Syntax error
print(f"'10 $ 2' -> {evaluate_condition('10 $ 2', variables)}") # Unknown token
print(f"'10 + 2 )' -> {evaluate_condition('10 + 2 )', variables)}") # Unexpected token after expression
print("\n--- Final result must be boolean ---")
print(f"'x + y' (as condition) -> {evaluate_condition('x + y', variables)}")
# Edge case: empty string
print(f"'' (empty string) -> {evaluate_condition('', variables)}")
# Edge case: only operator
print(f"'+' (only operator) -> {evaluate_condition('+', variables)}")
Key Features and Design Choices:
-
Tokenizer (tokenize function):
- Uses regular expressions for robust token identification.
- Handles whitespace skipping.
- Distinguishes keywords (
AND, OR, NOT, div, mod, true, false) from general VARIABLEs. This is important for the regex order.
- Converts
INTEGER and BOOLEAN string values to their Python types immediately.
- Adds an
EOF token to simplify parser termination.
-
Token Class: A simple container for token type, value, and original position (useful for error reporting).
-
PrattParser Class:
__init__: Initializes token stream, variable context, and registers token parsing rules.
_register_token: A central method to define how tokens are handled. It stores:
bp (Binding Power): An integer determining precedence. Higher means binds tighter.
nud_fn (Null Denotation): Function called when a token appears at the beginning of an expression (e.g., literals, variables, prefix operators). It takes the token itself.
led_fn (Left Denotation): Function called when a token appears after an expression (e.g., infix operators). It takes the token and the result of the expression to its left.
_get_rule, _get_binding_power, _nud, _led: Helper methods to retrieve and call the appropriate rules/functions for a token. These look up rules by operator value first (e.g., '+', 'AND') and then by type (e.g., 'INTEGER').
_register_tokens: This is where all token types and operators are defined with their binding powers and associated nud/led handler methods.
- Precedence:
OR: 10
AND: 20
- Comparisons (
==, !=, <, etc.): 30
- , (binary): 40
This implementation covers all the specified requirements and provides a good foundation for a more complex expression evaluator.