Debian Codegraph @

internal/decoder/type_error_v2.go

raw
1 //go:build go1.27 && goexperiment.jsonv2
2
3 package decoder
4
5 import (
6 stderrors "errors"
7 "fmt"
8 "reflect"
9 "strconv"
10 "strings"
11 "unsafe"
12
13 "github.com/goccy/go-json/internal/errors"
14 )
15
16 // newTypeError returns the type error as encoding/json of Go 1.27, which is made of encoding/json/v2, reports it.
17 // Offset is after the value, or after the key of a map entry. Struct is the name of the root type, and Field the
18 // path from it to the value: the names of the fields, the indices of the elements and the keys of the entries.
19 // An error at the root has neither.
20 // jsonPointerEscaper escapes a token of a JSON pointer ( RFC 6901 ).
21 var jsonPointerEscaper = strings.NewReplacer("~", "~0", "/", "~1")
22
23 func newTypeError(p *pendingTypeError, path []typeErrorStep, root reflect.Type) *errors.UnmarshalTypeError {
24 e := &errors.UnmarshalTypeError{Value: p.value, Type: p.typ, Offset: p.end, Err: p.err}
25 if !p.literal && (p.kind == arrayValue || p.kind == objectValue) {
26 e.Offset = p.start + 1
27 }
28 if p.noContext {
29 e.Offset = 0
30 return e
31 }
32 if len(path) > 0 {
33 if root.Kind() == reflect.Pointer {
34 root = root.Elem()
35 }
36 e.Struct = root.Name()
37 names := make([]string, len(path))
38 for i, step := range path {
39 names[i] = step.name
40 if step.isField {
41 // the key of a field as the input has it
42 names[i] = step.inputName
43 }
44 // encoding/json of Go 1.27 makes the path of the tokens of the JSON pointer of the value, which are
45 // escaped as a JSON pointer escapes them
46 names[i] = jsonPointerEscaper.Replace(names[i])
47 }
48 e.Field = strings.Join(names, ".")
49 }
50 return e
51 }
52
53 // base64Error records the error of the decoding of the string between start and end into typ, which is not
54 // base64: encoding/json of Go 1.27 reports it as a type error of the string, whose cause is the error.
55 func (ctx *RuntimeContext) base64Error(start, end int64, typ reflect.Type, err error) {
56 if ctx.typeError == nil {
57 ctx.typeError = &pendingTypeError{typ: typ, start: start, end: end, value: "string", kind: stringValue, err: err}
58 }
59 }
60
61 // numberKindError records the type error of the value at cursor, of another kind than a number or a string,
62 // which is decoded into a json.Number, and skips it: encoding/json of Go 1.27 reports it with no path and no
63 // offset.
64 func (ctx *RuntimeContext) numberKindError(cursor, depth int64, typ reflect.Type) (int64, error) {
65 first := ctx.typeError == nil
66 next, err := ctx.skipTypeError(cursor, depth, typ)
67 if err == nil && first {
68 ctx.typeError.noContext = true
69 }
70 return next, err
71 }
72
73 // numberStringError records the type error of the string between start and end, which is not a number, decoded
74 // into a json.Number: encoding/json of Go 1.27 reports the string, with no path and no offset.
75 func (ctx *RuntimeContext) numberStringError(start, end int64, typ reflect.Type) (int64, error) {
76 if ctx.typeError == nil {
77 ctx.typeError = &pendingTypeError{
78 typ: typ, start: start, end: end, value: "string " + string(ctx.Buf[start:end]), kind: stringValue,
79 literal: true, err: strconv.ErrSyntax, noContext: true,
80 }
81 }
82 return end, nil
83 }
84
85 // stringOptionUnquoted records the type error of the value at cursor of a field of the string option, which is not
86 // in a string, and skips it: encoding/json of Go 1.27 reports the value as a value of the type of the field.
87 func (ctx *RuntimeContext) stringOptionUnquoted(cursor, depth int64, typ reflect.Type) (int64, error) {
88 for typ.Kind() == reflect.Pointer {
89 typ = typ.Elem()
90 }
91 if typ == jsonNumberType {
92 return ctx.numberKindError(cursor, depth, typ)
93 }
94 return ctx.skipTypeError(cursor, depth, typ)
95 }
96
97 // methodError records err, which an unmarshal method of the value between cursor and end returned, if it is the
98 // first error, and returns end: encoding/json of Go 1.27 goes on after it, as after a type error, and returns it as
99 // it is.
100 func (ctx *RuntimeContext) methodError(_, end int64, err error, _, _ string) (int64, error) {
101 if ctx.typeError == nil {
102 ctx.typeError = &pendingTypeError{plain: err}
103 }
104 return end, nil
105 }
106
107 // timeKindTypeErrors is whether a value of a time.Time which is not a string or null is a type error: encoding/json
108 // of Go 1.27 reports it as a type error, after which the decoding goes on.
109 const timeKindTypeErrors = true
110
111 // stringOptionNumber reports whether the bytes of the string of a json.Number of the string option are stored as
112 // they are: encoding/json of Go 1.27 stores a number by the grammar of the numbers, and nothing else.
113 func stringOptionNumber(value []byte) bool {
114 return isValidNumber(value)
115 }
116
117 // stringOptionNumberDecoded is whether the bytes of the string of a json.Number of the string option, when they are
118 // not a number, are decoded as a JSON value: encoding/json of Go 1.27 reports them as a type error.
119 const stringOptionNumberDecoded = false
120
121 // stringOptionError records the type error of the string between start and end of a field of the string option,
122 // whose bytes are not a value of typ: encoding/json of Go 1.27 reports the bytes as a number for a number type,
123 // and else the string, whose cause is a syntax error.
124 func (ctx *RuntimeContext) stringOptionError(start, end int64, value []byte, typ reflect.Type) (int64, error) {
125 for typ.Kind() == reflect.Pointer {
126 typ = typ.Elem()
127 }
128 if typ == jsonNumberType {
129 return ctx.numberStringError(start, end, typ)
130 }
131 if ctx.typeError != nil {
132 return end, nil
133 }
134 p := &pendingTypeError{typ: typ, start: start, end: end, kind: stringValue, literal: true}
135 switch typ.Kind() {
136 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
137 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
138 reflect.Float32, reflect.Float64:
139 p.value = "number " + string(value)
140 case reflect.String:
141 // the bytes are decoded as a JSON string, whose syntax error is the cause
142 p.value = "string"
143 p.err = stringOptionStringError(value)
144 default:
145 p.value = "string " + string(ctx.Buf[start:end])
146 p.err = strconv.ErrSyntax
147 }
148 ctx.typeError = p
149 return end, nil
150 }
151
152 // stringOptionUnquotedAllocates is whether a nil pointer of a field of the string option is set to a zero value
153 // when the value of the field is not in a string: encoding/json of Go 1.27 sets it.
154 const stringOptionUnquotedAllocates = true
155
156 // StreamOffsetBase returns the position which the offsets of the type errors of a value of a stream are relative to,
157 // of the end of the previous value and of the start of the value: encoding/json of Go 1.27 reports them from the
158 // start of the value.
159 func StreamOffsetBase(_, valueStart int64) int64 {
160 return valueStart
161 }
162
163 // stringOptionAllocates reports whether a nil pointer of a field of the string option is set to a zero value when
164 // the value in the string of the field is not of its type: encoding/json of Go 1.27 sets it.
165 func stringOptionAllocates([]byte) bool {
166 return true
167 }
168
169 // errTextUnmarshalerKind is the cause of the type error of a value which is not a string, of a type which
170 // implements encoding.TextUnmarshaler, as encoding/json of Go 1.27 reports it.
171 var errTextUnmarshalerKind = stderrors.New("JSON value must be string type")
172
173 // textUnmarshalerKindError records the type error of the value at cursor, which is not a string, of a type whose
174 // pointer type typ implements encoding.TextUnmarshaler, and skips it: encoding/json of Go 1.27 reports the type
175 // of the value, and the cause of the error.
176 func (ctx *RuntimeContext) textUnmarshalerKindError(cursor, depth int64, typ reflect.Type) (int64, error) {
177 first := ctx.typeError == nil
178 next, err := ctx.skipTypeError(cursor, depth, typ.Elem())
179 if err == nil && first {
180 ctx.typeError.err = errTextUnmarshalerKind
181 }
182 return next, err
183 }
184
185 // ifaceTextUnmarshalerKindError records the type error of the value at cursor, which is not a string, of an
186 // interface value of ifaceType which holds a pointer of typ, which implements encoding.TextUnmarshaler, and skips
187 // it: encoding/json of Go 1.27 reports it as the one of the pointer ( see textUnmarshalerKindError ).
188 func (ctx *RuntimeContext) ifaceTextUnmarshalerKindError(cursor, depth int64, _, typ reflect.Type) (int64, error) {
189 return ctx.textUnmarshalerKindError(cursor, depth, typ)
190 }
191
192 // keptInterfaceTypeError records the type error of the value at cursor, which is not null, decoded into the
193 // value at p of the interface type typ, which has methods and holds no pointer, and skips it: encoding/json of Go
194 // 1.27 sets the interface value to nil, and reports the error at the start of the value.
195 func (ctx *RuntimeContext) keptInterfaceTypeError(cursor, depth int64, typ reflect.Type, p unsafe.Pointer) (int64, error) {
196 *(*[2]unsafe.Pointer)(p) = [2]unsafe.Pointer{}
197 first := ctx.typeError == nil
198 next, err := ctx.skipTypeError(cursor, depth, typ)
199 if err == nil && first {
200 ctx.typeError.atStart = true
201 }
202 return next, err
203 }
204
205 // textUnmarshalerNullSetsZero reports whether null sets a value of the kind, whose pointer type implements
206 // encoding.TextUnmarshaler, to its zero value: encoding/json of Go 1.27 leaves every such value as it is.
207 func textUnmarshalerNullSetsZero(reflect.Kind) bool {
208 return false
209 }
210
211 // errUnsettableEmbeddedPointer is the cause which encoding/json of Go 1.27 reports for a field promoted from an
212 // embedded pointer to an unexported struct, which can't be set.
213 var errUnsettableEmbeddedPointer = stderrors.New("cannot set embedded pointer to unexported struct type")
214
215 // unsettableFieldError records the type error of the value at cursor of a field of the struct typ which can't be
216 // set, as an embedded pointer to an unexported struct, and skips the value: encoding/json of Go 1.27 reports it as
217 // a type error of the struct at the start of the value.
218 func (ctx *RuntimeContext) unsettableFieldError(cursor, depth int64, typ reflect.Type, _ error) (int64, error) {
219 first := ctx.typeError == nil
220 next, err := ctx.skipTypeError(cursor, depth, typ)
221 if err == nil && first {
222 ctx.typeError.err = errUnsettableEmbeddedPointer
223 ctx.typeError.atStart = true
224 }
225 return next, err
226 }
227
228 // storesFloatsOutOfRange reports whether a number out of the range of a float is stored as ±Inf with its type
229 // error, as encoding/json of Go 1.27 does.
230 const storesFloatsOutOfRange = true
231
232 // floatRangeErrorOfInterface records the type error of the number between start and end, which is out of the
233 // range of a float64, decoded into the interface{} at p, and stores f, which is ±Inf, as encoding/json of Go 1.27
234 // does.
235 func (ctx *RuntimeContext) floatRangeErrorOfInterface(start, end int64, f float64, p unsafe.Pointer) {
236 **(**any)(unsafe.Pointer(&p)) = ctx.boxFloat(f)
237 ctx.numberTypeError(start, end, float64Type)
238 }
239
240 // stringOptionNumberStart reports whether c starts a number of a string of the string option which encoding/json
241 // reads: encoding/json of Go 1.27 reads whatever strconv reads.
242 func stringOptionNumberStart(byte) bool {
243 return true
244 }
245
246 // mapKeySupported reports whether encoding/json of Go 1.27 decodes the keys of a map of keyType, which dec
247 // decodes: any key but a bool and a key of a type which no key is decoded into.
248 func mapKeySupported(keyType reflect.Type, dec Decoder) bool {
249 if _, ok := dec.(*invalidDecoder); ok {
250 return false
251 }
252 return keyType.Kind() != reflect.Bool
253 }
254
255 // unsupportedMapKeys records the type error of the first key of the object at cursor of a map whose keys are not
256 // decoded ( see mapKeySupported ), and skips the object: encoding/json of Go 1.27 reports the key as a string of
257 // the type of the keys, and makes the map.
258 func (ctx *RuntimeContext) unsupportedMapKeys(d *mapDecoder, cursor, depth int64, p unsafe.Pointer) (int64, error) {
259 buf := ctx.Buf
260 if *(*unsafe.Pointer)(p) == nil {
261 *(*unsafe.Pointer)(p) = reflect.MakeMapWithSize(d.mapType, 0).UnsafePointer()
262 }
263 cursor = skipWhiteSpace(buf, cursor) + 1
264 for {
265 cursor = skipWhiteSpace(buf, cursor)
266 if buf[cursor] == '}' {
267 return cursor + 1, nil
268 }
269 keyStart := cursor
270 keyEnd, err := skipValue(buf, cursor, depth)
271 if err != nil {
272 return 0, err
273 }
274 if ctx.typeError == nil {
275 ctx.typeError = &pendingTypeError{
276 typ: d.keyType, start: keyStart, end: keyEnd, value: "string", kind: stringValue, atKey: true,
277 literal: true,
278 }
279 }
280 cursor = skipWhiteSpace(buf, keyEnd)
281 if buf[cursor] != ':' {
282 return 0, errors.ErrExpected("colon after object key", cursor)
283 }
284 end, err := skipValue(buf, skipWhiteSpace(buf, cursor+1), depth)
285 if err != nil {
286 return 0, err
287 }
288 cursor = skipWhiteSpace(buf, end)
289 switch buf[cursor] {
290 case ',':
291 cursor++
292 case '}':
293 return cursor + 1, nil
294 default:
295 return 0, errors.ErrExpected("comma after object value", cursor)
296 }
297 }
298 }
299
300 // stringOptionStringError returns the syntax error of the bytes of a string of the string option of a string,
301 // which are not a JSON string and nothing else, as encoding/json of Go 1.27 reports it.
302 func stringOptionStringError(value []byte) error {
303 if len(value) == 0 {
304 return errors.ErrSyntax("unexpected end of JSON input", 0)
305 }
306 if value[0] != '"' {
307 return errors.ErrSyntax(fmt.Sprintf("invalid character %s looking for beginning of object key string", quoteChar(value[0])), 0)
308 }
309 i := 1
310 for {
311 if i >= len(value) {
312 return errors.ErrSyntax("unexpected end of JSON input", 0)
313 }
314 c := value[i]
315 if c == '"' {
316 i++
317 break
318 }
319 if c != '\\' {
320 i++
321 continue
322 }
323 if i+1 >= len(value) {
324 return errors.ErrSyntax("unexpected end of JSON input", 0)
325 }
326 switch value[i+1] {
327 case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
328 i += 2
329 continue
330 case 'u':
331 if i+6 <= len(value) && isHex(value[i+2:i+6]) {
332 i += 6
333 continue
334 }
335 return errors.ErrSyntax(fmt.Sprintf("invalid escape sequence `%s` in string", value[i:min(i+6, len(value))]), 0)
336 }
337 return errors.ErrSyntax(fmt.Sprintf("invalid escape sequence `%s` in string", value[i:i+2]), 0)
338 }
339 if i < len(value) {
340 return errors.ErrSyntax(fmt.Sprintf("invalid character %s after string value", quoteChar(value[i])), 0)
341 }
342 return nil
343 }
344
345 // isHex reports whether every byte of b is a hexadecimal digit.
346 func isHex(b []byte) bool {
347 for _, c := range b {
348 if !('0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F') {
349 return false
350 }
351 }
352 return true
353 }