Skip to content

Commit

Permalink
support return statement and closure (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
wcho21 authored Dec 22, 2023
1 parent e89852e commit 6f7fafa
Show file tree
Hide file tree
Showing 11 changed files with 340 additions and 117 deletions.
12 changes: 12 additions & 0 deletions src/evaluator/evaluated/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import {
makeEvaluatedBoolean,
makeEvaluatedFunction,
makeEvaluatedEmpty,
wrapReturnValue,
} from "./";
import type { Evaluated } from "./";
import type {
FunctionExpression
} from "../../parser/syntax-tree";
Expand Down Expand Up @@ -80,3 +82,13 @@ describe("makeEvaluatedEmpty()", () => {
expect(evaluated.representation).toBe("(๋น„์–ด์žˆ์Œ)");
});
});

describe("wrapReturnValue()", () => {
it("wrap return value", () => {
const valueMock = {} as Evaluated;

const wrapped = wrapReturnValue(valueMock);

expect(wrapped.type).toBe("return value");
});
});
11 changes: 11 additions & 0 deletions src/evaluator/evaluated/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ export interface EvaluatedEmpty extends EvaluatedBase {
readonly type: "empty";
}

export interface ReturnValue {
readonly type: "return value";
readonly value: Evaluated;
}

export type Evaluated =
EvaluatedPrimitive |
EvaluatedFunction |
Expand Down Expand Up @@ -93,3 +98,9 @@ export const makeEvaluatedEmpty: MakeEvaluatedEmpty = () => ({
return "(๋น„์–ด์žˆ์Œ)";
},
});

export type WrapReturnValue = (value: Evaluated) => ReturnValue;
export const wrapReturnValue: WrapReturnValue = value => ({
type: "return value",
value,
});
24 changes: 23 additions & 1 deletion src/evaluator/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,31 @@ describe("evaluate()", () => {
const cases = [
{
name: "function call with function literal",
input: "ํ•จ์ˆ˜(๋ฐ”๋‚˜๋‚˜) { ๋ฐ”๋‚˜๋‚˜ + 1 }(42)",
input: "ํ•จ์ˆ˜(๋ฐ”๋‚˜๋‚˜) { ๊ฒฐ๊ณผ ๋ฐ”๋‚˜๋‚˜ + 1 }(42)",
expected: 43,
},
{
name: "function call with identifier",
input: "๋”ํ•˜๊ธฐ = ํ•จ์ˆ˜(์ˆซ์ž1, ์ˆซ์ž2) { ๊ฒฐ๊ณผ ์ˆซ์ž1 + ์ˆซ์ž2 } ๋”ํ•˜๊ธฐ(3, 4)",
expected: 7,
},
];

it.each(cases)("evaluate $name", testEvaluatingPrimitive);
});

describe("complex statements with function and calls", () => {
const cases = [
{
name: "make and call function containing branch statement",
input: "๊ณผ์ผ = ํ•จ์ˆ˜(์ƒ‰๊น”) { ๋งŒ์•ฝ (์ƒ‰๊น” == '๋นจ๊ฐ•') { ๊ฒฐ๊ณผ '์‚ฌ๊ณผ' } ์•„๋‹ˆ๋ฉด { 'ํฌ๋„' } } ๊ณผ์ผ('๋นจ๊ฐ•')",
expected: "์‚ฌ๊ณผ",
},
{
name: "make and call closure",
input: "๋”ํ•˜๊ธฐ = ํ•จ์ˆ˜(์ˆซ์ž1) { ๊ฒฐ๊ณผ ํ•จ์ˆ˜(์ˆซ์ž2) { ๊ฒฐ๊ณผ ์ˆซ์ž1+์ˆซ์ž2 } } ํ•˜๋‚˜๋”ํ•˜๊ธฐ = ๋”ํ•˜๊ธฐ(1) ํ•˜๋‚˜๋”ํ•˜๊ธฐ(4)",
expected: 5,
},
];

it.each(cases)("evaluate $name", testEvaluatingPrimitive);
Expand Down
Loading

0 comments on commit 6f7fafa

Please sign in to comment.