Debian Codegraph @

internal/decoder/type_error_legacy.go

raw
1 //go:build !go1.27 || !goexperiment.jsonv2
2
3 package decoder
4
5 import (
6 "encoding/json"
7 "fmt"
8 "reflect"
9 "strings"
10 "unsafe"
11
12 "github.com/goccy/go-json/internal/errors"
13 )
14
15 // newTypeError returns the type error as encoding/json before Go 1.27, and with GOEXPERIMENT=nojsonv2, reports
16 // it. Offset is after a literal and after the bracket of an array or an object, and at the first byte of a key.
17 // Struct is the struct type of the last field of the path, and Field the names of its fields, through their
18 // embedded fields since Go 1.24 ( see embeddedFieldNames ); the elements and the entries of the path have no name. An error in no field has neither.
19 func newTypeError(p *pendingTypeError, path []typeErrorStep, _ reflect.Type) *errors.UnmarshalTypeError {
20 e := &errors.UnmarshalTypeError{Value: p.value, Type: p.typ, Offset: p.end, Err: p.err}
21 if p.noContext {
22 return e
23 }
24 switch {
25 case p.atKey:
26 e.Offset = p.start + 1
27 case !p.literal && (p.kind == arrayValue || p.kind == objectValue):
28 e.Offset = p.start + 1
29 }
30 var names []string
31 for _, step := range path {
32 if !step.isField {
33 continue
34 }
35 e.Struct = step.structName
36 names = append(append(names, step.embedded...), step.name)
37 }
38 e.Field = strings.Join(names, ".")
39 return e
40 }
41
42 // base64Error records the error of the decoding of the string between start and end into typ, which is not
43 // base64: encoding/json before Go 1.27 returns the error of the decoding as it is.
44 func (ctx *RuntimeContext) base64Error(_, _ int64, _ reflect.Type, err error) {
45 if ctx.typeError == nil {
46 ctx.typeError = &pendingTypeError{plain: err}
47 }
48 }
49
50 // numberKindError records the type error of the value at cursor, of another kind than a number or a string,
51 // which is decoded into a json.Number, and skips it.
52 func (ctx *RuntimeContext) numberKindError(cursor, depth int64, typ reflect.Type) (int64, error) {
53 return ctx.skipTypeError(cursor, depth, typ)
54 }
55
56 // numberStringError returns the error of the string between start and end, which is not a number, decoded into
57 // a json.Number: encoding/json before Go 1.27 stops the decoding with it.
58 func (ctx *RuntimeContext) numberStringError(start, end int64, _ reflect.Type) (int64, error) {
59 return 0, fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", ctx.Buf[start:end])
60 }
61
62 // stringOptionUnquoted records the error of the value at cursor of a field of the string option, which is not in
63 // a string, and skips it: encoding/json before Go 1.27 reports it as an invalid use of the option.
64 func (ctx *RuntimeContext) stringOptionUnquoted(cursor, depth int64, typ reflect.Type) (int64, error) {
65 end, err := skipValue(ctx.Buf, skipWhiteSpace(ctx.Buf, cursor), depth)
66 if err != nil {
67 return 0, err
68 }
69 if ctx.typeError == nil {
70 ctx.typeError = &pendingTypeError{
71 plain: fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", typ),
72 }
73 }
74 return end, nil
75 }
76
77 // stringOptionError records or returns the error of the string between start and end of a field of the string
78 // option, whose bytes are not a value of typ, as encoding/json before Go 1.27 tells it from the first byte of the
79 // value and the kind of typ: a number out of the range of typ is a type error, a value which starts as no value
80 // of its kind stops the decoding, and any other one is an invalid use of the option.
81 func (ctx *RuntimeContext) stringOptionError(start, end int64, value []byte, typ reflect.Type) (int64, error) {
82 invalidUse := func() error {
83 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", value, typ)
84 }
85 save := func(err error) (int64, error) {
86 if ctx.typeError == nil {
87 ctx.typeError = &pendingTypeError{plain: err}
88 }
89 return end, nil
90 }
91 if len(value) == 0 {
92 return save(invalidUse())
93 }
94 elem := typ
95 for elem.Kind() == reflect.Pointer {
96 elem = elem.Elem()
97 }
98 invalidUse = func() error {
99 return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", value, elem)
100 }
101 switch c := value[0]; {
102 case c == 'n', c == 't', c == 'f':
103 return save(invalidUse())
104 case c == '"':
105 if elem == jsonNumberType {
106 // a JSON string, whose bytes must be a number
107 if s, ok := unquoteBytes(value); ok && !isValidNumber(s) {
108 return 0, fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", value)
109 }
110 }
111 if elem.Kind() == reflect.String {
112 return 0, invalidUse()
113 }
114 if ctx.typeError == nil {
115 ctx.typeError = &pendingTypeError{typ: elem, start: start, end: end, value: "string", kind: stringValue, literal: true}
116 }
117 return end, nil
118 case c != '-' && c-'0' > 9:
119 return 0, invalidUse()
120 }
121 switch elem.Kind() {
122 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
123 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
124 reflect.Float32, reflect.Float64:
125 if ctx.typeError == nil {
126 ctx.typeError = &pendingTypeError{
127 typ: elem, start: start, end: end, value: "number " + string(value), kind: numberValue, literal: true,
128 }
129 }
130 return end, nil
131 }
132 return 0, invalidUse()
133 }
134
135 // annotateMethodError sets the field of a type error, or the offset of a syntax error, which an unmarshal method
136 // of the value at cursor returned, as encoding/json before Go 1.27 does.
137 func annotateMethodError(cursor int64, err error, structName, fieldName string) {
138 switch e := err.(type) {
139 case *errors.UnmarshalTypeError:
140 e.Struct = structName
141 e.Field = fieldName
142 case *json.UnmarshalTypeError:
143 // the type error of encoding/json, which it sets as its own
144 e.Struct = structName
145 e.Field = fieldName
146 case *errors.SyntaxError:
147 e.Offset = cursor
148 }
149 }
150
151 // methodError returns err, which an unmarshal method of the value between cursor and end returned: encoding/json
152 // before Go 1.27 stops the decoding with it, with the field of a type error and the offset of a syntax error.
153 func (ctx *RuntimeContext) methodError(cursor, _ int64, err error, structName, fieldName string) (int64, error) {
154 annotateMethodError(cursor, err, structName, fieldName)
155 return 0, err
156 }
157
158 // timeKindTypeErrors is whether a value of a time.Time which is not a string or null is a type error: encoding/json
159 // before Go 1.27 gives it to the UnmarshalJSON of time.Time, whose error stops the decoding.
160 const timeKindTypeErrors = false
161
162 // stringOptionNumber reports whether the bytes of the string of a json.Number of the string option are stored as
163 // they are: encoding/json before Go 1.27 stores any bytes which start as a number does, without the grammar of the
164 // numbers, and decodes any other ones as a JSON value ( see stringOptionNumberDecoded ).
165 func stringOptionNumber(value []byte) bool {
166 return len(value) != 0 && (value[0] == '-' || value[0]-'0' <= 9)
167 }
168
169 // stringOptionNumberDecoded is whether the bytes of the string of a json.Number of the string option, when
170 // stringOptionNumber doesn't store them, are decoded as a JSON value, a string of a number or null, as encoding/json
171 // before Go 1.27 decodes them.
172 const stringOptionNumberDecoded = true
173
174 // stringOptionUnquotedAllocates is whether a nil pointer of a field of the string option is set to a zero value
175 // when the value of the field is not in a string: encoding/json before Go 1.27 leaves it.
176 const stringOptionUnquotedAllocates = false
177
178 // StreamOffsetBase returns the position which the offsets of the type errors of a value of a stream are relative to,
179 // of the end of the previous value and of the start of the value: encoding/json before Go 1.27 reports them from
180 // the end of the previous value.
181 func StreamOffsetBase(prevEnd, _ int64) int64 {
182 return prevEnd
183 }
184
185 // stringOptionAllocates reports whether a nil pointer of a field of the string option is set to a zero value when
186 // the value in the string of the field is not of its type: encoding/json before Go 1.27 leaves it for an empty
187 // string.
188 func stringOptionAllocates(value []byte) bool {
189 return len(value) > 0
190 }
191
192 // textUnmarshalerKindError records the type error of the value at cursor, which is not a string, of a type whose
193 // pointer type typ implements encoding.TextUnmarshaler, and skips it: encoding/json before Go 1.27 reports the
194 // pointer type.
195 func (ctx *RuntimeContext) textUnmarshalerKindError(cursor, depth int64, typ reflect.Type) (int64, error) {
196 return ctx.skipTypeError(cursor, depth, typ)
197 }
198
199 // ifaceTextUnmarshalerKindError records the type error of the value at cursor, which is not a string, of an
200 // interface value of ifaceType which holds a pointer of typ, which implements encoding.TextUnmarshaler, and skips
201 // it: encoding/json before Go 1.27 reports the interface type.
202 func (ctx *RuntimeContext) ifaceTextUnmarshalerKindError(cursor, depth int64, ifaceType, _ reflect.Type) (int64, error) {
203 return ctx.skipTypeError(cursor, depth, ifaceType)
204 }
205
206 // keptInterfaceTypeError records the type error of the value at cursor, which is not null, decoded into the
207 // value at p of the interface type typ, which has methods and holds no pointer, and skips it: encoding/json before
208 // Go 1.27 keeps the interface value, and reports the error as the other type errors.
209 func (ctx *RuntimeContext) keptInterfaceTypeError(cursor, depth int64, typ reflect.Type, _ unsafe.Pointer) (int64, error) {
210 return ctx.skipTypeError(cursor, depth, typ)
211 }
212
213 // textUnmarshalerNullSetsZero reports whether null sets a value of the kind, whose pointer type implements
214 // encoding.TextUnmarshaler, to its zero value: encoding/json before Go 1.27 does it for a slice, a map, a pointer
215 // and an interface value, as it does for any value of these kinds.
216 func textUnmarshalerNullSetsZero(kind reflect.Kind) bool {
217 switch kind {
218 case reflect.Slice, reflect.Map, reflect.Pointer, reflect.Interface:
219 return true
220 }
221 return false
222 }
223
224 // unsettableFieldError records err, the error of a field of the struct typ which can't be set, as an embedded
225 // pointer to an unexported struct, for the value at cursor, and skips the value: encoding/json before Go 1.27
226 // returns the error as it is.
227 func (ctx *RuntimeContext) unsettableFieldError(cursor, depth int64, _ reflect.Type, err error) (int64, error) {
228 buf := ctx.Buf
229 end, skipErr := skipValue(buf, skipWhiteSpace(buf, cursor), depth)
230 if skipErr != nil {
231 return 0, skipErr
232 }
233 if ctx.typeError == nil {
234 ctx.typeError = &pendingTypeError{plain: err}
235 }
236 return end, nil
237 }
238
239 // storesFloatsOutOfRange reports whether a number out of the range of a float is stored as ±Inf with its type
240 // error: encoding/json before Go 1.27 leaves the value as it is.
241 const storesFloatsOutOfRange = false
242
243 // floatRangeErrorOfInterface records the type error of the number between start and end, which is out of the
244 // range of a float64, decoded into the interface{} at p, of value f: encoding/json before Go 1.27 leaves the
245 // value as it is, and reports the error after the byte which follows the number.
246 func (ctx *RuntimeContext) floatRangeErrorOfInterface(start, end int64, _ float64, _ unsafe.Pointer) {
247 if ctx.typeError == nil {
248 ctx.typeError = &pendingTypeError{
249 typ: float64Type, start: start, end: end + 1, value: "number " + string(ctx.Buf[start:end]),
250 kind: numberValue, literal: true,
251 }
252 }
253 }
254
255 // stringOptionNumberStart reports whether c starts a number of a string of the string option which encoding/json
256 // before Go 1.27 reads: a minus sign or a digit. It reads the numbers of the keys of maps whatever they start with.
257 func stringOptionNumberStart(c byte) bool {
258 return c == '-' || c-'0' <= 9
259 }
260
261 // mapKeySupported reports whether encoding/json before Go 1.27 decodes the keys of a map of keyType, which dec
262 // decodes: strings, integers and the types which implement encoding.TextUnmarshaler.
263 func mapKeySupported(keyType reflect.Type, dec Decoder) bool {
264 if _, ok := dec.(*unmarshalTextDecoder); ok {
265 return true
266 }
267 switch keyType.Kind() {
268 case reflect.String,
269 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
270 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
271 return true
272 }
273 return false
274 }
275
276 // unsupportedMapKeys records the type error of the object at cursor of a map whose keys are not decoded ( see
277 // mapKeySupported ), and skips it: encoding/json before Go 1.27 reports the map, which is left.
278 func (ctx *RuntimeContext) unsupportedMapKeys(d *mapDecoder, cursor, depth int64, _ unsafe.Pointer) (int64, error) {
279 return ctx.skipTypeError(cursor, depth, d.mapType)
280 }