Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

slight refactoring regarding fields package #90

Merged
merged 4 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 5 additions & 20 deletions analyzer/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,23 @@ import (
"golang.org/x/tools/go/ast/inspector"

"github.com/GaijinEntertainment/go-exhaustruct/v3/internal/comment"
"github.com/GaijinEntertainment/go-exhaustruct/v3/internal/fields"
"github.com/GaijinEntertainment/go-exhaustruct/v3/internal/pattern"
"github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure"
)

type analyzer struct {
include pattern.List `exhaustruct:"optional"`
exclude pattern.List `exhaustruct:"optional"`

fieldsCache map[types.Type]fields.StructFields
fieldsCacheMu sync.RWMutex `exhaustruct:"optional"`

comments comment.Cache
structFields structure.FieldsCache `exhaustruct:"optional"`
comments comment.Cache `exhaustruct:"optional"`

typeProcessingNeed map[string]bool
typeProcessingNeedMu sync.RWMutex `exhaustruct:"optional"`
}

func NewAnalyzer(include, exclude []string) (*analysis.Analyzer, error) {
a := analyzer{
fieldsCache: make(map[types.Type]fields.StructFields),
typeProcessingNeed: make(map[string]bool),
comments: comment.Cache{},
}
Expand Down Expand Up @@ -271,24 +268,12 @@ func (a *analyzer) shouldProcessType(info *TypeInfo) bool {
return res
}

//revive:disable-next-line:unused-receiver
func (a *analyzer) litSkippedFields(
lit *ast.CompositeLit,
typ *types.Struct,
onlyExported bool,
) fields.StructFields {
a.fieldsCacheMu.RLock()
f, ok := a.fieldsCache[typ]
a.fieldsCacheMu.RUnlock()

if !ok {
a.fieldsCacheMu.Lock()
f = fields.NewStructFields(typ)
a.fieldsCache[typ] = f
a.fieldsCacheMu.Unlock()
}

return f.SkippedFields(lit, onlyExported)
) structure.Fields {
return a.structFields.Get(typ).Skipped(lit, onlyExported)
}

type TypeInfo struct {
Expand Down
35 changes: 35 additions & 0 deletions internal/structure/fields-cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package structure

import (
"go/types"
"sync"
)

type FieldsCache struct {
fields map[*types.Struct]Fields
mu sync.RWMutex
}

// Get returns a struct fields for a given type. In case if a struct fields is
// not found, it creates a new one from type definition.
func (c *FieldsCache) Get(typ *types.Struct) Fields {
c.mu.RLock()
fields, ok := c.fields[typ]
c.mu.RUnlock()

if ok {
return fields
}

c.mu.Lock()
defer c.mu.Unlock()

if c.fields == nil {
c.fields = make(map[*types.Struct]Fields)
}

fields = NewFields(typ)
c.fields[typ] = fields

return fields
}
43 changes: 23 additions & 20 deletions internal/fields/struct.go → internal/structure/fields.go
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
package fields
package structure

import (
"go/ast"
"go/types"
"reflect"
"strings"
)

const (
TagName = "exhaustruct"
OptionalTagValue = "optional"
tagName = "exhaustruct"
optionalTagValue = "optional"
)

type StructField struct {
type Field struct {
Name string
Exported bool
Optional bool
}

type StructFields []*StructField
type Fields []*Field

// NewStructFields creates a new [StructFields] from a given struct type.
// StructFields items are listed in order they appear in the struct.
func NewStructFields(strct *types.Struct) StructFields {
sf := make(StructFields, 0, strct.NumFields())
// NewFields creates a new [Fields] from a given struct type.
// Fields items are listed in order they appear in the struct.
func NewFields(strct *types.Struct) Fields {
sf := make(Fields, 0, strct.NumFields())

for i := 0; i < strct.NumFields(); i++ {
f := strct.Field(i)

sf = append(sf, &StructField{
sf = append(sf, &Field{
Name: f.Name(),
Exported: f.Exported(),
Optional: HasOptionalTag(strct.Tag(i)),
Expand All @@ -38,27 +39,29 @@ func NewStructFields(strct *types.Struct) StructFields {
}

func HasOptionalTag(tags string) bool {
return reflect.StructTag(tags).Get(TagName) == OptionalTagValue
return reflect.StructTag(tags).Get(tagName) == optionalTagValue
}

// String returns a comma-separated list of field names.
func (sf StructFields) String() (res string) {
func (sf Fields) String() string {
b := strings.Builder{}

for i := 0; i < len(sf); i++ {
if res != "" {
res += ", "
if b.Len() != 0 {
b.WriteString(", ")
}

res += sf[i].Name
b.WriteString(sf[i].Name)
}

return res
return b.String()
}

// SkippedFields returns a list of fields that are not present in the given
// Skipped returns a list of fields that are not present in the given
// literal, but expected to.
//
//revive:disable-next-line:cyclomatic
func (sf StructFields) SkippedFields(lit *ast.CompositeLit, onlyExported bool) StructFields {
func (sf Fields) Skipped(lit *ast.CompositeLit, onlyExported bool) Fields {
if len(lit.Elts) != 0 && !isNamedLiteral(lit) {
if len(lit.Elts) == len(sf) {
return nil
Expand All @@ -68,7 +71,7 @@ func (sf StructFields) SkippedFields(lit *ast.CompositeLit, onlyExported bool) S
}

em := sf.existenceMap()
res := make(StructFields, 0, len(sf))
res := make(Fields, 0, len(sf))

for i := 0; i < len(lit.Elts); i++ {
kv, ok := lit.Elts[i].(*ast.KeyValueExpr)
Expand Down Expand Up @@ -99,7 +102,7 @@ func (sf StructFields) SkippedFields(lit *ast.CompositeLit, onlyExported bool) S
return res
}

func (sf StructFields) existenceMap() map[string]bool {
func (sf Fields) existenceMap() map[string]bool {
m := make(map[string]bool, len(sf))

for i := 0; i < len(sf); i++ {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package fields_test
package structure_test

import (
"go/ast"
Expand All @@ -9,14 +9,14 @@
"github.com/stretchr/testify/suite"
"golang.org/x/tools/go/packages"

"github.com/GaijinEntertainment/go-exhaustruct/v3/internal/fields"
"github.com/GaijinEntertainment/go-exhaustruct/v3/internal/structure"
)

func Test_HasOptionalTag(t *testing.T) {
t.Parallel()

assert.True(t, fields.HasOptionalTag(`exhaustruct:"optional"`))
assert.False(t, fields.HasOptionalTag(`exhaustruct:"required"`))
assert.True(t, structure.HasOptionalTag(`exhaustruct:"optional"`))
assert.False(t, structure.HasOptionalTag(`exhaustruct:"required"`))
}

func TestStructFields(t *testing.T) {
Expand Down Expand Up @@ -47,7 +47,7 @@
s.Require().NotNil(s.scope)
}

func (s *StructFieldsSuite) getReferenceStructFields() fields.StructFields {
func (s *StructFieldsSuite) getReferenceStructFields() structure.Fields {
s.T().Helper()

obj := s.scope.Lookup("testStruct")
Expand All @@ -56,14 +56,14 @@
typ := s.pkg.TypesInfo.TypeOf(obj.Decl.(*ast.TypeSpec).Type) //nolint:forcetypeassert
s.Require().NotNil(typ)

return fields.NewStructFields(typ.Underlying().(*types.Struct)) //nolint:forcetypeassert
return structure.NewFields(typ.Underlying().(*types.Struct)) //nolint:forcetypeassert
}

func (s *StructFieldsSuite) TestNewStructFields() {
sf := s.getReferenceStructFields()

s.Assert().Len(sf, 4)
s.Assert().Equal(fields.StructFields{
s.Assert().Equal(structure.Fields{

Check failure on line 66 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Equal (testifylint)
{
Name: "ExportedRequired",
Exported: true,
Expand Down Expand Up @@ -103,20 +103,20 @@
if s.Assert().NotNil(unnamed) {
lit := unnamed.Decl.(*ast.ValueSpec).Values[0].(*ast.CompositeLit) //nolint:forcetypeassert
if s.Assert().NotNil(lit) {
s.Assert().Nil(sf.SkippedFields(lit, true))
s.Assert().Nil(sf.SkippedFields(lit, false))
s.Assert().Nil(sf.Skipped(lit, true))

Check failure on line 106 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Nil (testifylint)
s.Assert().Nil(sf.Skipped(lit, false))

Check failure on line 107 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Nil (testifylint)
}
}

unnamedIncomplete := s.scope.Lookup("_unnamedIncomplete")
if s.Assert().NotNil(unnamedIncomplete) {
lit := unnamedIncomplete.Decl.(*ast.ValueSpec).Values[0].(*ast.CompositeLit) //nolint:forcetypeassert
if s.Assert().NotNil(lit) {
s.Assert().Equal(fields.StructFields{
s.Assert().Equal(structure.Fields{

Check failure on line 115 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Equal (testifylint)
{"unexportedRequired", false, false},
{"ExportedOptional", true, true},
{"unexportedOptional", false, true},
}, sf.SkippedFields(lit, true))
}, sf.Skipped(lit, true))
}
}
}
Expand All @@ -128,33 +128,33 @@
if s.Assert().NotNil(named) {
lit := named.Decl.(*ast.ValueSpec).Values[0].(*ast.CompositeLit) //nolint:forcetypeassert
if s.Assert().NotNil(lit) {
s.Assert().Nil(sf.SkippedFields(lit, true))
s.Assert().Nil(sf.SkippedFields(lit, false))
s.Assert().Nil(sf.Skipped(lit, true))

Check failure on line 131 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Nil (testifylint)
s.Assert().Nil(sf.Skipped(lit, false))

Check failure on line 132 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Nil (testifylint)
}
}

namedIncomplete1 := s.scope.Lookup("_namedIncomplete1")
if s.Assert().NotNil(namedIncomplete1) {
lit := namedIncomplete1.Decl.(*ast.ValueSpec).Values[0].(*ast.CompositeLit) //nolint:forcetypeassert
if s.Assert().NotNil(lit) {
s.Assert().Nil(sf.SkippedFields(lit, true))
s.Assert().Equal(fields.StructFields{
s.Assert().Nil(sf.Skipped(lit, true))

Check failure on line 140 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Nil (testifylint)
s.Assert().Equal(structure.Fields{

Check failure on line 141 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Equal (testifylint)
{"unexportedRequired", false, false},
}, sf.SkippedFields(lit, false))
}, sf.Skipped(lit, false))
}
}

namedIncomplete2 := s.scope.Lookup("_namedIncomplete2")
if s.Assert().NotNil(namedIncomplete2) {
lit := namedIncomplete2.Decl.(*ast.ValueSpec).Values[0].(*ast.CompositeLit) //nolint:forcetypeassert
if s.Assert().NotNil(lit) {
s.Assert().Equal(fields.StructFields{
s.Assert().Equal(structure.Fields{

Check failure on line 151 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Equal (testifylint)
{"ExportedRequired", true, false},
}, sf.SkippedFields(lit, true))
s.Assert().Equal(fields.StructFields{
}, sf.Skipped(lit, true))
s.Assert().Equal(structure.Fields{

Check failure on line 154 in internal/structure/fields_test.go

View workflow job for this annotation

GitHub Actions / Lint (1.21, ubuntu-latest)

suite-extra-assert-call: need to simplify the assertion to s.Equal (testifylint)
{"ExportedRequired", true, false},
{"unexportedRequired", false, false},
}, sf.SkippedFields(lit, false))
}, sf.Skipped(lit, false))
}
}
}
Loading