parser: add UnexpectedTokenError
This commit is contained in:
parent
1f21bcc89f
commit
5b3f0262a7
1 changed files with 11 additions and 4 deletions
|
|
@ -16,6 +16,14 @@ class ParsingError(Exception):
|
|||
self.location = location
|
||||
|
||||
|
||||
class UnexpectedTokenError(ParsingError):
|
||||
def __init__(self, got: Token, wanted: Tokens | str):
|
||||
message = wanted
|
||||
if type(wanted) == Tokens:
|
||||
message = str(wanted)
|
||||
super().__init__(got.loc, f"Unexpected token '{got}', wanted {message}")
|
||||
|
||||
|
||||
class Parser:
|
||||
def __init__(self, tokens: List[Token]):
|
||||
self.tokens = tokens
|
||||
|
|
@ -54,7 +62,7 @@ class Parser:
|
|||
r = self.accept(token_type)
|
||||
logger.debug(f"Expecting {token_type}, got {r}")
|
||||
if r is False:
|
||||
raise ParsingError(self.token.loc, f"Unexpected token '{self.token}', wanted {token_type}")
|
||||
raise UnexpectedTokenError(self.token, token_type)
|
||||
return r
|
||||
|
||||
def number(self, mandatory: bool = False):
|
||||
|
|
@ -65,7 +73,7 @@ class Parser:
|
|||
logger.debug(f"Found integer {tok}")
|
||||
return Integer(value=int(tok.value))
|
||||
elif mandatory:
|
||||
raise ParsingError(self.token.loc, f"Unexpected token '{self.token}', wanted integer or float")
|
||||
raise UnexpectedTokenError(self.token, "integer or float")
|
||||
|
||||
def binary_op(self, operand_func: Callable[[], Value], operators: Dict[Tokens, Value]):
|
||||
operand = operand_func()
|
||||
|
|
@ -86,8 +94,7 @@ class Parser:
|
|||
elif num := self.number():
|
||||
return num
|
||||
else:
|
||||
raise ParsingError(self.token.loc, f"Unexpected token '{self.token}', wanted parenthesized expression or "
|
||||
f"number")
|
||||
raise UnexpectedTokenError(self.token, "parenthesized expression or number")
|
||||
|
||||
def term(self) -> Value:
|
||||
return self.binary_op(self.factor, operators={
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue