5
0
mirror of https://github.com/wailsapp/wails.git synced 2025-05-02 20:03:01 +08:00

Support anonymous struct fields

This commit is contained in:
Lea Anthony 2023-02-25 08:24:58 +11:00
parent cd11c0a83c
commit cc1a6a3d50
No known key found for this signature in database
GPG Key ID: 33DAF7BB90A58405
3 changed files with 48 additions and 6 deletions

View File

@ -62,6 +62,7 @@ type Project struct {
Path string
BoundMethods map[packagePath]map[structName][]*BoundMethod
Models map[packagePath]map[structName]*StructDef
anonymousStructIDCounter int
}
func ParseProject(projectPath string) (*Project, error) {
@ -353,6 +354,20 @@ func (p *Project) parseParameterType(field *ast.Field, pkg *ParsedPackage) *Para
result.IsPointer = true
case *ast.StructType:
result.IsStruct = true
if result.Name == "" {
// Anonymous struct
result.Name = p.anonymousStructID()
// Create a new struct definition
result := &StructDef{
Name: result.Name,
}
pkg.StructCache[result.Name] = result
// Parse the fields
result.Fields = p.parseStructFields(&ast.StructType{
Fields: t.Fields,
}, pkg)
_ = result
}
case *ast.SelectorExpr:
extPackage, err := p.getParsedPackageFromName(t.X.(*ast.Ident).Name, pkg)
if err != nil {
@ -503,6 +518,11 @@ func (p *Project) getPackageFromPath(packagedir string, packagepath string) (*as
return nil, fmt.Errorf("package not found in imported package %s", packagepath)
}
func (p *Project) anonymousStructID() string {
p.anonymousStructIDCounter++
return fmt.Sprintf("anon%d", p.anonymousStructIDCounter)
}
func getTypeString(expr ast.Expr) string {
switch t := expr.(type) {
case *ast.Ident:
@ -516,7 +536,7 @@ func getTypeString(expr ast.Expr) string {
case *ast.SelectorExpr:
return getTypeString(t.Sel)
default:
return "any"
return ""
}
}

View File

@ -865,6 +865,25 @@ func TestParseDirectory(t *testing.T) {
Package: "main",
},
},
{
Name: "Details",
Type: &ParameterType{
Name: "anon1",
IsStruct: true,
Package: "main",
},
},
},
},
"anon1": {
Name: "anon1",
Fields: []*Field{
{
Name: "Age",
Type: &ParameterType{
Name: "int",
},
},
},
},
},

View File

@ -11,6 +11,9 @@ import (
type Person struct {
Name string
Parent *Person
Details struct {
Age int
}
}
// GreetService is great