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
|
package walk
import (
"fmt"
"strings"
"math"
"unicode/utf8"
"bufio"
)
// int or string
type PathSegment interface {}
func stringPathSegment(segment PathSegment) string {
return fmt.Sprintf("%v", segment)
}
type Path []PathSegment
func (path Path) ToWalkValues() []Value {
var values []Value
for _, segment := range path {
switch s := segment.(type) {
case int:
values = append(values, ValueNumber(s))
case string:
values = append(values, ValueString(s))
default:
panic("Invalid PathSegment")
}
}
return values
}
func PathFromWalkValues(values []Value) Path {
var segments []PathSegment
for _, value := range values {
switch v := value.(type) {
case ValueNumber:
segments = append(segments, int(math.Round(float64(v))))
case ValueString:
segments = append(segments, string(v))
default:
panic("Invalid value in path")
}
}
return segments
}
type WalkItem struct {
Value []Atom
Path []Atom
}
type JSONOutStructure int
const (
JSONOutRoot JSONOutStructure = iota
JSONOutMap
JSONOutArray
JSONOutString
JSONOutValueEnd
)
type JSONOut struct {
structure []JSONOutStructure
writer *bufio.Writer
}
func (out *JSONOut) indent(adjust int) {
fmt.Fprint(out.writer, strings.Repeat("\t", len(out.structure) - 1 + adjust))
}
func (out *JSONOut) atomOut(key string, atom Atom) {
state := out.structure[len(out.structure) - 1]
switch state {
case JSONOutRoot, JSONOutMap, JSONOutArray:
switch atom.Typ {
case AtomNull, AtomBool, AtomNumber:
out.indent(0)
if state == JSONOutMap {
fmt.Fprintf(out.writer, "%q: ", key)
}
fmt.Fprint(out.writer, atom.String())
out.structure = append(out.structure, JSONOutValueEnd)
case AtomStringTerminal:
out.indent(0)
if state == JSONOutMap {
fmt.Fprintf(out.writer, "%q: ", key)
}
fmt.Fprint(out.writer, "\"")
out.structure = append(out.structure, JSONOutString)
case AtomTerminal:
switch ValueTerminal(atom.data) {
case MapBegin:
out.indent(0)
if state == JSONOutMap {
fmt.Fprintf(out.writer, "%q: ", key)
}
fmt.Fprint(out.writer, "{\n")
out.structure = append(out.structure, JSONOutMap)
case ArrayBegin:
out.indent(0)
if state == JSONOutMap {
fmt.Fprintf(out.writer, "%q: ", key)
}
fmt.Fprint(out.writer, "[\n")
out.structure = append(out.structure, JSONOutArray)
case MapEnd:
out.indent(-1)
if state != JSONOutMap {
panic("Map ended while not inside a map")
}
fmt.Fprint(out.writer, "}")
out.structure[len(out.structure) - 1] = JSONOutValueEnd
case ArrayEnd:
out.indent(-1)
if state != JSONOutArray {
panic("Array ended while not inside a array")
}
fmt.Fprint(out.writer, "]")
out.structure[len(out.structure) - 1] = JSONOutValueEnd
default:
panic("Invalid TerminalValue")
}
default:
panic("Invalid AtomType in root value")
}
case JSONOutValueEnd:
out.structure = out.structure[:len(out.structure) - 1]
underState := out.structure[len(out.structure) - 1]
if underState == JSONOutMap && atom.Typ == AtomTerminal && ValueTerminal(atom.data) == MapEnd {
fmt.Fprint(out.writer, "\n")
out.indent(-1)
fmt.Fprint(out.writer, "}")
out.structure[len(out.structure) - 1] = JSONOutValueEnd
} else if underState == JSONOutArray && atom.Typ == AtomTerminal && ValueTerminal(atom.data) == ArrayEnd {
fmt.Fprint(out.writer, "\n")
out.indent(-1)
fmt.Fprint(out.writer, "]")
out.structure[len(out.structure) - 1] = JSONOutValueEnd
} else if underState == JSONOutRoot {
panic("Tried to output JSON after root value has concluded")
} else {
fmt.Fprint(out.writer, ",\n")
out.atomOut(key, atom)
}
case JSONOutString:
if atom.Typ == AtomStringTerminal {
fmt.Fprint(out.writer, "\"")
out.structure[len(out.structure) - 1] = JSONOutValueEnd
} else {
fmt.Fprint(out.writer, atom.String())
}
default:
panic("Invalid JSONOutState")
}
}
func (out *JSONOut) Print(path Path, values []Atom) {
var segment PathSegment
if len(path) > 0 {
segment = path[len(path) - 1]
}
segmentString := stringPathSegment(segment)
for _, atom := range values {
out.atomOut(segmentString, atom)
}
}
func (out *JSONOut) AssertDone() {
out.writer.Flush()
if len(out.structure) != 2 || out.structure[0] != JSONOutRoot || out.structure[1] != JSONOutValueEnd {
panic("Program ended with incomplete JSON output")
}
}
func NewJSONOut(writer *bufio.Writer) JSONOut {
return JSONOut {
structure: []JSONOutStructure{JSONOutRoot},
writer: writer,
}
}
func ConcatData(first []Atom, second []Atom) []Atom {
res := make([]Atom, 0, len(first) + len(second))
res = append(res, first...)
res = append(res, second...)
return res
}
func Atomise(in []Value) (out []Atom) {
numAtoms := 0
for _, value := range in {
switch v := value.(type) {
case ValueTerminal, ValueNull, ValueBool, ValueNumber:
numAtoms++
case ValueString:
numAtoms += utf8.RuneCountInString(string(v)) + 2
default:
panic("Invalid WalkValue")
}
}
out = make([]Atom, 0, numAtoms)
for _, value := range in {
out = value.Atomise(out)
}
return out
}
type CompoundError int
const (
CompoundRuneOutsideString CompoundError = iota
CompoundUnknownAtom
CompoundMissingEnd
CompoundInvalidStringAtom
)
func (err CompoundError) Error() string {
switch err {
case CompoundRuneOutsideString:
return "Compound Error: Rune Outside String"
case CompoundUnknownAtom:
return "Compound Error: Unknown Atom"
case CompoundMissingEnd:
return "Compound Error: Missing End"
case CompoundInvalidStringAtom:
return "Compound Error: Invalid String Atom"
default:
panic("Invalid CompoundError")
}
}
type CompoundResult struct {
value Value
error error
}
func Compound(in []Atom) (out []Value, error error) {
numValues := 0
i := 0
inString := false
for _, atom := range in {
switch atom.Typ {
case AtomNull, AtomBool, AtomNumber, AtomTerminal:
if !inString {
numValues++
}
case AtomStringTerminal:
if inString {
numValues++
}
inString = !inString
}
}
i = 0
out = make([]Value, 0, numValues)
for {
if i >= len(in) {
break
}
atom := in[i]
i++
switch atom.Typ {
case AtomNull:
out = append(out, ValueNull{})
continue
case AtomBool:
out = append(out, ValueBool(atom.data != 0))
continue
case AtomNumber:
out = append(out, ValueNumber(math.Float64frombits(atom.data)))
continue
case AtomTerminal:
out = append(out, ValueTerminal(atom.data))
continue
case AtomStringRune:
return nil, CompoundRuneOutsideString
case AtomStringTerminal:
default:
return nil, CompoundUnknownAtom
}
// Handle string start
var builder strings.Builder
for {
if i >= len(in) {
return nil, CompoundMissingEnd
}
atom := in[i]
i++
if atom.Typ == AtomStringTerminal {
break
}
builder.WriteString(atom.String())
}
out = append(out, ValueString(builder.String()))
}
return out, nil
}
|