Files
agent-orchestrator-benchmark/calculators/builder-adversary-min/run-05/calc/lexer.py

49 lines
1.1 KiB
Python

from dataclasses import dataclass
from typing import Union
class LexError(Exception):
pass
@dataclass
class Token:
kind: str
value: Union[int, float, str, None]
_SINGLE = {
'+': 'PLUS',
'-': 'MINUS',
'*': 'STAR',
'/': 'SLASH',
'(': 'LPAREN',
')': 'RPAREN',
}
def tokenize(src: str) -> list:
tokens = []
i = 0
while i < len(src):
ch = src[i]
if ch in ' \t':
i += 1
elif ch in _SINGLE:
tokens.append(Token(_SINGLE[ch], ch))
i += 1
elif ch.isdigit() or ch == '.':
start = i
has_dot = False
while i < len(src) and (src[i].isdigit() or (src[i] == '.' and not has_dot)):
if src[i] == '.':
has_dot = True
i += 1
raw = src[start:i]
value = float(raw) if has_dot else int(raw)
tokens.append(Token('NUMBER', value))
else:
raise LexError(f"unexpected character {ch!r} at position {i}")
tokens.append(Token('EOF', None))
return tokens