-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
389 lines (345 loc) · 9.53 KB
/
formatter.go
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
................................................................................
. Copyright (c) 2009-2024 Crater Dog Technologies. All Rights Reserved. .
................................................................................
. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. .
. .
. This code is free software; you can redistribute it and/or modify it under .
. the terms of The MIT License (MIT), as published by the Open Source .
. Initiative. (See https://opensource.org/license/MIT) .
................................................................................
*/
package collection
import (
fmt "fmt"
ref "reflect"
stc "strconv"
sts "strings"
)
// CLASS ACCESS
// Reference
var formatterClass = &formatterClass_{
defaultMaximum_: 8,
}
// Function
/*
Formatter defines an implementation of a formatter-like class that uses Crater
Dog Collection Notation™ (CDCN) for formatting collections. This is required by
the Go `Stringer` interface when the `String()` method is called on a
collection. If not for the requirement to support the Go `Stringer` interface
this class would be located in the `cdcn` package with the rest of the CDCN
classes. Instead, the `cdcn.FormatterClass` must delegate its implementation to
this class to avoid circular dependencies.
*/
func Formatter() FormatterClassLike {
return formatterClass
}
// CLASS METHODS
// Target
type formatterClass_ struct {
defaultMaximum_ int
}
// Constants
func (c *formatterClass_) DefaultMaximum() int {
return c.defaultMaximum_
}
// Constructors
func (c *formatterClass_) Make() FormatterLike {
return &formatter_{
maximum_: c.defaultMaximum_,
}
}
func (c *formatterClass_) MakeWithMaximum(maximum int) FormatterLike {
if maximum < 0 {
maximum = c.defaultMaximum_
}
return &formatter_{
maximum_: maximum,
}
}
// INSTANCE METHODS
// Target
type formatter_ struct {
depth_ int
maximum_ int
result_ sts.Builder
}
// Attributes
func (v *formatter_) GetDepth() int {
return v.depth_
}
func (v *formatter_) GetMaximum() int {
return v.maximum_
}
// Public
func (v *formatter_) FormatCollection(collection Collection) string {
var reflected = ref.ValueOf(collection)
v.formatCollection(reflected)
v.appendNewline()
return v.getResult()
}
// Private
func (v *formatter_) appendNewline() {
var separator = "\n"
for level := 0; level < v.depth_; level++ {
separator += " "
}
v.result_.WriteString(separator)
}
func (v *formatter_) appendString(s string) {
v.result_.WriteString(s)
}
func (v *formatter_) formatArray(array ref.Value) {
var size = array.Len()
switch {
case v.depth_ == v.maximum_:
// Truncate the recursion.
v.appendString("...")
case size == 0:
v.appendString(" ")
case size == 1:
var value = array.Index(0)
v.formatValue(value.Interface())
default:
v.depth_++
for i := 0; i < size; i++ {
v.appendNewline()
var value = array.Index(i)
v.formatValue(value.Interface())
}
v.depth_--
v.appendNewline()
}
}
func (v *formatter_) formatAssociation(association ref.Value) {
var key = association.MethodByName("GetKey").Call([]ref.Value{})[0]
v.formatValue(key.Interface())
v.appendString(": ")
var value = association.MethodByName("GetValue").Call([]ref.Value{})[0]
v.formatValue(value.Interface())
}
func (v *formatter_) formatBoolean(boolean bool) {
v.appendString(stc.FormatBool(boolean))
}
func (v *formatter_) formatCollection(collection ref.Value) {
v.appendString("[")
var type_ = v.getName(collection)
switch collection.Kind() {
case ref.Array, ref.Slice:
v.formatArray(collection)
case ref.Map:
v.formatMap(collection)
case ref.Interface, ref.Pointer:
v.formatSequence(collection)
default:
panic(fmt.Sprintf(
"Attempted to format:\n value: %v\n type: %v\n kind: %v\n",
collection.Interface(),
collection.Type(),
collection.Kind(),
))
}
v.appendString("](" + type_ + ")")
}
func (v *formatter_) formatComplex(complex_ complex128) {
var real_ = real(complex_)
var imag_ = imag(complex_)
v.appendString("(")
v.formatFloat(real_)
if imag_ >= 0.0 {
v.appendString("+")
}
v.formatFloat(imag_)
v.appendString("i)")
}
func (v *formatter_) formatFloat(float float64) {
var str = stc.FormatFloat(float, 'G', -1, 64)
if !sts.Contains(str, ".") && !sts.Contains(str, "E") {
str += ".0"
}
v.appendString(str)
}
func (v *formatter_) formatInteger(integer int64) {
v.appendString(stc.FormatInt(integer, 10))
}
func (v *formatter_) formatMap(map_ ref.Value) {
var keys = map_.MapKeys()
var size = len(keys)
switch {
case v.depth_ == v.maximum_:
// Truncate the recursion.
v.appendString("...")
case size == 0:
v.appendString(":")
case size == 1:
var key = keys[0]
var value = map_.MapIndex(key)
v.formatValue(key.Interface())
v.appendString(": ")
v.formatValue(value.Interface())
default:
v.depth_++
for i := 0; i < size; i++ {
v.appendNewline()
var key = keys[i]
var value = map_.MapIndex(key)
v.formatValue(key.Interface())
v.appendString(": ")
v.formatValue(value.Interface())
}
v.depth_--
v.appendNewline()
}
}
func (v *formatter_) formatNil(value any) {
v.appendString("<nil>")
}
func (v *formatter_) formatRune(rune_ rune) {
v.appendString(stc.QuoteRune(rune_))
}
func (v *formatter_) formatSequence(sequence ref.Value) {
var iterator = sequence.MethodByName("GetIterator").Call([]ref.Value{})[0]
var size = sequence.MethodByName("GetSize").Call([]ref.Value{})[0].Interface()
switch {
case v.depth_ == v.maximum_:
// Truncate the recursion.
v.appendString("...")
case size == 0:
if sequence.MethodByName("GetKeys").IsValid() {
v.appendString(":") // This is an empty sequence of associations.
} else {
v.appendString(" ") // This is an empty sequence of values.
}
case size == 1:
var value = iterator.MethodByName("GetNext").Call([]ref.Value{})[0]
v.formatValue(value.Interface())
default:
v.depth_++
for iterator.MethodByName("HasNext").Call([]ref.Value{})[0].Interface().(bool) {
v.appendNewline()
var value = iterator.MethodByName("GetNext").Call([]ref.Value{})[0]
v.formatValue(value.Interface())
}
v.depth_--
v.appendNewline()
}
}
func (v *formatter_) formatString(string_ string) {
v.appendString(stc.Quote(string_))
}
func (v *formatter_) formatUnsigned(unsigned uint64) {
v.appendString("0x" + stc.FormatUint(unsigned, 16))
}
func (v *formatter_) formatValue(value any) {
// NOTE: Because the Go language doesn't handle generic types very well in
// type switches, we use reflection to handle all generic types.
switch actual := value.(type) {
// Handle primitive types.
case nil:
v.formatNil(actual)
case bool:
v.formatBoolean(actual)
case uint:
v.formatUnsigned(uint64(actual))
case uint8:
v.formatUnsigned(uint64(actual))
case uint16:
v.formatUnsigned(uint64(actual))
case uint32:
v.formatUnsigned(uint64(actual))
case uint64:
v.formatUnsigned(uint64(actual))
case uintptr:
v.formatUnsigned(uint64(actual))
case int:
v.formatInteger(int64(actual))
case int8:
v.formatInteger(int64(actual))
case int16:
v.formatInteger(int64(actual))
case int64:
v.formatInteger(int64(actual))
case float32:
v.formatFloat(float64(actual))
case float64:
v.formatFloat(float64(actual))
case complex64:
v.formatComplex(complex128(actual))
case complex128:
v.formatComplex(complex128(actual))
case rune:
v.formatRune(rune(actual))
case string:
v.formatString(actual)
// Handle generic types.
default:
var reflected = ref.ValueOf(value)
if reflected.MethodByName("GetKey").IsValid() {
v.formatAssociation(reflected)
} else if reflected.MethodByName("AsArray").IsValid() {
v.formatCollection(reflected)
} else {
switch reflected.Kind() {
case ref.Array, ref.Slice, ref.Map:
v.formatCollection(reflected)
default:
panic(fmt.Sprintf(
"Attempted to format:\n value: %v\n type: %v\n kind: %v\n",
reflected.Interface(),
reflected.Type(),
reflected.Kind(),
))
}
}
}
}
func (v *formatter_) getName(collection ref.Value) string {
// NOTE: This hack is necessary since Go does not handle type switches with
// generics very well.
var type_ = collection.Type().String()
switch {
case sts.HasPrefix(type_, "[]"):
return "array"
case sts.HasPrefix(type_, "collection.ArrayLike"):
return "Array"
case sts.HasPrefix(type_, "collection.array_"):
return "Array"
case sts.HasPrefix(type_, "map["):
return "map"
case sts.HasPrefix(type_, "collection.MapLike"):
return "Map"
case sts.HasPrefix(type_, "collection.map_"):
return "Map"
case sts.HasPrefix(type_, "*collection.set_"):
return "Set"
case sts.HasPrefix(type_, "collection.SetLike"):
return "Set"
case sts.HasPrefix(type_, "*collection.queue_"):
return "Queue"
case sts.HasPrefix(type_, "collection.QueueLike"):
return "Queue"
case sts.HasPrefix(type_, "*collection.stack_"):
return "Stack"
case sts.HasPrefix(type_, "collection.StackLike"):
return "Stack"
case sts.HasPrefix(type_, "*collection.list_"):
return "List"
case sts.HasPrefix(type_, "collection.ListLike"):
return "List"
case sts.HasPrefix(type_, "*collection.catalog_"):
return "Catalog"
case sts.HasPrefix(type_, "collection.CatalogLike"):
return "Catalog"
case sts.HasPrefix(type_, "*collection.association_"):
return "Association"
case sts.HasPrefix(type_, "collection.AssociationLike"):
return "Association"
default:
return "<unknown>"
}
}
func (v *formatter_) getResult() string {
var result = v.result_.String()
v.result_.Reset()
return result
}