Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/jsontext/errors.go

raw
1 // Copyright 2020 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 jsontext
6
7 import (
8 "bytes"
9 "io"
10 "strconv"
11
12 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/internal/jsonwire"
13 )
14
15 const errorPrefix = "jsontext: "
16
17 type ioError struct {
18 action string // either "read" or "write"
19 err error
20 }
21
22 func (e *ioError) Error() string {
23 return errorPrefix + e.action + " error: " + e.err.Error()
24 }
25 func (e *ioError) Unwrap() error {
26 return e.err
27 }
28
29 // SyntacticError is a description of a syntactic error that occurred when
30 // encoding or decoding JSON according to the grammar.
31 //
32 // The contents of this error as produced by this package may change over time.
33 type SyntacticError struct {
34 requireKeyedLiterals
35 nonComparable
36
37 // ByteOffset indicates that an error occurred after this byte offset.
38 ByteOffset int64
39 // JSONPointer indicates that an error occurred within this JSON value
40 // as indicated using the JSON Pointer notation (see RFC 6901).
41 JSONPointer Pointer
42
43 // Err is the underlying error.
44 Err error
45 }
46
47 // wrapSyntacticError wraps an error and annotates it with a precise location
48 // using the provided [encoderState] or [decoderState].
49 // If err is an [ioError] or [io.EOF], then it is not wrapped.
50 //
51 // It takes a relative offset pos that can be resolved into
52 // an absolute offset using state.offsetAt.
53 //
54 // It takes a where that specify how the JSON pointer is derived.
55 // If the underlying error is a [pointerSuffixError],
56 // then the suffix is appended to the derived pointer.
57 func wrapSyntacticError(state interface {
58 offsetAt(pos int) int64
59 AppendStackPointer(b []byte, where int) []byte
60 }, err error, pos, where int) error {
61 if _, ok := err.(*ioError); err == io.EOF || ok {
62 return err
63 }
64 offset := state.offsetAt(pos)
65 ptr := state.AppendStackPointer(nil, where)
66 if serr, ok := err.(*pointerSuffixError); ok {
67 ptr = serr.appendPointer(ptr)
68 err = serr.error
69 }
70 if d, ok := state.(*decoderState); ok && err == errMismatchDelim {
71 where := "at start of value"
72 if len(d.Tokens.Stack) > 0 && d.Tokens.Last.Length() > 0 {
73 switch {
74 case d.Tokens.Last.isArray():
75 where = "after array element (expecting ',' or ']')"
76 ptr = []byte(Pointer(ptr).Parent()) // problem is with parent array
77 case d.Tokens.Last.isObject():
78 where = "after object value (expecting ',' or '}')"
79 ptr = []byte(Pointer(ptr).Parent()) // problem is with parent object
80 }
81 }
82 err = jsonwire.NewInvalidCharacterError(d.buf[pos:], where)
83 }
84 return &SyntacticError{ByteOffset: offset, JSONPointer: Pointer(ptr), Err: err}
85 }
86
87 func (e *SyntacticError) Error() string {
88 pointer := e.JSONPointer
89 offset := e.ByteOffset
90 b := []byte(errorPrefix)
91 if e.Err != nil {
92 b = append(b, e.Err.Error()...)
93 if e.Err == ErrDuplicateName {
94 b = strconv.AppendQuote(append(b, ' '), pointer.LastToken())
95 pointer = pointer.Parent()
96 offset = 0 // not useful to print offset for duplicate names
97 }
98 } else {
99 b = append(b, "syntactic error"...)
100 }
101 if pointer != "" {
102 b = strconv.AppendQuote(append(b, " within "...), jsonwire.TruncatePointer(string(pointer), 100))
103 }
104 if offset > 0 {
105 b = strconv.AppendInt(append(b, " after offset "...), offset, 10)
106 }
107 return string(b)
108 }
109
110 func (e *SyntacticError) Unwrap() error {
111 return e.Err
112 }
113
114 // pointerSuffixError represents a JSON pointer suffix to be appended
115 // to [SyntacticError.JSONPointer]. It is an internal error type
116 // used within this package and does not appear in the public API.
117 //
118 // This type is primarily used to annotate errors in Encoder.WriteValue
119 // and Decoder.ReadValue with precise positions.
120 // At the time WriteValue or ReadValue is called, a JSON pointer to the
121 // upcoming value can be constructed using the Encoder/Decoder state.
122 // However, tracking pointers within values during normal operation
123 // would incur a performance penalty in the error-free case.
124 //
125 // To provide precise error locations without this overhead,
126 // the error is wrapped with object names or array indices
127 // as the call stack is popped when an error occurs.
128 // Since this happens in reverse order, pointerSuffixError holds
129 // the pointer in reverse and is only later reversed when appending to
130 // the pointer prefix.
131 //
132 // For example, if the encoder is at "/alpha/bravo/charlie"
133 // and an error occurs in WriteValue at "/xray/yankee/zulu", then
134 // the final pointer should be "/alpha/bravo/charlie/xray/yankee/zulu".
135 //
136 // As pointerSuffixError is populated during the error return path,
137 // it first contains "/zulu", then "/zulu/yankee",
138 // and finally "/zulu/yankee/xray".
139 // These tokens are reversed and concatenated to "/alpha/bravo/charlie"
140 // to form the full pointer.
141 type pointerSuffixError struct {
142 error
143
144 // reversePointer is a JSON pointer, but with each token in reverse order.
145 reversePointer []byte
146 }
147
148 // wrapWithObjectName wraps err with a JSON object name access,
149 // which must be a valid quoted JSON string.
150 func wrapWithObjectName(err error, quotedName []byte) error {
151 serr, _ := err.(*pointerSuffixError)
152 if serr == nil {
153 serr = &pointerSuffixError{error: err}
154 }
155 name := jsonwire.UnquoteMayCopy(quotedName, false)
156 serr.reversePointer = appendEscapePointerName(append(serr.reversePointer, '/'), name)
157 return serr
158 }
159
160 // wrapWithArrayIndex wraps err with a JSON array index access.
161 func wrapWithArrayIndex(err error, index int64) error {
162 serr, _ := err.(*pointerSuffixError)
163 if serr == nil {
164 serr = &pointerSuffixError{error: err}
165 }
166 serr.reversePointer = strconv.AppendUint(append(serr.reversePointer, '/'), uint64(index), 10)
167 return serr
168 }
169
170 // appendPointer appends the path encoded in e to the end of pointer.
171 func (e *pointerSuffixError) appendPointer(pointer []byte) []byte {
172 // Copy each token in reversePointer to the end of pointer in reverse order.
173 // Double reversal means that the appended suffix is now in forward order.
174 bi, bo := e.reversePointer, pointer
175 for len(bi) > 0 {
176 i := bytes.LastIndexByte(bi, '/')
177 bi, bo = bi[:i], append(bo, bi[i:]...)
178 }
179 return bo
180 }