Skip to content

Commit d5efe76

Browse files
committed
fix switch statements with empty expression (fixes #204)
1 parent e126332 commit d5efe76

File tree

3 files changed

+39
-10
lines changed

3 files changed

+39
-10
lines changed

compiler/expressions.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"strconv"
1010
"strings"
1111

12+
"github.com/gopherjs/gopherjs/compiler/analysis"
1213
"github.com/gopherjs/gopherjs/compiler/astutil"
1314
"github.com/gopherjs/gopherjs/compiler/typesutil"
1415

@@ -421,6 +422,15 @@ func (c *funcContext) translateExpr(expr ast.Expr) *expression {
421422
if _, ok := u.Elem().Underlying().(*types.Array); ok {
422423
return c.formatExpr("$equal(%s, %s, %s)", c.translateImplicitConversion(e.X, t), c.translateImplicitConversion(e.Y, t), c.typeName(u.Elem()))
423424
}
425+
case *types.Basic:
426+
if isBoolean(u) {
427+
if b, ok := analysis.BoolValue(e.X, c.p.Info.Info); ok && b {
428+
return c.translateExpr(e.Y)
429+
}
430+
if b, ok := analysis.BoolValue(e.Y, c.p.Info.Info); ok && b {
431+
return c.translateExpr(e.X)
432+
}
433+
}
424434
}
425435
return c.formatExpr("%s === %s", c.translateImplicitConversion(e.X, t), c.translateImplicitConversion(e.Y, t))
426436
default:

compiler/statements.go

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -67,17 +67,25 @@ func (c *funcContext) translateStmt(stmt ast.Stmt, label *types.Label) {
6767
if s.Init != nil {
6868
c.translateStmt(s.Init, nil)
6969
}
70-
var translateCond func(cond ast.Expr) *expression
71-
if s.Tag != nil {
70+
71+
tag := s.Tag
72+
if tag == nil {
73+
tag = ast.NewIdent("true")
74+
c.p.Types[tag] = types.TypeAndValue{Type: types.Typ[types.Bool], Value: exact.MakeBool(true)}
75+
}
76+
77+
if c.p.Types[tag].Value == nil {
7278
refVar := c.newVariable("_ref")
73-
c.Printf("%s = %s;", refVar, c.translateExpr(s.Tag))
74-
translateCond = func(cond ast.Expr) *expression {
75-
return c.translateExpr(&ast.BinaryExpr{
76-
X: c.newIdent(refVar, c.p.Types[s.Tag].Type),
77-
Op: token.EQL,
78-
Y: cond,
79-
})
80-
}
79+
c.Printf("%s = %s;", refVar, c.translateExpr(tag))
80+
tag = c.newIdent(refVar, c.p.Types[tag].Type)
81+
}
82+
83+
translateCond := func(cond ast.Expr) *expression {
84+
return c.translateExpr(&ast.BinaryExpr{
85+
X: tag,
86+
Op: token.EQL,
87+
Y: cond,
88+
})
8189
}
8290
c.translateBranchingStmt(s.Body.List, true, translateCond, nil, label, c.Flattened[s])
8391

tests/misc_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,3 +312,14 @@ func TestMapAssign(t *testing.T) {
312312
t.Fail()
313313
}
314314
}
315+
316+
func TestSwitchStatement(t *testing.T) {
317+
zero := 0
318+
var interfaceZero interface{} = zero
319+
switch {
320+
case interfaceZero:
321+
t.Fail()
322+
default:
323+
// ok
324+
}
325+
}

0 commit comments

Comments
 (0)