-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoml_tree.go
More file actions
316 lines (290 loc) · 8.88 KB
/
Copy pathtoml_tree.go
File metadata and controls
316 lines (290 loc) · 8.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Tree-based TOML→JSON translator. Used as a fallback when the streaming path
// detects an out-of-order section that requires re-entry into a closed table.
package tojson
import (
"bytes"
"fmt"
)
// --------------------------------------------------------------------------
// Intermediate JSON node tree
// --------------------------------------------------------------------------
// jnode is a node in the minimal JSON value tree built during TOML parsing.
// Exactly one of raw/obj/arr/aot is non-nil.
type jnode struct {
raw []byte // scalar: already-encoded JSON bytes
obj []*jpair // object: ordered key-value pairs
arr []*jnode // inline array (immutable after parse)
aot []*jnode // array-of-tables (grows with each [[header]])
}
type jpair struct {
key []byte
val *jnode
explicit bool // true when created by a [table] header line
}
var (
nodeTrue = &jnode{raw: []byte("true")}
nodeFalse = &jnode{raw: []byte("false")}
)
func newObjectNode() *jnode {
return &jnode{obj: make([]*jpair, 0, 4)}
}
func newScalarNode(raw []byte) *jnode {
return &jnode{raw: raw}
}
// findPair returns the jpair with the given key, or nil.
func (n *jnode) findPair(key []byte) *jpair {
for _, p := range n.obj {
if bytes.Equal(p.key, key) {
return p
}
}
return nil
}
// --------------------------------------------------------------------------
// Serializer
// --------------------------------------------------------------------------
func serializeNode(n *jnode, buf *bytes.Buffer) {
switch {
case n.raw != nil:
buf.Write(n.raw)
case n.obj != nil:
buf.WriteByte('{')
for i, p := range n.obj {
if i > 0 {
buf.WriteByte(',')
}
writeJSONString(p.key, buf)
buf.WriteByte(':')
serializeNode(p.val, buf)
}
buf.WriteByte('}')
case n.arr != nil:
buf.WriteByte('[')
for i, elem := range n.arr {
if i > 0 {
buf.WriteByte(',')
}
serializeNode(elem, buf)
}
buf.WriteByte(']')
case n.aot != nil:
buf.WriteByte('[')
for i, elem := range n.aot {
if i > 0 {
buf.WriteByte(',')
}
serializeNode(elem, buf)
}
buf.WriteByte(']')
}
}
// --------------------------------------------------------------------------
// Parser
// --------------------------------------------------------------------------
type tomlParser struct {
rawLines [][]byte
lineIdx int
root *jnode
ctx *jnode // current table context (reset by [header] and [[header]])
}
func newTOMLParser(input []byte) *tomlParser {
lines := bytes.Split(input, []byte{'\n'})
// remove spurious trailing empty element from Split
if len(lines) > 0 && len(lines[len(lines)-1]) == 0 {
lines = lines[:len(lines)-1]
}
root := newObjectNode()
return &tomlParser{rawLines: lines, root: root, ctx: root}
}
func tomlConvertTree(input []byte) ([]byte, error) {
p := newTOMLParser(input)
if err := p.parseDocument(); err != nil {
return nil, err
}
var buf bytes.Buffer
buf.Grow(len(input))
serializeNode(p.root, &buf)
return buf.Bytes(), nil
}
func (p *tomlParser) parseDocument() error {
for p.lineIdx < len(p.rawLines) {
line := p.rawLines[p.lineIdx]
p.lineIdx++
line = bytes.TrimRight(line, " \t\r")
line = stripComment(line, false)
trimmed := bytes.TrimSpace(line)
if len(trimmed) == 0 {
continue
}
leading := leadingSpaces(line)
if bytes.HasPrefix(trimmed, []byte("[[")) {
if err := p.parseArrayTableHeader(trimmed); err != nil {
return atLineCol(p.lineIdx-1, leading, err)
}
} else if trimmed[0] == '[' {
if err := p.parseTableHeader(trimmed); err != nil {
return atLineCol(p.lineIdx-1, leading, err)
}
} else {
if err := p.parseKeyValue(trimmed, p.lineIdx-1, leading, p.ctx); err != nil {
return err
}
}
}
return nil
}
// --------------------------------------------------------------------------
// Table headers
// --------------------------------------------------------------------------
func (p *tomlParser) parseTableHeader(line []byte) error {
if len(line) < 2 || line[0] != '[' || line[len(line)-1] != ']' {
return fmt.Errorf("malformed table header: %s", line)
}
inner := line[1 : len(line)-1]
var pathBuf [tomlMaxNesting][]byte
path, rest, err := parseTOMLKeyPath(inner, pathBuf[:0])
if err != nil {
return err
}
rest = bytes.TrimSpace(rest)
if len(rest) != 0 {
return fmt.Errorf("unexpected content after table header key: %s", rest)
}
if len(path) == 0 {
return fmt.Errorf("empty table header")
}
node, err := p.getOrCreateNode(p.root, path[:len(path)-1], false)
if err != nil {
return err
}
lastKey := path[len(path)-1]
existing := node.findPair(lastKey)
if existing != nil {
switch {
case existing.val.raw != nil:
return fmt.Errorf("cannot define table %q: key already has a scalar value", bytes.Join(path, []byte(".")))
case existing.val.arr != nil:
return fmt.Errorf("cannot define table %q: key already has an inline array", bytes.Join(path, []byte(".")))
case existing.explicit:
return fmt.Errorf("duplicate table header [%s]", bytes.Join(path, []byte(".")))
case existing.val.aot != nil:
// [a] after [[a]] — enter the last aot element
p.ctx = existing.val.aot[len(existing.val.aot)-1]
return nil
}
// implicit object — mark explicit and use it
existing.explicit = true
p.ctx = existing.val
return nil
}
newNode := newObjectNode()
node.obj = append(node.obj, &jpair{key: lastKey, val: newNode, explicit: true})
p.ctx = newNode
return nil
}
func (p *tomlParser) parseArrayTableHeader(line []byte) error {
if len(line) < 4 || !bytes.HasPrefix(line, []byte("[[")) || !bytes.HasSuffix(line, []byte("]]")) {
return fmt.Errorf("malformed array-of-tables header: %s", line)
}
inner := line[2 : len(line)-2]
var pathBuf [tomlMaxNesting][]byte
path, rest, err := parseTOMLKeyPath(inner, pathBuf[:0])
if err != nil {
return err
}
rest = bytes.TrimSpace(rest)
if len(rest) != 0 {
return fmt.Errorf("unexpected content after array-of-tables header key: %s", rest)
}
if len(path) == 0 {
return fmt.Errorf("empty array-of-tables header")
}
node, err := p.getOrCreateNode(p.root, path[:len(path)-1], false)
if err != nil {
return err
}
lastKey := path[len(path)-1]
existing := node.findPair(lastKey)
newEntry := newObjectNode()
if existing != nil {
if existing.val.aot == nil {
return fmt.Errorf("cannot use [[%s]]: key already exists as a non-array", bytes.Join(path, []byte(".")))
}
existing.val.aot = append(existing.val.aot, newEntry)
} else {
aotNode := &jnode{aot: []*jnode{newEntry}}
node.obj = append(node.obj, &jpair{key: lastKey, val: aotNode})
}
p.ctx = newEntry
return nil
}
// getOrCreateNode navigates or creates a path of intermediate object nodes
// under root. Used for table headers and dotted key traversal.
func (p *tomlParser) getOrCreateNode(root *jnode, path [][]byte, _ bool) (*jnode, error) {
cur := root
for i, key := range path {
if cur.obj == nil {
return nil, fmt.Errorf("cannot navigate into non-object node at %q", bytes.Join(path[:i+1], []byte(".")))
}
pair := cur.findPair(key)
if pair == nil {
next := newObjectNode()
cur.obj = append(cur.obj, &jpair{key: key, val: next})
cur = next
continue
}
v := pair.val
switch {
case v.raw != nil:
return nil, fmt.Errorf("key %q already has a scalar value", bytes.Join(path[:i+1], []byte(".")))
case v.arr != nil:
return nil, fmt.Errorf("key %q is an inline array and cannot have subtables", bytes.Join(path[:i+1], []byte(".")))
case v.aot != nil:
cur = v.aot[len(v.aot)-1]
default:
cur = v
}
}
return cur, nil
}
// --------------------------------------------------------------------------
// Key-value parsing
// --------------------------------------------------------------------------
func (p *tomlParser) parseKeyValue(line []byte, rawLine int, leading int, ctx *jnode) error {
var pathBuf [tomlMaxNesting][]byte
path, rest, err := parseTOMLKeyPath(line, pathBuf[:0])
if err != nil {
return atLineCol(rawLine, leading, err)
}
rest = bytes.TrimSpace(rest)
if len(rest) == 0 || rest[0] != '=' {
return atLineCol(rawLine, leading+len(line)-len(rest), fmt.Errorf("expected '=' after key, got: %s", rest))
}
rest = bytes.TrimSpace(rest[1:])
valCol := leading + len(line) - len(rest)
var targetNode *jnode
if len(path) > 1 {
targetNode, err = p.getOrCreateNode(ctx, path[:len(path)-1], false)
if err != nil {
return atLineCol(rawLine, leading, err)
}
} else {
targetNode = ctx
}
lastKey := path[len(path)-1]
if targetNode.findPair(lastKey) != nil {
return atLineCol(rawLine, leading, fmt.Errorf("duplicate key %q", lastKey))
}
raw, consumed, err := parseTOMLValue(rest, p.rawLines, p.lineIdx-1)
if err != nil {
return atLineCol(rawLine, valCol, err)
}
p.lineIdx += consumed
targetNode.obj = append(targetNode.obj, &jpair{key: lastKey, val: raw})
return nil
}
// fromTOMLTree converts TOML to JSON using the tree-based path directly,
// skipping the streaming attempt.
func fromTOMLTree(src []byte) ([]byte, error) {
return tomlConvertTree(src)
}