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
|
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:
|
class Parser:
|
||||||
def __init__(self, tokens: List[Token]):
|
def __init__(self, tokens: List[Token]):
|
||||||
self.tokens = tokens
|
self.tokens = tokens
|
||||||
|
|
@ -54,7 +62,7 @@ class Parser:
|
||||||
r = self.accept(token_type)
|
r = self.accept(token_type)
|
||||||
logger.debug(f"Expecting {token_type}, got {r}")
|
logger.debug(f"Expecting {token_type}, got {r}")
|
||||||
if r is False:
|
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
|
return r
|
||||||
|
|
||||||
def number(self, mandatory: bool = False):
|
def number(self, mandatory: bool = False):
|
||||||
|
|
@ -65,7 +73,7 @@ class Parser:
|
||||||
logger.debug(f"Found integer {tok}")
|
logger.debug(f"Found integer {tok}")
|
||||||
return Integer(value=int(tok.value))
|
return Integer(value=int(tok.value))
|
||||||
elif mandatory:
|
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]):
|
def binary_op(self, operand_func: Callable[[], Value], operators: Dict[Tokens, Value]):
|
||||||
operand = operand_func()
|
operand = operand_func()
|
||||||
|
|
@ -86,8 +94,7 @@ class Parser:
|
||||||
elif num := self.number():
|
elif num := self.number():
|
||||||
return num
|
return num
|
||||||
else:
|
else:
|
||||||
raise ParsingError(self.token.loc, f"Unexpected token '{self.token}', wanted parenthesized expression or "
|
raise UnexpectedTokenError(self.token, "parenthesized expression or number")
|
||||||
f"number")
|
|
||||||
|
|
||||||
def term(self) -> Value:
|
def term(self) -> Value:
|
||||||
return self.binary_op(self.factor, operators={
|
return self.binary_op(self.factor, operators={
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue