From bb783f8f31797597ca0349434e236e6df923e14b Mon Sep 17 00:00:00 2001 From: Marc Vertes Date: Tue, 7 Nov 2023 21:49:01 +0100 Subject: parser: implement switch statement A VM instruction `EqualSet` has been added to preserve the left operand on the stack in case of failure, to allow efficient multiple tests on the same value. Both the pattern 'if/else if' and the classical case clauses have been implemented. --- parser/interpreter_test.go | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) (limited to 'parser/interpreter_test.go') diff --git a/parser/interpreter_test.go b/parser/interpreter_test.go index 02cd105..d73d282 100644 --- a/parser/interpreter_test.go +++ b/parser/interpreter_test.go @@ -125,22 +125,33 @@ f(3)`, res: "4"}, }) } -/* func TestSwitch(t *testing.T) { - run(t, []etest{{ - src: ` -func f(a int) int { + src0 := `func f(a int) int { switch a { - default: - a = 0 - case 1,2: - a = a+1 - case 3: - a = a+2 + default: a = 0 + case 1,2: a = a+1 + case 3: a = a+2 + } + return a +} +` + src1 := `func f(a int) int { + switch { + case a < 3: return 2 + case a < 5: return 5 + default: a = 0 } return a } -f(3)`, res: "5"}, +` + run(t, []etest{ + {src: src0 + "f(1)", res: "2"}, + {src: src0 + "f(2)", res: "3"}, + {src: src0 + "f(3)", res: "5"}, + {src: src0 + "f(4)", res: "0"}, + + {src: src1 + "f(1)", res: "2"}, + {src: src1 + "f(4)", res: "5"}, + {src: src1 + "f(6)", res: "0"}, }) } -*/ -- cgit v1.2.3