From afcde0a69b921df9596edb834749cab94554e708 Mon Sep 17 00:00:00 2001 From: mappu Date: Sat, 10 Aug 2024 12:54:26 +1200 Subject: [PATCH] genbindings: inheritance support --- cmd/genbindings/clang2il.go | 20 ++++++++++++++++++++ cmd/genbindings/emitgo.go | 15 ++++++++++++++- cmd/genbindings/intermediate.go | 2 +- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/cmd/genbindings/clang2il.go b/cmd/genbindings/clang2il.go index 1f1eab1d..0baa9422 100644 --- a/cmd/genbindings/clang2il.go +++ b/cmd/genbindings/clang2il.go @@ -76,6 +76,26 @@ func processClassType(node map[string]interface{}, className string) (CppClass, } } + // Check if this (publicly) inherits another class + if bases, ok := node["bases"].([]interface{}); ok { + for _, base := range bases { + base, ok := base.(map[string]interface{}) + if !ok { + continue + } + + access, ok := base["access"].(string) + if !(ok && access == "public") { + continue + } + + if typ, ok := base["type"].(map[string]interface{}); ok { + if qualType, ok := typ["qualType"].(string); ok { + ret.Inherits = append(ret.Inherits, qualType) + } + } + } + } // Parse all methods diff --git a/cmd/genbindings/emitgo.go b/cmd/genbindings/emitgo.go index ee4f26cb..be424319 100644 --- a/cmd/genbindings/emitgo.go +++ b/cmd/genbindings/emitgo.go @@ -93,6 +93,14 @@ import "C" ret.WriteString(` type ` + c.ClassName + ` struct { h C.P` + c.ClassName + ` + `) + + // Embed all inherited types to directly allow calling inherited methods + for _, base := range c.Inherits { + ret.WriteString(base + "\n") + } + + ret.WriteString(` } func (this *` + c.ClassName + `) cPointer() C.P` + c.ClassName + ` { @@ -104,13 +112,18 @@ import "C" `) + localInit := "h: ret" + for _, base := range c.Inherits { + localInit += ", " + base + ": " + base + "{h: ret}" + } + for i, ctor := range c.Ctors { preamble, forwarding := emitParametersGo2CABIForwarding(ctor) ret.WriteString(` // New` + c.ClassName + maybeSuffix(i) + ` constructs a new ` + c.ClassName + ` object. func New` + c.ClassName + maybeSuffix(i) + `(` + emitParametersGo(ctor.Parameters) + `) { ` + preamble + ` ret := C.` + c.ClassName + `_new` + maybeSuffix(i) + `(` + forwarding + `) - return &` + c.ClassName + `{h: ret} + return &` + c.ClassName + `{` + localInit + `} } `) diff --git a/cmd/genbindings/intermediate.go b/cmd/genbindings/intermediate.go index 77778e2f..1ac2adcd 100644 --- a/cmd/genbindings/intermediate.go +++ b/cmd/genbindings/intermediate.go @@ -71,7 +71,7 @@ type CppClass struct { ClassName string Abstract bool Ctors []CppMethod // only use the parameters - Extends []string + Inherits []string // other class names Methods []CppMethod Props []CppProperty }