Debian Codegraph @

v2/generator/generator.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 generator
18
19 import (
20 "bytes"
21 "io"
22
23 "k8s.io/gengo/v2/namer"
24 "k8s.io/gengo/v2/parser"
25 "k8s.io/gengo/v2/types"
26 )
27
28 // Target describes a Go package into which code will be generated. A single
29 // Target may have many Generators, each of which emits one file.
30 type Target interface {
31 // Name returns the package short name (as in `package foo`).
32 Name() string
33 // Path returns the package import path (as in `import "example.com/foo"`).
34 Path() string
35 // Dir returns the location of the resulting package on disk. This may be
36 // the same directory as an input package (when generating code in-place)
37 // or a different directory entirely.
38 Dir() string
39
40 // Filter should return true if this package cares about this type.
41 // Otherwise, this type will be omitted from the type ordering for
42 // this package.
43 Filter(*Context, *types.Type) bool
44
45 // Header should return a header for the file, including comment markers.
46 // Useful for copyright notices and doc strings. Include an
47 // autogeneration notice! Do not include the "package x" line.
48 Header(filename string) []byte
49
50 // Generators returns the list of generators for this package. It is
51 // allowed for more than one generator to write to the same file.
52 // A Context is passed in case the list of generators depends on the
53 // input types.
54 Generators(*Context) []Generator
55 }
56
57 type File struct {
58 Name string
59 FileType string
60 PackageName string
61 Header []byte
62 PackagePath string
63 PackageDir string
64 Imports map[string]struct{}
65 Vars bytes.Buffer
66 Consts bytes.Buffer
67 Body bytes.Buffer
68 }
69
70 type FileType interface {
71 AssembleFile(f *File, path string) error
72 }
73
74 // Generator is the contract for anything that wants to do auto-generation.
75 // It's expected that the io.Writers passed to the below functions will be
76 // ErrorTrackers; this allows implementations to not check for io errors,
77 // making more readable code.
78 //
79 // The call order for the functions that take a Context is:
80 // 1. Filter() // Subsequent calls see only types that pass this.
81 // 2. Namers() // Subsequent calls see the namers provided by this.
82 // 3. PackageVars()
83 // 4. PackageConsts()
84 // 5. Init()
85 // 6. GenerateType() // Called N times, once per type in the context's Order.
86 // 7. Imports()
87 //
88 // You may have multiple generators for the same file.
89 type Generator interface {
90 // The name of this generator. Will be included in generated comments.
91 Name() string
92
93 // Filter should return true if this generator cares about this type.
94 // (otherwise, GenerateType will not be called.)
95 //
96 // Filter is called before any of the generator's other functions;
97 // subsequent calls will get a context with only the types that passed
98 // this filter.
99 Filter(*Context, *types.Type) bool
100
101 // If this generator needs special namers, return them here. These will
102 // override the original namers in the context if there is a collision.
103 // You may return nil if you don't need special names. These names will
104 // be available in the context passed to the rest of the generator's
105 // functions.
106 //
107 // A use case for this is to return a namer that tracks imports.
108 Namers(*Context) namer.NameSystems
109
110 // Init should write an init function, and any other content that's not
111 // generated per-type. (It's not intended for generator specific
112 // initialization! Do that when your Target constructs the
113 // Generators.)
114 Init(*Context, io.Writer) error
115
116 // Finalize should write finish up functions, and any other content that's not
117 // generated per-type.
118 Finalize(*Context, io.Writer) error
119
120 // PackageVars should emit an array of variable lines. They will be
121 // placed in a var ( ... ) block. There's no need to include a leading
122 // \t or trailing \n.
123 PackageVars(*Context) []string
124
125 // PackageConsts should emit an array of constant lines. They will be
126 // placed in a const ( ... ) block. There's no need to include a leading
127 // \t or trailing \n.
128 PackageConsts(*Context) []string
129
130 // GenerateType should emit the code for a particular type.
131 GenerateType(*Context, *types.Type, io.Writer) error
132
133 // Imports should return a list of necessary imports. They will be
134 // formatted correctly. You do not need to include quotation marks,
135 // return only the package name; alternatively, you can also return
136 // imports in the format `name "path/to/pkg"`. Imports will be called
137 // after Init, PackageVars, PackageConsts, and GenerateType, to allow
138 // you to keep track of what imports you actually need.
139 Imports(*Context) []string
140
141 // Preferred file name of this generator, not including a path. It is
142 // allowed for multiple generators to use the same filename, but it's
143 // up to you to make sure they don't have colliding import names.
144 // TODO: provide per-file import tracking, removing the requirement
145 // that generators coordinate..
146 Filename() string
147
148 // A registered file type in the context to generate this file with. If
149 // the FileType is not found in the context, execution will stop.
150 FileType() string
151 }
152
153 // Context is global context for individual generators to consume.
154 type Context struct {
155 // A map from the naming system to the names for that system. E.g., you
156 // might have public names and several private naming systems.
157 Namers namer.NameSystems
158
159 // All the types, in case you want to look up something.
160 Universe types.Universe
161
162 // All the user-specified packages. This is after recursive expansion.
163 Inputs []string
164
165 // The canonical ordering of the types (will be filtered by both the
166 // Target's and Generator's Filter methods).
167 Order []*types.Type
168
169 // A set of types this context can process. If this is empty or nil,
170 // the default "go" filetype will be provided.
171 FileTypes map[string]FileType
172
173 // Allows generators to add packages at runtime.
174 parser *parser.Parser
175 }
176
177 // NewContext generates a context from the given parser, naming systems, and
178 // the naming system you wish to construct the canonical ordering from.
179 func NewContext(p *parser.Parser, nameSystems namer.NameSystems, canonicalOrderName string) (*Context, error) {
180 universe, err := p.NewUniverse()
181 if err != nil {
182 return nil, err
183 }
184
185 c := &Context{
186 Namers: namer.NameSystems{},
187 Universe: universe,
188 Inputs: p.UserRequestedPackages(),
189 FileTypes: map[string]FileType{
190 GoFileType: NewGoFile(),
191 },
192 parser: p,
193 }
194
195 for name, systemNamer := range nameSystems {
196 c.Namers[name] = systemNamer
197 if name == canonicalOrderName {
198 orderer := namer.Orderer{Namer: systemNamer}
199 c.Order = orderer.OrderUniverse(universe)
200 }
201 }
202 return c, nil
203 }
204
205 // LoadPackages adds Go packages to the context.
206 func (c *Context) LoadPackages(patterns ...string) ([]*types.Package, error) {
207 return c.parser.LoadPackagesTo(&c.Universe, patterns...)
208 }
209
210 // FindPackages expands Go package patterns into a list of package import
211 // paths, akin to `go list -find`.
212 func (c *Context) FindPackages(patterns ...string) ([]string, error) {
213 return c.parser.FindPackages(patterns...)
214 }