| 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 := range n { |
| 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 |
// addFieldInfo adds finfo to tinfo.fields if there are no |
| 280 |
// conflicts, or if conflicts arise from previous fields that were |
| 281 |
// obtained from deeper embedded structures than finfo. In the latter |
| 282 |
// case, the conflicting entries are dropped. |
| 283 |
// A conflict occurs when the path (parent + name) to a field is |
| 284 |
// itself a prefix of another path, or when two paths match exactly. |
| 285 |
// It is okay for field paths to share a common, shorter prefix. |
| 286 |
func addFieldInfo(typ fakereflect.TypeAndCanAddr, tinfo *typeInfo, newf *fieldInfo) error { |
| 287 |
var conflicts []int |
| 288 |
Loop: |
| 289 |
// First, figure all conflicts. Most working code will have none. |
| 290 |
for i := range tinfo.fields { |
| 291 |
oldf := &tinfo.fields[i] |
| 292 |
if oldf.flags&fMode != newf.flags&fMode { |
| 293 |
continue |
| 294 |
} |
| 295 |
if oldf.xmlns != "" && newf.xmlns != "" && oldf.xmlns != newf.xmlns { |
| 296 |
continue |
| 297 |
} |
| 298 |
minl := min(len(newf.parents), len(oldf.parents)) |
| 299 |
for p := range minl { |
| 300 |
if oldf.parents[p] != newf.parents[p] { |
| 301 |
continue Loop |
| 302 |
} |
| 303 |
} |
| 304 |
if len(oldf.parents) > len(newf.parents) { |
| 305 |
if oldf.parents[len(newf.parents)] == newf.name { |
| 306 |
conflicts = append(conflicts, i) |
| 307 |
} |
| 308 |
} else if len(oldf.parents) < len(newf.parents) { |
| 309 |
if newf.parents[len(oldf.parents)] == oldf.name { |
| 310 |
conflicts = append(conflicts, i) |
| 311 |
} |
| 312 |
} else { |
| 313 |
if newf.name == oldf.name { |
| 314 |
conflicts = append(conflicts, i) |
| 315 |
} |
| 316 |
} |
| 317 |
} |
| 318 |
// Without conflicts, add the new field and return. |
| 319 |
if conflicts == nil { |
| 320 |
tinfo.fields = append(tinfo.fields, *newf) |
| 321 |
return nil |
| 322 |
} |
| 323 |
|
| 324 |
// If any conflict is shallower, ignore the new field. |
| 325 |
// This matches the Go field resolution on embedding. |
| 326 |
for _, i := range conflicts { |
| 327 |
if len(tinfo.fields[i].idx) < len(newf.idx) { |
| 328 |
return nil |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
// Otherwise, if any of them is at the same depth level, it's an error. |
| 333 |
for _, i := range conflicts { |
| 334 |
oldf := &tinfo.fields[i] |
| 335 |
if len(oldf.idx) == len(newf.idx) { |
| 336 |
f1 := typ.FieldByIndex(oldf.idx) |
| 337 |
f2 := typ.FieldByIndex(newf.idx) |
| 338 |
return &TagPathError{typ, f1.Name, f1.Tag.Get("xml"), f2.Name, f2.Tag.Get("xml")} |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
// Otherwise, the new field is shallower, and thus takes precedence, |
| 343 |
// so drop the conflicting fields from tinfo and append the new one. |
| 344 |
for c := len(conflicts) - 1; c >= 0; c-- { |
| 345 |
i := conflicts[c] |
| 346 |
copy(tinfo.fields[i:], tinfo.fields[i+1:]) |
| 347 |
tinfo.fields = tinfo.fields[:len(tinfo.fields)-1] |
| 348 |
} |
| 349 |
tinfo.fields = append(tinfo.fields, *newf) |
| 350 |
return nil |
| 351 |
} |
| 352 |
|
| 353 |
// A TagPathError represents an error in the unmarshaling process |
| 354 |
// caused by the use of field tags with conflicting paths. |
| 355 |
type TagPathError struct { |
| 356 |
Struct fakereflect.TypeAndCanAddr |
| 357 |
Field1, Tag1 string |
| 358 |
Field2, Tag2 string |
| 359 |
} |
| 360 |
|
| 361 |
func (e *TagPathError) Error() string { |
| 362 |
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) |
| 363 |
} |
| 364 |
|
| 365 |
// value returns v's field value corresponding to finfo. |
| 366 |
// It's equivalent to v.FieldByIndex(finfo.idx), but when passed |
| 367 |
// initNilPointers, it initializes and dereferences pointers as necessary. |
| 368 |
// When passed dontInitNilPointers and a nil pointer is reached, the function |
| 369 |
// returns a zero reflect.Value. |
| 370 |
func (finfo *fieldInfo) value(v fakereflect.TypeAndCanAddr) fakereflect.TypeAndCanAddr { |
| 371 |
for i, x := range finfo.idx { |
| 372 |
if i > 0 { |
| 373 |
t := v |
| 374 |
if t.IsPtr() && t.Elem().IsStruct() { |
| 375 |
v = v.Elem() |
| 376 |
} |
| 377 |
} |
| 378 |
v = v.Field(x).Type |
| 379 |
} |
| 380 |
return v |
| 381 |
} |