| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 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 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
func Regex(options ...RegexOptions) cel.EnvOption { |
| 105 |
s := ®exLib{ |
| 106 |
version: math.MaxUint32, |
| 107 |
} |
| 108 |
for _, o := range options { |
| 109 |
s = o(s) |
| 110 |
} |
| 111 |
return cel.Lib(s) |
| 112 |
} |
| 113 |
|
| 114 |
|
| 115 |
type RegexOptions func(*regexLib) *regexLib |
| 116 |
|
| 117 |
|
| 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 |
|
| 130 |
func (r *regexLib) LibraryName() string { |
| 131 |
return "cel.lib.ext.regex" |
| 132 |
} |
| 133 |
|
| 134 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 293 |
if len(matches) > 1 { |
| 294 |
capturedGroup := matches[1] |
| 295 |
|
| 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 |
|
| 343 |
|
| 344 |
targetCost := targetSize.Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.StringTraversalCostFactor) |
| 345 |
|
| 346 |
regexCost := estimateSize(c, args[1]).Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.RegexStringLengthCostFactor) |
| 347 |
|
| 348 |
resultSize := &checker.SizeEstimate{Min: 0, Max: targetSize.Max} |
| 349 |
|
| 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 |
|
| 364 |
|
| 365 |
targetCost := targetSize.Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.StringTraversalCostFactor) |
| 366 |
|
| 367 |
regexCost := estimateSize(c, args[1]).Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.RegexStringLengthCostFactor) |
| 368 |
|
| 369 |
resultSize := &checker.SizeEstimate{Min: 0, Max: targetSize.Max} |
| 370 |
|
| 371 |
allocationSize := resultSize.Add(checker.FixedSizeEstimate(common.ListCreateBaseCost)) |
| 372 |
|
| 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 |
|
| 389 |
|
| 390 |
targetCost := targetSize.Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.StringTraversalCostFactor) |
| 391 |
|
| 392 |
regexCost := estimateSize(c, args[1]).Add(checker.FixedSizeEstimate(1)).MultiplyByCostFactor(common.RegexStringLengthCostFactor) |
| 393 |
|
| 394 |
|
| 395 |
allReplacedSize := targetSize.Max * replacementSize.Max |
| 396 |
noneReplacedSize := targetSize.Max |
| 397 |
|
| 398 |
resultSize := &checker.SizeEstimate{Min: noneReplacedSize, Max: allReplacedSize} |
| 399 |
if replacementSize.Max == 0 { |
| 400 |
resultSize = &checker.SizeEstimate{Min: allReplacedSize, Max: noneReplacedSize} |
| 401 |
} |
| 402 |
|
| 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 |
|
| 417 |
searchCost := targetCost * regexCost |
| 418 |
|
| 419 |
totalCost := float64(callCost) + searchCost + float64(actualSize(result)) |
| 420 |
|
| 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 |
|
| 431 |
searchCost := targetCost * regexCost |
| 432 |
|
| 433 |
totalCost := float64(callCost) + searchCost + float64(actualSize(result)) + common.ListCreateBaseCost |
| 434 |
|
| 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 |
|
| 445 |
searchCost := targetCost * regexCost |
| 446 |
|
| 447 |
totalCost := float64(callCost) + searchCost + float64(actualSize(result)) |
| 448 |
|
| 449 |
finalCost := uint64(totalCost) |
| 450 |
return &finalCost |
| 451 |
} |
| 452 |
} |