-
Notifications
You must be signed in to change notification settings - Fork 42
/
xsd.go
346 lines (310 loc) · 8.9 KB
/
xsd.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
package importer
import (
"bytes"
"encoding/xml"
"fmt"
"os"
"sort"
"strconv"
"strings"
"aqwari.net/xml/xsd"
"github.com/anz-bank/sysl/pkg/syslutil"
"github.com/anz-bank/sysl/pkg/utils"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type XSDImporter struct {
appName string
pkg string
types TypeList
logger *logrus.Logger
}
func MakeXSDImporter(logger *logrus.Logger) *XSDImporter {
return &XSDImporter{
logger: logger,
}
}
func (i *XSDImporter) LoadFile(path string) (string, error) {
bs, err := os.ReadFile(path)
if err != nil {
return "", err
}
return i.Load(string(bs))
}
func (i *XSDImporter) Load(input string) (string, error) {
xsd.StandardSchema = [][]byte{} // Ignore all the standard schemas,
specs, err := xsd.Parse([]byte(input))
if err != nil {
return "", err
}
i.types = TypeList{}
for _, schema := range specs {
schemaTypes := loadSchemaTypes(schema, i.logger)
i.types.Add(schemaTypes.Items()...)
}
i.types.Sort()
info := SyslInfo{
OutputData: OutputData{
AppName: i.appName,
Package: i.pkg,
},
Description: "",
Title: "",
}
result := &bytes.Buffer{}
w := newWriter(result, i.logger)
if err := w.Write(info, i.types); err != nil {
return "", err
}
return result.String(), nil
}
// Configure allows the imported Sysl application name, package and import directories to be specified.
func (i *XSDImporter) Configure(arg *ImporterArg) (Importer, error) {
if arg.AppName == "" {
return nil, errors.New("application name not provided")
}
i.appName = arg.AppName
i.pkg = arg.PackageName
return i, nil
}
func makeNamespacedType(name xml.Name, target Type) Type {
return &ImportedBuiltInAlias{
baseType: baseType{name: fmt.Sprintf("%s:%s", name.Space, name.Local)},
Target: target,
}
}
// nolint:revive,stylecheck
var (
XSD_BOOLEAN = strings.ToLower(xsd.Boolean.String())
XSD_BYTE = strings.ToLower(xsd.Byte.String())
XSD_DATE = strings.ToLower(xsd.Date.String())
XSD_DATETIME = strings.ToLower(xsd.DateTime.String())
XSD_DECIMAL = strings.ToLower(xsd.Decimal.String())
XSD_INT = strings.ToLower(xsd.Int.String())
XSD_INTEGER = strings.ToLower(xsd.Integer.String())
XSD_STRING = strings.ToLower(xsd.String.String())
XSD_TIME = strings.ToLower(xsd.Time.String())
XSD_NMTOKEN = strings.ToLower(xsd.NMTOKEN.String())
)
func loadSchemaTypes(schema xsd.Schema, logger *logrus.Logger) TypeList {
types := TypeList{}
var xsdToSyslMappings = map[string]string{
XSD_BOOLEAN: syslutil.Type_BOOL,
// XSD_BYTE: syslutil.Type_BYTES,
XSD_DATE: syslutil.Type_DATE,
// XSD_DATETIME: syslutil.Type_DATETIME,
// XSD_DECIMAL: syslutil.Type_DECIMAL,
// XSD_INT: syslutil.Type_INT,
XSD_INTEGER: syslutil.Type_INT,
XSD_STRING: syslutil.Type_STRING,
XSD_TIME: syslutil.Type_STRING,
XSD_NMTOKEN: syslutil.Type_STRING,
}
for swaggerName, syslName := range xsdToSyslMappings {
from := xml.Name{Space: "http://www.w3.org/2001/XMLSchema", Local: swaggerName}
to := &SyslBuiltIn{name: syslName}
types.Add(makeNamespacedType(from, to))
}
keys := make([]xml.Name, 0, len(schema.Types))
for key := range schema.Types {
keys = append(keys, key)
}
sort.Slice(keys, func(i, j int) bool {
return strings.Compare(
fmt.Sprintf("%s:%s", keys[i].Space, keys[i].Local),
fmt.Sprintf("%s:%s", keys[j].Space, keys[j].Local)) < 0
})
for _, name := range keys {
data := schema.Types[name]
if name.Local == "_self" {
rootType := data.(*xsd.ComplexType)
if rootType.Elements == nil {
/**
Some xsd doesn't have element tag is around tag complexType or simpleType, so it can't get _self's elements
with parsing of aqwari.net/xml/xsd. For example:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="User">
<xs:sequence>
<xs:element name="id" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
*/
continue
}
data = rootType.Elements[0].Type
t := findType(data, &types)
if t == nil {
t = makeType(name, data, &types, logger)
if name.Space != "" {
types.Add(makeNamespacedType(name, t))
}
}
switch x := t.(type) {
case *StandardType:
if !utils.Contains("~xml_root", x.Attributes()) {
x.AddAttributes([]string{"~xml_root"})
}
default:
}
} else if t := findType(data, &types); t == nil {
types.Add(makeType(name, data, &types, logger))
}
}
return types
}
func findType(t xsd.Type, knownTypes *TypeList) Type {
if res, found := knownTypes.Find(fmt.Sprintf("%s:%s", xsd.XMLName(t).Space, xsd.XMLName(t).Local)); found {
return res
}
if res, found := knownTypes.Find(xsd.XMLName(t).Local); found {
return res
}
return nil
}
func makeType(_ xml.Name, from xsd.Type, knownTypes *TypeList, logger *logrus.Logger) Type {
switch t := from.(type) {
case *xsd.ComplexType:
if isExtendedType(t) {
return makeExtendedType(t, knownTypes, logger)
}
return makeComplexType(t, knownTypes, logger)
case *xsd.SimpleType:
return makeSimpleType(t, knownTypes, logger)
case xsd.Builtin:
return makeXsdBuiltinType(t, knownTypes)
}
return nil
}
func makeComplexType(from *xsd.ComplexType, knownTypes *TypeList, logger *logrus.Logger) Type {
createChildItem := func(name xml.Name, data xsd.Type, isAttr, optional, plural bool) Field {
childType := findType(data, knownTypes)
if childType == nil {
childType = makeType(name, data, knownTypes, logger)
knownTypes.Add(childType)
}
f := Field{
Name: name.Local,
Type: childType,
}
if isAttr {
f.Attrs = []string{"~xml_attribute"}
}
f.Optional = optional
if from, ok := data.(*xsd.SimpleType); ok && from.Restriction.Min > 0 {
spec := sizeSpec{
Min: int(from.Restriction.Min),
Max: int(from.Restriction.Max),
}
if spec.Max > 0 {
spec.MaxType = MaxSpecified
}
f.SizeSpec = &spec
}
if plural {
f.Type = &Array{Items: f.Type}
}
return f
}
item := &StandardType{
baseType: baseType{name: from.Name.Local},
}
for _, child := range getAllElements(from) {
c := createChildItem(child.Name, child.Type, false, child.Optional, child.Plural)
if c.SizeSpec == nil {
c.SizeSpec = makeSizeSpecFromAttrs(child.Attr)
}
item.Properties = append(item.Properties, c)
}
for _, child := range from.Attributes {
c := createChildItem(child.Name, child.Type, true, child.Optional, child.Plural)
if c.SizeSpec == nil {
c.SizeSpec = makeSizeSpecFromAttrs(child.Attr)
}
item.Properties = append(item.Properties, c)
}
return item
}
func makeSizeSpecFromAttrs(attrs []xml.Attr) *sizeSpec {
ss := sizeSpec{}
changed := false
for _, attr := range attrs {
switch attr.Name.Local {
case "maxOccurs":
if attr.Value == "unbounded" {
ss.MaxType = OpenEnded
changed = true
} else if val, err := strconv.ParseInt(attr.Value, 0, 32); err == nil {
ss.MaxType = MaxSpecified
ss.Max = int(val)
changed = true
}
case "minOccurs":
if val, err := strconv.ParseInt(attr.Value, 0, 32); err == nil {
ss.Min = int(val)
changed = changed || val > 0
}
}
}
if changed {
return &ss
}
return nil
}
// isExtendedType detects if a *xsd.ComplexType is an extended type from the use of <xsd:simpleContent>
// An extended type is characterised by an xsd.ComplexType with extended true and no Attributes or Elements.
// An example XSD snippet is as follows:
//
// <xs:complexType>
//
// <xs:simpleContent>
// <xs:extension base="xs:token"/>
// </xs:simpleContent>
//
// </xs:complexType>
//
// See https://www.obj-sys.com/docs/acv65/CCppHTML/ch04s02s10.html
func isExtendedType(from *xsd.ComplexType) bool {
return from.Extends && len(from.Attributes) == 0 && len(from.Elements) == 0
}
func makeExtendedType(from *xsd.ComplexType, knownTypes *TypeList, logger *logrus.Logger) Type {
return &Alias{
baseType: baseType{name: from.Name.Local},
Target: makeType(from.Name, from.Base, knownTypes, logger),
}
}
func makeSimpleType(from *xsd.SimpleType, knownTypes *TypeList, logger *logrus.Logger) Type {
item := &Alias{
baseType: baseType{name: from.Name.Local},
Target: makeType(from.Name, from.Base, knownTypes, logger),
}
return item
}
func makeXsdBuiltinType(from xsd.Builtin, knownTypes *TypeList) Type {
typeStr := syslutil.Type_STRING
switch from {
case xsd.Integer, xsd.Int:
typeStr = syslutil.Type_INT
}
t, _ := knownTypes.Find(typeStr)
return t
}
/*
* Sysl doesn't support extend syntax, so merges its all ansestor's elements to itself.
*/
func getAllElements(current xsd.Type) []xsd.Element {
if current == nil {
return nil
}
if concreteCurrent, cok := current.(*xsd.ComplexType); cok {
parent := concreteCurrent.Base
if parent == nil || parent == xsd.AnyType {
return concreteCurrent.Elements
} else if concreteParent, pok := parent.(*xsd.ComplexType); pok {
return append(getAllElements(concreteParent), concreteCurrent.Elements...)
}
}
return nil
}