Resolve an arithmetic expression that might include register names. Registers names will be substituted with their current value before proceeding to evaluate the expression. Args: expr: an expression to evaluate Returns: final evaluation re
(self, expr: str)
| 88 | return re.sub(r'\$(\w+)', __sub_reg, expr) |
| 89 | |
| 90 | def resolve_expr(self, expr: str) -> int: |
| 91 | """Resolve an arithmetic expression that might include register names. |
| 92 | |
| 93 | Registers names will be substituted with their current value before |
| 94 | proceeding to evaluate the expression. |
| 95 | |
| 96 | Args: |
| 97 | expr: an expression to evaluate |
| 98 | |
| 99 | Returns: |
| 100 | final evaluation result |
| 101 | |
| 102 | Raises: |
| 103 | KeyError: if `expr` contains an unrecognized register name |
| 104 | ValueError: if `expr` contains disallowed tokens |
| 105 | SyntaxError: if `expr` contains a broken arithmetic syntax |
| 106 | """ |
| 107 | |
| 108 | try: |
| 109 | # look for registers names and replace them with their actual values |
| 110 | expr = self.sub_reg_values(expr) |
| 111 | |
| 112 | # expr contains an unrecognized register name |
| 113 | except KeyError as ex: |
| 114 | raise KeyError(f'unrecognized register name: {ex.args[0]}') from ex |
| 115 | |
| 116 | try: |
| 117 | # expr should contain only values and aithmetic tokens by now; attempt to evaluate it |
| 118 | res = safe_arith(expr) |
| 119 | |
| 120 | # expr contains a disallowed token |
| 121 | except ValueError as ex: |
| 122 | raise ValueError('only integers, hexadecimals, octals, arithmetic and bitwise operators are allowed') from ex |
| 123 | |
| 124 | # arithmetic syntax is broken |
| 125 | except SyntaxError as ex: |
| 126 | raise SyntaxError('error evaluating arithmetic expression') from ex |
| 127 | |
| 128 | return res |
| 129 | |
| 130 | def handle_set(self, line: str) -> Tuple[str, int]: |
| 131 | """ |
no test coverage detected