<p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>

<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;1 + 1&quot;
<strong>Output:</strong> 2
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot; 2-1 + 2 &quot;
<strong>Output:</strong> 3
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;(1+(4+5+2)-3)+(6+8)&quot;
<strong>Output:</strong> 23
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>
	<li><code>s</code> consists of digits, <code>&#39;+&#39;</code>, <code>&#39;-&#39;</code>, <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code>, and <code>&#39; &#39;</code>.</li>
	<li><code>s</code> represents a valid expression.</li>
	<li><code>&#39;+&#39;</code> is <strong>not</strong> used as a unary operation (i.e., <code>&quot;+1&quot;</code> and <code>&quot;+(2 + 3)&quot;</code> is invalid).</li>
	<li><code>&#39;-&#39;</code> could be used as a unary operation (i.e., <code>&quot;-1&quot;</code> and <code>&quot;-(2 + 3)&quot;</code> is valid).</li>
	<li>There will be no two consecutive operators in the input.</li>
	<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>

"""
Expr -> Term RestExpr
RestExpr -> binop Term RestExpr | epsilon
Term -> ( Expr ) | num | - Term
"""

class eof: ...

text = lambda t: lambda token: t == token
binop = lambda token: token in ["+", "-"]
num = lambda token: isinstance(token, int)

digits = set("0123456789")

def tokenize(s: str):
    tokens = []
    
    i = 0
    while i < len(s):
        ch = s[i]
        if ch == " ":
            i += 1
            continue
        if ch in digits:
            current = []
            while i < len(s) and s[i] in digits:
                current.append(s[i])
                i += 1
            tokens.append(int("".join(current)))
            continue
        tokens.append(ch)
        i += 1
    tokens.append(eof)
    return tokens

def evaluate(rpn):
    stack = []
    for token in rpn:
        if num(token):
            stack.append(token)
            continue
        right = stack.pop()
        left = stack.pop()
        if token == "+":
            stack.append(left + right)
            continue
        if token == "-":
            stack.append(left - right)
            continue
    assert len(stack) == 1
    return stack[-1]

class Solution:
    def calculate(self, s: str) -> int:
        tokens = tokenize(s)[::-1]
        stack = []

        def eat(cond):
            if isinstance(cond, str):
                cond = text(cond)
            if cond(peek()):
                return tokens.pop()
            raise RuntimeError("eat exception")

        def peek():
            return tokens[-1]

        """
        Expr -> Term RestExpr
        RestExpr -> binop Term RestExpr | epsilon
        Term -> ( Expr ) | num | - Term
        """

        def parse_term():
            # print("parsing term", peek(), tokens[::-1])
            # print(peek(), num(peek()))
            if peek() == "(":
                eat("("); parse_expr(); eat(")")
                return
            if num(peek()):
                stack.append(eat(num))
                return
            if peek() == "-":
                eat("-"); stack.append(0); parse_term(); stack.append("-")
                return
            raise RuntimeError("term error")
        
        def parse_expr():
            parse_term(); parse_restexpr()
        
        def parse_restexpr():
            if binop(peek()):
                op = eat(binop)
                parse_term()
                stack.append(op)
                parse_restexpr()

        parse_expr(); eat(text(eof))

        return evaluate(stack)
25259