2021-03-03 14:01:32 +00:00
|
|
|
package spec
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
2023-05-24 11:01:50 +00:00
|
|
|
"git.kmsign.com/royalcat/repogen/internal/code"
|
2021-03-03 14:01:32 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// FieldReference is a reference path to access to the field
|
|
|
|
type FieldReference []code.StructField
|
|
|
|
|
|
|
|
// ReferencedField returns the last struct field
|
|
|
|
func (r FieldReference) ReferencedField() code.StructField {
|
|
|
|
return r[len(r)-1]
|
|
|
|
}
|
|
|
|
|
2022-11-09 04:21:11 +00:00
|
|
|
// ReferencingCode returns a string containing name of the referenced fields
|
|
|
|
// concatenating with period (.).
|
2021-05-03 07:12:58 +00:00
|
|
|
func (r FieldReference) ReferencingCode() string {
|
|
|
|
var fieldNames []string
|
|
|
|
for _, field := range r {
|
|
|
|
fieldNames = append(fieldNames, field.Name)
|
|
|
|
}
|
|
|
|
return strings.Join(fieldNames, ".")
|
|
|
|
}
|
|
|
|
|
2021-03-03 14:01:32 +00:00
|
|
|
type fieldResolver struct {
|
2022-10-17 10:57:49 +00:00
|
|
|
Structs map[string]code.Struct
|
2021-03-03 14:01:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r fieldResolver) ResolveStructField(structModel code.Struct, tokens []string) (FieldReference, bool) {
|
|
|
|
fieldName := strings.Join(tokens, "")
|
|
|
|
field, ok := structModel.Fields.ByName(fieldName)
|
|
|
|
if ok {
|
|
|
|
return FieldReference{field}, true
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := len(tokens) - 1; i > 0; i-- {
|
|
|
|
fieldName := strings.Join(tokens[:i], "")
|
|
|
|
field, ok := structModel.Fields.ByName(fieldName)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
fieldSimpleType, ok := getSimpleType(field.Type)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2022-10-17 10:57:49 +00:00
|
|
|
childStruct, ok := r.Structs[fieldSimpleType.Code()]
|
2021-03-03 14:01:32 +00:00
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
fields, ok := r.ResolveStructField(childStruct, tokens[i:])
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
return append(FieldReference{field}, fields...), true
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, false
|
|
|
|
}
|
|
|
|
|
|
|
|
func getSimpleType(t code.Type) (code.SimpleType, bool) {
|
|
|
|
switch t := t.(type) {
|
|
|
|
case code.SimpleType:
|
|
|
|
return t, true
|
|
|
|
case code.PointerType:
|
|
|
|
return getSimpleType(t.ContainedType)
|
|
|
|
default:
|
|
|
|
return "", false
|
|
|
|
}
|
|
|
|
}
|