===== ISTEM =====
Solve the following programming task.

TASK: Basic Expression Calculator

Write a function 'calculate(s)' that evaluates a mathematical expression string containing addition (+), subtraction (-), multiplication (*), integer division (//) and parentheses, with correct operator precedence, without using eval or exec.

STARTER CODE (python):
def calculate(s: str) -> int:
    # Write your code here
    pass


RULES:
- Keep the function name and signature EXACTLY as given.
- Return working code only. No explanations.
- Put the code in a single ``` block.
- Try to solve it first. If you genuinely cannot, write only this single
  line instead of producing faulty code: CANNOT_SOLVE

===== HAM YANIT =====
```python
def calculate(s: str) -> int:
    tokens = []
    i = 0
    n = len(s)
    while i < n:
        if s[i].isspace():
            i += 1
        elif s[i].isdigit():
            j = i
            while j < n and s[j].isdigit():
                j += 1
            tokens.append(int(s[i:j]))
            i = j
        elif s[i : i + 2] == "//":
            tokens.append("//")
            i += 2
        elif s[i] in "+-*/()":
            tokens.append("//" if s[i] == "/" else s[i])
            i += 1
        else:
            i += 1

    pos = 0

    def advance():
        nonlocal pos
        pos += 1

    def parse_expr():
        val = parse_term()
        while pos < len(tokens) and tokens[pos] in ("+", "-"):
            op = tokens[pos]
            advance()
            rhs = parse_term()
            if op == "+":
                val += rhs
            else:
                val -= rhs
        return val

    def parse_term():
        val = parse_factor()
        while pos < len(tokens) and tokens[pos] in ("*", "//"):
            op = tokens[pos]
            advance()
            rhs = parse_factor()
            if op == "*":
                val *= rhs
            else:
                val //= rhs
        return val

    def parse_factor():
        nonlocal pos
        if pos < len(tokens) and tokens[pos] == "+":
            advance()
            return parse_factor()
        elif pos < len(tokens) and tokens[pos] == "-":
            advance()
            return -parse_factor()
        return parse_primary()

    def parse_primary():
        tok = tokens[pos]
        advance()
        if tok == "(":
            val = parse_expr()
            if pos < len(tokens) and tokens[pos] == ")":
                advance()
            return val
        return tok

    return parse_expr() if tokens else 0
```