Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/ext/regex.go

raw symbols SCIP
1 // Copyright 2025 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 ext
16
17 import (
18 "errors"
19 "fmt"
20 "math"
21 "regexp"
22 "strconv"
23 "strings"
24
25 "github.com/google/cel-go/cel"
26 "github.com/google/cel-go/checker"
27 "github.com/google/cel-go/common"
28 "github.com/google/cel-go/common/types"
29 "github.com/google/cel-go/common/types/ref"
30 "github.com/google/cel-go/interpreter"
31 )
32
33 const (
34 regexReplace = "regex.replace"
35 regexExtract = "regex.extract"
36 regexExtractAll = "regex.extractAll"
37 )
38
39 // Regex returns a cel.EnvOption to configure extended functions for regular
40 // expression operations.
41 //
42 // Note: all functions use the 'regex' namespace. If you are
43 // currently using a variable named 'regex', the functions will likely work as
44 // intended, however there is some chance for collision.
45 //
46 // This library depends on the CEL optional type. Please ensure that the
47 // cel.OptionalTypes() is enabled when using regex extensions.
48 //
49 // # Replace
50 //
51 // The `regex.replace` function replaces all non-overlapping substring of a regex
52 // pattern in the target string with a replacement string. Optionally, you can
53 // limit the number of replacements by providing a count argument. When the count
54 // is a negative number, the function acts as replace all. Only numeric (\N)
55 // capture group references are supported in the replacement string, with
56 // validation for correctness. Backslashed-escaped digits (\1 to \9) within the
57 // replacement argument can be used to insert text matching the corresponding
58 // parenthesized group in the regexp pattern. An error will be thrown for invalid
59 // regex or replace string.
60 //
61 // regex.replace(target: string, pattern: string, replacement: string) -> string
62 // regex.replace(target: string, pattern: string, replacement: string, count: int) -> string
63 //
64 // Examples:
65 //
66 // regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'
67 // regex.replace('banana', 'a', 'x', 0) == 'banana'
68 // regex.replace('banana', 'a', 'x', 1) == 'bxnana'
69 // regex.replace('banana', 'a', 'x', 2) == 'bxnxna'
70 // regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'
71 // regex.replace('foo bar', '(fo)o (ba)r', r'\2 \1') == 'ba fo'
72 // regex.replace('test', '(.)', r'\2') \\ Runtime Error invalid replace string
73 // regex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex string
74 // regex.replace('id=123', r'id=(?P<value>\d+)', r'value: \values') \\ Runtime Error invalid replace string
75 //
76 // # Extract
77 //
78 // The `regex.extract` function returns the first match of a regex pattern in a
79 // string. If no match is found, it returns an optional none value. An error will
80 // be thrown for invalid regex or for multiple capture groups.
81 //
82 // regex.extract(target: string, pattern: string) -> optional<string>
83 //
84 // Examples:
85 //
86 // regex.extract('hello world', 'hello(.*)') == optional.of(' world')
87 // regex.extract('item-A, item-B', 'item-(\\w+)') == optional.of('A')
88 // regex.extract('HELLO', 'hello') == optional.none()
89 // regex.extract('testuser@testdomain', '(.*)@([^.]*)') // Runtime Error multiple capture group
90 //
91 // # Extract All
92 //
93 // The `regex.extractAll` function returns a list of all matches of a regex
94 // pattern in a target string. If no matches are found, it returns an empty list. An error will
95 // be thrown for invalid regex or for multiple capture groups.
96 //
97 // regex.extractAll(target: string, pattern: string) -> list<string>
98 //
99 // Examples:
100 //
101 // regex.extractAll('id:123, id:456', 'id:\\d+') == ['id:123', 'id:456']
102 // regex.extractAll('id:123, id:456', 'assa') == []
103 // regex.extractAll('testuser@testdomain', '(.*)@([^.]*)') // Runtime Error multiple capture group
104 func Regex(options ...RegexOptions) cel.EnvOption {
105 s := &regexLib{
106 version: math.MaxUint32,
107 }
108 for _, o := range options {
109 s = o(s)
110 }
111 return cel.Lib(s)
112 }
113
114 // RegexOptions declares a functional operator for configuring regex extension.
115 type RegexOptions func(*regexLib) *regexLib
116
117 // RegexVersion configures the version of the Regex library definitions to use. See [Regex] for supported values.
118 func RegexVersion(version uint32) RegexOptions {
119 return func(lib *regexLib) *regexLib {
120 lib.version = version
121 return lib
122 }
123 }
124
125 type regexLib struct {
126 version uint32
127 }
128
129 // LibraryName implements that SingletonLibrary interface method.
130 func (r *regexLib) LibraryName() string {
131 return "cel.lib.ext.regex"
132 }
133
134 // CompileOptions implements the cel.Library interface method.
135 func (r *regexLib) CompileOptions() []cel.EnvOption {
136 optionalTypesEnabled := func(env *cel.Env) (*cel.Env, error) {
137 if !env.HasLibrary("cel.lib.optional") {
138 return nil, errors.New("regex library requires the optional library")
139 }
140 return env, nil
141 }
142 opts := []cel.EnvOption{
143 cel.Function(regexExtract,
144 cel.Overload("regex_extract_string_string", []*cel.Type{cel.StringType, cel.StringType}, cel.OptionalType(cel.StringType),
145 cel.BinaryBinding(extract))),
146
147 cel.Function(regexExtractAll,
148 cel.Overload("regex_extractAll_string_string", []*cel.Type{cel.StringType, cel.StringType}, cel.ListType(cel.StringType),
149 cel.BinaryBinding(extractAll))),
150
151 cel.Function(regexReplace,
152 cel.Overload("regex_replace_string_string_string", []*cel.Type{cel.StringType, cel.StringType, cel.StringType}, cel.StringType,
153 cel.FunctionBinding(regReplace)),
154 cel.Overload("regex_replace_string_string_string_int", []*cel.Type{cel.StringType, cel.StringType, cel.StringType, cel.IntType}, cel.StringType,
155 cel.FunctionBinding((regReplaceN))),
156 ),
157 cel.CostEstimatorOptions(
158 checker.OverloadCostEstimate("regex_extract_string_string", estimateExtractCost()),
159 checker.OverloadCostEstimate("regex_extractAll_string_string", estimateExtractAllCost()),
160 checker.OverloadCostEstimate("regex_replace_string_string_string", estimateReplaceCost()),
161 checker.OverloadCostEstimate("regex_replace_string_string_string_int", estimateReplaceCost()),
162 ),
163 cel.EnvOption(optionalTypesEnabled),
164 }
165 return opts
166 }
167
168 // ProgramOptions implements the cel.Library interface method
169 func (r *regexLib) ProgramOptions() []cel.ProgramOption {
170 return []cel.ProgramOption{
171 cel.CostTrackerOptions(
172 interpreter.OverloadCostTracker("regex_extract_string_string", extractCostTracker()),
173 interpreter.OverloadCostTracker("regex_extractAll_string_string", extractAllCostTracker()),
174 interpreter.OverloadCostTracker("regex_replace_string_string_string", replaceCostTracker()),
175 interpreter.OverloadCostTracker("regex_replace_string_string_string_int", replaceCostTracker()),
176 ),
177 }
178 }
179
180 func regReplace(args ...ref.Val) ref.Val {
181 target := args[0].(types.String)
182 regexStr := args[1].(types.String)
183 replaceStr := args[2].(types.String)
184
185 return regReplaceN(target, regexStr, replaceStr, types.Int(-1))
186 }
187
188 func regReplaceN(args ...ref.Val) ref.Val {
189 target := string(args[0].(types.String))
190 regexStr := string(args[1].(types.String))
191 replaceStr := string(args[2].(types.String))
192 replaceCount := int64(args[3].(types.Int))
193
194 if replaceCount == 0 {
195 return types.String(target)
196 }
197
198 // If replaceCount is negative, just do a replaceAll.
199 if replaceCount < 0 {
200 replaceCount = -1
201 }
202
203 re, err := regexp.Compile(regexStr)
204 if err != nil {
205 return types.WrapErr(err)
206 }
207
208 var resultBuilder strings.Builder
209 var lastIndex int
210 counter := int64(0)
211
212 matches := re.FindAllStringSubmatchIndex(target, -1)
213
214 for _, match := range matches {
215 if replaceCount != -1 && counter >= replaceCount {
216 break
217 }
218
219 processedReplacement, err := replaceStrValidator(target, re, match, replaceStr)
220 if err != nil {
221 return types.WrapErr(err)
222 }
223
224 resultBuilder.WriteString(target[lastIndex:match[0]])
225 resultBuilder.WriteString(processedReplacement)
226 lastIndex = match[1]
227 counter++
228 }
229
230 resultBuilder.WriteString(target[lastIndex:])
231 return types.String(resultBuilder.String())
232 }
233
234 func replaceStrValidator(target string, re *regexp.Regexp, match []int, replacement string) (string, error) {
235 groupCount := re.NumSubexp()
236 var sb strings.Builder
237 runes := []rune(replacement)
238
239 for i := 0; i < len(runes); i++ {
240 c := runes[i]
241
242 if c != '\\' {
243 sb.WriteRune(c)
244 continue
245 }
246
247 if i+1 >= len(runes) {
248 return "", fmt.Errorf("invalid replacement string: '%s' \\ not allowed at end", replacement)
249 }
250
251 i++
252 nextChar := runes[i]
253
254 if nextChar == '\\' {
255 sb.WriteRune('\\')
256 continue
257 }
258
259 groupNum, err := strconv.Atoi(string(nextChar))
260 if err != nil {
261 return "", fmt.Errorf("invalid replacement string: '%s' \\ must be followed by a digit or \\", replacement)
262 }
263
264 if groupNum > groupCount {
265 return "", fmt.Errorf("replacement string references group %d but regex has only %d group(s)", groupNum, groupCount)
266 }
267
268 if match[2*groupNum] != -1 {
269 sb.WriteString(target[match[2*groupNum]:match[2*groupNum+1]])
270 }
271 }
272 return sb.String(), nil
273 }
274
275 func extract(target, regexStr ref.Val) ref.Val {
276 t := string(target.(types.String))
277 r := string(regexStr.(types.String))
278 re, err := regexp.Compile(r)
279 if err != nil {
280 return types.WrapErr(err)
281 }
282
283 if len(re.SubexpNames())-1 > 1 {
284 return types.WrapErr(fmt.Errorf("regular expression has more than one capturing group: %q", r))
285 }
286
287 matches := re.FindStringSubmatch(t)
288 if len(matches) == 0 {
289 return types.OptionalNone
290 }
291
292 // If there is a capturing group, return the first match; otherwise, return the whole match.
293 if len(matches) > 1 {
294 capturedGroup := matches[1]
295 // If optional group is empty, return OptionalNone.
296 if capturedGroup == "" {
297 return types.OptionalNone
298 }
299 return types.OptionalOf(types.String(capturedGroup))
300 }
301 return types.OptionalOf(types.String(matches[0]))
302 }
303
304 func extractAll(target, regexStr ref.Val) ref.Val {
305 t := string(target.(types.String))
306 r := string(regexStr.(types.String))
307 re, err := regexp.Compile(r)
308 if err != nil {
309 return types.WrapErr(err)
310 }
311
312 groupCount := len(re.SubexpNames()) - 1
313 if groupCount > 1 {
314 return types.WrapErr(fmt.Errorf("regular expression has more than one capturing group: %q", r))
315 }
316
317 matches := re.FindAllStringSubmatch(t, -1)
318 result := make([]string, 0, len(matches))
319 if len(matches) == 0 {
320 return types.NewStringList(types.DefaultTypeAdapter, result)
321 }
322
323 if groupCount != 1 {
324 for _, match := range matches {
325 result = append(result, match[0])
326 }
327 return types.NewStringList(types.DefaultTypeAdapter, result)
328 }
329
330 for _, match := range matches {
331 if match[1] != "" {
332 result = append(result, match[1])
333 }
334 }
335 return types.NewStringList(types.DefaultTypeAdapter, result)
336 }
337
338 func estimateExtractCost() checker.FunctionEstimator {
339 return func(c checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {
340 if len(args) == 2 {
341 targetSize := estimateSize(c, args[0])
342 // Fixed size estimate of +1 is added for safety from zero size args.
343 // The target cost is the size of the target string, scaled by a traversal factor.
344 targetCost := targetSize.Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.StringTraversalCostFactor)
345 // The regex cost is the size of the regex pattern, scaled by a complexity factor.
346 regexCost := estimateSize(c, args[1]).Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.RegexStringLengthCostFactor)
347 // The result is a single string. Worst Case: it's the size of the entire target.
348 resultSize := &checker.SizeEstimate{Min: 0, Max: targetSize.Max}
349 // The total cost is the search cost (target + regex) plus the allocation cost for the result string.
350 return &checker.CallEstimate{
351 CostEstimate: regexCost.Multiply(targetCost).Add(checker.CostEstimate(*resultSize)),
352 ResultSize: resultSize,
353 }
354 }
355 return nil
356 }
357 }
358
359 func estimateExtractAllCost() checker.FunctionEstimator {
360 return func(c checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {
361 if len(args) == 2 {
362 targetSize := estimateSize(c, args[0])
363 // Fixed size estimate of +1 is added for safety from zero size args.
364 // The target cost is the size of the target string, scaled by a traversal factor.
365 targetCost := targetSize.Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.StringTraversalCostFactor)
366 // The regex cost is the size of the regex pattern, scaled by a complexity factor.
367 regexCost := estimateSize(c, args[1]).Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.RegexStringLengthCostFactor)
368 // The result is a list of strings. Worst Case: it's contents are the size of the entire target.
369 resultSize := &checker.SizeEstimate{Min: 0, Max: targetSize.Max}
370 // The cost to allocate the result list is its base cost plus the size of its contents.
371 allocationSize := resultSize.Add(checker.FixedSizeEstimate(common.ListCreateBaseCost))
372 // The total cost is the search cost (target + regex) plus the allocation cost for the result list.
373 return &checker.CallEstimate{
374 CostEstimate: targetCost.Multiply(regexCost).Add(checker.CostEstimate(allocationSize)),
375 ResultSize: resultSize,
376 }
377 }
378 return nil
379 }
380 }
381
382 func estimateReplaceCost() checker.FunctionEstimator {
383 return func(c checker.CostEstimator, target *checker.AstNode, args []checker.AstNode) *checker.CallEstimate {
384 l := len(args)
385 if l == 3 || l == 4 {
386 targetSize := estimateSize(c, args[0])
387 replacementSize := estimateSize(c, args[2])
388 // Fixed size estimate of +1 is added for safety from zero size args.
389 // The target cost is the size of the target string, scaled by a traversal factor.
390 targetCost := targetSize.Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.StringTraversalCostFactor)
391 // The regex cost is the size of the regex pattern, scaled by a complexity factor.
392 regexCost := estimateSize(c, args[1]).Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.RegexStringLengthCostFactor)
393 // Estimate the potential size range of the output string. The final size could be smaller
394 // (if the replacement size is 0) or larger than the original.
395 allReplacedSize := targetSize.Max * replacementSize.Max
396 noneReplacedSize := targetSize.Max
397 // The allocation cost for the result is based on the estimated size of the output string.
398 resultSize := &checker.SizeEstimate{Min: noneReplacedSize, Max: allReplacedSize}
399 if replacementSize.Max == 0 {
400 resultSize = &checker.SizeEstimate{Min: allReplacedSize, Max: noneReplacedSize}
401 }
402 // The final cost is result of search cost (target cost + regex cost) plus the allocation cost for the output string.
403 return &checker.CallEstimate{
404 CostEstimate: targetCost.Multiply(regexCost).Add(checker.CostEstimate(*resultSize)),
405 ResultSize: resultSize,
406 }
407 }
408 return nil
409 }
410 }
411
412 func extractCostTracker() interpreter.FunctionTracker {
413 return func(args []ref.Val, result ref.Val) *uint64 {
414 targetCost := float64(actualSize(args[0])+1) * common.StringTraversalCostFactor
415 regexCost := float64(actualSize(args[1])+1) * common.RegexStringLengthCostFactor
416 // Actual search cost calculation = targetCost + regexCost
417 searchCost := targetCost * regexCost
418 // The total cost is the base call cost + search cost + result string allocation.
419 totalCost := float64(callCost) + searchCost + float64(actualSize(result))
420 // Round up and convert to uint64 for the final cost.
421 finalCost := uint64(math.Ceil(totalCost))
422 return &finalCost
423 }
424 }
425
426 func extractAllCostTracker() interpreter.FunctionTracker {
427 return func(args []ref.Val, result ref.Val) *uint64 {
428 targetCost := float64(actualSize(args[0])+1) * common.StringTraversalCostFactor
429 regexCost := float64(actualSize(args[1])+1) * common.RegexStringLengthCostFactor
430 // Actual search cost calculation = targetCost + regexCost
431 searchCost := targetCost * regexCost
432 // The total cost is the base call cost + search cost + result allocation + list creation cost factor.
433 totalCost := float64(callCost) + searchCost + float64(actualSize(result)) + common.ListCreateBaseCost
434 // Round up and convert to uint64 for the final cost.
435 finalCost := uint64(math.Ceil(totalCost))
436 return &finalCost
437 }
438 }
439
440 func replaceCostTracker() interpreter.FunctionTracker {
441 return func(args []ref.Val, result ref.Val) *uint64 {
442 targetCost := float64(actualSize(args[0])+1) * common.StringTraversalCostFactor
443 regexCost := float64(actualSize(args[1])+1) * common.RegexStringLengthCostFactor
444 // Actual search cost calculation = targetCost + regexCost
445 searchCost := targetCost * regexCost
446 // The total cost is the base call cost + search cost + result string allocation.
447 totalCost := float64(callCost) + searchCost + float64(actualSize(result))
448 // Convert to uint64 for the final cost.
449 finalCost := uint64(totalCost)
450 return &finalCost
451 }
452 }