hbui
2024-07-22 879c209d64f0c139706e5cb73b1c4c95ec532004
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import math
 
from lark import Transformer, v_args
 
@v_args(inline=True)
class ExpressionTransformer(Transformer):
 
 
    def add(self, left, right) -> str:
        result = f"{left} + {right}"
        return result
 
    def sub(self, left, right) -> str:
        result = f"{left} - {right}"
        return result
 
    def mul(self, left, right) -> str:
        result = f"{left} * {right}"
        return result
 
    def div(self, left, right) -> str:
        result = f"{left} / {right}"
        return result
 
    def exponent(self, left, right) -> str:
        result = f"{left} ** {right}"
        return result
 
    def number(self, n) -> str:
        return f"{n}"
 
    def neg(self, expr) -> str:
        return f"-{expr}"
 
    def var(self, id:str) -> str:
        if id == 'x':
            return id
        elif hasattr(math, id):
            return f"math.{id}"
        else:
            raise ValueError(f"{id} must be 'x' one of constants in math module")
 
    def function(self, name, argv) -> str:
        if hasattr(math, name):
            return f"math.{name}({argv})"
        else:
            raise ValueError(f"'{name}' is not a valid function name in math module")
 
    def argv(self, *arg) -> str:
        return f"{', '.join(arg)}"