Skip to content

Spike: Simplified calculator #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions lark-sandbox/calculator.lark
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
expression : term ((PLUS | MINUS) term)*

term : factor ((MULTIPLY | DIVIDE) factor)*

factor : (PLUS | MINUS) factor
| power

power : primary (POWER factor)*

primary : NUMBER
| "(" expression ")"

PLUS : "+"
MINUS : "-"
MULTIPLY : "*"
DIVIDE : "/"
POWER : "**"

%import common.WS_INLINE
%import common.NUMBER

%ignore WS_INLINE
12 changes: 12 additions & 0 deletions lark-sandbox/calculator_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import os

from lark import Lark

grammar = open(os.path.join(os.path.dirname(__file__), "calculator.lark"), "r").read()
parser = Lark(grammar, start="expression")


def test_calculator():
ast = parser.parse("(1 + 2) * 3 - -4 ** 5")
assert ast
print(ast.pretty())
1 change: 0 additions & 1 deletion lark-sandbox/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ addopts =
# Print all `print(...)` statements in the console
--capture=no
# pytest-cov:
--cov=app
--cov-report=term:skip-covered
--cov-report=html
--cov-report=xml
Expand Down
34 changes: 34 additions & 0 deletions src/Calculator/Expression.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { BinaryOperator, UnaryOperator } from "./TokenType";

export abstract class Expression {}

export class BinaryOperation extends Expression {
constructor(
public readonly left: Expression,
public readonly operator: BinaryOperator,
public readonly right: Expression
) {
super();
}
}

export class UnaryOperation extends Expression {
constructor(
public readonly operator: UnaryOperator,
public readonly child: Expression
) {
super();
}
}

export class VariableAccess extends Expression {
constructor(public readonly name: string) {
super();
}
}

export class NumberLiteral extends Expression {
constructor(public readonly value: number) {
super();
}
}
41 changes: 41 additions & 0 deletions src/Calculator/Interpreter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { UndefinedVariableError, ZeroDivisionError } from "./errors";
import { Interpreter, SymbolTable } from "./Interpreter";
import { Parser } from "./Parser";
import { Tokenizer } from "./Tokenizer";

describe("Interpreter", () => {
it("evaluates", () => {
const tokens = new Tokenizer("1 + 2 * 3").tokenize();
const expression = new Parser(tokens).parse();
const interpreter = new Interpreter(expression);

expect(interpreter.evaluate()).toBe(7);
});

it("evaluates with variables", () => {
const tokens = new Tokenizer("1 + foo + bar").tokenize();
const expression = new Parser(tokens).parse();
const variables: SymbolTable = { foo: 2, bar: 3 };
const interpreter = new Interpreter(expression, variables);

expect(interpreter.evaluate()).toBe(6);
});

it("raises an error when variable is not defined", () => {
const tokens = new Tokenizer("1 + foo + bar").tokenize();
const expression = new Parser(tokens).parse();
const interpreter = new Interpreter(expression);

expect(() => interpreter.evaluate()).toThrow(UndefinedVariableError);
expect(() => interpreter.evaluate()).toThrow("Variable foo is not defined");
});

it("raises an error on division by zero", () => {
const tokens = new Tokenizer("1/0").tokenize();
const expression = new Parser(tokens).parse();
const interpreter = new Interpreter(expression);

expect(() => interpreter.evaluate()).toThrow(ZeroDivisionError);
expect(() => interpreter.evaluate()).toThrow("Division by zero");
});
});
94 changes: 94 additions & 0 deletions src/Calculator/Interpreter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { UndefinedVariableError, ZeroDivisionError } from "./errors";
import {
BinaryOperation,
Expression,
NumberLiteral,
UnaryOperation,
VariableAccess,
} from "./Expression";

export type SymbolTable = Record<string, number>;

