Debian Codegraph @

common/containers/container.go

raw symbols SCIP
1 // Copyright 2018 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package containers defines types and functions for resolving qualified names within a namespace
16 // or type provided to CEL.
17 package containers
18
19 import (
20 "fmt"
21 "strings"
22 "unicode"
23
24 "github.com/google/cel-go/common/ast"
25 )
26
27 var (
28 // DefaultContainer has an empty container name.
29 DefaultContainer *Container = nil
30
31 // Empty map to search for aliases when needed.
32 noAliases = make(map[string]string)
33 )
34
35 // NewContainer creates a new Container with the fully-qualified name.
36 func NewContainer(opts ...ContainerOption) (*Container, error) {
37 var c *Container
38 var err error
39 for _, opt := range opts {
40 c, err = opt(c)
41 if err != nil {
42 return nil, err
43 }
44 }
45 return c, nil
46 }
47
48 // Container holds a reference to an optional qualified container name and set of aliases.
49 //
50 // The program container can be used to simplify variable, function, and type specification within
51 // CEL programs and behaves more or less like a C++ namespace. See ResolveCandidateNames for more
52 // details.
53 type Container struct {
54 name string
55 aliases map[string]string
56 }
57
58 // Extend creates a new Container with the existing settings and applies a series of
59 // ContainerOptions to further configure the new container.
60 func (c *Container) Extend(opts ...ContainerOption) (*Container, error) {
61 if c == nil {
62 return NewContainer(opts...)
63 }
64 // Copy the name and aliases of the existing container.
65 ext := &Container{name: c.Name()}
66 if len(c.AliasSet()) > 0 {
67 aliasSet := make(map[string]string, len(c.AliasSet()))
68 for k, v := range c.AliasSet() {
69 aliasSet[k] = v
70 }
71 ext.aliases = aliasSet
72 }
73 // Apply the new options to the container.
74 var err error
75 for _, opt := range opts {
76 ext, err = opt(ext)
77 if err != nil {
78 return nil, err
79 }
80 }
81 return ext, nil
82 }
83
84 // Name returns the fully-qualified name of the container.
85 //
86 // The name may conceptually be a namespace, package, or type.
87 func (c *Container) Name() string {
88 if c == nil {
89 return ""
90 }
91 return c.name
92 }
93
94 // ResolveCandidateNames returns the candidates name of namespaced identifiers in C++ resolution
95 // order.
96 //
97 // Names which shadow other names are returned first. If a name includes a leading dot ('.'),
98 // the name is treated as an absolute identifier which cannot be shadowed.
99 //
100 // Given a container name a.b.c.M.N and a type name R.s, this will deliver in order:
101 //
102 // a.b.c.M.N.R.s
103 // a.b.c.M.R.s
104 // a.b.c.R.s
105 // a.b.R.s
106 // a.R.s
107 // R.s
108 //
109 // If aliases or abbreviations are configured for the container, then alias names will take
110 // precedence over containerized names.
111 func (c *Container) ResolveCandidateNames(name string) []string {
112 if strings.HasPrefix(name, ".") {
113 qn := name[1:]
114 alias, isAlias := c.findAlias(qn)
115 if isAlias {
116 return []string{alias}
117 }
118 return []string{qn}
119 }
120 alias, isAlias := c.findAlias(name)
121 if isAlias {
122 return []string{alias}
123 }
124 if c.Name() == "" {
125 return []string{name}
126 }
127 nextCont := c.Name()
128 candidates := []string{nextCont + "." + name}
129 for i := strings.LastIndex(nextCont, "."); i >= 0; i = strings.LastIndex(nextCont, ".") {
130 nextCont = nextCont[:i]
131 candidates = append(candidates, nextCont+"."+name)
132 }
133 return append(candidates, name)
134 }
135
136 // AliasSet returns the alias to fully-qualified name mapping stored in the container.
137 func (c *Container) AliasSet() map[string]string {
138 if c == nil || c.aliases == nil {
139 return noAliases
140 }
141 return c.aliases
142 }
143
144 // findAlias takes a name as input and returns an alias expansion if one exists.
145 //
146 // If the name is qualified, the first component of the qualified name is checked against known
147 // aliases. Any alias that is found in a qualified name is expanded in the result:
148 //
149 // alias: R -> my.alias.R
150 // name: R.S.T
151 // output: my.alias.R.S.T
152 //
153 // Note, the name must not have a leading dot.
154 func (c *Container) findAlias(name string) (string, bool) {
155 // If an alias exists for the name, ensure it is searched last.
156 simple := name
157 qualifier := ""
158 dot := strings.Index(name, ".")
159 if dot >= 0 {
160 simple = name[0:dot]
161 qualifier = name[dot:]
162 }
163 alias, found := c.AliasSet()[simple]
164 if !found {
165 return "", false
166 }
167 return alias + qualifier, true
168 }
169
170 // ContainerOption specifies a functional configuration option for a Container.
171 //
172 // Note, ContainerOption implementations must be able to handle nil container inputs.
173 type ContainerOption func(*Container) (*Container, error)
174
175 // Abbrevs configures a set of simple names as abbreviations for fully-qualified names.
176 //
177 // An abbreviation (abbrev for short) is a simple name that expands to a fully-qualified name.
178 // Abbreviations can be useful when working with variables, functions, and especially types from
179 // multiple namespaces:
180 //
181 // // CEL object construction
182 // qual.pkg.version.ObjTypeName{
183 // field: alt.container.ver.FieldTypeName{value: ...}
184 // }
185 //
186 // Only one the qualified names above may be used as the CEL container, so at least one of these
187 // references must be a long qualified name within an otherwise short CEL program. Using the
188 // following abbreviations, the program becomes much simpler:
189 //
190 // // CEL Go option
191 // Abbrevs("qual.pkg.version.ObjTypeName", "alt.container.ver.FieldTypeName")
192 // // Simplified Object construction
193 // ObjTypeName{field: FieldTypeName{value: ...}}
194 //
195 // There are a few rules for the qualified names and the simple abbreviations generated from them:
196 // - Qualified names must be dot-delimited, e.g. `package.subpkg.name`.
197 // - The last element in the qualified name is the abbreviation.
198 // - Abbreviations must not collide with each other.
199 // - The abbreviation must not collide with unqualified names in use.
200 //
201 // Abbreviations are distinct from container-based references in the following important ways:
202 // - Abbreviations must expand to a fully-qualified name.
203 // - Expanded abbreviations do not participate in namespace resolution.
204 // - Abbreviation expansion is done instead of the container search for a matching identifier.
205 // - Containers follow C++ namespace resolution rules with searches from the most qualified name
206 // to the least qualified name.
207 // - Container references within the CEL program may be relative, and are resolved to fully
208 // qualified names at either type-check time or program plan time, whichever comes first.
209 //
210 // If there is ever a case where an identifier could be in both the container and as an
211 // abbreviation, the abbreviation wins as this will ensure that the meaning of a program is
212 // preserved between compilations even as the container evolves.
213 func Abbrevs(qualifiedNames ...string) ContainerOption {
214 return func(c *Container) (*Container, error) {
215 for _, qn := range qualifiedNames {
216 qn = strings.TrimSpace(qn)
217 for _, r := range qn {
218 if !isIdentifierChar(r) {
219 return nil, fmt.Errorf(
220 "invalid qualified name: %s, wanted name of the form 'qualified.name'", qn)
221 }
222 }
223 ind := strings.LastIndex(qn, ".")
224 if ind <= 0 || ind >= len(qn)-1 {
225 return nil, fmt.Errorf(
226 "invalid qualified name: %s, wanted name of the form 'qualified.name'", qn)
227 }
228 alias := qn[ind+1:]
229 var err error
230 c, err = aliasAs("abbreviation", qn, alias)(c)
231 if err != nil {
232 return nil, err
233 }
234 }
235 return c, nil
236 }
237 }
238
239 // Alias associates a fully-qualified name with a user-defined alias.
240 //
241 // In general, Abbrevs is preferred to Alias since the names generated from the Abbrevs option
242 // are more easily traced back to source code. The Alias option is useful for propagating alias
243 // configuration from one Container instance to another, and may also be useful for remapping
244 // poorly chosen protobuf message / package names.
245 //
246 // Note: all of the rules that apply to Abbrevs also apply to Alias.
247 func Alias(qualifiedName, alias string) ContainerOption {
248 return aliasAs("alias", qualifiedName, alias)
249 }
250
251 func aliasAs(kind, qualifiedName, alias string) ContainerOption {
252 return func(c *Container) (*Container, error) {
253 if len(alias) == 0 || strings.Contains(alias, ".") {
254 return nil, fmt.Errorf(
255 "%s must be non-empty and simple (not qualified): %s=%s", kind, kind, alias)
256 }
257
258 if qualifiedName[0:1] == "." {
259 return nil, fmt.Errorf("qualified name must not begin with a leading '.': %s",
260 qualifiedName)
261 }
262 ind := strings.LastIndex(qualifiedName, ".")
263 if ind <= 0 || ind == len(qualifiedName)-1 {
264 return nil, fmt.Errorf("%s must refer to a valid qualified name: %s",
265 kind, qualifiedName)
266 }
267 aliasRef, found := c.AliasSet()[alias]
268 if found {
269 return nil, fmt.Errorf(
270 "%s collides with existing reference: name=%s, %s=%s, existing=%s",
271 kind, qualifiedName, kind, alias, aliasRef)
272 }
273 if strings.HasPrefix(c.Name(), alias+".") || c.Name() == alias {
274 return nil, fmt.Errorf(
275 "%s collides with container name: name=%s, %s=%s, container=%s",
276 kind, qualifiedName, kind, alias, c.Name())
277 }
278 if c == nil {
279 c = &Container{}
280 }
281 if c.aliases == nil {
282 c.aliases = make(map[string]string)
283 }
284 c.aliases[alias] = qualifiedName
285 return c, nil
286 }
287 }
288
289 func isIdentifierChar(r rune) bool {
290 return r <= unicode.MaxASCII && (r == '.' || r == '_' || unicode.IsLetter(r) || unicode.IsNumber(r))
291 }
292
293 // Name sets the fully-qualified name of the Container.
294 func Name(name string) ContainerOption {
295 return func(c *Container) (*Container, error) {
296 if len(name) > 0 && name[0:1] == "." {
297 return nil, fmt.Errorf("container name must not contain a leading '.': %s", name)
298 }
299 if c.Name() == name {
300 return c, nil
301 }
302 if c == nil {
303 return &Container{name: name}, nil
304 }
305 c.name = name
306 return c, nil
307 }
308 }
309
310 // ToQualifiedName converts an expression AST into a qualified name if possible, with a boolean
311 // 'found' value that indicates if the conversion is successful.
312 func ToQualifiedName(e ast.Expr) (string, bool) {
313 switch e.Kind() {
314 case ast.IdentKind:
315 id := e.AsIdent()
316 return id, true
317 case ast.SelectKind:
318 sel := e.AsSelect()
319 // Test only expressions are not valid as qualified names.
320 if sel.IsTestOnly() {
321 return "", false
322 }
323 if qual, found := ToQualifiedName(sel.Operand()); found {
324 return qual + "." + sel.FieldName(), true
325 }
326 }
327 return "", false
328 }