Debian Codegraph @

examples/set-gen/generators/sets.go

raw
1 /*
2 Copyright 2015 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 // Package generators has the generators for the set-gen utility.
18 package generators
19
20 import (
21 "io"
22
23 "k8s.io/gengo/args"
24 "k8s.io/gengo/generator"
25 "k8s.io/gengo/namer"
26 "k8s.io/gengo/types"
27
28 "k8s.io/klog/v2"
29 )
30
31 // NameSystems returns the name system used by the generators in this package.
32 func NameSystems() namer.NameSystems {
33 return namer.NameSystems{
34 "public": namer.NewPublicNamer(0),
35 "private": namer.NewPrivateNamer(0),
36 "raw": namer.NewRawNamer("", nil),
37 }
38 }
39
40 // DefaultNameSystem returns the default name system for ordering the types to be
41 // processed by the generators in this package.
42 func DefaultNameSystem() string {
43 return "public"
44 }
45
46 // Packages makes the sets package definition.
47 func Packages(_ *generator.Context, arguments *args.GeneratorArgs) generator.Packages {
48 boilerplate, err := arguments.LoadGoBoilerplate()
49 if err != nil {
50 klog.Fatalf("Failed loading boilerplate: %v", err)
51 }
52
53 return generator.Packages{&generator.DefaultPackage{
54 PackageName: "sets",
55 PackagePath: arguments.OutputPackagePath,
56 HeaderText: boilerplate,
57 PackageDocumentation: []byte(
58 `// Package sets has auto-generated set types.
59 `),
60 // GeneratorFunc returns a list of generators. Each generator makes a
61 // single file.
62 GeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {
63 generators = []generator.Generator{
64 // Always generate a "doc.go" file.
65 generator.DefaultGen{OptionalName: "doc"},
66 // Make a separate file for the Empty type, since it's shared by every type.
67 generator.DefaultGen{
68 OptionalName: "empty",
69 OptionalBody: []byte(emptyTypeDecl),
70 },
71 }
72 // Since we want a file per type that we generate a set for, we
73 // have to provide a function for this.
74 for _, t := range c.Order {
75 generators = append(generators, &genSet{
76 DefaultGen: generator.DefaultGen{
77 // Use the privatized version of the
78 // type name as the file name.
79 //
80 // TODO: make a namer that converts
81 // camelCase to '-' separation for file
82 // names?
83 OptionalName: c.Namers["private"].Name(t),
84 },
85 outputPackage: arguments.OutputPackagePath,
86 typeToMatch: t,
87 imports: generator.NewImportTracker(),
88 })
89 }
90 return generators
91 },
92 FilterFunc: func(c *generator.Context, t *types.Type) bool {
93 // It would be reasonable to filter by the type's package here.
94 // It might be necessary if your input directory has a big
95 // import graph.
96 switch t.Kind {
97 case types.Map, types.Slice, types.Pointer:
98 // These types can't be keys in a map.
99 return false
100 case types.Builtin:
101 return true
102 case types.Struct:
103 // Only some structs can be keys in a map. This is triggered by the line
104 // // +genset
105 // or
106 // // +genset=true
107 return extractBoolTagOrDie("genset", t.CommentLines) == true
108 }
109 return false
110 },
111 }}
112 }
113
114 // genSet produces a file with a set for a single type.
115 type genSet struct {
116 generator.DefaultGen
117 outputPackage string
118 typeToMatch *types.Type
119 imports namer.ImportTracker
120 }
121
122 // Filter ignores all but one type because we're making a single file per type.
123 func (g *genSet) Filter(c *generator.Context, t *types.Type) bool { return t == g.typeToMatch }
124
125 func (g *genSet) Namers(c *generator.Context) namer.NameSystems {
126 return namer.NameSystems{
127 "raw": namer.NewRawNamer(g.outputPackage, g.imports),
128 }
129 }
130
131 func (g *genSet) Imports(c *generator.Context) (imports []string) {
132 return append(g.imports.ImportLines(), "reflect", "sort")
133 }
134
135 // args constructs arguments for templates. Usage:
136 // g.args(t, "key1", value1, "key2", value2, ...)
137 //
138 // 't' is loaded with the key 'type'.
139 //
140 // We could use t directly as the argument, but doing it this way makes it easy
141 // to mix in additional parameters. This feature is not used in this set
142 // generator, but is present as an example.
143 func (g *genSet) args(t *types.Type, kv ...interface{}) interface{} {
144 m := map[interface{}]interface{}{"type": t}
145 for i := 0; i < len(kv)/2; i++ {
146 m[kv[i*2]] = kv[i*2+1]
147 }
148 return m
149 }
150
151 // GenerateType makes the body of a file implementing a set for type t.
152 func (g *genSet) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
153 sw := generator.NewSnippetWriter(w, c, "$", "$")
154 sw.Do(setCode, g.args(t))
155 sw.Do("func less$.type|public$(lhs, rhs $.type|raw$) bool {\n", g.args(t))
156 g.lessBody(sw, t)
157 sw.Do("}\n", g.args(t))
158 return sw.Error()
159 }
160
161 func (g *genSet) lessBody(sw *generator.SnippetWriter, t *types.Type) {
162 // TODO: make this recursive, handle pointers and multiple nested structs...
163 switch t.Kind {
164 case types.Struct:
165 for _, m := range types.FlattenMembers(t.Members) {
166 sw.Do("if lhs.$.Name$ < rhs.$.Name$ { return true }\n", m)
167 sw.Do("if lhs.$.Name$ > rhs.$.Name$ { return false }\n", m)
168 }
169 sw.Do("return false\n", nil)
170 default:
171 sw.Do("return lhs < rhs\n", nil)
172 }
173 }
174
175 // written to the "empty.go" file.
176 var emptyTypeDecl = `
177 // Empty is public since it is used by some internal API objects for conversions between external
178 // string arrays and internal sets, and conversion logic requires public types today.
179 type Empty struct{}
180 `
181
182 // Written for every type. If you've never used text/template before:
183 // $.type$ refers to the source type; |public means to
184 // call the function giving the public name, |raw the raw type name.
185 var setCode = `// sets.$.type|public$ is a set of $.type|raw$s, implemented via map[$.type|raw$]struct{} for minimal memory consumption.
186 type $.type|public$ map[$.type|raw$]Empty
187
188 // New$.type|public$ creates a $.type|public$ from a list of values.
189 func New$.type|public$(items ...$.type|raw$) $.type|public$ {
190 ss := make($.type|public$, len(items))
191 ss.Insert(items...)
192 return ss
193 }
194
195 // $.type|public$KeySet creates a $.type|public$ from a keys of a map[$.type|raw$](? extends interface{}).
196 // If the value passed in is not actually a map, this will panic.
197 func $.type|public$KeySet(theMap interface{}) $.type|public$ {
198 v := reflect.ValueOf(theMap)
199 ret := $.type|public${}
200
201 for _, keyValue := range v.MapKeys() {
202 ret.Insert(keyValue.Interface().($.type|raw$))
203 }
204 return ret
205 }
206
207 // Insert adds items to the set.
208 func (s $.type|public$) Insert(items ...$.type|raw$) $.type|public$ {
209 for _, item := range items {
210 s[item] = Empty{}
211 }
212 return s
213 }
214
215 // Delete removes all items from the set.
216 func (s $.type|public$) Delete(items ...$.type|raw$) $.type|public$ {
217 for _, item := range items {
218 delete(s, item)
219 }
220 return s
221 }
222
223 // Has returns true if and only if item is contained in the set.
224 func (s $.type|public$) Has(item $.type|raw$) bool {
225 _, contained := s[item]
226 return contained
227 }
228
229 // HasAll returns true if and only if all items are contained in the set.
230 func (s $.type|public$) HasAll(items ...$.type|raw$) bool {
231 for _, item := range items {
232 if !s.Has(item) {
233 return false
234 }
235 }
236 return true
237 }
238
239 // HasAny returns true if any items are contained in the set.
240 func (s $.type|public$) HasAny(items ...$.type|raw$) bool {
241 for _, item := range items {
242 if s.Has(item) {
243 return true
244 }
245 }
246 return false
247 }
248
249 // Clone returns a new set which is a copy of the current set.
250 func (s $.type|public$) Clone() $.type|public$ {
251 result := make($.type|public$, len(s))
252 for key := range s {
253 result.Insert(key)
254 }
255 return result
256 }
257
258 // Difference returns a set of objects that are not in s2.
259 // For example:
260 // s1 = {a1, a2, a3}
261 // s2 = {a1, a2, a4, a5}
262 // s1.Difference(s2) = {a3}
263 // s2.Difference(s1) = {a4, a5}
264 func (s1 $.type|public$) Difference(s2 $.type|public$) $.type|public$ {
265 result := New$.type|public$()
266 for key := range s1 {
267 if !s2.Has(key) {
268 result.Insert(key)
269 }
270 }
271 return result
272 }
273
274 // SymmetricDifference returns a set of elements which are in either of the sets, but not in their intersection.
275 // For example:
276 // s1 = {a1, a2, a3}
277 // s2 = {a1, a2, a4, a5}
278 // s1.SymmetricDifference(s2) = {a3, a4, a5}
279 // s2.SymmetricDifference(s1) = {a3, a4, a5}
280 func (s1 $.type|public$) SymmetricDifference(s2 $.type|public$) $.type|public$ {
281 return s1.Difference(s2).Union(s2.Difference(s1))
282 }
283
284 // Union returns a new set which includes items in either s1 or s2.
285 // For example:
286 // s1 = {a1, a2}
287 // s2 = {a3, a4}
288 // s1.Union(s2) = {a1, a2, a3, a4}
289 // s2.Union(s1) = {a1, a2, a3, a4}
290 func (s1 $.type|public$) Union(s2 $.type|public$) $.type|public$ {
291 result := s1.Clone()
292 for key := range s2 {
293 result.Insert(key)
294 }
295 return result
296 }
297
298 // Intersection returns a new set which includes the item in BOTH s1 and s2
299 // For example:
300 // s1 = {a1, a2}
301 // s2 = {a2, a3}
302 // s1.Intersection(s2) = {a2}
303 func (s1 $.type|public$) Intersection(s2 $.type|public$) $.type|public$ {
304 var walk, other $.type|public$
305 result := New$.type|public$()
306 if s1.Len() < s2.Len() {
307 walk = s1
308 other = s2
309 } else {
310 walk = s2
311 other = s1
312 }
313 for key := range walk {
314 if other.Has(key) {
315 result.Insert(key)
316 }
317 }
318 return result
319 }
320
321 // IsSuperset returns true if and only if s1 is a superset of s2.
322 func (s1 $.type|public$) IsSuperset(s2 $.type|public$) bool {
323 for item := range s2 {
324 if !s1.Has(item) {
325 return false
326 }
327 }
328 return true
329 }
330
331 // Equal returns true if and only if s1 is equal (as a set) to s2.
332 // Two sets are equal if their membership is identical.
333 // (In practice, this means same elements, order doesn't matter)
334 func (s1 $.type|public$) Equal(s2 $.type|public$) bool {
335 return len(s1) == len(s2) && s1.IsSuperset(s2)
336 }
337
338 type sortableSliceOf$.type|public$ []$.type|raw$
339
340 func (s sortableSliceOf$.type|public$) Len() int { return len(s) }
341 func (s sortableSliceOf$.type|public$) Less(i, j int) bool { return less$.type|public$(s[i], s[j]) }
342 func (s sortableSliceOf$.type|public$) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
343
344 // List returns the contents as a sorted $.type|raw$ slice.
345 func (s $.type|public$) List() []$.type|raw$ {
346 res := make(sortableSliceOf$.type|public$, 0, len(s))
347 for key := range s {
348 res = append(res, key)
349 }
350 sort.Sort(res)
351 return []$.type|raw$(res)
352 }
353
354 // UnsortedList returns the slice with contents in random order.
355 func (s $.type|public$) UnsortedList() []$.type|raw$ {
356 res :=make([]$.type|raw$, 0, len(s))
357 for key := range s {
358 res = append(res, key)
359 }
360 return res
361 }
362
363 // Returns a single element from the set.
364 func (s $.type|public$) PopAny() ($.type|raw$, bool) {
365 for key := range s {
366 s.Delete(key)
367 return key, true
368 }
369 var zeroValue $.type|raw$
370 return zeroValue, false
371 }
372
373 // Len returns the size of the set.
374 func (s $.type|public$) Len() int {
375 return len(s)
376 }
377
378 `