-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgo_lang.go
271 lines (259 loc) · 6.76 KB
/
go_lang.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
// -----------------------------------------------------------------------------
// ZR Library zr/[go_lang.go]
// (c) balarabe@protonmail.com License: MIT
// -----------------------------------------------------------------------------
package zr
// # Interface
// GoStringerEx interface
//
// # Functions
// GoName(s string) string
// GoString(value interface{}, optIndentAt ...int) string
// WriteGoString(value interface{}, indentAt int, buf *bytes.Buffer)
//
// # Helper Function
// indentPos(optIndentAt []int) int
import (
"bytes"
"fmt"
"reflect"
"sort"
"strings"
)
// -----------------------------------------------------------------------------
// # Interface
// GoStringerEx interface is implemented by objects that can output
// their definitions in Go language syntax. It extends the standard
// fmt.GoStringer interface with an optional indent parameter.
type GoStringerEx interface {
GoStringEx(indentAt int) string
} // GoStringerEx
// -----------------------------------------------------------------------------
// # Functions
// GoName converts a name to a Go language convention name.
// It removes underscores from names and changes names to 'TitleCase'.
func GoName(s string) string {
ret := strings.TrimSpace(s)
if len(ret) == 0 {
return ""
}
// replace undserscores with spaces to isolate words
if strings.Contains(ret, "_") {
ret = strings.ReplaceAll(ret, "_", " ")
}
// capitalize the fist letter of every word
ret = TitleCase(ret)
//
// the word 'ID' should be all-capital
if ContainsI(ret, "id") {
ret = ReplaceWord(ret, "id", "ID", IgnoreCase)
}
// remove spaces to get a camel-case string
if strings.Contains(ret, " ") {
ret = strings.ReplaceAll(ret, " ", "")
}
return ret
} // GoName
// GoString converts fundamental types to strings in Go Language syntax.
// You can copy its output and paste in source code if needed.
//
// If the type of value implements fmt.GoStringer or zr.GoStringerEx
// interfaces, uses the method provided by the interface.
//
// optIndentAt: omit this optional argument to place all output
// on one line, or specify 0 or more tab positions
// to indent the output on multiple lines.
//
func GoString(value interface{}, optIndentAt ...int) string {
var (
useGoStringer = true
indentAt = indentPos(optIndentAt)
buf bytes.Buffer
)
WriteGoString(value, useGoStringer, indentAt, &buf)
return buf.String()
} // GoString
// WriteGoString writes a fundamental type
// in Go language syntax to a buffer.
//
// It is called by zr.GoString() function and various
// types' GoString() methods to generate their results.
//
// value: the value being read
//
// useGoStringer: when true, calls GoString() or GoStringEx() if
// value implements any of these methods.
//
// indentAt: specifies if output should be on a single
// line (-1) or indented to a number of tab stops.
//
// buf: pointer to output buffer
func WriteGoString(
value interface{},
useGoStringer bool,
indentAt int,
buf *bytes.Buffer,
) {
// write multiple strings to buffer
ws := func(a ...string) {
for _, s := range a {
buf.WriteString(s)
}
}
writeGoString := func(value interface{}) {
WriteGoString(value, useGoStringer, indentAt, buf)
}
if value == nil {
ws("nil")
return
}
if useGoStringer {
switch v := value.(type) {
case GoStringerEx:
{
ws(v.GoStringEx(indentAt))
return
}
case fmt.GoStringer:
ws(v.GoString())
return
}
}
v := reflect.ValueOf(value)
t := reflect.TypeOf(value)
switch v.Kind() {
case reflect.Bool:
{
if v.Bool() {
ws("true")
} else {
ws("false")
}
return
}
case reflect.Int, reflect.Int64, reflect.Int32,
reflect.Int16, reflect.Int8:
{
ws(String(v.Int()))
return
}
case reflect.Uint, reflect.Uint64, reflect.Uint32,
reflect.Uint16, reflect.Uint8:
{
ws(String(v.Uint()))
return
}
case reflect.Uintptr:
{
// TODO: handle Uintptr
break
}
case reflect.Float64, reflect.Float32:
{
ws(String(v.Float()))
return
}
case reflect.Complex64, reflect.Complex128, reflect.Array,
reflect.Chan, reflect.Func, reflect.Interface:
{
// TODO: handle multiple types
break
}
case reflect.Map:
{
ws("map[", t.Key().String(), "]", t.Elem().String(), "{")
//
// since MapKeys are returned in no specific order,
// append each key-value in map to a string array
// then sort it to ensure the result is consistent
lines := make([]string, 0, v.Len())
for _, key := range v.MapKeys() {
lines = append(lines,
TabSpace+GoString(key.Interface())+": "+
GoString(v.MapIndex(key).Interface())+",")
}
sort.Strings(lines)
//
// write out the array
for _, s := range lines {
ws("\n", s)
}
ws("\n}")
return
}
case reflect.Ptr:
{
writeGoString(v.Elem().Interface())
return
}
case reflect.Slice:
{
ws(t.String(), "{")
manyLines := v.Len() > 0 && v.Index(0).Kind() == reflect.Slice
for i, n := 0, v.Len(); i < n; i++ {
if i > 0 {
ws(",")
}
if manyLines {
ws("\n", TabSpace)
} else if i > 0 {
ws(" ")
}
writeGoString(v.Index(i).Interface())
}
if manyLines {
ws(",\n")
}
ws("}")
return
}
case reflect.String:
{
ws(`"`, strings.ReplaceAll(value.(string), `"`, `\"`), `"`)
return
}
case reflect.Struct:
{
ws(t.String(), "{")
for i, n := 0, t.NumField(); i < n; i++ {
if !v.Field(i).CanInterface() {
continue
}
if i > 0 {
ws(", ")
}
ws(t.Field(i).Name, ": ")
writeGoString(v.Field(i).Interface())
}
ws("}")
return
}
case reflect.UnsafePointer:
break // TODO: reflect.UnsafePointer
}
// finally, try using fmt.Stringer (treat value as a string)
if v, ok := value.(fmt.Stringer); ok {
ws(GoString(v.String()))
return
}
// if value is still not processed, log an error, try to use fmt.Sprint()
mod.Error("Type", t, "(kind:", v.Kind(), ") not handled:", value)
ws("(", fmt.Sprint(value), ")")
} // WriteGoString
// -----------------------------------------------------------------------------
// # Helper Function
// indentPos helps to read the indent position from the optinal argument
func indentPos(optIndentAt []int) int {
ret := -1
n := len(optIndentAt)
switch {
case n == 1:
{
ret = optIndentAt[0]
}
case n > 1:
mod.Error(EInvalidArg, "optIndentAt", ":", optIndentAt)
}
return ret
} // indentPos
//eof