Skip to content

Commit 43d3c42

Browse files
committed
compiler: fix incorrect emitted Javascript for type switch
This brings the code emitted for a type switch with a *js.Object case in line with the runtime $assertType function. In the case of a *js.Object value, we have to dereference via .$val.object. Fixes #682
1 parent 2b1d432 commit 43d3c42

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

compiler/statements.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ func (c *funcContext) translateStmt(stmt ast.Stmt, label *types.Label) {
126126
if _, isInterface := implicit.Type().Underlying().(*types.Interface); !isInterface {
127127
value += ".$val"
128128
}
129+
if typesutil.IsJsObject(implicit.Type().Underlying()) {
130+
value += ".object"
131+
}
129132
bodyPrefix = []ast.Stmt{&ast.AssignStmt{
130133
Lhs: []ast.Expr{c.newIdent(c.objectName(implicit), implicit.Type())},
131134
Tok: token.DEFINE,

js/js_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,3 +571,28 @@ func TestUint8Array(t *testing.T) {
571571
t.Errorf("Non-empty byte array is not externalized as a Uint8Array")
572572
}
573573
}
574+
575+
func TestTypeSwitchJsObject(t *testing.T) {
576+
obj := js.Global.Get("Object").New()
577+
obj.Set("foo", "bar")
578+
579+
exp := "bar"
580+
581+
if act := obj.Get("foo").String(); act != exp {
582+
t.Fatalf("Direct access to *js.Object field gave %q; expected %q", act, exp)
583+
}
584+
585+
var x interface{} = obj
586+
switch x := x.(type) {
587+
case *js.Object:
588+
if act := x.Get("foo").String(); act != exp {
589+
t.Fatalf("Value passed through interface and type switch gave %q; expected %q", act, exp)
590+
}
591+
}
592+
593+
if y, ok := x.(*js.Object); ok {
594+
if act := y.Get("foo").String(); act != exp {
595+
t.Fatalf("Value passed through interface and type assert gave %q; expected %q", act, exp)
596+
}
597+
}
598+
}

0 commit comments

Comments
 (0)