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

fix: track the visited structures in the checkStruct function #19

Merged
merged 2 commits into from
Feb 11, 2023
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
10 changes: 7 additions & 3 deletions musttag.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ func run(pass *analysis.Pass, funcs map[string]Func) (any, error) {
return // not a struct argument.
}

reportPos, ok := checkStruct(s, fn.Tag)
reportPos, ok := checkStruct(s, fn.Tag, make(map[string]struct{}))
if ok {
return // nothing to report.
}
Expand Down Expand Up @@ -225,7 +225,8 @@ func parseStruct(t types.Type, pos token.Pos) (*structInfo, bool) {

// checkStruct recursively checks the given struct and returns the position for report,
// in case one of its fields is missing the tag.
func checkStruct(s *structInfo, tag string) (token.Pos, bool) {
func checkStruct(s *structInfo, tag string, visited map[string]struct{}) (token.Pos, bool) {
visited[s.String()] = struct{}{}
for i := 0; i < s.NumFields(); i++ {
if !s.Field(i).Exported() {
continue
Expand All @@ -241,7 +242,10 @@ func checkStruct(s *structInfo, tag string) (token.Pos, bool) {
if !ok {
continue
}
if pos, ok := checkStruct(nested, tag); !ok {
if _, ok := visited[nested.String()]; ok {
continue
}
if pos, ok := checkStruct(nested, tag, visited); !ok {
return pos, false
}
}
Expand Down
11 changes: 11 additions & 0 deletions testdata/src/tests/tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -473,3 +473,14 @@ func nonStructArgument() {
func nilObject() {
json.Marshal(nil)
}

// test for stack overflow issue: https://github.com/junk1tm/musttag/issues/16
func selfType() {
tmzane marked this conversation as resolved.
Show resolved Hide resolved
type Human struct {
Mom *Human `json:"mom"`
Dad *Human `json:"dad"`
Children []*Human `json:"children"`
}
var v *Human
json.Marshal(v)
}