honnef.co/go/tools@v0.5.0-0.dev.0.20240520180541-dcae280a5e87/staticcheck/fakexml/typeinfo.go (about) 1 // Copyright 2011 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 fakexml 6 7 import ( 8 "fmt" 9 "strconv" 10 "strings" 11 "sync" 12 13 "honnef.co/go/tools/go/types/typeutil" 14 "honnef.co/go/tools/staticcheck/fakereflect" 15 ) 16 17 // typeInfo holds details for the xml representation of a type. 18 type typeInfo struct { 19 xmlname *fieldInfo 20 fields []fieldInfo 21 } 22 23 // fieldInfo holds details for the xml representation of a single field. 24 type fieldInfo struct { 25 idx []int 26 name string 27 xmlns string 28 flags fieldFlags 29 parents []string 30 } 31 32 type fieldFlags int 33 34 const ( 35 fElement fieldFlags = 1 << iota 36 fAttr 37 fCDATA 38 fCharData 39 fInnerXML 40 fComment 41 fAny 42 43 fOmitEmpty 44 45 fMode = fElement | fAttr | fCDATA | fCharData | fInnerXML | fComment | fAny 46 47 xmlName = "XMLName" 48 ) 49 50 func (f fieldFlags) String() string { 51 switch f { 52 case fAttr: 53 return "attr" 54 case fCDATA: 55 return "cdata" 56 case fCharData: 57 return "chardata" 58 case fInnerXML: 59 return "innerxml" 60 case fComment: 61 return "comment" 62 case fAny: 63 return "any" 64 case fOmitEmpty: 65 return "omitempty" 66 case fAny | fAttr: 67 return "any,attr" 68 default: 69 return strconv.Itoa(int(f)) 70 } 71 } 72 73 var tinfoMap sync.Map // map[reflect.Type]*typeInfo 74 75 // getTypeInfo returns the typeInfo structure with details necessary 76 // for marshaling and unmarshaling typ. 77 func getTypeInfo(typ fakereflect.TypeAndCanAddr) (*typeInfo, error) { 78 if ti, ok := tinfoMap.Load(typ); ok { 79 return ti.(*typeInfo), nil 80 } 81 82 tinfo := &typeInfo{} 83 if typ.IsStruct() && !typeutil.IsTypeWithName(typ.Type, "encoding/xml.Name") { 84 n := typ.NumField() 85 for i := 0; i < n; i++ { 86 f := typ.Field(i) 87 if (!f.IsExported() && !f.Anonymous) || f.Tag.Get("xml") == "-" { 88 continue // Private field 89 } 90 91 // For embedded structs, embed its fields. 92 if f.Anonymous { 93 t := f.Type 94 if t.IsPtr() { 95 t = t.Elem() 96 } 97 if t.IsStruct() { 98 inner, err := getTypeInfo(t) 99 if err != nil { 100 return nil, err 101 } 102 if tinfo.xmlname == nil { 103 tinfo.xmlname = inner.xmlname 104 } 105 for _, finfo := range inner.fields { 106 finfo.idx = append([]int{i}, finfo.idx...) 107 if err := addFieldInfo(typ, tinfo, &finfo); err != nil { 108 return nil, err 109 } 110 } 111 continue 112 } 113 } 114 115 finfo, err := StructFieldInfo(f) 116 if err != nil { 117 return nil, err 118 } 119 120 if f.Name == xmlName { 121 tinfo.xmlname = finfo 122 continue 123 } 124 125 // Add the field if it doesn't conflict with other fields. 126 if err := addFieldInfo(typ, tinfo, finfo); err != nil { 127 return nil, err 128 } 129 } 130 } 131 132 ti, _ := tinfoMap.LoadOrStore(typ, tinfo) 133 return ti.(*typeInfo), nil 134 } 135 136 // StructFieldInfo builds and returns a fieldInfo for f. 137 func StructFieldInfo(f fakereflect.StructField) (*fieldInfo, error) { 138 finfo := &fieldInfo{idx: f.Index} 139 140 // Split the tag from the xml namespace if necessary. 141 tag := f.Tag.Get("xml") 142 if i := strings.Index(tag, " "); i >= 0 { 143 finfo.xmlns, tag = tag[:i], tag[i+1:] 144 } 145 146 // Parse flags. 147 tokens := strings.Split(tag, ",") 148 if len(tokens) == 1 { 149 finfo.flags = fElement 150 } else { 151 tag = tokens[0] 152 for _, flag := range tokens[1:] { 153 switch flag { 154 case "attr": 155 finfo.flags |= fAttr 156 case "cdata": 157 finfo.flags |= fCDATA 158 case "chardata": 159 finfo.flags |= fCharData 160 case "innerxml": 161 finfo.flags |= fInnerXML 162 case "comment": 163 finfo.flags |= fComment 164 case "any": 165 finfo.flags |= fAny 166 case "omitempty": 167 finfo.flags |= fOmitEmpty 168 } 169 } 170 171 // Validate the flags used. 172 switch mode := finfo.flags & fMode; mode { 173 case 0: 174 finfo.flags |= fElement 175 case fAttr, fCDATA, fCharData, fInnerXML, fComment, fAny, fAny | fAttr: 176 if f.Name == xmlName { 177 return nil, fmt.Errorf("cannot use option %s on XMLName field", mode) 178 } else if tag != "" && mode != fAttr { 179 return nil, fmt.Errorf("cannot specify name together with option ,%s", mode) 180 } 181 default: 182 // This will also catch multiple modes in a single field. 183 return nil, fmt.Errorf("invalid combination of options: %q", f.Tag.Get("xml")) 184 } 185 if finfo.flags&fMode == fAny { 186 finfo.flags |= fElement 187 } 188 if finfo.flags&fOmitEmpty != 0 && finfo.flags&(fElement|fAttr) == 0 { 189 return nil, fmt.Errorf("can only use omitempty on elements and attributes") 190 } 191 } 192 193 // Use of xmlns without a name is not allowed. 194 if finfo.xmlns != "" && tag == "" { 195 return nil, fmt.Errorf("namespace without name: %q", f.Tag.Get("xml")) 196 } 197 198 if f.Name == xmlName { 199 // The XMLName field records the XML element name. Don't 200 // process it as usual because its name should default to 201 // empty rather than to the field name. 202 finfo.name = tag 203 return finfo, nil 204 } 205 206 if tag == "" { 207 // If the name part of the tag is completely empty, get 208 // default from XMLName of underlying struct if feasible, 209 // or field name otherwise. 210 if xmlname := lookupXMLName(f.Type); xmlname != nil { 211 finfo.xmlns, finfo.name = xmlname.xmlns, xmlname.name 212 } else { 213 finfo.name = f.Name 214 } 215 return finfo, nil 216 } 217 218 // Prepare field name and parents. 219 parents := strings.Split(tag, ">") 220 if parents[0] == "" { 221 parents[0] = f.Name 222 } 223 if parents[len(parents)-1] == "" { 224 return nil, fmt.Errorf("trailing '>'") 225 } 226 finfo.name = parents[len(parents)-1] 227 if len(parents) > 1 { 228 if (finfo.flags & fElement) == 0 { 229 return nil, fmt.Errorf("%s chain not valid with %s flag", tag, strings.Join(tokens[1:], ",")) 230 } 231 finfo.parents = parents[:len(parents)-1] 232 } 233 234 // If the field type has an XMLName field, the names must match 235 // so that the behavior of both marshaling and unmarshaling 236 // is straightforward and unambiguous. 237 if finfo.flags&fElement != 0 { 238 ftyp := f.Type 239 xmlname := lookupXMLName(ftyp) 240 if xmlname != nil && xmlname.name != finfo.name { 241 return nil, fmt.Errorf("name %q conflicts with name %q in %s.XMLName", finfo.name, xmlname.name, ftyp) 242 } 243 } 244 return finfo, nil 245 } 246 247 // lookupXMLName returns the fieldInfo for typ's XMLName field 248 // in case it exists and has a valid xml field tag, otherwise 249 // it returns nil. 250 func lookupXMLName(typ fakereflect.TypeAndCanAddr) (xmlname *fieldInfo) { 251 seen := map[fakereflect.TypeAndCanAddr]struct{}{} 252 for typ.IsPtr() { 253 typ = typ.Elem() 254 if _, ok := seen[typ]; ok { 255 // Loop in type graph, e.g. 'type P *P' 256 return nil 257 } 258 seen[typ] = struct{}{} 259 } 260 if !typ.IsStruct() { 261 return nil 262 } 263 for i, n := 0, typ.NumField(); i < n; i++ { 264 f := typ.Field(i) 265 if f.Name != xmlName { 266 continue 267 } 268 finfo, err := StructFieldInfo(f) 269 if err == nil && finfo.name != "" { 270 return finfo 271 } 272 // Also consider errors as a non-existent field tag 273 // and let getTypeInfo itself report the error. 274 break 275 } 276 return nil 277 } 278 279 func min(a, b int) int { 280 if a <= b { 281 return a 282 } 283 return b 284 } 285 286 // addFieldInfo adds finfo to tinfo.fields if there are no 287 // conflicts, or if conflicts arise from previous fields that were 288 // obtained from deeper embedded structures than finfo. In the latter 289 // case, the conflicting entries are dropped. 290 // A conflict occurs when the path (parent + name) to a field is 291 // itself a prefix of another path, or when two paths match exactly. 292 // It is okay for field paths to share a common, shorter prefix. 293 func addFieldInfo(typ fakereflect.TypeAndCanAddr, tinfo *typeInfo, newf *fieldInfo) error { 294 var conflicts []int 295 Loop: 296 // First, figure all conflicts. Most working code will have none. 297 for i := range tinfo.fields { 298 oldf := &tinfo.fields[i] 299 if oldf.flags&fMode != newf.flags&fMode { 300 continue 301 } 302 if oldf.xmlns != "" && newf.xmlns != "" && oldf.xmlns != newf.xmlns { 303 continue 304 } 305 minl := min(len(newf.parents), len(oldf.parents)) 306 for p := 0; p < minl; p++ { 307 if oldf.parents[p] != newf.parents[p] { 308 continue Loop 309 } 310 } 311 if len(oldf.parents) > len(newf.parents) { 312 if oldf.parents[len(newf.parents)] == newf.name { 313 conflicts = append(conflicts, i) 314 } 315 } else if len(oldf.parents) < len(newf.parents) { 316 if newf.parents[len(oldf.parents)] == oldf.name { 317 conflicts = append(conflicts, i) 318 } 319 } else { 320 if newf.name == oldf.name { 321 conflicts = append(conflicts, i) 322 } 323 } 324 } 325 // Without conflicts, add the new field and return. 326 if conflicts == nil { 327 tinfo.fields = append(tinfo.fields, *newf) 328 return nil 329 } 330 331 // If any conflict is shallower, ignore the new field. 332 // This matches the Go field resolution on embedding. 333 for _, i := range conflicts { 334 if len(tinfo.fields[i].idx) < len(newf.idx) { 335 return nil 336 } 337 } 338 339 // Otherwise, if any of them is at the same depth level, it's an error. 340 for _, i := range conflicts { 341 oldf := &tinfo.fields[i] 342 if len(oldf.idx) == len(newf.idx) { 343 f1 := typ.FieldByIndex(oldf.idx) 344 f2 := typ.FieldByIndex(newf.idx) 345 return &TagPathError{typ, f1.Name, f1.Tag.Get("xml"), f2.Name, f2.Tag.Get("xml")} 346 } 347 } 348 349 // Otherwise, the new field is shallower, and thus takes precedence, 350 // so drop the conflicting fields from tinfo and append the new one. 351 for c := len(conflicts) - 1; c >= 0; c-- { 352 i := conflicts[c] 353 copy(tinfo.fields[i:], tinfo.fields[i+1:]) 354 tinfo.fields = tinfo.fields[:len(tinfo.fields)-1] 355 } 356 tinfo.fields = append(tinfo.fields, *newf) 357 return nil 358 } 359 360 // A TagPathError represents an error in the unmarshaling process 361 // caused by the use of field tags with conflicting paths. 362 type TagPathError struct { 363 Struct fakereflect.TypeAndCanAddr 364 Field1, Tag1 string 365 Field2, Tag2 string 366 } 367 368 func (e *TagPathError) Error() string { 369 return fmt.Sprintf("%s field %q with tag %q conflicts with field %q with tag %q", e.Struct, e.Field1, e.Tag1, e.Field2, e.Tag2) 370 } 371 372 // value returns v's field value corresponding to finfo. 373 // It's equivalent to v.FieldByIndex(finfo.idx), but when passed 374 // initNilPointers, it initializes and dereferences pointers as necessary. 375 // When passed dontInitNilPointers and a nil pointer is reached, the function 376 // returns a zero reflect.Value. 377 func (finfo *fieldInfo) value(v fakereflect.TypeAndCanAddr) fakereflect.TypeAndCanAddr { 378 for i, x := range finfo.idx { 379 if i > 0 { 380 t := v 381 if t.IsPtr() && t.Elem().IsStruct() { 382 v = v.Elem() 383 } 384 } 385 v = v.Field(x).Type 386 } 387 return v 388 }