transform: optimize reflect.Type Implements() method

This commit adds a new transform that converts reflect Implements()
calls to runtime.interfaceImplements. At the moment, the Implements()
method is not yet implemented (how ironic) but if the value passed to
Implements is known at compile time the method call can be optimized to
runtime.interfaceImplements to make it a regular interface assert.

This commit is the last change necessary to add basic support for the
encoding/json package. The json package is certainly not yet fully
supported, but some trivial objects can be converted to JSON.
This commit is contained in:
Ayke van Laethem
2021-03-24 16:07:44 +01:00
committed by Ron Evans
parent c5ec955081
commit bcce296ca3
12 changed files with 242 additions and 8 deletions
+20
View File
@@ -0,0 +1,20 @@
package main
import (
"encoding/json"
)
func main() {
println("int:", encode(3))
println("float64:", encode(3.14))
println("string:", encode("foo"))
println("slice of strings:", encode([]string{"foo", "bar"}))
}
func encode(itf interface{}) string {
buf, err := json.Marshal(itf)
if err != nil {
panic("failed to JSON encode: " + err.Error())
}
return string(buf)
}
+4
View File
@@ -0,0 +1,4 @@
int: 3
float64: 3.14
string: "foo"
slice of strings: ["foo","bar"]
+16
View File
@@ -1,6 +1,7 @@
package main
import (
"errors"
"reflect"
"unsafe"
)
@@ -28,6 +29,14 @@ type (
}
)
var (
errorValue = errors.New("test error")
errorType = reflect.TypeOf((*error)(nil)).Elem()
stringerType = reflect.TypeOf((*interface {
String() string
})(nil)).Elem()
)
func main() {
println("matching types")
println(reflect.TypeOf(int(3)) == reflect.TypeOf(int(5)))
@@ -285,6 +294,13 @@ func main() {
println("PtrTo failed for type myslice")
}
if reflect.TypeOf(errorValue).Implements(errorType) != true {
println("errorValue.Implements(errorType) was false, expected true")
}
if reflect.TypeOf(errorValue).Implements(stringerType) != false {
println("errorValue.Implements(errorType) was true, expected false")
}
println("\nstruct tags")
TestStructTag()
}