|
| 1 | +from typing import Dict, Callable |
| 2 | +from ..domain.formula import Formula, Conjunction, Disjunction, Implication, Biconditional |
| 3 | +from .token_stream import TokenStream |
| 4 | +from .token import TokenType |
| 5 | +from .expression_builder import ExpressionBuilder |
| 6 | + |
| 7 | + |
| 8 | +class BinaryOperatorBuilder(ExpressionBuilder): |
| 9 | + _PRECEDENCE: Dict[TokenType, int] = { |
| 10 | + TokenType.BICONDITIONAL: 1, |
| 11 | + TokenType.IMPLICATION: 2, |
| 12 | + TokenType.DISJUNCTION: 3, |
| 13 | + TokenType.CONJUNCTION: 4, |
| 14 | + } |
| 15 | + |
| 16 | + _OPERATOR_CONSTRUCTORS: Dict[TokenType, Callable[[Formula, Formula], Formula]] = { |
| 17 | + TokenType.CONJUNCTION: Conjunction, |
| 18 | + TokenType.DISJUNCTION: Disjunction, |
| 19 | + TokenType.IMPLICATION: Implication, |
| 20 | + TokenType.BICONDITIONAL: Biconditional, |
| 21 | + } |
| 22 | + |
| 23 | + _RIGHT_ASSOCIATIVE: set = {TokenType.IMPLICATION} |
| 24 | + |
| 25 | + def __init__(self, primary_builder: ExpressionBuilder): |
| 26 | + self._primary_builder = primary_builder |
| 27 | + |
| 28 | + def build(self, stream: TokenStream) -> Formula: |
| 29 | + return self._build_binary_operator(stream, 1) |
| 30 | + |
| 31 | + def _build_binary_operator(self, stream: TokenStream, min_precedence: int) -> Formula: |
| 32 | + left = self._primary_builder.build(stream) |
| 33 | + |
| 34 | + while not stream.is_eof(): |
| 35 | + token = stream.current_token |
| 36 | + if token is None: |
| 37 | + break |
| 38 | + |
| 39 | + if token.type == TokenType.RIGHT_PAREN: |
| 40 | + break |
| 41 | + |
| 42 | + if token.type not in self._PRECEDENCE: |
| 43 | + break |
| 44 | + |
| 45 | + op_precedence = self._PRECEDENCE[token.type] |
| 46 | + if op_precedence < min_precedence: |
| 47 | + break |
| 48 | + |
| 49 | + stream.advance() |
| 50 | + |
| 51 | + if token.type in self._RIGHT_ASSOCIATIVE: |
| 52 | + right = self._build_binary_operator(stream, op_precedence) |
| 53 | + else: |
| 54 | + right = self._build_binary_operator(stream, op_precedence + 1) |
| 55 | + |
| 56 | + constructor = self._OPERATOR_CONSTRUCTORS[token.type] |
| 57 | + left = constructor(left, right) |
| 58 | + |
| 59 | + return left |
0 commit comments