Skip to content

Commit

Permalink
cmd/go: add vet check for json/xml omitempty struct tags on non-basic…
Browse files Browse the repository at this point in the history
… types

Fixes golang/go#51261

Change-Id: Ic71f614acd3a78a9db73483ccefe613cb7f66e5d
  • Loading branch information
andig committed Oct 16, 2023
1 parent 43c41b5 commit 249f415
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions go/analysis/passes/structtag/structtag.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"go/types"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"

Expand Down Expand Up @@ -83,8 +84,10 @@ func (s *namesSeen) Set(key, name string, level int, pos token.Pos) {
(*s)[uniqueName{key, name, level}] = pos
}

var checkTagDups = []string{"json", "xml"}
var checkTagSpaces = map[string]bool{"json": true, "xml": true, "asn1": true}
var (
checkTagDups = []string{"json", "xml"}
checkTagSpaces = map[string]bool{"json": true, "xml": true, "asn1": true}
)

// checkCanonicalFieldTag checks a single struct field tag.
func checkCanonicalFieldTag(pass *analysis.Pass, field *types.Var, tag string, seen *namesSeen) {
Expand All @@ -103,6 +106,20 @@ func checkCanonicalFieldTag(pass *analysis.Pass, field *types.Var, tag string, s
pass.Reportf(field.Pos(), "struct field tag %#q not compatible with reflect.StructTag.Get: %s", tag, err)
}

// Check for use of json or xml omitempty tags with unsupported field types.
for _, enc := range [...]string{"json", "xml"} {
typ := field.Type()
switch typ.Underlying().(type) {
case *types.Basic, *types.Array, *types.Map, *types.Slice, *types.Interface, *types.Pointer:
continue
}

val := reflect.StructTag(tag).Get(enc)
if slices.Contains(strings.Split(val, ","), "omitempty") {
pass.Reportf(field.Pos(), "struct field %s has %s tag but underlying type %s is not an omittable type", field.Name(), val, typ.String())
}
}

// Check for use of json or xml tags with unexported fields.

// Embedded struct. Nothing to do for now, but that
Expand Down

0 comments on commit 249f415

Please sign in to comment.