bind: add __str__ support for all types

Change-Id: I08693a03f232fe1d8e91233f5e40d1dcdad6e316
This commit is contained in:
Sebastien Binet 2015-08-05 11:34:16 +02:00
parent a03b288886
commit 114a95e0ba
2 changed files with 42 additions and 35 deletions

View File

@ -767,40 +767,7 @@ func (g *cpyGen) genStructProtocols(cpy Struct) {
}
func (g *cpyGen) genStructTPStr(cpy Struct) {
g.decl.Printf("\n/* __str__ support for %[1]s.%[2]s */\n",
cpy.pkg.Name(),
cpy.sym.goname,
)
g.decl.Printf(
"static PyObject*\ncpy_func_%s_tp_str(PyObject *self);\n",
cpy.sym.id,
)
g.impl.Printf(
"static PyObject*\ncpy_func_%s_tp_str(PyObject *self) {\n",
cpy.sym.id,
)
if (cpy.prots & ProtoStringer) == 0 {
g.impl.Indent()
g.impl.Printf("return PyObject_Repr(self);\n")
g.impl.Outdent()
g.impl.Printf("}\n\n")
return
}
var m Func
for _, f := range cpy.meths {
if f.GoName() == "String" {
m = f
break
}
}
g.impl.Indent()
g.impl.Printf("return cpy_func_%[1]s(self, 0);\n", m.ID())
g.impl.Outdent()
g.impl.Printf("}\n\n")
g.genTypeTPStr(cpy.sym)
}
func (g *cpyGen) genStructConverters(cpy Struct) {
@ -1034,7 +1001,14 @@ func (g *cpyGen) genTypeTPStr(sym *symbol) {
)
g.impl.Indent()
g.impl.Printf("return PyObject_Repr(self);\n")
g.impl.Printf("%[1]s c_self = ((%[2]s*)self)->cgopy;\n",
sym.cgoname,
sym.cpyname,
)
g.impl.Printf("GoString str = cgo_func_%[1]s_str(c_self);\n",
sym.id,
)
g.impl.Printf("return cgopy_cnv_c2py_string(&str);\n")
g.impl.Outdent()
g.impl.Printf("}\n\n")
}

View File

@ -26,6 +26,7 @@ package main
import "C"
import (
"fmt"
"sync"
"unsafe"
@ -33,6 +34,7 @@ import (
)
var _ = unsafe.Pointer(nil)
var _ = fmt.Sprintf
// --- begin cgo helpers ---
@ -351,6 +353,25 @@ func (g *goGen) genStruct(s Struct) {
g.Printf("return (cgo_type_%[1]s)(unsafe.Pointer(&o))\n", s.ID())
g.Outdent()
g.Printf("}\n\n")
// support for __str__
g.Printf("//export cgo_func_%[1]s_str\n", s.ID())
g.Printf(
"func cgo_func_%[1]s_str(self %[2]s) string {\n",
s.ID(),
s.sym.cgoname,
)
g.Indent()
if (s.prots & ProtoStringer) == 0 {
g.Printf("return fmt.Sprintf(\"%%#v\", ")
g.Printf("*(*%[1]s.%[2]s)(unsafe.Pointer(self)))\n", pkgname, s.GoName())
} else {
g.Printf("return (*%[1]s.%[2]s)(unsafe.Pointer(self)).String()\n",
pkgname, s.GoName(),
)
}
g.Outdent()
g.Printf("}\n\n")
}
func (g *goGen) genMethod(s Struct, m Func) {
@ -507,6 +528,18 @@ func (g *goGen) genType(sym *symbol) {
g.Outdent()
g.Printf("}\n\n")
// support for __str__
g.Printf("//export cgo_func_%[1]s_str\n", sym.id)
g.Printf(
"func cgo_func_%[1]s_str(self %[2]s) string {\n",
sym.id,
sym.cgoname,
)
g.Indent()
g.Printf("return fmt.Sprintf(\"%%#v\", ")
g.Printf("*(*%[1]s)(unsafe.Pointer(self)))\n", sym.goname)
g.Outdent()
g.Printf("}\n\n")
}
func (g *goGen) genPreamble() {