export class Interpreter {
constructor(
private readonly expression: Expression,
private readonly symbolTable: SymbolTable = {}
) {}

public evaluate(): number {
return this.visitExpression(this.expression);
}

private visitExpression(expression: Expression): number {
if (expression instanceof BinaryOperation) {
return this.visitBinaryOperation(expression);
}

if (expression instanceof UnaryOperation) {
return this.visitUnaryOperation(expression);
}

if (expression instanceof VariableAccess) {
return this.visitVariableAccess(expression);
}

if (expression instanceof NumberLiteral) {
return this.visitNumberLiteral(expression);
}

return 0;
}

private visitBinaryOperation(expression: BinaryOperation): number {
const left = this.visitExpression(expression.left);
const right = this.visitExpression(expression.right);

switch (expression.operator) {
case "+":
return left + right;
case "-":
return left + right;
case "*":
return left * right;
case "/": {
if (right === 0) {
throw new ZeroDivisionError();
}

return left / right;
}
case "**":
return left ** right;
default:
throw new Error(`Unsupported binary operator ${expression.operator}`);
}
}

private visitUnaryOperation(expression: UnaryOperation) {
const value = this.visitExpression(expression.child);

switch (expression.operator) {
case "+":
return value;
case "-":
return value * -1;
default:
throw new Error(`Unsupported unary operator ${expression.operator}`);
}
}

private visitVariableAccess(expression: VariableAccess): number {
const name = expression.name;
const value = this.symbolTable[name];

if (value === undefined) {
throw new UndefinedVariableError(name);
}

return value;
}

private visitNumberLiteral(expression: NumberLiteral) {
return expression.value;
}
}
54 changes: 54 additions & 0 deletions src/Calculator/Parser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { IllegalTokenError } from "./errors";
import {
BinaryOperation,
NumberLiteral,
UnaryOperation,
VariableAccess,
} from "./Expression";
import { Parser } from "./Parser";
import { Tokenizer } from "./Tokenizer";

describe("Parser", () => {
it("generates a valid AST", () => {
const tokens = new Tokenizer("(1.5 + 2) * 3 - -foo ** 5").tokenize();
const expression = new Parser(tokens).parse();

expect(expression).toEqual(
new BinaryOperation(
new BinaryOperation(
new BinaryOperation(
new NumberLiteral(1.5),
"+",
new NumberLiteral(2)
),
"*",
new NumberLiteral(3)
),
"-",
new UnaryOperation(
"-",
new BinaryOperation(
new VariableAccess("foo"),
"**",
new NumberLiteral(5)
)
)
)
);
});

it.each`
input | error
${"(1 + 2 *"} | ${"Unexpected 'eof' at position 8"}
${"** **"} | ${"Unexpected '**' at position 0"}
${"1 2"} | ${"Expected 'eof' but got 'number' at position 2"}
`(
"throws error when the given input has invalid syntax",
({ input, error }) => {
const tokens = new Tokenizer(input).tokenize();

expect(() => new Parser(tokens).parse()).toThrow(IllegalTokenError);
expect(() => new Parser(tokens).parse()).toThrow(error);
}
);
});
126 changes: 126 additions & 0 deletions src/Calculator/Parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { IllegalTokenError } from "./errors";
import {
Expression,
BinaryOperation,
NumberLiteral,
UnaryOperation,
VariableAccess,
} from "./Expression";
import { Token } from "./Token";
import { TokenType } from "./TokenType";

export class Parser {
private position = 0;

constructor(private tokens: Token[]) {}

parse(): Expression {
const expression = this.expression();
this.consume("eof");

return expression;
}

// term ((PLUS | MINUS) term)*
private expression(): Expression {
let left = this.term();

while (this.currentToken.type === "+" || this.currentToken.type === "-") {
const operator = this.currentToken.type;
this.consume(operator);

left = new BinaryOperation(left, operator, this.term());
}

return left;
}

// factor ((MULTIPLY | DIVIDE) factor)*
private term(): Expression {
let left = this.factor();

while (this.currentToken.type === "*" || this.currentToken.type === "/") {
const operator = this.currentToken.type;
this.consume(operator);

left = new BinaryOperation(left, operator, this.factor());
}

return left;
}

// : (PLUS | MINUS) factor
// | power
private factor(): Expression {
if (this.currentToken.type === "+" || this.currentToken.type === "-") {
const operator = this.currentToken.type;
this.consume(operator);

return new UnaryOperation(operator, this.factor());
}

return this.power();
}

// primary (POWER factor)*
private power(): Expression {
let left = this.primary();

while (this.currentToken.type === "**") {
this.consume("**");
left = new BinaryOperation(left, "**", this.factor());
}

return left;
}

// : NUMBER
// | IDENTIFIER
// | group
private primary(): Expression {
if (this.currentToken.type === "number") {
const value = this.currentToken.value as number;
this.consume("number");

return new NumberLiteral(value);
}

if (this.currentToken.type === "identifier") {
const name = this.currentToken.value as string;
this.consume("identifier");

return new VariableAccess(name);
}

if (this.currentToken.type === "(") {
return this.group();
}

throw new IllegalTokenError(this.currentToken);
}

// "(" expression ")"
private group(): Expression {
this.consume("(");
const expression = this.expression();
this.consume(")");

return expression;
}

private get currentToken(): Token {
return this.tokens[this.position];
}

private consume(tokenType: TokenType): void {
if (this.currentToken.type !== tokenType) {
throw new IllegalTokenError(this.currentToken, tokenType);
}

this.advance();
}

private advance() {
this.position += 1;
}
}
Loading