all repos — calc @ 168142049029d45a2e0dd423b296de40d3f2dfab

a simple python calculator

structs.py (view raw)

 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
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
from dataclasses import dataclass
from typing import Any, List
from enum import auto, IntEnum


class TokenTypes(IntEnum):
    INT = auto()
    FLOAT = auto()
    PLUS = auto()
    MINUS = auto()
    MULT = auto()
    DIV = auto()
    OPEN_PAREN = auto()
    CLOSE_PAREN = auto()
    EOF = auto()


@dataclass()
class Token:
    type: TokenTypes
    value: Any
    line: int


class ASTNodeTypes(IntEnum):
    Program = auto()
    ExpressionStatement = auto()
    BinaryExpression = auto()
    UnaryExpression = auto()
    Literal = auto()


@dataclass()
class AST:
    type: ASTNodeTypes


@dataclass()
class Program(AST):
    body: List[AST]


@dataclass()
class ExpressionStatement(AST):
    expression: AST


@dataclass()
class Literal(AST):
    value: Any

    def __init__(self, value: Any):
        self.type = ASTNodeTypes.Literal
        self.value = value


@dataclass()
class BinaryExpression(AST):
    left: Literal
    right: Literal
    operator: Token

    def __init__(self, left: Literal, right: Literal, operator: Token):
        self.type = ASTNodeTypes.BinaryExpression
        self.left = left
        self.right = right
        self.operator = operator


@dataclass()
class UnaryExpression(Literal):
    operator: Token

    def __init__(self, operator: Token, value: Any):
        self.type = ASTNodeTypes.UnaryExpression
        self.operator = operator
        self.value = value