forked from xuri/xgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genRust.go
343 lines (327 loc) · 12.5 KB
/
genRust.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
// Copyright 2020 - 2021 The xgen Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.
//
// Package xgen written in pure Go providing a set of functions that allow you
// to parse XSD (XML schema files). This library needs Go version 1.10 or
// later.
package xgen
import (
"fmt"
"os"
"reflect"
"strings"
)
var (
rustBuildinType = map[string]bool{
"i8": true,
"i16": true,
"i32": true,
"i64": true,
"i128": true,
"isize": true,
"u8": true,
"u16": true,
"u32": true,
"u64": true,
"u128": true,
"usize": true,
"f32": true,
"f64": true,
"Vec<char>": true,
"Vec<String>": true,
"Vec<u8>": true,
"bool": true,
"char": true,
"String": true,
}
rustKeywords = map[string]bool{
"as": true,
"break": true,
"const": true,
"continue": true,
"crate": true,
"dyn": true,
"else": true,
"enum": true,
"extern": true,
"false": true,
"fn": true,
"for": true,
"if": true,
"impl": true,
"in": true,
"let": true,
"loop": true,
"match": true,
"mod": true,
"move": true,
"mut": true,
"pub": true,
"ref": true,
"return": true,
"Self": true,
"self": true,
"static": true,
"struct": true,
"super": true,
"trait": true,
"true": true,
"type": true,
"unsafe": true,
"use": true,
"where": true,
"while": true,
"abstract": true,
"async": true,
"await": true,
"become": true,
"box": true,
"do": true,
"final": true,
"macro": true,
"override": true,
"priv": true,
"try": true,
"typeof": true,
"unsized": true,
"virtual": true,
"yield": true,
}
)
// GenRust generate Go programming language source code for XML schema
// definition files.
func (gen *CodeGenerator) GenRust() error {
fieldNameCount = make(map[string]int)
for _, ele := range gen.ProtoTree {
if ele == nil {
continue
}
funcName := fmt.Sprintf("Rust%s", reflect.TypeOf(ele).String()[6:])
callFuncByName(gen, funcName, []reflect.Value{reflect.ValueOf(ele)})
}
f, err := os.Create(gen.FileWithExtension(".rs"))
if err != nil {
return err
}
defer f.Close()
var extern = `#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_xml_rs;
use serde_xml_rs::from_reader;`
source := []byte(fmt.Sprintf("%s\n\n%s\n%s", copyright, extern, gen.Field))
f.Write(source)
return err
}
// genRustFieldName generate struct field name for Rust code.
func genRustFieldName(name string) (fieldName string) {
for _, str := range strings.Split(name, ":") {
fieldName += MakeFirstUpperCase(str)
}
var tmp string
for _, str := range strings.Split(fieldName, ".") {
tmp += MakeFirstUpperCase(str)
}
fieldName = tmp
fieldName = ToSnakeCase(strings.Replace(fieldName, "-", "", -1))
if _, ok := rustKeywords[fieldName]; ok {
fieldName += "_attr"
}
return
}
// genRustStructName generate struct name for Rust code.
func genRustStructName(name string, unique bool) (structName string) {
for _, str := range strings.Split(name, ":") {
structName += MakeFirstUpperCase(str)
}
var tmp string
for _, str := range strings.Split(structName, ".") {
tmp += MakeFirstUpperCase(str)
}
structName = tmp
structName = strings.NewReplacer("-", "", "_", "").Replace(structName)
if unique {
fieldNameCount[structName]++
if count := fieldNameCount[structName]; count != 1 {
structName = fmt.Sprintf("%s%d", structName, count)
}
}
return
}
// genRustFieldType generate struct field type for Rust code.
func genRustFieldType(name string) string {
if _, ok := rustBuildinType[name]; ok {
return name
}
fieldType := genRustStructName(name, false)
if fieldType != "" {
return fieldType
}
return "char"
}
// RustSimpleType generates code for simple type XML schema in Rust language
// syntax.
func (gen *CodeGenerator) RustSimpleType(v *SimpleType) {
if v.List {
if _, ok := gen.StructAST[v.Name]; !ok {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(v.Base), gen.ProtoTree))
content := fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", v.Name, genRustFieldName(v.Name), fieldType)
gen.StructAST[v.Name] = content
fieldName := genRustStructName(v.Name, true)
gen.Field += fmt.Sprintf("\n%s#[derive(Debug, Deserialize, Serialize, PartialEq)]\npub struct %s {\n%s}\n", genFieldComment(fieldName, v.Doc, "//"), fieldName, gen.StructAST[v.Name])
return
}
}
if v.Union && len(v.MemberTypes) > 0 {
if _, ok := gen.StructAST[v.Name]; !ok {
var content string
for _, member := range toSortedPairs(v.MemberTypes) {
memberName := member.key
memberType := member.value
if memberType == "" { // fix order issue
memberType = getBasefromSimpleType(memberName, gen.ProtoTree)
}
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", v.Name, genRustFieldName(memberName), genRustFieldType(memberType))
}
gen.StructAST[v.Name] = content
gen.Field += fmt.Sprintf("\n#[derive(Debug, Deserialize, Serialize, PartialEq)]\npub struct %s {\n%s}\n", genRustStructName(v.Name, true), gen.StructAST[v.Name])
}
return
}
if _, ok := gen.StructAST[v.Name]; !ok {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(v.Base), gen.ProtoTree))
content := fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", v.Name, genRustFieldName(v.Name), fieldType)
gen.StructAST[v.Name] = content
fieldName := genRustStructName(v.Name, true)
gen.Field += fmt.Sprintf("\n%s#[derive(Debug, Deserialize, Serialize, PartialEq)]\npub struct %s {\n%s}\n", genFieldComment(fieldName, v.Doc, "//"), fieldName, gen.StructAST[v.Name])
}
}
// RustComplexType generates code for complex type XML schema in Rust language
// syntax.
func (gen *CodeGenerator) RustComplexType(v *ComplexType) {
if _, ok := gen.StructAST[v.Name]; !ok {
var content string
for _, attrGroup := range v.AttributeGroup {
fieldType := getBasefromSimpleType(trimNSPrefix(attrGroup.Ref), gen.ProtoTree)
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", attrGroup.Name, genRustFieldName(attrGroup.Name), genRustFieldType(fieldType))
}
for _, attribute := range v.Attributes {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(attribute.Type), gen.ProtoTree))
if attribute.Optional {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Option<%s>,\n", attribute.Name, genRustFieldName(attribute.Name), fieldType)
} else {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", attribute.Name, genRustFieldName(attribute.Name), fieldType)
}
}
for _, group := range v.Groups {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(group.Ref), gen.ProtoTree))
fieldName := genRustFieldName(group.Name)
if group.Plural {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", group.Name, fieldName, fieldType)
} else {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", group.Name, fieldName, fieldType)
}
}
for _, element := range v.Elements {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(element.Type), gen.ProtoTree))
fieldName := genRustFieldName(element.Name)
if element.Plural {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", element.Name, fieldName, fieldType)
} else {
if element.Optional {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Option<%s>,\n", element.Name, fieldName, fieldType)
} else {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", element.Name, fieldName, fieldType)
}
}
}
if len(v.Base) > 0 {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(v.Base), gen.ProtoTree))
if isRustBuiltInType(v.Base) {
content += fmt.Sprintf("\t#[serde(rename = \"$value\")]\n\tpub value: %s,\n", fieldType)
} else {
fieldName := genRustFieldName(fieldType)
// If the type is not a built-in one, add the base type as a nested field tagged with flatten
content += fmt.Sprintf("\t#[serde(flatten)]\n\tpub %s: %s,\n", fieldName, fieldType)
}
}
gen.StructAST[v.Name] = content
fieldName := genRustStructName(v.Name, true)
gen.Field += fmt.Sprintf("\n%s#[derive(Debug, Deserialize, Serialize, PartialEq)]\npub struct %s {\n%s}\n", genFieldComment(fieldName, v.Doc, "//"), fieldName, gen.StructAST[v.Name])
}
}
func isRustBuiltInType(typeName string) bool {
_, builtIn := rustBuildinType[typeName]
return builtIn
}
// RustGroup generates code for group XML schema in Rust language syntax.
func (gen *CodeGenerator) RustGroup(v *Group) {
if _, ok := gen.StructAST[v.Name]; !ok {
var content string
for _, element := range v.Elements {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(element.Type), gen.ProtoTree))
fieldName := genRustFieldName(element.Name)
if v.Plural {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", element.Name, fieldName, fieldType)
} else {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", element.Name, fieldName, fieldType)
}
}
for _, group := range v.Groups {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(group.Ref), gen.ProtoTree))
fieldName := genRustFieldName(group.Name)
if v.Plural {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", group.Name, fieldName, fieldType)
} else {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", group.Name, fieldName, fieldType)
}
}
gen.StructAST[v.Name] = content
fieldName := genRustStructName(v.Name, true)
gen.Field += fmt.Sprintf("\n%s#[derive(Debug, Deserialize, Serialize, PartialEq)]\npub struct %s {\n%s}\n", genFieldComment(fieldName, v.Doc, "//"), fieldName, gen.StructAST[v.Name])
}
}
// RustAttributeGroup generates code for attribute group XML schema in Rust language
// syntax.
func (gen *CodeGenerator) RustAttributeGroup(v *AttributeGroup) {
if _, ok := gen.StructAST[v.Name]; !ok {
var content string
for _, attribute := range v.Attributes {
if attribute.Optional {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Option<%s>,\n", attribute.Name, genRustFieldName(attribute.Name), genRustFieldType(getBasefromSimpleType(trimNSPrefix(attribute.Type), gen.ProtoTree)))
} else {
content += fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", attribute.Name, genRustFieldName(attribute.Name), genRustFieldType(getBasefromSimpleType(trimNSPrefix(attribute.Type), gen.ProtoTree)))
}
}
gen.StructAST[v.Name] = content
fieldName := genRustStructName(v.Name, true)
gen.Field += fmt.Sprintf("\n%s#[derive(Debug, Deserialize, Serialize, PartialEq)]\npub struct %s {\n%s}\n", genFieldComment(fieldName, v.Doc, "//"), fieldName, gen.StructAST[v.Name])
}
}
// RustElement generates code for element XML schema in Rust language syntax.
func (gen *CodeGenerator) RustElement(v *Element) {
if _, ok := gen.StructAST[v.Name]; !ok {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(v.Type), gen.ProtoTree))
fieldName := genRustFieldName(v.Name)
if v.Plural {
gen.StructAST[v.Name] = fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", v.Name, fieldName, fieldType)
} else {
gen.StructAST[v.Name] = fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", v.Name, fieldName, fieldType)
}
gen.Field += fmt.Sprintf("\n%s#[derive(Debug, Deserialize, Serialize, PartialEq)]\npub struct %s {\n%s}\n", genFieldComment(fieldName, v.Doc, "//"), fieldName, gen.StructAST[v.Name])
}
}
// RustAttribute generates code for attribute XML schema in Rust language syntax.
func (gen *CodeGenerator) RustAttribute(v *Attribute) {
if _, ok := gen.StructAST[v.Name]; !ok {
fieldType := genRustFieldType(getBasefromSimpleType(trimNSPrefix(v.Type), gen.ProtoTree))
fieldName := genRustFieldName(v.Name)
if v.Plural {
gen.StructAST[v.Name] = fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: Vec<%s>,\n", v.Name, fieldName, fieldType)
} else {
gen.StructAST[v.Name] = fmt.Sprintf("\t#[serde(rename = \"%s\")]\n\tpub %s: %s,\n", v.Name, fieldName, fieldType)
}
gen.Field += fmt.Sprintf("\n%s#[derive(Debug, Deserialize, Serialize, PartialEq)]\npub struct %s {\n%s}\n", genFieldComment(fieldName, v.Doc, "//"), fieldName, gen.StructAST[v.Name])
}
}