Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/fields.go

raw
1 // Copyright 2021 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 json
6
7 import (
8 "cmp"
9 "errors"
10 "fmt"
11 "io"
12 "reflect"
13 "slices"
14 "strconv"
15 "strings"
16 "unicode"
17 "unicode/utf8"
18
19 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonflags"
20 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
21 )
22
23 type isZeroer interface {
24 IsZero() bool
25 }
26
27 var isZeroerType = reflect.TypeFor[isZeroer]()
28
29 type structFields struct {
30 flattened []structField // listed in depth-first ordering
31 byActualName map[string]*structField
32 byFoldedName map[string][]*structField
33 inlinedFallback *structField
34 }
35
36 // reindex recomputes index to avoid bounds check during runtime.
37 //
38 // During the construction of each [structField] in [makeStructFields],
39 // the index field is 0-indexed. However, before it returns,
40 // the 0th field is stored in index0 and index stores the remainder.
41 func (sf *structFields) reindex() {
42 reindex := func(f *structField) {
43 f.index0 = f.index[0]
44 f.index = f.index[1:]
45 if len(f.index) == 0 {
46 f.index = nil // avoid pinning the backing slice
47 }
48 }
49 for i := range sf.flattened {
50 reindex(&sf.flattened[i])
51 }
52 if sf.inlinedFallback != nil {
53 reindex(sf.inlinedFallback)
54 }
55 }
56
57 // lookupByFoldedName looks up name by a case-insensitive match
58 // that also ignores the presence of dashes and underscores.
59 func (fs *structFields) lookupByFoldedName(name []byte) []*structField {
60 return fs.byFoldedName[string(foldName(name))]
61 }
62
63 type structField struct {
64 id int // unique numeric ID in breadth-first ordering
65 index0 int // 0th index into a struct according to [reflect.Type.FieldByIndex]
66 index []int // 1st index and remainder according to [reflect.Type.FieldByIndex]
67 typ reflect.Type
68 fncs *arshaler
69 isZero func(addressableValue) bool
70 isEmpty func(addressableValue) bool
71 fieldOptions
72 }
73
74 var errNoExportedFields = errors.New("Go struct has no exported fields")
75
76 func makeStructFields(root reflect.Type) (fs structFields, serr *SemanticError) {
77 orErrorf := func(serr *SemanticError, t reflect.Type, f string, a ...any) *SemanticError {
78 return cmp.Or(serr, &SemanticError{GoType: t, Err: fmt.Errorf(f, a...)})
79 }
80
81 // Setup a queue for a breath-first search.
82 var queueIndex int
83 type queueEntry struct {
84 typ reflect.Type
85 index []int
86 visitChildren bool // whether to recursively visit inlined field in this struct
87 }
88 queue := []queueEntry{{root, nil, true}}
89 seen := map[reflect.Type]bool{root: true}
90
91 // Perform a breadth-first search over all reachable fields.
92 // This ensures that len(f.index) will be monotonically increasing.
93 var allFields, inlinedFallbacks []structField
94 for queueIndex < len(queue) {
95 qe := queue[queueIndex]
96 queueIndex++
97
98 t := qe.typ
99 inlinedFallbackIndex := -1 // index of last inlined fallback field in current struct
100 namesIndex := make(map[string]int) // index of each field with a given JSON object name in current struct
101 var hasAnyJSONTag bool // whether any Go struct field has a `json` tag
102 var hasAnyJSONField bool // whether any JSON serializable fields exist in current struct
103 for i := range t.NumField() {
104 sf := t.Field(i)
105 _, hasTag := sf.Tag.Lookup("json")
106 hasAnyJSONTag = hasAnyJSONTag || hasTag
107 options, ignored, err := parseFieldOptions(sf)
108 if err != nil {
109 serr = cmp.Or(serr, &SemanticError{GoType: t, Err: err})
110 }
111 if ignored {
112 continue
113 }
114 hasAnyJSONField = true
115 f := structField{
116 // Allocate a new slice (len=N+1) to hold both
117 // the parent index (len=N) and the current index (len=1).
118 // Do this to avoid clobbering the memory of the parent index.
119 index: append(append(make([]int, 0, len(qe.index)+1), qe.index...), i),
120 typ: sf.Type,
121 fieldOptions: options,
122 }
123 if sf.Anonymous && !f.hasName {
124 if indirectType(f.typ).Kind() != reflect.Struct {
125 serr = orErrorf(serr, t, "embedded Go struct field %s of non-struct type must be explicitly given a JSON name", sf.Name)
126 } else {
127 f.inline = true // implied by use of Go embedding without an explicit name
128 }
129 }
130 if f.inline || f.unknown {
131 // Handle an inlined field that serializes to/from
132 // zero or more JSON object members.
133
134 switch f.fieldOptions {
135 case fieldOptions{name: f.name, quotedName: f.quotedName, inline: true}:
136 case fieldOptions{name: f.name, quotedName: f.quotedName, unknown: true}:
137 case fieldOptions{name: f.name, quotedName: f.quotedName, inline: true, unknown: true}:
138 serr = orErrorf(serr, t, "Go struct field %s cannot have both `inline` and `unknown` specified", sf.Name)
139 f.inline = false // let `unknown` take precedence
140 default:
141 serr = orErrorf(serr, t, "Go struct field %s cannot have any options other than `inline` or `unknown` specified", sf.Name)
142 if f.hasName {
143 continue // invalid inlined field; treat as ignored
144 }
145 f.fieldOptions = fieldOptions{name: f.name, quotedName: f.quotedName, inline: f.inline, unknown: f.unknown}
146 if f.inline && f.unknown {
147 f.inline = false // let `unknown` take precedence
148 }
149 }
150
151 // Reject any types with custom serialization otherwise
152 // it becomes impossible to know what sub-fields to inline.
153 tf := indirectType(f.typ)
154 if implementsAny(tf, allMethodTypes...) && tf != jsontextValueType {
155 serr = orErrorf(serr, t, "inlined Go struct field %s of type %s must not implement marshal or unmarshal methods", sf.Name, tf)
156 }
157
158 // Handle an inlined field that serializes to/from
159 // a finite number of JSON object members backed by a Go struct.
160 if tf.Kind() == reflect.Struct {
161 if f.unknown {
162 serr = orErrorf(serr, t, "inlined Go struct field %s of type %s with `unknown` tag must be a Go map of string key or a jsontext.Value", sf.Name, tf)
163 continue // invalid inlined field; treat as ignored
164 }
165 if qe.visitChildren {
166 queue = append(queue, queueEntry{tf, f.index, !seen[tf]})
167 }
168 seen[tf] = true
169 continue
170 } else if !sf.IsExported() {
171 serr = orErrorf(serr, t, "inlined Go struct field %s is not exported", sf.Name)
172 continue // invalid inlined field; treat as ignored
173 }
174
175 // Handle an inlined field that serializes to/from any number of
176 // JSON object members back by a Go map or jsontext.Value.
177 switch {
178 case tf == jsontextValueType:
179 f.fncs = nil // specially handled in arshal_inlined.go
180 case tf.Kind() == reflect.Map && tf.Key().Kind() == reflect.String:
181 if implementsAny(tf.Key(), allMethodTypes...) {
182 serr = orErrorf(serr, t, "inlined map field %s of type %s must have a string key that does not implement marshal or unmarshal methods", sf.Name, tf)
183 continue // invalid inlined field; treat as ignored
184 }
185 f.fncs = lookupArshaler(tf.Elem())
186 default:
187 serr = orErrorf(serr, t, "inlined Go struct field %s of type %s must be a Go struct, Go map of string key, or jsontext.Value", sf.Name, tf)
188 continue // invalid inlined field; treat as ignored
189 }
190
191 // Reject multiple inlined fallback fields within the same struct.
192 if inlinedFallbackIndex >= 0 {
193 serr = orErrorf(serr, t, "inlined Go struct fields %s and %s cannot both be a Go map or jsontext.Value", t.Field(inlinedFallbackIndex).Name, sf.Name)
194 // Still append f to inlinedFallbacks as there is still a
195 // check for a dominant inlined fallback before returning.
196 }
197 inlinedFallbackIndex = i
198
199 inlinedFallbacks = append(inlinedFallbacks, f)
200 } else {
201 // Handle normal Go struct field that serializes to/from
202 // a single JSON object member.
203
204 // Unexported fields cannot be serialized except for
205 // embedded fields of a struct type,
206 // which might promote exported fields of their own.
207 if !sf.IsExported() {
208 tf := indirectType(f.typ)
209 if !(sf.Anonymous && tf.Kind() == reflect.Struct) {
210 serr = orErrorf(serr, t, "Go struct field %s is not exported", sf.Name)
211 continue
212 }
213 // Unfortunately, methods on the unexported field
214 // still cannot be called.
215 if implementsAny(tf, allMethodTypes...) ||
216 (f.omitzero && implementsAny(tf, isZeroerType)) {
217 serr = orErrorf(serr, t, "Go struct field %s is not exported for method calls", sf.Name)
218 continue
219 }
220 }
221
222 // Provide a function that uses a type's IsZero method.
223 switch {
224 case sf.Type.Kind() == reflect.Interface && sf.Type.Implements(isZeroerType):
225 f.isZero = func(va addressableValue) bool {
226 // Avoid panics calling IsZero on a nil interface or
227 // non-nil interface with nil pointer.
228 return va.IsNil() || (va.Elem().Kind() == reflect.Pointer && va.Elem().IsNil()) || va.Interface().(isZeroer).IsZero()
229 }
230 case sf.Type.Kind() == reflect.Pointer && sf.Type.Implements(isZeroerType):
231 f.isZero = func(va addressableValue) bool {
232 // Avoid panics calling IsZero on nil pointer.
233 return va.IsNil() || va.Interface().(isZeroer).IsZero()
234 }
235 case sf.Type.Implements(isZeroerType):
236 f.isZero = func(va addressableValue) bool { return va.Interface().(isZeroer).IsZero() }
237 case reflect.PointerTo(sf.Type).Implements(isZeroerType):
238 f.isZero = func(va addressableValue) bool { return va.Addr().Interface().(isZeroer).IsZero() }
239 }
240
241 // Provide a function that can determine whether the value would
242 // serialize as an empty JSON value.
243 switch sf.Type.Kind() {
244 case reflect.String, reflect.Map, reflect.Array, reflect.Slice:
245 f.isEmpty = func(va addressableValue) bool { return va.Len() == 0 }
246 case reflect.Pointer, reflect.Interface:
247 f.isEmpty = func(va addressableValue) bool { return va.IsNil() }
248 }
249
250 // Reject multiple fields with same name within the same struct.
251 if j, ok := namesIndex[f.name]; ok {
252 serr = orErrorf(serr, t, "Go struct fields %s and %s conflict over JSON object name %q", t.Field(j).Name, sf.Name, f.name)
253 // Still append f to allFields as there is still a
254 // check for a dominant field before returning.
255 }
256 namesIndex[f.name] = i
257
258 f.id = len(allFields)
259 f.fncs = lookupArshaler(sf.Type)
260 allFields = append(allFields, f)
261 }
262 }
263
264 // NOTE: New users to the json package are occasionally surprised that
265 // unexported fields are ignored. This occurs by necessity due to our
266 // inability to directly introspect such fields with Go reflection
267 // without the use of unsafe.
268 //
269 // To reduce friction here, refuse to serialize any Go struct that
270 // has no JSON serializable fields, has at least one Go struct field,
271 // and does not have any `json` tags present. For example,
272 // errors returned by errors.New would fail to serialize.
273 isEmptyStruct := t.NumField() == 0
274 if !isEmptyStruct && !hasAnyJSONTag && !hasAnyJSONField {
275 serr = cmp.Or(serr, &SemanticError{GoType: t, Err: errNoExportedFields})
276 }
277 }
278
279 // Sort the fields by exact name (breaking ties by depth and
280 // then by presence of an explicitly provided JSON name).
281 // Select the dominant field from each set of fields with the same name.
282 // If multiple fields have the same name, then the dominant field
283 // is the one that exists alone at the shallowest depth,
284 // or the one that is uniquely tagged with a JSON name.
285 // Otherwise, no dominant field exists for the set.
286 flattened := allFields[:0]
287 slices.SortStableFunc(allFields, func(x, y structField) int {
288 return cmp.Or(
289 strings.Compare(x.name, y.name),
290 cmp.Compare(len(x.index), len(y.index)),
291 boolsCompare(!x.hasName, !y.hasName))
292 })
293 for len(allFields) > 0 {
294 n := 1 // number of fields with the same exact name
295 for n < len(allFields) && allFields[n-1].name == allFields[n].name {
296 n++
297 }
298 if n == 1 || len(allFields[0].index) != len(allFields[1].index) || allFields[0].hasName != allFields[1].hasName {
299 flattened = append(flattened, allFields[0]) // only keep field if there is a dominant field
300 }
301 allFields = allFields[n:]
302 }
303
304 // Sort the fields according to a breadth-first ordering
305 // so that we can re-number IDs with the smallest possible values.
306 // This optimizes use of uintSet such that it fits in the 64-entry bit set.
307 slices.SortFunc(flattened, func(x, y structField) int {
308 return cmp.Compare(x.id, y.id)
309 })
310 for i := range flattened {
311 flattened[i].id = i
312 }
313
314 // Sort the fields according to a depth-first ordering
315 // as the typical order that fields are marshaled.
316 slices.SortFunc(flattened, func(x, y structField) int {
317 return slices.Compare(x.index, y.index)
318 })
319
320 // Compute the mapping of fields in the byActualName map.
321 // Pre-fold all names so that we can lookup folded names quickly.
322 fs = structFields{
323 flattened: flattened,
324 byActualName: make(map[string]*structField, len(flattened)),
325 byFoldedName: make(map[string][]*structField, len(flattened)),
326 }
327 for i, f := range fs.flattened {
328 foldedName := string(foldName([]byte(f.name)))
329 fs.byActualName[f.name] = &fs.flattened[i]
330 fs.byFoldedName[foldedName] = append(fs.byFoldedName[foldedName], &fs.flattened[i])
331 }
332 for foldedName, fields := range fs.byFoldedName {
333 if len(fields) > 1 {
334 // The precedence order for conflicting ignoreCase names
335 // is by breadth-first order, rather than depth-first order.
336 slices.SortFunc(fields, func(x, y *structField) int {
337 return cmp.Compare(x.id, y.id)
338 })
339 fs.byFoldedName[foldedName] = fields
340 }
341 }
342 if n := len(inlinedFallbacks); n == 1 || (n > 1 && len(inlinedFallbacks[0].index) != len(inlinedFallbacks[1].index)) {
343 fs.inlinedFallback = &inlinedFallbacks[0] // dominant inlined fallback field
344 }
345 fs.reindex()
346 return fs, serr
347 }
348
349 // indirectType unwraps one level of pointer indirection
350 // similar to how Go only allows embedding either T or *T,
351 // but not **T or P (which is a named pointer).
352 func indirectType(t reflect.Type) reflect.Type {
353 if t.Kind() == reflect.Pointer && t.Name() == "" {
354 t = t.Elem()
355 }
356 return t
357 }
358
359 // matchFoldedName matches a case-insensitive name depending on the options.
360 // It assumes that foldName(f.name) == foldName(name).
361 //
362 // Case-insensitive matching is used if the `case:ignore` tag option is specified
363 // or the MatchCaseInsensitiveNames call option is specified
364 // (and the `case:strict` tag option is not specified).
365 // Functionally, the `case:ignore` and `case:strict` tag options take precedence.
366 //
367 // The v1 definition of case-insensitivity operated under strings.EqualFold
368 // and would strictly compare dashes and underscores,
369 // while the v2 definition would ignore the presence of dashes and underscores.
370 // Thus, if the MatchCaseSensitiveDelimiter call option is specified,
371 // the match is further restricted to using strings.EqualFold.
372 func (f *structField) matchFoldedName(name []byte, flags *jsonflags.Flags) bool {
373 if f.casing == caseIgnore || (flags.Get(jsonflags.MatchCaseInsensitiveNames) && f.casing != caseStrict) {
374 if !flags.Get(jsonflags.MatchCaseSensitiveDelimiter) || strings.EqualFold(string(name), f.name) {
375 return true
376 }
377 }
378 return false
379 }
380
381 const (
382 caseIgnore = 1
383 caseStrict = 2
384 )
385
386 type fieldOptions struct {
387 name string
388 quotedName string // quoted name per RFC 8785, section 3.2.2.2.
389 hasName bool
390 nameNeedEscape bool
391 casing int8 // either 0, caseIgnore, or caseStrict
392 inline bool
393 unknown bool
394 omitzero bool
395 omitempty bool
396 string bool
397 format string
398 }
399
400 // parseFieldOptions parses the `json` tag in a Go struct field as
401 // a structured set of options configuring parameters such as
402 // the JSON member name and other features.
403 func parseFieldOptions(sf reflect.StructField) (out fieldOptions, ignored bool, err error) {
404 tag, hasTag := sf.Tag.Lookup("json")
405 tagOrig := tag
406
407 // Check whether this field is explicitly ignored.
408 if tag == "-" {
409 return fieldOptions{}, true, nil
410 }
411
412 // Check whether this field is unexported and not embedded,
413 // which Go reflection cannot mutate for the sake of serialization.
414 //
415 // An embedded field of an unexported type is still capable of
416 // forwarding exported fields, which may be JSON serialized.
417 // This technically operates on the edge of what is permissible by
418 // the Go language, but the most recent decision is to permit this.
419 //
420 // See https://go.dev/issue/24153 and https://go.dev/issue/32772.
421 if !sf.IsExported() && !sf.Anonymous {
422 // Tag options specified on an unexported field suggests user error.
423 if hasTag {
424 err = cmp.Or(err, fmt.Errorf("unexported Go struct field %s cannot have non-ignored `json:%q` tag", sf.Name, tag))
425 }
426 return fieldOptions{}, true, err
427 }
428
429 // Determine the JSON member name for this Go field. A user-specified name
430 // may be provided as either an identifier or a single-quoted string.
431 // The single-quoted string allows arbitrary characters in the name.
432 // See https://go.dev/issue/2718 and https://go.dev/issue/3546.
433 out.name = sf.Name // always starts with an uppercase character
434 if len(tag) > 0 && !strings.HasPrefix(tag, ",") {
435 // For better compatibility with v1, accept almost any unescaped name.
436 n := len(tag) - len(strings.TrimLeftFunc(tag, func(r rune) bool {
437 return !strings.ContainsRune(",\\'\"`", r) // reserve comma, backslash, and quotes
438 }))
439 name := tag[:n]
440
441 // If the next character is not a comma, then the name is either
442 // malformed (if n > 0) or a single-quoted name.
443 // In either case, call consumeTagOption to handle it further.
444 var err2 error
445 if !strings.HasPrefix(tag[n:], ",") && len(name) != len(tag) {
446 name, n, err2 = consumeTagOption(tag)
447 if err2 != nil {
448 err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err2))
449 }
450 }
451 if !utf8.ValidString(name) {
452 err = cmp.Or(err, fmt.Errorf("Go struct field %s has JSON object name %q with invalid UTF-8", sf.Name, name))
453 name = string([]rune(name)) // replace invalid UTF-8 with utf8.RuneError
454 }
455 if name == "-" && tag[0] == '-' {
456 defer func() { // defer to let other errors take precedence
457 err = cmp.Or(err, fmt.Errorf("Go struct field %s has JSON object name %q; either "+
458 "use `json:\"-\"` to ignore the field or "+
459 "use `json:\"'-'%s` to specify %q as the name", sf.Name, out.name, strings.TrimPrefix(strconv.Quote(tagOrig), `"-`), name))
460 }()
461 }
462 if err2 == nil {
463 out.hasName = true
464 out.name = name
465 }
466 tag = tag[n:]
467 }
468 b, _ := jsonwire.AppendQuote(nil, out.name, &jsonflags.Flags{})
469 out.quotedName = string(b)
470 out.nameNeedEscape = jsonwire.NeedEscape(out.name)
471
472 // Handle any additional tag options (if any).
473 var wasFormat bool
474 seenOpts := make(map[string]bool)
475 for len(tag) > 0 {
476 // Consume comma delimiter.
477 if tag[0] != ',' {
478 err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid character %q before next option (expecting ',')", sf.Name, tag[0]))
479 } else {
480 tag = tag[len(","):]
481 if len(tag) == 0 {
482 err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid trailing ',' character", sf.Name))
483 break
484 }
485 }
486
487 // Consume and process the tag option.
488 opt, n, err2 := consumeTagOption(tag)
489 if err2 != nil {
490 err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err2))
491 }
492 rawOpt := tag[:n]
493 tag = tag[n:]
494 switch {
495 case wasFormat:
496 err = cmp.Or(err, fmt.Errorf("Go struct field %s has `format` tag option that was not specified last", sf.Name))
497 case strings.HasPrefix(rawOpt, "'") && strings.TrimFunc(opt, isLetterOrDigit) == "":
498 err = cmp.Or(err, fmt.Errorf("Go struct field %s has unnecessarily quoted appearance of `%s` tag option; specify `%s` instead", sf.Name, rawOpt, opt))
499 }
500 switch opt {
501 case "case":
502 if !strings.HasPrefix(tag, ":") {
503 err = cmp.Or(err, fmt.Errorf("Go struct field %s is missing value for `case` tag option; specify `case:ignore` or `case:strict` instead", sf.Name))
504 break
505 }
506 tag = tag[len(":"):]
507 opt, n, err2 := consumeTagOption(tag)
508 if err2 != nil {
509 err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed value for `case` tag option: %v", sf.Name, err2))
510 break
511 }
512 rawOpt := tag[:n]
513 tag = tag[n:]
514 if strings.HasPrefix(rawOpt, "'") {
515 err = cmp.Or(err, fmt.Errorf("Go struct field %s has unnecessarily quoted appearance of `case:%s` tag option; specify `case:%s` instead", sf.Name, rawOpt, opt))
516 }
517 switch opt {
518 case "ignore":
519 out.casing |= caseIgnore
520 case "strict":
521 out.casing |= caseStrict
522 default:
523 err = cmp.Or(err, fmt.Errorf("Go struct field %s has unknown `case:%s` tag value", sf.Name, rawOpt))
524 }
525 case "inline":
526 out.inline = true
527 case "unknown":
528 out.unknown = true
529 case "omitzero":
530 out.omitzero = true
531 case "omitempty":
532 out.omitempty = true
533 case "string":
534 out.string = true
535 case "format":
536 if !strings.HasPrefix(tag, ":") {
537 err = cmp.Or(err, fmt.Errorf("Go struct field %s is missing value for `format` tag option", sf.Name))
538 break
539 }
540 tag = tag[len(":"):]
541 opt, n, err2 := consumeTagOption(tag)
542 if err2 != nil {
543 err = cmp.Or(err, fmt.Errorf("Go struct field %s has malformed value for `format` tag option: %v", sf.Name, err2))
544 break
545 }
546 tag = tag[n:]
547 out.format = opt
548 wasFormat = true
549 default:
550 // Reject keys that resemble one of the supported options.
551 // This catches invalid mutants such as "omitEmpty" or "omit_empty".
552 normOpt := strings.ReplaceAll(strings.ToLower(opt), "_", "")
553 switch normOpt {
554 case "case", "inline", "unknown", "omitzero", "omitempty", "string", "format":
555 err = cmp.Or(err, fmt.Errorf("Go struct field %s has invalid appearance of `%s` tag option; specify `%s` instead", sf.Name, opt, normOpt))
556 }
557
558 // NOTE: Everything else is ignored. This does not mean it is
559 // forward compatible to insert arbitrary tag options since
560 // a future version of this package may understand that tag.
561 }
562
563 // Reject duplicates.
564 switch {
565 case out.casing == caseIgnore|caseStrict:
566 err = cmp.Or(err, fmt.Errorf("Go struct field %s cannot have both `case:ignore` and `case:strict` tag options", sf.Name))
567 case seenOpts[opt]:
568 err = cmp.Or(err, fmt.Errorf("Go struct field %s has duplicate appearance of `%s` tag option", sf.Name, rawOpt))
569 }
570 seenOpts[opt] = true
571 }
572 return out, false, err
573 }
574
575 // consumeTagOption consumes the next option,
576 // which is either a Go identifier or a single-quoted string.
577 // If the next option is invalid, it returns all of in until the next comma,
578 // and reports an error.
579 func consumeTagOption(in string) (string, int, error) {
580 // For legacy compatibility with v1, assume options are comma-separated.
581 i := strings.IndexByte(in, ',')
582 if i < 0 {
583 i = len(in)
584 }
585
586 switch r, _ := utf8.DecodeRuneInString(in); {
587 // Option as a Go identifier.
588 case r == '_' || unicode.IsLetter(r):
589 n := len(in) - len(strings.TrimLeftFunc(in, isLetterOrDigit))
590 return in[:n], n, nil
591 // Option as a single-quoted string.
592 case r == '\'':
593 // The grammar is nearly identical to a double-quoted Go string literal,
594 // but uses single quotes as the terminators. The reason for a custom
595 // grammar is because both backtick and double quotes cannot be used
596 // verbatim in a struct tag.
597 //
598 // Convert a single-quoted string to a double-quote string and rely on
599 // strconv.Unquote to handle the rest.
600 var inEscape bool
601 b := []byte{'"'}
602 n := len(`'`)
603 for len(in) > n {
604 r, rn := utf8.DecodeRuneInString(in[n:])
605 switch {
606 case inEscape:
607 if r == '\'' {
608 b = b[:len(b)-1] // remove escape character: `\'` => `'`
609 }
610 inEscape = false
611 case r == '\\':
612 inEscape = true
613 case r == '"':
614 b = append(b, '\\') // insert escape character: `"` => `\"`
615 case r == '\'':
616 b = append(b, '"')
617 n += len(`'`)
618 out, err := strconv.Unquote(string(b))
619 if err != nil {
620 return in[:i], i, fmt.Errorf("invalid single-quoted string: %s", in[:n])
621 }
622 return out, n, nil
623 }
624 b = append(b, in[n:][:rn]...)
625 n += rn
626 }
627 if n > 10 {
628 n = 10 // limit the amount of context printed in the error
629 }
630 return in[:i], i, fmt.Errorf("single-quoted string not terminated: %s...", in[:n])
631 case len(in) == 0:
632 return in[:i], i, io.ErrUnexpectedEOF
633 default:
634 return in[:i], i, fmt.Errorf("invalid character %q at start of option (expecting Unicode letter or single quote)", r)
635 }
636 }
637
638 func isLetterOrDigit(r rune) bool {
639 return r == '_' || unicode.IsLetter(r) || unicode.IsNumber(r)
640 }
641
642 // boolsCompare compares x and y, ordering false before true.
643 func boolsCompare(x, y bool) int {
644 switch {
645 case !x && y:
646 return -1
647 default:
648 return 0
649 case x && !y:
650 return +1
651 }
652 }