| 1 | // Copyright 2020 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 contains CEL extension libraries where each library defines a related set of |
| 16 | // constants, functions, macros, or other configuration settings which may not be covered by |
| 17 | // the core CEL spec. |
| 18 | package ext |
| 19 | |
| 20 | import ( |
| 21 | "fmt" |
| 22 | "math" |
| 23 | "reflect" |
| 24 | "strings" |
| 25 | "unicode" |
| 26 | "unicode/utf8" |
| 27 | |
| 28 | "golang.org/x/text/language" |
| 29 | |
| 30 | "github.com/google/cel-go/cel" |
| 31 | "github.com/google/cel-go/common/types" |
| 32 | "github.com/google/cel-go/common/types/ref" |
| 33 | "github.com/google/cel-go/common/types/traits" |
| 34 | ) |
| 35 | |
| 36 | const ( |
| 37 | defaultLocale = "en-US" |
| 38 | defaultPrecision = 6 |
| 39 | ) |
| 40 | |
| 41 | // Strings returns a cel.EnvOption to configure extended functions for string manipulation. |
| 42 | // As a general note, all indices are zero-based. |
| 43 | // |
| 44 | // # CharAt |
| 45 | // |
| 46 | // Returns the character at the given position. If the position is negative, or greater than |
| 47 | // the length of the string, the function will produce an error: |
| 48 | // |
| 49 | // <string>.charAt(<int>) -> <string> |
| 50 | // |
| 51 | // Examples: |
| 52 | // |
| 53 | // 'hello'.charAt(4) // return 'o' |
| 54 | // 'hello'.charAt(5) // return '' |
| 55 | // 'hello'.charAt(-1) // error |
| 56 | // |
| 57 | // # Format |
| 58 | // |
| 59 | // Introduced at version: 1 |
| 60 | // |
| 61 | // Returns a new string with substitutions being performed, printf-style. |
| 62 | // The valid formatting clauses are: |
| 63 | // |
| 64 | // `%s` - substitutes a string. This can also be used on bools, lists, maps, bytes, |
| 65 | // Duration and Timestamp, in addition to all numerical types (int, uint, and double). |
| 66 | // Note that the dot/period decimal separator will always be used when printing a list |
| 67 | // or map that contains a double, and that null can be passed (which results in the |
| 68 | // string "null") in addition to types. |
| 69 | // `%d` - substitutes an integer. |
| 70 | // `%f` - substitutes a double with fixed-point precision. The default precision is 6, but |
| 71 | // this can be adjusted. The strings `Infinity`, `-Infinity`, and `NaN` are also valid input |
| 72 | // for this clause. |
| 73 | // `%e` - substitutes a double in scientific notation. The default precision is 6, but this |
| 74 | // can be adjusted. |
| 75 | // `%b` - substitutes an integer with its equivalent binary string. Can also be used on bools. |
| 76 | // `%x` - substitutes an integer with its equivalent in hexadecimal, or if given a string or |
| 77 | // bytes, will output each character's equivalent in hexadecimal. |
| 78 | // `%X` - same as above, but with A-F capitalized. |
| 79 | // `%o` - substitutes an integer with its equivalent in octal. |
| 80 | // |
| 81 | // <string>.format(<list>) -> <string> |
| 82 | // |
| 83 | // Examples: |
| 84 | // |
| 85 | // "this is a string: %s\nand an integer: %d".format(["str", 42]) // returns "this is a string: str\nand an integer: 42" |
| 86 | // "a double substituted with %%s: %s".format([64.2]) // returns "a double substituted with %s: 64.2" |
| 87 | // "string type: %s".format([type(string)]) // returns "string type: string" |
| 88 | // "timestamp: %s".format([timestamp("2023-02-03T23:31:20+00:00")]) // returns "timestamp: 2023-02-03T23:31:20Z" |
| 89 | // "duration: %s".format([duration("1h45m47s")]) // returns "duration: 6347s" |
| 90 | // "%f".format([3.14]) // returns "3.140000" |
| 91 | // "scientific notation: %e".format([2.71828]) // returns "scientific notation: 2.718280\u202f\u00d7\u202f10\u2070\u2070" |
| 92 | // "5 in binary: %b".format([5]), // returns "5 in binary; 101" |
| 93 | // "26 in hex: %x".format([26]), // returns "26 in hex: 1a" |
| 94 | // "26 in hex (uppercase): %X".format([26]) // returns "26 in hex (uppercase): 1A" |
| 95 | // "30 in octal: %o".format([30]) // returns "30 in octal: 36" |
| 96 | // "a map inside a list: %s".format([[1, 2, 3, {"a": "x", "b": "y", "c": "z"}]]) // returns "a map inside a list: [1, 2, 3, {"a":"x", "b":"y", "c":"d"}]" |
| 97 | // "true bool: %s - false bool: %s\nbinary bool: %b".format([true, false, true]) // returns "true bool: true - false bool: false\nbinary bool: 1" |
| 98 | // |
| 99 | // Passing an incorrect type (a string to `%b`) is considered an error, as well as attempting |
| 100 | // to use more formatting clauses than there are arguments (`%d %d %d` while passing two ints, for instance). |
| 101 | // If compile-time checking is enabled, and the formatting string is a constant, and the argument list is a literal, |
| 102 | // then letting any arguments go unused/unformatted is also considered an error. |
| 103 | // |
| 104 | // # IndexOf |
| 105 | // |
| 106 | // Returns the integer index of the first occurrence of the search string. If the search string is |
| 107 | // not found the function returns -1. |
| 108 | // |
| 109 | // The function also accepts an optional position from which to begin the substring search. If the |
| 110 | // substring is the empty string, the index where the search starts is returned (zero or custom). |
| 111 | // |
| 112 | // <string>.indexOf(<string>) -> <int> |
| 113 | // <string>.indexOf(<string>, <int>) -> <int> |
| 114 | // |
| 115 | // Examples: |
| 116 | // |
| 117 | // 'hello mellow'.indexOf('') // returns 0 |
| 118 | // 'hello mellow'.indexOf('ello') // returns 1 |
| 119 | // 'hello mellow'.indexOf('jello') // returns -1 |
| 120 | // 'hello mellow'.indexOf('', 2) // returns 2 |
| 121 | // 'hello mellow'.indexOf('ello', 2) // returns 7 |
| 122 | // 'hello mellow'.indexOf('ello', 20) // returns -1 |
| 123 | // 'hello mellow'.indexOf('ello', -1) // error |
| 124 | // |
| 125 | // # Join |
| 126 | // |
| 127 | // Returns a new string where the elements of string list are concatenated. |
| 128 | // |
| 129 | // The function also accepts an optional separator which is placed between elements in the resulting string. |
| 130 | // |
| 131 | // <list<string>>.join() -> <string> |
| 132 | // <list<string>>.join(<string>) -> <string> |
| 133 | // |
| 134 | // Examples: |
| 135 | // |
| 136 | // ['hello', 'mellow'].join() // returns 'hellomellow' |
| 137 | // ['hello', 'mellow'].join(' ') // returns 'hello mellow' |
| 138 | // [].join() // returns '' |
| 139 | // [].join('/') // returns '' |
| 140 | // |
| 141 | // # LastIndexOf |
| 142 | // |
| 143 | // Returns the integer index at the start of the last occurrence of the search string. If the |
| 144 | // search string is not found the function returns -1. |
| 145 | // |
| 146 | // The function also accepts an optional position which represents the last index to be |
| 147 | // considered as the beginning of the substring match. If the substring is the empty string, |
| 148 | // the index where the search starts is returned (string length or custom). |
| 149 | // |
| 150 | // <string>.lastIndexOf(<string>) -> <int> |
| 151 | // <string>.lastIndexOf(<string>, <int>) -> <int> |
| 152 | // |
| 153 | // Examples: |
| 154 | // |
| 155 | // 'hello mellow'.lastIndexOf('') // returns 12 |
| 156 | // 'hello mellow'.lastIndexOf('ello') // returns 7 |
| 157 | // 'hello mellow'.lastIndexOf('jello') // returns -1 |
| 158 | // 'hello mellow'.lastIndexOf('ello', 6) // returns 1 |
| 159 | // 'hello mellow'.lastIndexOf('ello', 20) // returns -1 |
| 160 | // 'hello mellow'.lastIndexOf('ello', -1) // error |
| 161 | // |
| 162 | // # LowerAscii |
| 163 | // |
| 164 | // Returns a new string where all ASCII characters are lower-cased. |
| 165 | // |
| 166 | // This function does not perform Unicode case-mapping for characters outside the ASCII range. |
| 167 | // |
| 168 | // <string>.lowerAscii() -> <string> |
| 169 | // |
| 170 | // Examples: |
| 171 | // |
| 172 | // 'TacoCat'.lowerAscii() // returns 'tacocat' |
| 173 | // 'TacoCÆt Xii'.lowerAscii() // returns 'tacocÆt xii' |
| 174 | // |
| 175 | // # Strings.Quote |
| 176 | // |
| 177 | // Introduced in version: 1 |
| 178 | // |
| 179 | // Takes the given string and makes it safe to print (without any formatting due to escape sequences). |
| 180 | // If any invalid UTF-8 characters are encountered, they are replaced with \uFFFD. |
| 181 | // |
| 182 | // strings.quote(<string>) |
| 183 | // |
| 184 | // Examples: |
| 185 | // |
| 186 | // strings.quote('single-quote with "double quote"') // returns '"single-quote with \"double quote\""' |
| 187 | // strings.quote("two escape sequences \a\n") // returns '"two escape sequences \\a\\n"' |
| 188 | // |
| 189 | // # Replace |
| 190 | // |
| 191 | // Returns a new string based on the target, which replaces the occurrences of a search string |
| 192 | // with a replacement string if present. The function accepts an optional limit on the number of |
| 193 | // substring replacements to be made. |
| 194 | // |
| 195 | // When the replacement limit is 0, the result is the original string. When the limit is a negative |
| 196 | // number, the function behaves the same as replace all. |
| 197 | // |
| 198 | // <string>.replace(<string>, <string>) -> <string> |
| 199 | // <string>.replace(<string>, <string>, <int>) -> <string> |
| 200 | // |
| 201 | // Examples: |
| 202 | // |
| 203 | // 'hello hello'.replace('he', 'we') // returns 'wello wello' |
| 204 | // 'hello hello'.replace('he', 'we', -1) // returns 'wello wello' |
| 205 | // 'hello hello'.replace('he', 'we', 1) // returns 'wello hello' |
| 206 | // 'hello hello'.replace('he', 'we', 0) // returns 'hello hello' |
| 207 | // 'hello hello'.replace('', '_') // returns '_h_e_l_l_o_ _h_e_l_l_o_' |
| 208 | // 'hello hello'.replace('h', '') // returns 'ello ello' |
| 209 | // |
| 210 | // # Split |
| 211 | // |
| 212 | // Returns a list of strings split from the input by the given separator. The function accepts |
| 213 | // an optional argument specifying a limit on the number of substrings produced by the split. |
| 214 | // |
| 215 | // When the split limit is 0, the result is an empty list. When the limit is 1, the result is the |
| 216 | // target string to split. When the limit is a negative number, the function behaves the same as |
| 217 | // split all. |
| 218 | // |
| 219 | // <string>.split(<string>) -> <list<string>> |
| 220 | // <string>.split(<string>, <int>) -> <list<string>> |
| 221 | // |
| 222 | // Examples: |
| 223 | // |
| 224 | // 'hello hello hello'.split(' ') // returns ['hello', 'hello', 'hello'] |
| 225 | // 'hello hello hello'.split(' ', 0) // returns [] |
| 226 | // 'hello hello hello'.split(' ', 1) // returns ['hello hello hello'] |
| 227 | // 'hello hello hello'.split(' ', 2) // returns ['hello', 'hello hello'] |
| 228 | // 'hello hello hello'.split(' ', -1) // returns ['hello', 'hello', 'hello'] |
| 229 | // |
| 230 | // # Substring |
| 231 | // |
| 232 | // Returns the substring given a numeric range corresponding to character positions. Optionally |
| 233 | // may omit the trailing range for a substring from a given character position until the end of |
| 234 | // a string. |
| 235 | // |
| 236 | // Character offsets are 0-based with an inclusive start range and exclusive end range. It is an |
| 237 | // error to specify an end range that is lower than the start range, or for either the start or end |
| 238 | // index to be negative or exceed the string length. |
| 239 | // |
| 240 | // <string>.substring(<int>) -> <string> |
| 241 | // <string>.substring(<int>, <int>) -> <string> |
| 242 | // |
| 243 | // Examples: |
| 244 | // |
| 245 | // 'tacocat'.substring(4) // returns 'cat' |
| 246 | // 'tacocat'.substring(0, 4) // returns 'taco' |
| 247 | // 'tacocat'.substring(-1) // error |
| 248 | // 'tacocat'.substring(2, 1) // error |
| 249 | // |
| 250 | // # Trim |
| 251 | // |
| 252 | // Returns a new string which removes the leading and trailing whitespace in the target string. |
| 253 | // The trim function uses the Unicode definition of whitespace which does not include the |
| 254 | // zero-width spaces. See: https://en.wikipedia.org/wiki/Whitespace_character#Unicode |
| 255 | // |
| 256 | // <string>.trim() -> <string> |
| 257 | // |
| 258 | // Examples: |
| 259 | // |
| 260 | // ' \ttrim\n '.trim() // returns 'trim' |
| 261 | // |
| 262 | // # UpperAscii |
| 263 | // |
| 264 | // Returns a new string where all ASCII characters are upper-cased. |
| 265 | // |
| 266 | // This function does not perform Unicode case-mapping for characters outside the ASCII range. |
| 267 | // |
| 268 | // <string>.upperAscii() -> <string> |
| 269 | // |
| 270 | // Examples: |
| 271 | // |
| 272 | // 'TacoCat'.upperAscii() // returns 'TACOCAT' |
| 273 | // 'TacoCÆt Xii'.upperAscii() // returns 'TACOCÆT XII' |
| 274 | // |
| 275 | // # Reverse |
| 276 | // |
| 277 | // Introduced at version: 3 |
| 278 | // |
| 279 | // Returns a new string whose characters are the same as the target string, only formatted in |
| 280 | // reverse order. |
| 281 | // This function relies on converting strings to rune arrays in order to reverse |
| 282 | // |
| 283 | // <string>.reverse() -> <string> |
| 284 | // |
| 285 | // Examples: |
| 286 | // |
| 287 | // 'gums'.reverse() // returns 'smug' |
| 288 | // 'John Smith'.reverse() // returns 'htimS nhoJ' |
| 289 | // |
| 290 | // Introduced at version: 4 |
| 291 | // |
| 292 | // Formatting updated to adhere to https://github.com/google/cel-spec/blob/master/doc/extensions/strings.md. |
| 293 | // |
| 294 | // <string>.format(<list>) -> <string> |
| 295 | func Strings(options ...StringsOption) cel.EnvOption { |
| 296 | s := &stringLib{ |
| 297 | version: math.MaxUint32, |
| 298 | } |
| 299 | for _, o := range options { |
| 300 | s = o(s) |
| 301 | } |
| 302 | return cel.Lib(s) |
| 303 | } |
| 304 | |
| 305 | type stringLib struct { |
| 306 | locale string |
| 307 | version uint32 |
| 308 | } |
| 309 | |
| 310 | // LibraryName implements the SingletonLibrary interface method. |
| 311 | func (*stringLib) LibraryName() string { |
| 312 | return "cel.lib.ext.strings" |
| 313 | } |
| 314 | |
| 315 | // StringsOption is a functional interface for configuring the strings library. |
| 316 | type StringsOption func(*stringLib) *stringLib |
| 317 | |
| 318 | // StringsLocale configures the library with the given locale. The locale tag will |
| 319 | // be checked for validity at the time that EnvOptions are configured. If this option |
| 320 | // is not passed, string.format will behave as if en_US was passed as the locale. |
| 321 | // |
| 322 | // If StringsVersion is greater than or equal to 4, this option is ignored. |
| 323 | func StringsLocale(locale string) StringsOption { |
| 324 | return func(sl *stringLib) *stringLib { |
| 325 | sl.locale = locale |
| 326 | return sl |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | // StringsVersion configures the version of the string library. |
| 331 | // |
| 332 | // The version limits which functions are available. Only functions introduced |
| 333 | // below or equal to the given version included in the library. If this option |
| 334 | // is not set, all functions are available. |
| 335 | // |
| 336 | // See the library documentation to determine which version a function was introduced. |
| 337 | // If the documentation does not state which version a function was introduced, it can |
| 338 | // be assumed to be introduced at version 0, when the library was first created. |
| 339 | func StringsVersion(version uint32) StringsOption { |
| 340 | return func(lib *stringLib) *stringLib { |
| 341 | lib.version = version |
| 342 | return lib |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | // StringsValidateFormatCalls validates type-checked ASTs to ensure that string.format() calls have |
| 347 | // valid formatting clauses and valid argument types for each clause. |
| 348 | // |
| 349 | // Deprecated |
| 350 | func StringsValidateFormatCalls(value bool) StringsOption { |
| 351 | return func(s *stringLib) *stringLib { |
| 352 | return s |
| 353 | } |
| 354 | } |
| 355 | |
| 356 | // CompileOptions implements the Library interface method. |
| 357 | func (lib *stringLib) CompileOptions() []cel.EnvOption { |
| 358 | formatLocale := "en_US" |
| 359 | if lib.version < 4 && lib.locale != "" { |
| 360 | // ensure locale is properly-formed if set |
| 361 | _, err := language.Parse(lib.locale) |
| 362 | if err != nil { |
| 363 | return []cel.EnvOption{ |
| 364 | func(e *cel.Env) (*cel.Env, error) { |
| 365 | return nil, fmt.Errorf("failed to parse locale: %w", err) |
| 366 | }, |
| 367 | } |
| 368 | } |
| 369 | formatLocale = lib.locale |
| 370 | } |
| 371 | |
| 372 | opts := []cel.EnvOption{ |
| 373 | cel.Function("charAt", |
| 374 | cel.MemberOverload("string_char_at_int", []*cel.Type{cel.StringType, cel.IntType}, cel.StringType, |
| 375 | cel.BinaryBinding(func(str, ind ref.Val) ref.Val { |
| 376 | s := str.(types.String) |
| 377 | i := ind.(types.Int) |
| 378 | return stringOrError(charAt(string(s), int64(i))) |
| 379 | }))), |
| 380 | cel.Function("indexOf", |
| 381 | cel.MemberOverload("string_index_of_string", []*cel.Type{cel.StringType, cel.StringType}, cel.IntType, |
| 382 | cel.BinaryBinding(func(str, substr ref.Val) ref.Val { |
| 383 | s := str.(types.String) |
| 384 | sub := substr.(types.String) |
| 385 | return intOrError(indexOf(string(s), string(sub))) |
| 386 | })), |
| 387 | cel.MemberOverload("string_index_of_string_int", []*cel.Type{cel.StringType, cel.StringType, cel.IntType}, cel.IntType, |
| 388 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 389 | s := args[0].(types.String) |
| 390 | sub := args[1].(types.String) |
| 391 | offset := args[2].(types.Int) |
| 392 | return intOrError(indexOfOffset(string(s), string(sub), int64(offset))) |
| 393 | }))), |
| 394 | cel.Function("lastIndexOf", |
| 395 | cel.MemberOverload("string_last_index_of_string", []*cel.Type{cel.StringType, cel.StringType}, cel.IntType, |
| 396 | cel.BinaryBinding(func(str, substr ref.Val) ref.Val { |
| 397 | s := str.(types.String) |
| 398 | sub := substr.(types.String) |
| 399 | return intOrError(lastIndexOf(string(s), string(sub))) |
| 400 | })), |
| 401 | cel.MemberOverload("string_last_index_of_string_int", []*cel.Type{cel.StringType, cel.StringType, cel.IntType}, cel.IntType, |
| 402 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 403 | s := args[0].(types.String) |
| 404 | sub := args[1].(types.String) |
| 405 | offset := args[2].(types.Int) |
| 406 | return intOrError(lastIndexOfOffset(string(s), string(sub), int64(offset))) |
| 407 | }))), |
| 408 | cel.Function("lowerAscii", |
| 409 | cel.MemberOverload("string_lower_ascii", []*cel.Type{cel.StringType}, cel.StringType, |
| 410 | cel.UnaryBinding(func(str ref.Val) ref.Val { |
| 411 | s := str.(types.String) |
| 412 | return stringOrError(lowerASCII(string(s))) |
| 413 | }))), |
| 414 | cel.Function("replace", |
| 415 | cel.MemberOverload( |
| 416 | "string_replace_string_string", []*cel.Type{cel.StringType, cel.StringType, cel.StringType}, cel.StringType, |
| 417 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 418 | str := args[0].(types.String) |
| 419 | old := args[1].(types.String) |
| 420 | new := args[2].(types.String) |
| 421 | return stringOrError(replace(string(str), string(old), string(new))) |
| 422 | })), |
| 423 | cel.MemberOverload( |
| 424 | "string_replace_string_string_int", []*cel.Type{cel.StringType, cel.StringType, cel.StringType, cel.IntType}, cel.StringType, |
| 425 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 426 | str := args[0].(types.String) |
| 427 | old := args[1].(types.String) |
| 428 | new := args[2].(types.String) |
| 429 | n := args[3].(types.Int) |
| 430 | return stringOrError(replaceN(string(str), string(old), string(new), int64(n))) |
| 431 | }))), |
| 432 | cel.Function("split", |
| 433 | cel.MemberOverload("string_split_string", []*cel.Type{cel.StringType, cel.StringType}, cel.ListType(cel.StringType), |
| 434 | cel.BinaryBinding(func(str, separator ref.Val) ref.Val { |
| 435 | s := str.(types.String) |
| 436 | sep := separator.(types.String) |
| 437 | return listStringOrError(split(string(s), string(sep))) |
| 438 | })), |
| 439 | cel.MemberOverload("string_split_string_int", []*cel.Type{cel.StringType, cel.StringType, cel.IntType}, cel.ListType(cel.StringType), |
| 440 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 441 | s := args[0].(types.String) |
| 442 | sep := args[1].(types.String) |
| 443 | n := args[2].(types.Int) |
| 444 | return listStringOrError(splitN(string(s), string(sep), int64(n))) |
| 445 | }))), |
| 446 | cel.Function("substring", |
| 447 | cel.MemberOverload("string_substring_int", []*cel.Type{cel.StringType, cel.IntType}, cel.StringType, |
| 448 | cel.BinaryBinding(func(str, offset ref.Val) ref.Val { |
| 449 | s := str.(types.String) |
| 450 | off := offset.(types.Int) |
| 451 | return stringOrError(substr(string(s), int64(off))) |
| 452 | })), |
| 453 | cel.MemberOverload("string_substring_int_int", []*cel.Type{cel.StringType, cel.IntType, cel.IntType}, cel.StringType, |
| 454 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 455 | s := args[0].(types.String) |
| 456 | start := args[1].(types.Int) |
| 457 | end := args[2].(types.Int) |
| 458 | return stringOrError(substrRange(string(s), int64(start), int64(end))) |
| 459 | }))), |
| 460 | cel.Function("trim", |
| 461 | cel.MemberOverload("string_trim", []*cel.Type{cel.StringType}, cel.StringType, |
| 462 | cel.UnaryBinding(func(str ref.Val) ref.Val { |
| 463 | s := str.(types.String) |
| 464 | return stringOrError(trimSpace(string(s))) |
| 465 | }))), |
| 466 | cel.Function("upperAscii", |
| 467 | cel.MemberOverload("string_upper_ascii", []*cel.Type{cel.StringType}, cel.StringType, |
| 468 | cel.UnaryBinding(func(str ref.Val) ref.Val { |
| 469 | s := str.(types.String) |
| 470 | return stringOrError(upperASCII(string(s))) |
| 471 | }))), |
| 472 | } |
| 473 | if lib.version >= 1 { |
| 474 | if lib.version >= 4 { |
| 475 | opts = append(opts, cel.Function("format", |
| 476 | cel.MemberOverload("string_format", []*cel.Type{cel.StringType, cel.ListType(cel.DynType)}, cel.StringType, |
| 477 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 478 | s := string(args[0].(types.String)) |
| 479 | formatArgs := args[1].(traits.Lister) |
| 480 | return stringOrError(parseFormatStringV2(s, &stringFormatterV2{}, &stringArgList{formatArgs})) |
| 481 | })))) |
| 482 | } else { |
| 483 | opts = append(opts, cel.Function("format", |
| 484 | cel.MemberOverload("string_format", []*cel.Type{cel.StringType, cel.ListType(cel.DynType)}, cel.StringType, |
| 485 | cel.FunctionBinding(func(args ...ref.Val) ref.Val { |
| 486 | s := string(args[0].(types.String)) |
| 487 | formatArgs := args[1].(traits.Lister) |
| 488 | return stringOrError(parseFormatString(s, &stringFormatter{}, &stringArgList{formatArgs}, formatLocale)) |
| 489 | })))) |
| 490 | } |
| 491 | opts = append(opts, |
| 492 | cel.Function("strings.quote", cel.Overload("strings_quote", []*cel.Type{cel.StringType}, cel.StringType, |
| 493 | cel.UnaryBinding(func(str ref.Val) ref.Val { |
| 494 | s := str.(types.String) |
| 495 | return stringOrError(quote(string(s))) |
| 496 | })))) |
| 497 | } |
| 498 | if lib.version >= 2 { |
| 499 | opts = append(opts, |
| 500 | cel.Function("join", |
| 501 | cel.MemberOverload("list_join", []*cel.Type{cel.ListType(cel.StringType)}, cel.StringType, |
| 502 | cel.UnaryBinding(func(list ref.Val) ref.Val { |
| 503 | l := list.(traits.Lister) |
| 504 | return stringOrError(joinValSeparator(l, "")) |
| 505 | })), |
| 506 | cel.MemberOverload("list_join_string", []*cel.Type{cel.ListType(cel.StringType), cel.StringType}, cel.StringType, |
| 507 | cel.BinaryBinding(func(list, delim ref.Val) ref.Val { |
| 508 | l := list.(traits.Lister) |
| 509 | d := delim.(types.String) |
| 510 | return stringOrError(joinValSeparator(l, string(d))) |
| 511 | }))), |
| 512 | ) |
| 513 | } else { |
| 514 | opts = append(opts, |
| 515 | cel.Function("join", |
| 516 | cel.MemberOverload("list_join", []*cel.Type{cel.ListType(cel.StringType)}, cel.StringType, |
| 517 | cel.UnaryBinding(func(list ref.Val) ref.Val { |
| 518 | l, err := list.ConvertToNative(stringListType) |
| 519 | if err != nil { |
| 520 | return types.WrapErr(err) |
| 521 | } |
| 522 | return stringOrError(join(l.([]string))) |
| 523 | })), |
| 524 | cel.MemberOverload("list_join_string", []*cel.Type{cel.ListType(cel.StringType), cel.StringType}, cel.StringType, |
| 525 | cel.BinaryBinding(func(list, delim ref.Val) ref.Val { |
| 526 | l, err := list.ConvertToNative(stringListType) |
| 527 | if err != nil { |
| 528 | return types.WrapErr(err) |
| 529 | } |
| 530 | d := delim.(types.String) |
| 531 | return stringOrError(joinSeparator(l.([]string), string(d))) |
| 532 | }))), |
| 533 | ) |
| 534 | } |
| 535 | if lib.version >= 3 { |
| 536 | opts = append(opts, |
| 537 | cel.Function("reverse", |
| 538 | cel.MemberOverload("string_reverse", []*cel.Type{cel.StringType}, cel.StringType, |
| 539 | cel.UnaryBinding(func(str ref.Val) ref.Val { |
| 540 | s := str.(types.String) |
| 541 | return stringOrError(reverse(string(s))) |
| 542 | }))), |
| 543 | ) |
| 544 | } |
| 545 | if lib.version >= 1 { |
| 546 | if lib.version >= 4 { |
| 547 | opts = append(opts, cel.ASTValidators(stringFormatValidatorV2{})) |
| 548 | } else { |
| 549 | opts = append(opts, cel.ASTValidators(stringFormatValidator{})) |
| 550 | } |
| 551 | } |
| 552 | return opts |
| 553 | } |
| 554 | |
| 555 | // ProgramOptions implements the Library interface method. |
| 556 | func (*stringLib) ProgramOptions() []cel.ProgramOption { |
| 557 | return []cel.ProgramOption{} |
| 558 | } |
| 559 | |
| 560 | func charAt(str string, ind int64) (string, error) { |
| 561 | i := int(ind) |
| 562 | runes := []rune(str) |
| 563 | if i < 0 || i > len(runes) { |
| 564 | return "", fmt.Errorf("index out of range: %d", ind) |
| 565 | } |
| 566 | if i == len(runes) { |
| 567 | return "", nil |
| 568 | } |
| 569 | return string(runes[i]), nil |
| 570 | } |
| 571 | |
| 572 | func indexOf(str, substr string) (int64, error) { |
| 573 | return indexOfOffset(str, substr, int64(0)) |
| 574 | } |
| 575 | |
| 576 | func indexOfOffset(str, substr string, offset int64) (int64, error) { |
| 577 | if substr == "" { |
| 578 | return offset, nil |
| 579 | } |
| 580 | off := int(offset) |
| 581 | runes := []rune(str) |
| 582 | subrunes := []rune(substr) |
| 583 | if off < 0 { |
| 584 | return -1, fmt.Errorf("index out of range: %d", off) |
| 585 | } |
| 586 | // If the offset exceeds the length, return -1 rather than error. |
| 587 | if off >= len(runes) { |
| 588 | return -1, nil |
| 589 | } |
| 590 | for i := off; i < len(runes)-(len(subrunes)-1); i++ { |
| 591 | found := true |
| 592 | for j := 0; j < len(subrunes); j++ { |
| 593 | if runes[i+j] != subrunes[j] { |
| 594 | found = false |
| 595 | break |
| 596 | } |
| 597 | } |
| 598 | if found { |
| 599 | return int64(i), nil |
| 600 | } |
| 601 | } |
| 602 | return -1, nil |
| 603 | } |
| 604 | |
| 605 | func lastIndexOf(str, substr string) (int64, error) { |
| 606 | runes := []rune(str) |
| 607 | if substr == "" { |
| 608 | return int64(len(runes)), nil |
| 609 | } |
| 610 | |
| 611 | if len(str) < len(substr) { |
| 612 | return -1, nil |
| 613 | } |
| 614 | return lastIndexOfOffset(str, substr, int64(len(runes)-1)) |
| 615 | } |
| 616 | |
| 617 | func lastIndexOfOffset(str, substr string, offset int64) (int64, error) { |
| 618 | if substr == "" { |
| 619 | return offset, nil |
| 620 | } |
| 621 | off := int(offset) |
| 622 | runes := []rune(str) |
| 623 | subrunes := []rune(substr) |
| 624 | if off < 0 { |
| 625 | return -1, fmt.Errorf("index out of range: %d", off) |
| 626 | } |
| 627 | // If the offset is far greater than the length return -1 |
| 628 | if off >= len(runes) { |
| 629 | return -1, nil |
| 630 | } |
| 631 | if off > len(runes)-len(subrunes) { |
| 632 | off = len(runes) - len(subrunes) |
| 633 | } |
| 634 | for i := off; i >= 0; i-- { |
| 635 | found := true |
| 636 | for j := 0; j < len(subrunes); j++ { |
| 637 | if runes[i+j] != subrunes[j] { |
| 638 | found = false |
| 639 | break |
| 640 | } |
| 641 | } |
| 642 | if found { |
| 643 | return int64(i), nil |
| 644 | } |
| 645 | } |
| 646 | return -1, nil |
| 647 | } |
| 648 | |
| 649 | func lowerASCII(str string) (string, error) { |
| 650 | runes := []rune(str) |
| 651 | for i, r := range runes { |
| 652 | if r <= unicode.MaxASCII { |
| 653 | r = unicode.ToLower(r) |
| 654 | runes[i] = r |
| 655 | } |
| 656 | } |
| 657 | return string(runes), nil |
| 658 | } |
| 659 | |
| 660 | func replace(str, old, new string) (string, error) { |
| 661 | return strings.ReplaceAll(str, old, new), nil |
| 662 | } |
| 663 | |
| 664 | func replaceN(str, old, new string, n int64) (string, error) { |
| 665 | return strings.Replace(str, old, new, int(n)), nil |
| 666 | } |
| 667 | |
| 668 | func split(str, sep string) ([]string, error) { |
| 669 | return strings.Split(str, sep), nil |
| 670 | } |
| 671 | |
| 672 | func splitN(str, sep string, n int64) ([]string, error) { |
| 673 | return strings.SplitN(str, sep, int(n)), nil |
| 674 | } |
| 675 | |
| 676 | func substr(str string, start int64) (string, error) { |
| 677 | runes := []rune(str) |
| 678 | if int(start) < 0 || int(start) > len(runes) { |
| 679 | return "", fmt.Errorf("index out of range: %d", start) |
| 680 | } |
| 681 | return string(runes[start:]), nil |
| 682 | } |
| 683 | |
| 684 | func substrRange(str string, start, end int64) (string, error) { |
| 685 | runes := []rune(str) |
| 686 | l := len(runes) |
| 687 | if start > end { |
| 688 | return "", fmt.Errorf("invalid substring range. start: %d, end: %d", start, end) |
| 689 | } |
| 690 | if int(start) < 0 || int(start) > l { |
| 691 | return "", fmt.Errorf("index out of range: %d", start) |
| 692 | } |
| 693 | if int(end) < 0 || int(end) > l { |
| 694 | return "", fmt.Errorf("index out of range: %d", end) |
| 695 | } |
| 696 | return string(runes[int(start):int(end)]), nil |
| 697 | } |
| 698 | |
| 699 | func trimSpace(str string) (string, error) { |
| 700 | return strings.TrimSpace(str), nil |
| 701 | } |
| 702 | |
| 703 | func upperASCII(str string) (string, error) { |
| 704 | runes := []rune(str) |
| 705 | for i, r := range runes { |
| 706 | if r <= unicode.MaxASCII { |
| 707 | r = unicode.ToUpper(r) |
| 708 | runes[i] = r |
| 709 | } |
| 710 | } |
| 711 | return string(runes), nil |
| 712 | } |
| 713 | |
| 714 | func reverse(str string) (string, error) { |
| 715 | chars := []rune(str) |
| 716 | for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { |
| 717 | chars[i], chars[j] = chars[j], chars[i] |
| 718 | } |
| 719 | return string(chars), nil |
| 720 | } |
| 721 | |
| 722 | func joinSeparator(strs []string, separator string) (string, error) { |
| 723 | return strings.Join(strs, separator), nil |
| 724 | } |
| 725 | |
| 726 | func join(strs []string) (string, error) { |
| 727 | return strings.Join(strs, ""), nil |
| 728 | } |
| 729 | |
| 730 | func joinValSeparator(strs traits.Lister, separator string) (string, error) { |
| 731 | sz := strs.Size().(types.Int) |
| 732 | var sb strings.Builder |
| 733 | for i := types.Int(0); i < sz; i++ { |
| 734 | if i != 0 { |
| 735 | sb.WriteString(separator) |
| 736 | } |
| 737 | elem := strs.Get(i) |
| 738 | str, ok := elem.(types.String) |
| 739 | if !ok { |
| 740 | return "", fmt.Errorf("join: invalid input: %v", elem) |
| 741 | } |
| 742 | sb.WriteString(string(str)) |
| 743 | } |
| 744 | return sb.String(), nil |
| 745 | } |
| 746 | |
| 747 | // quote implements a string quoting function. The string will be wrapped in |
| 748 | // double quotes, and all valid CEL escape sequences will be escaped to show up |
| 749 | // literally if printed. If the input contains any invalid UTF-8, the invalid runes |
| 750 | // will be replaced with utf8.RuneError. |
| 751 | func quote(s string) (string, error) { |
| 752 | var quotedStrBuilder strings.Builder |
| 753 | for _, c := range sanitize(s) { |
| 754 | switch c { |
| 755 | case '\a': |
| 756 | quotedStrBuilder.WriteString("\\a") |
| 757 | case '\b': |
| 758 | quotedStrBuilder.WriteString("\\b") |
| 759 | case '\f': |
| 760 | quotedStrBuilder.WriteString("\\f") |
| 761 | case '\n': |
| 762 | quotedStrBuilder.WriteString("\\n") |
| 763 | case '\r': |
| 764 | quotedStrBuilder.WriteString("\\r") |
| 765 | case '\t': |
| 766 | quotedStrBuilder.WriteString("\\t") |
| 767 | case '\v': |
| 768 | quotedStrBuilder.WriteString("\\v") |
| 769 | case '\\': |
| 770 | quotedStrBuilder.WriteString("\\\\") |
| 771 | case '"': |
| 772 | quotedStrBuilder.WriteString("\\\"") |
| 773 | default: |
| 774 | quotedStrBuilder.WriteRune(c) |
| 775 | } |
| 776 | } |
| 777 | escapedStr := quotedStrBuilder.String() |
| 778 | return "\"" + escapedStr + "\"", nil |
| 779 | } |
| 780 | |
| 781 | // sanitize replaces all invalid runes in the given string with utf8.RuneError. |
| 782 | func sanitize(s string) string { |
| 783 | var sanitizedStringBuilder strings.Builder |
| 784 | for _, r := range s { |
| 785 | if !utf8.ValidRune(r) { |
| 786 | sanitizedStringBuilder.WriteRune(utf8.RuneError) |
| 787 | } else { |
| 788 | sanitizedStringBuilder.WriteRune(r) |
| 789 | } |
| 790 | } |
| 791 | return sanitizedStringBuilder.String() |
| 792 | } |
| 793 | |
| 794 | var ( |
| 795 | stringListType = reflect.TypeOf([]string{}) |
| 796 | ) |