| 1 | // Copyright 2010 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package structtag defines an Analyzer that checks struct field tags |
| 6 | // are well formed. |
| 7 | package structtag |
| 8 | |
| 9 | import ( |
| 10 | "errors" |
| 11 | "go/ast" |
| 12 | "go/token" |
| 13 | "go/types" |
| 14 | "path/filepath" |
| 15 | "reflect" |
| 16 | "slices" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | |
| 20 | "fmt" |
| 21 | |
| 22 | "golang.org/x/tools/go/analysis" |
| 23 | "golang.org/x/tools/go/analysis/passes/inspect" |
| 24 | "golang.org/x/tools/go/ast/inspector" |
| 25 | ) |
| 26 | |
| 27 | const Doc = `check that struct field tags conform to reflect.StructTag.Get |
| 28 | |
| 29 | Also report certain struct tags (json, xml) used with unexported fields.` |
| 30 | |
| 31 | var Analyzer = &analysis.Analyzer{ |
| 32 | Name: "structtag", |
| 33 | Doc: Doc, |
| 34 | URL: "https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/structtag", |
| 35 | Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 36 | RunDespiteErrors: true, |
| 37 | Run: run, |
| 38 | } |
| 39 | |
| 40 | func run(pass *analysis.Pass) (any, error) { |
| 41 | inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 42 | |
| 43 | nodeFilter := []ast.Node{ |
| 44 | (*ast.StructType)(nil), |
| 45 | } |
| 46 | inspect.Preorder(nodeFilter, func(n ast.Node) { |
| 47 | styp, ok := pass.TypesInfo.Types[n.(*ast.StructType)].Type.(*types.Struct) |
| 48 | // Type information may be incomplete. |
| 49 | if !ok { |
| 50 | return |
| 51 | } |
| 52 | var seen namesSeen |
| 53 | for i := 0; i < styp.NumFields(); i++ { |
| 54 | field := styp.Field(i) |
| 55 | tag := styp.Tag(i) |
| 56 | checkCanonicalFieldTag(pass, field, tag, &seen) |
| 57 | } |
| 58 | }) |
| 59 | return nil, nil |
| 60 | } |
| 61 | |
| 62 | // namesSeen keeps track of encoding tags by their key, name, and nested level |
| 63 | // from the initial struct. The level is taken into account because equal |
| 64 | // encoding key names only conflict when at the same level; otherwise, the lower |
| 65 | // level shadows the higher level. |
| 66 | type namesSeen map[uniqueName]token.Pos |
| 67 | |
| 68 | type uniqueName struct { |
| 69 | key string // "xml" or "json" |
| 70 | name string // the encoding name |
| 71 | level int // anonymous struct nesting level |
| 72 | } |
| 73 | |
| 74 | func (s *namesSeen) Get(key, name string, level int) (token.Pos, bool) { |
| 75 | if *s == nil { |
| 76 | *s = make(map[uniqueName]token.Pos) |
| 77 | } |
| 78 | pos, ok := (*s)[uniqueName{key, name, level}] |
| 79 | return pos, ok |
| 80 | } |
| 81 | |
| 82 | func (s *namesSeen) Set(key, name string, level int, pos token.Pos) { |
| 83 | if *s == nil { |
| 84 | *s = make(map[uniqueName]token.Pos) |
| 85 | } |
| 86 | (*s)[uniqueName{key, name, level}] = pos |
| 87 | } |
| 88 | |
| 89 | var checkTagDups = []string{"json", "xml"} |
| 90 | var checkTagSpaces = map[string]bool{"json": true, "xml": true, "asn1": true} |
| 91 | |
| 92 | // checkCanonicalFieldTag checks a single struct field tag. |
| 93 | func checkCanonicalFieldTag(pass *analysis.Pass, field *types.Var, tag string, seen *namesSeen) { |
| 94 | if strings.HasPrefix(pass.Pkg.Path(), "encoding/") { |
| 95 | // These packages know how to use their own APIs. |
| 96 | // Sometimes they are testing what happens to incorrect programs. |
| 97 | return |
| 98 | } |
| 99 | |
| 100 | for _, key := range checkTagDups { |
| 101 | checkTagDuplicates(pass, tag, key, field, field, seen, 1) |
| 102 | } |
| 103 | |
| 104 | if err := validateStructTag(tag); err != nil { |
| 105 | pass.Report(analysis.Diagnostic{ |
| 106 | Pos: field.Pos(), |
| 107 | End: field.Pos() + token.Pos(len(field.Name())), |
| 108 | Message: fmt.Sprintf("struct field tag %#q not compatible with reflect.StructTag.Get: %s", tag, err), |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | // Check for use of json or xml tags with unexported fields. |
| 113 | |
| 114 | // Embedded struct. Nothing to do for now, but that |
| 115 | // may change, depending on what happens with issue 7363. |
| 116 | // TODO(adonovan): investigate, now that issue is fixed. |
| 117 | if field.Anonymous() { |
| 118 | return |
| 119 | } |
| 120 | |
| 121 | if field.Exported() { |
| 122 | return |
| 123 | } |
| 124 | |
| 125 | for _, enc := range [...]string{"json", "xml"} { |
| 126 | switch reflect.StructTag(tag).Get(enc) { |
| 127 | // Ignore warning if the field not exported and the tag is marked as |
| 128 | // ignored. |
| 129 | case "", "-": |
| 130 | default: |
| 131 | pass.Report(analysis.Diagnostic{ |
| 132 | Pos: field.Pos(), |
| 133 | End: field.Pos() + token.Pos(len(field.Name())), |
| 134 | Message: fmt.Sprintf("struct field %s has %s tag but is not exported", field.Name(), enc), |
| 135 | }) |
| 136 | return |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | // checkTagDuplicates checks a single struct field tag to see if any tags are |
| 142 | // duplicated. nearest is the field that's closest to the field being checked, |
| 143 | // while still being part of the top-level struct type. |
| 144 | func checkTagDuplicates(pass *analysis.Pass, tag, key string, nearest, field *types.Var, seen *namesSeen, level int) { |
| 145 | val := reflect.StructTag(tag).Get(key) |
| 146 | if val == "-" { |
| 147 | // Ignored, even if the field is anonymous. |
| 148 | return |
| 149 | } |
| 150 | if val == "" || val[0] == ',' { |
| 151 | if !field.Anonymous() { |
| 152 | // Ignored if the field isn't anonymous. |
| 153 | return |
| 154 | } |
| 155 | typ, ok := field.Type().Underlying().(*types.Struct) |
| 156 | if !ok { |
| 157 | return |
| 158 | } |
| 159 | for i := 0; i < typ.NumFields(); i++ { |
| 160 | field := typ.Field(i) |
| 161 | if !field.Exported() { |
| 162 | continue |
| 163 | } |
| 164 | tag := typ.Tag(i) |
| 165 | checkTagDuplicates(pass, tag, key, nearest, field, seen, level+1) |
| 166 | } |
| 167 | return |
| 168 | } |
| 169 | if key == "xml" && field.Name() == "XMLName" { |
| 170 | // XMLName defines the XML element name of the struct being |
| 171 | // checked. That name cannot collide with element or attribute |
| 172 | // names defined on other fields of the struct. Vet does not have a |
| 173 | // check for untagged fields of type struct defining their own name |
| 174 | // by containing a field named XMLName; see issue 18256. |
| 175 | return |
| 176 | } |
| 177 | if i := strings.Index(val, ","); i >= 0 { |
| 178 | if key == "xml" { |
| 179 | // Use a separate namespace for XML attributes. |
| 180 | if slices.Contains(strings.Split(val[i:], ","), "attr") { |
| 181 | key += " attribute" // Key is part of the error message. |
| 182 | } |
| 183 | } |
| 184 | val = val[:i] |
| 185 | } |
| 186 | if pos, ok := seen.Get(key, val, level); ok { |
| 187 | alsoPos := pass.Fset.Position(pos) |
| 188 | alsoPos.Column = 0 |
| 189 | |
| 190 | // Make the "also at" position relative to the current position, |
| 191 | // to ensure that all warnings are unambiguous and correct. For |
| 192 | // example, via anonymous struct fields, it's possible for the |
| 193 | // two fields to be in different packages and directories. |
| 194 | thisPos := pass.Fset.Position(field.Pos()) |
| 195 | rel, err := filepath.Rel(filepath.Dir(thisPos.Filename), alsoPos.Filename) |
| 196 | if err != nil { |
| 197 | // Possibly because the paths are relative; leave the |
| 198 | // filename alone. |
| 199 | } else { |
| 200 | alsoPos.Filename = rel |
| 201 | } |
| 202 | |
| 203 | pass.Report(analysis.Diagnostic{ |
| 204 | Pos: nearest.Pos(), |
| 205 | End: nearest.Pos() + token.Pos(len(nearest.Name())), |
| 206 | Message: fmt.Sprintf("struct field %s repeats %s tag %q also at %s", field.Name(), key, val, alsoPos), |
| 207 | }) |
| 208 | } else { |
| 209 | seen.Set(key, val, level, field.Pos()) |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | var ( |
| 214 | errTagSyntax = errors.New("bad syntax for struct tag pair") |
| 215 | errTagKeySyntax = errors.New("bad syntax for struct tag key") |
| 216 | errTagValueSyntax = errors.New("bad syntax for struct tag value") |
| 217 | errTagValueSpace = errors.New("suspicious space in struct tag value") |
| 218 | errTagSpace = errors.New("key:\"value\" pairs not separated by spaces") |
| 219 | ) |
| 220 | |
| 221 | // validateStructTag parses the struct tag and returns an error if it is not |
| 222 | // in the canonical format, which is a space-separated list of key:"value" |
| 223 | // settings. The value may contain spaces. |
| 224 | func validateStructTag(tag string) error { |
| 225 | // This code is based on the StructTag.Lookup code in package reflect. |
| 226 | |
| 227 | n := 0 |
| 228 | for ; tag != ""; n++ { |
| 229 | if n > 0 && tag != "" && tag[0] != ' ' { |
| 230 | // More restrictive than reflect, but catches likely mistakes |
| 231 | // like `x:"foo",y:"bar"`, which parses as `x:"foo" ,y:"bar"` with second key ",y". |
| 232 | return errTagSpace |
| 233 | } |
| 234 | // Skip leading space. |
| 235 | i := 0 |
| 236 | for i < len(tag) && tag[i] == ' ' { |
| 237 | i++ |
| 238 | } |
| 239 | tag = tag[i:] |
| 240 | if tag == "" { |
| 241 | break |
| 242 | } |
| 243 | |
| 244 | // Scan to colon. A space, a quote or a control character is a syntax error. |
| 245 | // Strictly speaking, control chars include the range [0x7f, 0x9f], not just |
| 246 | // [0x00, 0x1f], but in practice, we ignore the multi-byte control characters |
| 247 | // as it is simpler to inspect the tag's bytes than the tag's runes. |
| 248 | i = 0 |
| 249 | for i < len(tag) && tag[i] > ' ' && tag[i] != ':' && tag[i] != '"' && tag[i] != 0x7f { |
| 250 | i++ |
| 251 | } |
| 252 | if i == 0 { |
| 253 | return errTagKeySyntax |
| 254 | } |
| 255 | if i+1 >= len(tag) || tag[i] != ':' { |
| 256 | return errTagSyntax |
| 257 | } |
| 258 | if tag[i+1] != '"' { |
| 259 | return errTagValueSyntax |
| 260 | } |
| 261 | key := tag[:i] |
| 262 | tag = tag[i+1:] |
| 263 | |
| 264 | // Scan quoted string to find value. |
| 265 | i = 1 |
| 266 | for i < len(tag) && tag[i] != '"' { |
| 267 | if tag[i] == '\\' { |
| 268 | i++ |
| 269 | } |
| 270 | i++ |
| 271 | } |
| 272 | if i >= len(tag) { |
| 273 | return errTagValueSyntax |
| 274 | } |
| 275 | qvalue := tag[:i+1] |
| 276 | tag = tag[i+1:] |
| 277 | |
| 278 | value, err := strconv.Unquote(qvalue) |
| 279 | if err != nil { |
| 280 | return errTagValueSyntax |
| 281 | } |
| 282 | |
| 283 | if !checkTagSpaces[key] { |
| 284 | continue |
| 285 | } |
| 286 | |
| 287 | switch key { |
| 288 | case "xml": |
| 289 | // If the first or last character in the XML tag is a space, it is |
| 290 | // suspicious. |
| 291 | if strings.Trim(value, " ") != value { |
| 292 | return errTagValueSpace |
| 293 | } |
| 294 | |
| 295 | // If there are multiple spaces, they are suspicious. |
| 296 | if strings.Count(value, " ") > 1 { |
| 297 | return errTagValueSpace |
| 298 | } |
| 299 | |
| 300 | // If there is no comma, skip the rest of the checks. |
| 301 | comma := strings.IndexRune(value, ',') |
| 302 | if comma < 0 { |
| 303 | continue |
| 304 | } |
| 305 | |
| 306 | // If the character before a comma is a space, this is suspicious. |
| 307 | if comma > 0 && value[comma-1] == ' ' { |
| 308 | return errTagValueSpace |
| 309 | } |
| 310 | value = value[comma+1:] |
| 311 | case "json": |
| 312 | // JSON allows using spaces in the name, so skip it. |
| 313 | comma := strings.IndexRune(value, ',') |
| 314 | if comma < 0 { |
| 315 | continue |
| 316 | } |
| 317 | value = value[comma+1:] |
| 318 | } |
| 319 | |
| 320 | if strings.IndexByte(value, ' ') >= 0 { |
| 321 | return errTagValueSpace |
| 322 | } |
| 323 | } |
| 324 | return nil |
| 325 | } |