...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package openapi
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 import (
47 "cuelang.org/go/cue"
48 "cuelang.org/go/cue/ast"
49 )
50
51
52 func newCoreBuilder(c *buildContext) *builder {
53 b := newRootBuilder(c)
54 b.properties = map[string]*builder{}
55 return b
56 }
57
58 func (b *builder) coreSchemaWithName(name cue.Selector) *ast.StructLit {
59 oldPath := b.ctx.path
60 b.ctx.path = append(b.ctx.path, name)
61 s := b.coreSchema()
62 b.ctx.path = oldPath
63 return s
64 }
65
66
67 func (b *builder) coreSchema() *ast.StructLit {
68 switch b.kind {
69 case cue.ListKind:
70 if b.items != nil {
71 b.setType("array", "")
72 schema := b.items.coreSchemaWithName(cue.AnyString)
73 b.setSingle("items", schema, false)
74 }
75
76 case cue.StructKind:
77 p := &OrderedMap{}
78 for _, k := range b.keys {
79 sub := b.properties[k]
80 p.Set(k, sub.coreSchemaWithName(cue.Str(k)))
81 }
82 if p.len() > 0 || b.items != nil {
83 b.setType("object", "")
84 }
85 if p.len() > 0 {
86 b.setSingle("properties", (*ast.StructLit)(p), false)
87 }
88
89 if b.items != nil {
90 schema := b.items.coreSchemaWithName(cue.AnyString)
91 b.setSingle("additionalProperties", schema, false)
92 }
93 }
94
95
96
97
98 if len(b.values) == 1 {
99 return b.fillSchema(b.values[0])
100 }
101
102
103
104
105 return b.finish()
106 }
107
108
109
110
111 func (b *builder) buildCore(v cue.Value) {
112 b.pushNode(v)
113 defer b.popNode()
114
115 if !b.ctx.expandRefs {
116 _, r := v.Reference()
117 if len(r) > 0 {
118 return
119 }
120 }
121 b.getDoc(v)
122 format := extractFormat(v)
123 if format != "" {
124 b.format = format
125 } else {
126 v = v.Eval()
127 b.kind = v.IncompleteKind()
128
129 switch b.kind {
130 case cue.StructKind:
131 if typ, ok := v.Elem(); ok {
132 if !b.checkCycle(typ) {
133 return
134 }
135 if b.items == nil {
136 b.items = newCoreBuilder(b.ctx)
137 }
138 b.items.buildCore(typ)
139 }
140 b.buildCoreStruct(v)
141
142 case cue.ListKind:
143 if typ, ok := v.Elem(); ok {
144 if !b.checkCycle(typ) {
145 return
146 }
147 if b.items == nil {
148 b.items = newCoreBuilder(b.ctx)
149 }
150 b.items.buildCore(typ)
151 }
152 }
153 }
154
155 for _, bv := range b.values {
156 if bv.Equals(v) {
157 return
158 }
159 }
160 b.values = append(b.values, v)
161 }
162
163 func (b *builder) buildCoreStruct(v cue.Value) {
164 op, args := v.Expr()
165 switch op {
166 case cue.OrOp, cue.AndOp:
167 for _, v := range args {
168 b.buildCore(v)
169 }
170 }
171 for i, _ := v.Fields(cue.Optional(true), cue.Hidden(false)); i.Next(); {
172 label := i.Label()
173 sub, ok := b.properties[label]
174 if !ok {
175 sub = newCoreBuilder(b.ctx)
176 b.properties[label] = sub
177 b.keys = append(b.keys, label)
178 }
179 sub.buildCore(i.Value())
180 }
181 }
182
View as plain text