Debian Codegraph @

pkg/cel/library/regex.go

raw
1 /*
2 Copyright 2022 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 library
18
19 import (
20 "regexp"
21
22 "github.com/google/cel-go/cel"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/common/types/ref"
25 "github.com/google/cel-go/interpreter"
26 )
27
28 // Regex provides a CEL function library extension of regex utility functions.
29 //
30 // find / findAll
31 //
32 // Returns substrings that match the provided regular expression. find returns the first match. findAll may optionally
33 // be provided a limit. If the limit is set and >= 0, no more than the limit number of matches are returned.
34 //
35 // <string>.find(<string>) <string>
36 // <string>.findAll(<string>) <list <string>>
37 // <string>.findAll(<string>, <int>) <list <string>>
38 //
39 // Examples:
40 //
41 // "abc 123".find('[0-9]*') // returns '123'
42 // "abc 123".find('xyz') // returns ''
43 // "123 abc 456".findAll('[0-9]*') // returns ['123', '456']
44 // "123 abc 456".findAll('[0-9]*', 1) // returns ['123']
45 // "123 abc 456".findAll('xyz') // returns []
46 func Regex() cel.EnvOption {
47 return cel.Lib(regexLib)
48 }
49
50 var regexLib = &regex{}
51
52 type regex struct{}
53
54 func (*regex) LibraryName() string {
55 return "kubernetes.regex"
56 }
57
58 func (*regex) Types() []*cel.Type {
59 return []*cel.Type{}
60 }
61
62 func (*regex) declarations() map[string][]cel.FunctionOpt {
63 return regexLibraryDecls
64 }
65
66 var regexLibraryDecls = map[string][]cel.FunctionOpt{
67 "find": {
68 cel.MemberOverload("string_find_string", []*cel.Type{cel.StringType, cel.StringType}, cel.StringType,
69 cel.BinaryBinding(find))},
70 "findAll": {
71 cel.MemberOverload("string_find_all_string", []*cel.Type{cel.StringType, cel.StringType},
72 cel.ListType(cel.StringType),
73 cel.BinaryBinding(func(str, regex ref.Val) ref.Val {
74 return findAll(str, regex, types.Int(-1))
75 })),
76 cel.MemberOverload("string_find_all_string_int",
77 []*cel.Type{cel.StringType, cel.StringType, cel.IntType},
78 cel.ListType(cel.StringType),
79 cel.FunctionBinding(findAll)),
80 },
81 }
82
83 func (*regex) CompileOptions() []cel.EnvOption {
84 options := []cel.EnvOption{}
85 for name, overloads := range regexLibraryDecls {
86 options = append(options, cel.Function(name, overloads...))
87 }
88 return options
89 }
90
91 func (*regex) ProgramOptions() []cel.ProgramOption {
92 return []cel.ProgramOption{
93 cel.OptimizeRegex(FindRegexOptimization, FindAllRegexOptimization),
94 }
95 }
96
97 func find(strVal ref.Val, regexVal ref.Val) ref.Val {
98 str, ok := strVal.Value().(string)
99 if !ok {
100 return types.MaybeNoSuchOverloadErr(strVal)
101 }
102 regex, ok := regexVal.Value().(string)
103 if !ok {
104 return types.MaybeNoSuchOverloadErr(regexVal)
105 }
106 re, err := regexp.Compile(regex)
107 if err != nil {
108 return types.NewErr("Illegal regex: %v", err.Error())
109 }
110 result := re.FindString(str)
111 return types.String(result)
112 }
113
114 func findAll(args ...ref.Val) ref.Val {
115 argn := len(args)
116 if argn < 2 || argn > 3 {
117 return types.NoSuchOverloadErr()
118 }
119 str, ok := args[0].Value().(string)
120 if !ok {
121 return types.MaybeNoSuchOverloadErr(args[0])
122 }
123 regex, ok := args[1].Value().(string)
124 if !ok {
125 return types.MaybeNoSuchOverloadErr(args[1])
126 }
127 n := int64(-1)
128 if argn == 3 {
129 n, ok = args[2].Value().(int64)
130 if !ok {
131 return types.MaybeNoSuchOverloadErr(args[2])
132 }
133 }
134
135 re, err := regexp.Compile(regex)
136 if err != nil {
137 return types.NewErr("Illegal regex: %v", err.Error())
138 }
139
140 result := re.FindAllString(str, int(n))
141
142 return types.NewStringList(types.DefaultTypeAdapter, result)
143 }
144
145 // FindRegexOptimization optimizes the 'find' function by compiling the regex pattern and
146 // reporting any compilation errors at program creation time, and using the compiled regex pattern for all function
147 // call invocations.
148 var FindRegexOptimization = &interpreter.RegexOptimization{
149 Function: "find",
150 RegexIndex: 1,
151 Factory: func(call interpreter.InterpretableCall, regexPattern string) (interpreter.InterpretableCall, error) {
152 compiledRegex, err := regexp.Compile(regexPattern)
153 if err != nil {
154 return nil, err
155 }
156 return interpreter.NewCall(call.ID(), call.Function(), call.OverloadID(), call.Args(), func(args ...ref.Val) ref.Val {
157 if len(args) != 2 {
158 return types.NoSuchOverloadErr()
159 }
160 in, ok := args[0].Value().(string)
161 if !ok {
162 return types.MaybeNoSuchOverloadErr(args[0])
163 }
164 return types.String(compiledRegex.FindString(in))
165 }), nil
166 },
167 }
168
169 // FindAllRegexOptimization optimizes the 'findAll' function by compiling the regex pattern and
170 // reporting any compilation errors at program creation time, and using the compiled regex pattern for all function
171 // call invocations.
172 var FindAllRegexOptimization = &interpreter.RegexOptimization{
173 Function: "findAll",
174 RegexIndex: 1,
175 Factory: func(call interpreter.InterpretableCall, regexPattern string) (interpreter.InterpretableCall, error) {
176 compiledRegex, err := regexp.Compile(regexPattern)
177 if err != nil {
178 return nil, err
179 }
180 return interpreter.NewCall(call.ID(), call.Function(), call.OverloadID(), call.Args(), func(args ...ref.Val) ref.Val {
181 argn := len(args)
182 if argn < 2 || argn > 3 {
183 return types.NoSuchOverloadErr()
184 }
185 str, ok := args[0].Value().(string)
186 if !ok {
187 return types.MaybeNoSuchOverloadErr(args[0])
188 }
189 n := int64(-1)
190 if argn == 3 {
191 n, ok = args[2].Value().(int64)
192 if !ok {
193 return types.MaybeNoSuchOverloadErr(args[2])
194 }
195 }
196
197 result := compiledRegex.FindAllString(str, int(n))
198 return types.NewStringList(types.DefaultTypeAdapter, result)
199 }), nil
200 },
201 }