Skip to content

Commit

Permalink
challenge 7.2 done
Browse files Browse the repository at this point in the history
  • Loading branch information
BaLiKfromUA committed May 10, 2023
1 parent ddedab3 commit b91c23d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
12 changes: 1 addition & 11 deletions pylox/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,22 +50,12 @@ def run(self, src: str) -> None:
tokens = Scanner(src).scan_tokens()
ast = Parser(tokens, self.report_error).parse()
if ast is not None:
print(self.stringify(self.interpreter.evaluate(ast)))
print(self.interpreter.interpret(ast))
except LoxSyntaxError as e:
self.report_error(e)
except LoxRuntimeError as e:
self.report_runtime_error(e)

@staticmethod
def stringify(value: typing.Any) -> str:
if value is None:
return "nil"

if type(value) is float and float(value).is_integer():
return str(int(value))

return str(value)

@staticmethod
def _build_error_string(err: LoxException) -> str:
return f"{err.line + 1}: [bold red]{err.message}[/bold red]"
Expand Down
18 changes: 17 additions & 1 deletion pylox/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@


class Interpreter(ast.ExprVisitor):
def interpret(self, expr: ast.Expr):
return self.stringify(self.evaluate(expr))

def evaluate(self, expr: ast.Expr) -> typing.Any:
return expr.accept(self)

Expand Down Expand Up @@ -40,9 +43,12 @@ def visit_binary_expr(self, expr: ast.Binary):
if type(left) is str and type(right) is str:
return left + right

if type(left) is str or type(right) is str:
return str(left) + str(right)

raise LoxRuntimeError(
expr.operator,
"Operands must be two numbers of two strings.",
"Operands must be numbers or strings.",
)
case TokenType.SLASH:
self.check_number_operands(expr.operator, left, right)
Expand Down Expand Up @@ -96,3 +102,13 @@ def check_number_operands(op: Token, left, right: typing.Any) -> None:
if Interpreter.is_number(left) and Interpreter.is_number(right):
return
raise LoxRuntimeError(op, "Operands must be a numbers.")

@staticmethod
def stringify(value: typing.Any) -> str:
if value is None:
return "nil"

if type(value) is float and float(value).is_integer():
return str(int(value))

return str(value)

0 comments on commit b91c23d

Please sign in to comment.