Skip to content

Commit 249f415

Browse files
committed
cmd/go: add vet check for json/xml omitempty struct tags on non-basic types
Fixes golang/go#51261 Change-Id: Ic71f614acd3a78a9db73483ccefe613cb7f66e5d
1 parent 43c41b5 commit 249f415

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

go/analysis/passes/structtag/structtag.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"go/types"
1414
"path/filepath"
1515
"reflect"
16+
"slices"
1617
"strconv"
1718
"strings"
1819

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

86-
var checkTagDups = []string{"json", "xml"}
87-
var checkTagSpaces = map[string]bool{"json": true, "xml": true, "asn1": true}
87+
var (
88+
checkTagDups = []string{"json", "xml"}
89+
checkTagSpaces = map[string]bool{"json": true, "xml": true, "asn1": true}
90+
)
8891

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

109+
// Check for use of json or xml omitempty tags with unsupported field types.
110+
for _, enc := range [...]string{"json", "xml"} {
111+
typ := field.Type()
112+
switch typ.Underlying().(type) {
113+
case *types.Basic, *types.Array, *types.Map, *types.Slice, *types.Interface, *types.Pointer:
114+
continue
115+
}
116+
117+
val := reflect.StructTag(tag).Get(enc)
118+
if slices.Contains(strings.Split(val, ","), "omitempty") {
119+
pass.Reportf(field.Pos(), "struct field %s has %s tag but underlying type %s is not an omittable type", field.Name(), val, typ.String())
120+
}
121+
}
122+
106123
// Check for use of json or xml tags with unexported fields.
107124

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

0 commit comments

Comments
 (0)