-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
lang.go
419 lines (364 loc) · 10.6 KB
/
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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package colfer
import (
_ "embed"
"bytes"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
"unicode"
"unicode/utf8"
"github.com/pascaldekloe/name"
"golang.org/x/mod/modfile"
)
// CKeywords are the reserved tokens for C code.
// Some entries are redundant due to the use of a Go parser.
var cKeywords = map[string]struct{}{
"auto": {}, "break": {}, "case": {}, "char": {},
"const": {}, "continue": {}, "default": {}, "do": {},
"double": {}, "else": {}, "enum": {}, "extern": {},
"float": {}, "for": {}, "goto": {}, "if": {},
"int": {}, "long": {}, "register": {}, "return": {},
"short": {}, "signed": {}, "sizeof": {}, "static": {},
"struct": {}, "switch": {}, "typedef": {}, "union": {},
"unsigned": {}, "void": {}, "volatile": {}, "while": {},
}
// GenerateC writes the code into file "Colfer.h" and "Colfer.c".
func GenerateC(basedir string, packages Packages) error {
for _, p := range packages {
for _, t := range p.Structs {
t.NameNative = strings.ToLower(name.SnakeCase(p.Name + "_" + t.Name))
for _, f := range t.Fields {
f.NameNative = strings.ToLower(name.SnakeCase(f.Name))
if _, ok := cKeywords[f.NameNative]; ok {
f.NameNative += "_"
}
switch f.Type {
case "bool":
f.TypeNative = "char"
case "uint8", "uint16", "uint32", "uint64", "int32", "int64":
f.TypeNative = f.Type + "_t"
case "float32":
f.TypeNative = "float"
case "float64":
f.TypeNative = "double"
case "timestamp":
f.TypeNative = "timespec"
case "binary", "text":
f.TypeNative = "colfer_" + f.Type
}
}
}
}
if err := os.MkdirAll(basedir, os.ModeDir|os.ModePerm); err != nil {
return err
}
f, err := os.Create(filepath.Join(basedir, "Colfer.h"))
if err != nil {
return err
}
if err := template.Must(template.New("C-header").Parse(cHeaderTemplate)).Execute(f, packages); err != nil {
return err
}
if err = f.Close(); err != nil {
return err
}
f, err = os.Create(filepath.Join(basedir, "Colfer.c"))
if err != nil {
return err
}
if err := template.Must(template.New("C").Parse(cTemplate)).Execute(f, packages); err != nil {
return err
}
return f.Close()
}
//go:embed template/c-header.txt
var cHeaderTemplate string
//go:embed template/c.txt
var cTemplate string
// ECMAKeywords are the reserved tokens for ECMA Script.
// Some entries are redundant due to the use of a Go parser.
var eCMAKeywords = map[string]struct{}{
"break": {}, "case": {}, "catch": {}, "class": {},
"const": {}, "continue": {}, "debugger": {}, "default": {},
"delete": {}, "do": {}, "else": {}, "enum": {},
"export": {}, "extends": {}, "finally": {}, "for": {},
"function": {}, "if": {}, "import": {}, "in": {},
"instanceof": {}, "new": {}, "return": {}, "super": {},
"switch": {}, "this": {}, "throw": {}, "try": {},
"typeof": {}, "var": {}, "void": {}, "while": {},
"with": {}, "yield": {},
}
// GenerateECMA writes the code into file "Colfer.js".
func GenerateECMA(basedir string, packages Packages) error {
for _, p := range packages {
p.NameNative = strings.Replace(p.Name, "/", "_", -1)
if _, ok := eCMAKeywords[p.NameNative]; ok {
p.NameNative += "_"
}
for _, t := range p.Structs {
t.NameNative = name.CamelCase(t.Name, true)
for _, f := range t.Fields {
f.NameNative = name.CamelCase(f.Name, false)
if _, ok := eCMAKeywords[f.NameNative]; ok {
f.NameNative += "_"
}
}
}
}
t := template.New("ecma-code")
template.Must(t.Parse(ecmaCode))
template.Must(t.New("marshal").Parse(ecmaMarshal))
template.Must(t.New("unmarshal").Parse(ecmaUnmarshal))
if err := os.MkdirAll(basedir, os.ModeDir|os.ModePerm); err != nil {
return err
}
f, err := os.Create(filepath.Join(basedir, "Colfer.js"))
if err != nil {
return err
}
defer f.Close()
return t.Execute(f, packages)
}
//go:embed template/ecma.txt
var ecmaCode string
//go:embed template/ecma-marshal.txt
var ecmaMarshal string
//go:embed template/ecma-unmarshal.txt
var ecmaUnmarshal string
// GoMod looks for a Go modules definition.
// ModDir is the root directory when found.
// ModPkg is the root package when found.
func goMod(dir string) (modDir, modPkg string, err error) {
dir, err = filepath.Abs(dir)
if err != nil {
return "", "", err
}
for n := 0; n < 32; n++ {
path := filepath.Join(dir, "go.mod")
text, err := ioutil.ReadFile(path)
if err != nil {
if !os.IsNotExist(err) {
return "", "", err
}
// The path does not end in a separator
// unless it is the root directory.
if dir[len(dir)-1] == filepath.Separator {
break
}
// try parent directory
dir = filepath.Dir(dir)
continue
}
return dir, modfile.ModulePath(text), nil
}
return "", "", nil // not found
}
// GenerateGo writes the code into file "Colfer.go".
func GenerateGo(basedir string, packages Packages) error {
t := template.New("go-code")
template.Must(t.Parse(goCode))
template.Must(t.New("marshal-field").Parse(goMarshalField))
template.Must(t.New("marshal-field-len").Parse(goMarshalFieldLen))
template.Must(t.New("unmarshal-field").Parse(goUnmarshalField))
template.Must(t.New("unmarshal-varint").Parse(goUnmarshalVarint))
modDir, modPkg, err := goMod(basedir)
if err != nil {
return err
}
for _, p := range packages {
p.NameNative = p.Name[strings.LastIndexByte(p.Name, '/')+1:]
for _, t := range p.Structs {
t.NameNative = name.CamelCase(t.Name, true)
for _, f := range t.Fields {
f.NameNative = name.CamelCase(f.Name, true)
}
}
}
for _, p := range packages {
for _, t := range p.Structs {
for _, f := range t.Fields {
switch f.Type {
default:
if f.TypeRef == nil {
f.TypeNative = f.Type
} else {
f.TypeNative = f.TypeRef.NameNative
if f.TypeRef.Pkg != p {
f.TypeNative = f.TypeRef.Pkg.NameNative + "." + f.TypeNative
}
}
case "timestamp":
f.TypeNative = "time.Time"
case "text":
f.TypeNative = "string"
case "binary":
f.TypeNative = "[]byte"
}
}
}
var buf bytes.Buffer
if err := t.Execute(&buf, p); err != nil {
return err
}
path := filepath.Join(basedir, p.Name)
if modPkg != "" && strings.HasPrefix(p.Name, modPkg+"/") {
path = filepath.Join(modDir, p.Name[len(modPkg):])
}
if err := os.MkdirAll(path, 0777); err != nil {
return err
}
path = filepath.Join(path, "Colfer.go")
if err := ioutil.WriteFile(path, buf.Bytes(), 0666); err != nil {
return err
}
if _, err := FormatFile(path); err != nil {
return err
}
}
return nil
}
//go:embed template/go.txt
var goCode string
//go:embed template/go-marshal-field.txt
var goMarshalField string
//go:embed template/go-marshal-field-len.txt
var goMarshalFieldLen string
//go:embed template/go-unmarshal-field.txt
var goUnmarshalField string
//go:embed template/go-unmarshal-varint.txt
var goUnmarshalVarint string
// JavaKeywords are the reserved tokens for Java code.
// Some entries are redundant due to the use of a Go parser.
var javaKeywords = map[string]struct{}{
"abstract": {}, "assert": {}, "boolean": {}, "break": {},
"byte": {}, "case": {}, "catch": {}, "char": {},
"class": {}, "const": {}, "continue": {}, "default": {},
"do": {}, "double": {}, "else": {}, "enum": {},
"extends": {}, "final": {}, "finally": {}, "float": {},
"for": {}, "goto": {}, "if": {}, "implements": {},
"import": {}, "instanceof": {}, "int": {}, "interface": {},
"long": {}, "native": {}, "new": {}, "package": {},
"private": {}, "protected": {}, "public": {}, "return": {},
"short": {}, "static": {}, "strictfp": {}, "super": {},
"switch": {}, "synchronized": {}, "this": {}, "throw": {},
"throws": {}, "transient": {}, "try": {}, "void": {},
"volatile": {}, "while": {},
}
func toJavaName(name string) string {
name = strings.ReplaceAll(name, "/", ".")
segments := strings.Split(name, ".")
var escapes bool
for i, s := range segments {
if _, ok := javaKeywords[s]; ok {
segments[i] = s + "_"
escapes = true
}
}
if escapes {
return strings.Join(segments, ".")
}
return name
}
// GenerateJava writes the code into the respective ".java" files.
func GenerateJava(basedir string, packages Packages) error {
titleCache := make(map[string]string)
funcs := template.FuncMap{"title": func(s string) string {
if t, ok := titleCache[s]; ok {
return t
}
r, size := utf8.DecodeRuneInString(s)
if size == 0 {
return s
}
t := string([]rune{unicode.ToUpper(r)}) + s[size:]
titleCache[s] = t
return t
}}
packageTemplate := template.New("java-package")
template.Must(packageTemplate.Parse(javaPackage))
codeTemplate := template.New("java-code").Funcs(funcs)
template.Must(codeTemplate.Parse(javaCode))
for _, p := range packages {
p.NameNative = toJavaName(p.Name)
p.SuperClassNative = toJavaName(p.SuperClass)
p.InterfaceNatives = make([]string, len(p.Interfaces))
for i, s := range p.Interfaces {
p.InterfaceNatives[i] = toJavaName(s)
}
for _, t := range p.Structs {
t.NameNative = name.CamelCase(t.Name, true)
for _, f := range t.Fields {
f.NameNative = name.CamelCase(f.Name, false)
if _, ok := javaKeywords[f.NameNative]; ok {
f.NameNative += "_"
}
}
}
}
for _, p := range packages {
pkgdir := filepath.Join(basedir, strings.Replace(p.NameNative, ".", string([]rune{filepath.Separator}), -1))
if err := os.MkdirAll(pkgdir, os.ModeDir|os.ModePerm); err != nil {
return err
}
if doc := p.DocText(" * "); doc != "" {
f, err := os.Create(filepath.Join(pkgdir, "package-info.java"))
if err != nil {
return err
}
defer f.Close()
if err := packageTemplate.Execute(f, p); err != nil {
return err
}
}
for _, t := range p.Structs {
for _, f := range t.Fields {
switch f.Type {
default:
if f.TypeRef == nil {
f.TypeNative = f.Type
} else {
f.TypeNative = f.TypeRef.NameNative
if f.TypeRef.Pkg != p {
f.TypeNative = f.TypeRef.Pkg.NameNative + "." + f.TypeNative
}
}
case "bool":
f.TypeNative = "boolean"
case "uint8":
f.TypeNative = "byte"
case "uint16":
f.TypeNative = "short"
case "uint32", "int32":
f.TypeNative = "int"
case "uint64", "int64":
f.TypeNative = "long"
case "float32":
f.TypeNative = "float"
case "float64":
f.TypeNative = "double"
case "timestamp":
f.TypeNative = "java.time.Instant"
case "text":
f.TypeNative = "String"
case "binary":
f.TypeNative = "byte[]"
}
}
f, err := os.Create(filepath.Join(pkgdir, t.NameNative+".java"))
if err != nil {
return err
}
defer f.Close()
if err := codeTemplate.Execute(f, t); err != nil {
return err
}
}
}
return nil
}
//go:embed template/java-package.txt
var javaPackage string
//go:embed template/java.txt
var javaCode string