Skip to content

Commit 5fc26c0

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 c7ececa commit 5fc26c0

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

compiler/statements.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,9 @@ func (c *funcContext) translateStmt(stmt ast.Stmt, label *types.Label) {
123123
var bodyPrefix []ast.Stmt
124124
if implicit := c.p.Implicits[clause]; implicit != nil {
125125
value := refVar
126-
if _, isInterface := implicit.Type().Underlying().(*types.Interface); !isInterface {
126+
if typesutil.IsJsObject(implicit.Type().Underlying()) {
127+
value += ".$val.object"
128+
} else if _, ok := implicit.Type().Underlying().(*types.Interface); !ok {
127129
value += ".$val"
128130
}
129131
bodyPrefix = []ast.Stmt{&ast.AssignStmt{

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)