Parcourir la source

Fixed switch statement compilation when no match and result needed. Fixes #87

Dmitry Panov il y a 6 ans
Parent
commit
90fe3e56b5
2 fichiers modifiés avec 45 ajouts et 1 suppressions
  1. 4 1
      compiler_stmt.go
  2. 41 0
      compiler_test.go

+ 4 - 1
compiler_stmt.go

@@ -783,8 +783,11 @@ func (c *compiler) compileSwitchStatement(v *ast.SwitchStatement, needResult boo
 		c.compileStatements(s.Consequent, nr)
 	}
 	if jumpNoMatch != -1 {
+		if needResult {
+			c.emit(jump(2))
+		}
 		c.p.code[jumpNoMatch] = jump(len(c.p.code) - jumpNoMatch)
-		if len(v.Body) == 0 && needResult {
+		if needResult {
 			c.emit(loadUndef)
 		}
 	}

+ 41 - 0
compiler_test.go

@@ -1618,6 +1618,47 @@ func TestSwitchNoMatch(t *testing.T) {
 	testScript1(SCRIPT, _undefined, t)
 }
 
+func TestSwitchNoMatchNoDefault(t *testing.T) {
+	const SCRIPT = `
+		switch (1) {
+		case 0:
+		}
+	`
+
+	testScript1(SCRIPT, _undefined, t)
+}
+
+func TestSwitchNoMatchNoDefaultNoResult(t *testing.T) {
+	const SCRIPT = `
+		switch (1) {
+		case 0:
+		}
+		42;
+	`
+
+	testScript1(SCRIPT, intToValue(42), t)
+}
+
+func TestSwitchNoMatchNoDefaultNoResultMatch(t *testing.T) {
+	const SCRIPT = `
+		switch (1) {
+		case 1:
+		}
+		42;
+	`
+
+	testScript1(SCRIPT, intToValue(42), t)
+}
+
+func TestEmptySwitchNoResult(t *testing.T) {
+	const SCRIPT = `
+		switch (1) {}
+		42;
+	`
+
+	testScript1(SCRIPT, intToValue(42), t)
+}
+
 func TestGetOwnPropertyNames(t *testing.T) {
 	const SCRIPT = `
 	var o = {