ext
packageThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
Extensions
CEL extensions are a related set of constants, functions, macros, or otherfeatures which may not be covered by the core CEL spec.
Bindings
Returns a cel.EnvOption to configure support for local variable bindingsin expressions.
Cel.Bind
Binds a simple identifier to an initialization expression which may be usedin a subsequent result expression. Bindings may also be nested within eachother.
cel.bind(<varName>, <initExpr>, <resultExpr>)Examples:
cel.bind(a, 'hello',cel.bind(b, 'world', a + b + b + a)) // "helloworldworldhello"// Avoid a list allocation within the exists comprehension.cel.bind(valid_values, [a, b, c],[d, e, f].exists(elem, elem in valid_values))Local bindings are not guaranteed to be evaluated before use.
Encoders
Encoding utilities for marshalling data into standardized representations.
Base64.Decode
Decodes base64-encoded string to bytes.
This function will return an error if the string input is notbase64-encoded.
base64.decode(<string>) -> <bytes>Examples:
base64.decode('aGVsbG8=') // return b'hello'base64.decode('aGVsbG8') // errorBase64.Encode
Encodes bytes to a base64-encoded string.
base64.encode(<bytes>) -> <string>Example:
base64.encode(b'hello') // return 'aGVsbG8='Math
Math helper macros and functions.
Note, all macros use the 'math' namespace; however, at the time of macroexpansion the namespace looks just like any other identifier. If you arecurrently using a variable named 'math', the macro will likely work just asintended; however, there is some chance for collision.
Math.Greatest
Returns the greatest valued number present in the arguments to the macro.
Greatest is a variable argument count macro which must take at least oneargument. Simple numeric and list literals are supported as valid argumenttypes; however, other literals will be flagged as errors during macroexpansion. If the argument expression does not resolve to a numeric orlist(numeric) type during type-checking, or during runtime then an errorwill be produced. If a list argument is empty, this too will produce anerror.
math.greatest(<arg>, ...) -> <double|int|uint>Examples:
math.greatest(1) // 1math.greatest(1u, 2u) // 2umath.greatest(-42.0, -21.5, -100.0) // -21.5math.greatest([-42.0, -21.5, -100.0]) // -21.5math.greatest(numbers) // numbers must be list(numeric)math.greatest() // parse errormath.greatest('string') // parse errormath.greatest(a, b) // check-time error if a or b is non-numericmath.greatest(dyn('string')) // runtime errorMath.Least
Returns the least valued number present in the arguments to the macro.
Least is a variable argument count macro which must take at least oneargument. Simple numeric and list literals are supported as valid argumenttypes; however, other literals will be flagged as errors during macroexpansion. If the argument expression does not resolve to a numeric orlist(numeric) type during type-checking, or during runtime then an errorwill be produced. If a list argument is empty, this too will produce anerror.
math.least(<arg>, ...) -> <double|int|uint>Examples:
math.least(1) // 1math.least(1u, 2u) // 1umath.least(-42.0, -21.5, -100.0) // -100.0math.least([-42.0, -21.5, -100.0]) // -100.0math.least(numbers) // numbers must be list(numeric)math.least() // parse errormath.least('string') // parse errormath.least(a, b) // check-time error if a or b is non-numericmath.least(dyn('string')) // runtime errorMath.BitOr
Introduced at version: 1
Performs a bitwise-OR operation over two int or uint values.
math.bitOr(<int>, <int>) -> <int>math.bitOr(<uint>, <uint>) -> <uint>Examples:
math.bitOr(1u, 2u) // returns 3umath.bitOr(-2, -4) // returns -2Math.BitAnd
Introduced at version: 1
Performs a bitwise-AND operation over two int or uint values.
math.bitAnd(<int>, <int>) -> <int>math.bitAnd(<uint>, <uint>) -> <uint>Examples:
math.bitAnd(3u, 2u) // return 2umath.bitAnd(3, 5) // returns 3math.bitAnd(-3, -5) // returns -7Math.BitXor
Introduced at version: 1
math.bitXor(<int>, <int>) -> <int>math.bitXor(<uint>, <uint>) -> <uint>Performs a bitwise-XOR operation over two int or uint values.
Examples:
math.bitXor(3u, 5u) // returns 6umath.bitXor(1, 3) // returns 2Math.BitNot
Introduced at version: 1
Function which accepts a single int or uint and performs a bitwise-NOTones-complement of the given binary value.
math.bitNot(<int>) -> <int>math.bitNot(<uint>) -> <uint>Examples
math.bitNot(1) // returns -1math.bitNot(-1) // return 0math.bitNot(0u) // returns 18446744073709551615uMath.BitShiftLeft
Introduced at version: 1
Perform a left shift of bits on the first parameter, by the amount of bitsspecified in the second parameter. The first parameter is either a uint oran int. The second parameter must be an int.
When the second parameter is 64 or greater, 0 will be always be returnedsince the number of bits shifted is greater than or equal to the total bitlength of the number being shifted. Negative valued bit shifts will resultin a runtime error.
math.bitShiftLeft(<int>, <int>) -> <int>math.bitShiftLeft(<uint>, <int>) -> <uint>Examples
math.bitShiftLeft(1, 2) // returns 4math.bitShiftLeft(-1, 2) // returns -4math.bitShiftLeft(1u, 2) // return 4umath.bitShiftLeft(1u, 200) // returns 0uMath.BitShiftRight
Introduced at version: 1
Perform a right shift of bits on the first parameter, by the amount of bitsspecified in the second parameter. The first parameter is either a uint oran int. The second parameter must be an int.
When the second parameter is 64 or greater, 0 will always be returned sincethe number of bits shifted is greater than or equal to the total bit lengthof the number being shifted. Negative valued bit shifts will result in aruntime error.
The sign bit extension will not be preserved for this operation: vacant bitson the left are filled with 0.
math.bitShiftRight(<int>, <int>) -> <int>math.bitShiftRight(<uint>, <int>) -> <uint>Examples
math.bitShiftRight(1024, 2) // returns 256math.bitShiftRight(1024u, 2) // returns 256umath.bitShiftRight(1024u, 64) // returns 0uMath.Ceil
Introduced at version: 1
Compute the ceiling of a double value.
math.ceil(<double>) -> <double>Examples:
math.ceil(1.2) // returns 2.0math.ceil(-1.2) // returns -1.0Math.Floor
Introduced at version: 1
Compute the floor of a double value.
math.floor(<double>) -> <double>Examples:
math.floor(1.2) // returns 1.0math.floor(-1.2) // returns -2.0Math.Round
Introduced at version: 1
Rounds the double value to the nearest whole number with ties rounding awayfrom zero, e.g. 1.5 -> 2.0, -1.5 -> -2.0.
math.round(<double>) -> <double>Examples:
math.round(1.2) // returns 1.0math.round(1.5) // returns 2.0math.round(-1.5) // returns -2.0Math.Trunc
Introduced at version: 1
Truncates the fractional portion of the double value.
math.trunc(<double>) -> <double>Examples:
math.trunc(-1.3) // returns -1.0math.trunc(1.3) // returns 1.0Math.Abs
Introduced at version: 1
Returns the absolute value of the numeric type provided as input. If thevalue is NaN, the output is NaN. If the input is int64 min, the functionwill result in an overflow error.
math.abs(<double>) -> <double>math.abs(<int>) -> <int>math.abs(<uint>) -> <uint>Examples:
math.abs(-1) // returns 1math.abs(1) // returns 1math.abs(-9223372036854775808) // overlflow errorMath.Sign
Introduced at version: 1
Returns the sign of the numeric type, either -1, 0, 1 as an int, double, oruint depending on the overload. For floating point values, if NaN isprovided as input, the output is also NaN. The implementation does notdifferentiate between positive and negative zero.
math.sign(<double>) -> <double>math.sign(<int>) -> <int>math.sign(<uint>) -> <uint>Examples:
math.sign(-42) // returns -1math.sign(0) // returns 0math.sign(42) // returns 1Math.IsInf
Introduced at version: 1
Returns true if the input double value is -Inf or +Inf.
math.isInf(<double>) -> <bool>Examples:
math.isInf(1.0/0.0) // returns truemath.isInf(1.2) // returns falseMath.IsNaN
Introduced at version: 1
Returns true if the input double value is NaN, false otherwise.
math.isNaN(<double>) -> <bool>Examples:
math.isNaN(0.0/0.0) // returns truemath.isNaN(1.2) // returns falseMath.IsFinite
Introduced at version: 1
Returns true if the value is a finite number. Equivalent in behavior to:!math.isNaN(double) && !math.isInf(double)
math.isFinite(<double>) -> <bool>Examples:
math.isFinite(0.0/0.0) // returns falsemath.isFinite(1.2) // returns trueMath.Sqrt
Introduced at version: 2
Returns the square root of the given input as doubleThrows error for negative or non-numeric inputs
math.sqrt(<double>) -> <double>math.sqrt(<int>) -> <double>math.sqrt(<uint>) -> <double>Examples:
math.sqrt(81) // returns 9.0math.sqrt(985.25) // returns 31.388692231439016math.sqrt(-15) // returns NaNProtos
Protos configure extended macros and functions for proto manipulation.
Note, all macros use the 'proto' namespace; however, at the time of macroexpansion the namespace looks just like any other identifier. If you arecurrently using a variable named 'proto', the macro will likely work just asyou intend; however, there is some chance for collision.
Protos.GetExt
Macro which generates a select expression that retrieves an extension fieldfrom the input proto2 syntax message. If the field is not set, the defaultvalue forthe extension field is returned according to safe-traversal semantics.
proto.getExt(<msg>, <fully.qualified.extension.name>) -> <field-type>Example:
proto.getExt(msg, google.expr.proto2.test.int32_ext) // returns int valueProtos.HasExt
Macro which generates a test-only select expression that determines whetheran extension field is set on a proto2 syntax message.
proto.hasExt(<msg>, <fully.qualified.extension.name>) -> <bool>Example:
proto.hasExt(msg, google.expr.proto2.test.int32_ext) // returns true || falseLists
Extended functions for list manipulation. As a general note, all indices arezero-based.
Distinct
Introduced in version 2 (cost support in version 3)
Returns the distinct elements of a list.
<list(T)>.distinct() -> <list(T)>Examples:
[1, 2, 2, 3, 3, 3].distinct() // return [1, 2, 3]["b", "b", "c", "a", "c"].distinct() // return ["b", "c", "a"][1, "b", 2, "b"].distinct() // return [1, "b", 2]Flatten
Introduced in version 1 (cost support in version 3)
Flattens a list recursively.If an optional depth is provided, the list is flattened to a the specificied level.A negative depth value will result in an error.
<list>.flatten(<list>) -> <list><list>.flatten(<list>, <int>) -> <list>Examples:
[1,[2,3],[4]].flatten() // return [1, 2, 3, 4][1,[2,[3,4]]].flatten() // return [1, 2, [3, 4]][1,2,[],[],[3,4]].flatten() // return [1, 2, 3, 4][1,[2,[3,[4]]]].flatten(2) // return [1, 2, 3, [4]][1,[2,[3,[4]]]].flatten(-1) // errorRange
Introduced in version 2 (cost support in version 3)
Returns a list of integers from 0 to n-1.
lists.range(<int>) -> <list(int)>Examples:
lists.range(5) -> [0, 1, 2, 3, 4]Reverse
Introduced in version 2 (cost support in version 3)
Returns the elements of a list in reverse order.
<list(T)>.reverse() -> <list(T)>Examples:
[5, 3, 1, 2].reverse() // return [2, 1, 3, 5]Slice
Introduced in version 0 (cost support in version 3)
Returns a new sub-list using the indexes provided.
<list>.slice(<int>, <int>) -> <list>Examples:
[1,2,3,4].slice(1, 3) // return [2, 3][1,2,3,4].slice(2, 4) // return [3, 4]Sort
Introduced in version 2 (cost support in version 3)
Sorts a list with comparable elements. If the element type is not comparableor the element types are not the same, the function will produce an error.
<list(T)>.sort() -> <list(T)>T in {int, uint, double, bool, duration, timestamp, string, bytes}Examples:
[3, 2, 1].sort() // return [1, 2, 3]["b", "c", "a"].sort() // return ["a", "b", "c"][1, "b"].sort() // error[[1, 2, 3]].sort() // errorSortBy
Introduced in version 2 (cost support in version 3)
Sorts a list by a key value, i.e., the order is determined by the result ofan expression applied to each element of the list.
<list(T)>.sortBy(<bindingName>, <keyExpr>) -> <list(T)>keyExpr returns a value in {int, uint, double, bool, duration, timestamp, string, bytes}Examples:
[ Player { name: "foo", score: 0 }, Player { name: "bar", score: -10 }, Player { name: "baz", score: 1000 },].sortBy(e, e.score).map(e, e.name)== ["bar", "foo", "baz"]Last
Introduced in the OptionalTypes library version 2
Returns an optional with the last value from the list oroptional.None if thelist is empty.
<list(T)>.last() -> <Optional(T)>Examples:
[1, 2, 3].last().value() == 3[].last().orValue('test') == 'test'This is syntactic sugar for list[list.size()-1].
First
Introduced in the OptionalTypes library version 2
Returns an optional with the first value from the list oroptional.None if thelist is empty.
<list(T)>.first() -> <Optional(T)>Examples:
[1, 2, 3].first().value() == 1 [].first().orValue('test') == 'test'Sets
Sets provides set relationship tests.
There is no set type within CEL, and while one may be introduced in thefuture, there are cases where alist type is known to behave like a set.For such cases, this library provides some basic functionality fordetermining set containment, equivalence, and intersection.
Sets.Contains
Returns whether the first list argument contains all elements in the secondlist argument. The list may contain elements of any type and standard CELequality is used to determine whether a value exists in both lists. If thesecond list is empty, the result will always return true.
sets.contains(list(T), list(T)) -> boolExamples:
sets.contains([], []) // truesets.contains([], [1]) // falsesets.contains([1, 2, 3, 4], [2, 3]) // truesets.contains([1, 2.0, 3u], [1.0, 2u, 3]) // trueSets.Equivalent
Returns whether the first and second list are set equivalent. Lists are setequivalent if for every item in the first list, there is an element in thesecond which is equal. The lists may not be of the same size as they do notguarantee the elements within them are unique, so size does not factor intothe computation.
sets.equivalent(list(T), list(T)) -> boolExamples:
sets.equivalent([], []) // truesets.equivalent([1], [1, 1]) // truesets.equivalent([1], [1u, 1.0]) // truesets.equivalent([1, 2, 3], [3u, 2.0, 1]) // trueSets.Intersects
Returns whether the first list has at least one element whose value is equalto an element in the second list. If either list is empty, the result willbe false.
sets.intersects(list(T), list(T)) -> boolExamples:
sets.intersects([1], []) // falsesets.intersects([1], [1, 2]) // truesets.intersects([[1], [2, 3]], [[1, 2], [2, 3.0]]) // trueStrings
Extended functions for string manipulation. As a general note, all indices arezero-based.
CharAt
Returns the character at the given position. If the position is negative, orgreater than the length of the string, the function will produce an error:
<string>.charAt(<int>) -> <string>Examples:
'hello'.charAt(4) // return 'o''hello'.charAt(5) // return '''hello'.charAt(-1) // errorIndexOf
Returns the integer index of the first occurrence of the search string. If thesearch string is not found the function returns -1.
The function also accepts an optional position from which to begin thesubstring search. If the substring is the empty string, the index where thesearch starts is returned (zero or custom).
<string>.indexOf(<string>) -> <int><string>.indexOf(<string>, <int>) -> <int>Examples:
'hello mellow'.indexOf('') // returns 0'hello mellow'.indexOf('ello') // returns 1'hello mellow'.indexOf('jello') // returns -1'hello mellow'.indexOf('', 2) // returns 2'hello mellow'.indexOf('ello', 2) // returns 7'hello mellow'.indexOf('ello', 20) // returns -1'hello mellow'.indexOf('ello', -1) // errorJoin
Returns a new string where the elements of string list are concatenated.
The function also accepts an optional separator which is placed betweenelements in the resulting string.
<list<string>>.join() -> <string><list<string>>.join(<string>) -> <string>Examples:
['hello', 'mellow'].join() // returns 'hellomellow'['hello', 'mellow'].join(' ') // returns 'hello mellow'[].join() // returns ''[].join('/') // returns ''LastIndexOf
Returns the integer index of the last occurrence of the search string. If thesearch string is not found the function returns -1.
The function also accepts an optional position which represents the last indexto be considered as the beginning of the substring match. If the substring isthe empty string, the index where the search starts is returned (string lengthor custom).
<string>.lastIndexOf(<string>) -> <int><string>.lastIndexOf(<string>, <int>) -> <int>Examples:
'hello mellow'.lastIndexOf('') // returns 12'hello mellow'.lastIndexOf('ello') // returns 7'hello mellow'.lastIndexOf('jello') // returns -1'hello mellow'.lastIndexOf('ello', 6) // returns 1'hello mellow'.lastIndexOf('ello', 20) // returns -1'hello mellow'.lastIndexOf('ello', -1) // errorLowerAscii
Returns a new string where all ASCII characters are lower-cased.
This function does not perform Unicode case-mapping for characters outside theASCII range.
<string>.lowerAscii() -> <string>Examples:
'TacoCat'.lowerAscii() // returns 'tacocat' 'TacoCÆt Xii'.lowerAscii() // returns 'tacocÆt xii'Quote
Introduced in version 1
Takes the given string and makes it safe to print (without any formatting due to escape sequences).If any invalid UTF-8 characters are encountered, they are replaced with \uFFFD.
strings.quote(<string>)Examples:
strings.quote('single-quote with "double quote"') // returns '"single-quote with \"double quote\""'strings.quote("two escape sequences \a\n") // returns '"two escape sequences \\a\\n"'Replace
Returns a new string based on the target, which replaces the occurrences of asearch string with a replacement string if present. The function accepts anoptional limit on the number of substring replacements to be made.
When the replacement limit is 0, the result is the original string. When thelimit is a negative number, the function behaves the same as replace all.
<string>.replace(<string>, <string>) -> <string><string>.replace(<string>, <string>, <int>) -> <string>Examples:
'hello hello'.replace('he', 'we') // returns 'wello wello''hello hello'.replace('he', 'we', -1) // returns 'wello wello''hello hello'.replace('he', 'we', 1) // returns 'wello hello''hello hello'.replace('he', 'we', 0) // returns 'hello hello'Split
Returns a list of strings split from the input by the given separator. Thefunction accepts an optional argument specifying a limit on the number ofsubstrings produced by the split.
When the split limit is 0, the result is an empty list. When the limit is 1,the result is the target string to split. When the limit is a negativenumber, the function behaves the same as split all.
<string>.split(<string>) -> <list<string>><string>.split(<string>, <int>) -> <list<string>>Examples:
'hello hello hello'.split(' ') // returns ['hello', 'hello', 'hello']'hello hello hello'.split(' ', 0) // returns []'hello hello hello'.split(' ', 1) // returns ['hello hello hello']'hello hello hello'.split(' ', 2) // returns ['hello', 'hello hello']'hello hello hello'.split(' ', -1) // returns ['hello', 'hello', 'hello']Substring
Returns the substring given a numeric range corresponding to characterpositions. Optionally may omit the trailing range for a substring from a givencharacter position until the end of a string.
Character offsets are 0-based with an inclusive start range and exclusive endrange. It is an error to specify an end range that is lower than the startrange, or for either the start or end index to be negative or exceed the stringlength.
<string>.substring(<int>) -> <string><string>.substring(<int>, <int>) -> <string>Examples:
'tacocat'.substring(4) // returns 'cat''tacocat'.substring(0, 4) // returns 'taco''tacocat'.substring(-1) // error'tacocat'.substring(2, 1) // errorTrim
Returns a new string which removes the leading and trailing whitespace in thetarget string. The trim function uses the Unicode definition of whitespacewhich does not include the zero-width spaces. See:https://en.wikipedia.org/wiki/Whitespace_character#Unicode
<string>.trim() -> <string>Examples:
' \ttrim\n '.trim() // returns 'trim'UpperAscii
Returns a new string where all ASCII characters are upper-cased.
This function does not perform Unicode case-mapping for characters outside theASCII range.
<string>.upperAscii() -> <string>Examples:
'TacoCat'.upperAscii() // returns 'TACOCAT' 'TacoCÆt Xii'.upperAscii() // returns 'TACOCÆT XII'Reverse
Returns a new string whose characters are the same as the target string, only formatted inreverse order.This function relies on converting strings to rune arrays in order to reverse.It can be located in Version 3 of strings.
<string>.reverse() -> <string>Examples:
'gums'.reverse() // returns 'smug''John Smith'.reverse() // returns 'htimS nhoJ'TwoVarComprehensions
TwoVarComprehensions introduces support for two-variable comprehensions.
The two-variable form of comprehensions looks similar to the one-variablecounterparts. Where possible, the same macro names were used and additionalmacro signatures added. The notable distinction for two-variable comprehensionsis the introduction oftransformList,transformMap, andtransformMapEntrysupport for list and map types rather than the more traditionalmap andfilter macros.
All
Comprehension which tests whether all elements in the list or map satisfy agiven predicate. Theall macro evaluates in a manner consistent with logicalAND and will short-circuit when encountering afalse value.
<list>.all(indexVar, valueVar, <predicate>) -> bool<map>.all(keyVar, valueVar, <predicate>) -> boolExamples:
[1, 2, 3].all(i, j, i < j) // returns true{'hello': 'world', 'taco': 'taco'}.all(k, v, k != v) // returns false// Combines two-variable comprehension with single variable{'h': ['hello', 'hi'], 'j': ['joke', 'jog']} .all(k, vals, vals.all(v, v.startsWith(k))) // returns trueExists
Comprehension which tests whether any element in a list or map exists whichsatisfies a given predicate. Theexists macro evaluates in a manner consistentwith logical OR and will short-circuit when encountering atrue value.
<list>.exists(indexVar, valueVar, <predicate>) -> bool<map>.exists(keyVar, valueVar, <predicate>) -> boolExamples:
{'greeting': 'hello', 'farewell': 'goodbye'} .exists(k, v, k.startsWith('good') || v.endsWith('bye')) // returns true[1, 2, 4, 8, 16].exists(i, v, v == 1024 && i == 10) // returns falseExistsOne
Comprehension which tests whether exactly one element in a list or map existswhich satisfies a given predicate expression. This comprehension does notshort-circuit in keeping with the one-variable exists one macro semantics.
<list>.existsOne(indexVar, valueVar, <predicate>)<map>.existsOne(keyVar, valueVar, <predicate>)This macro may also be used with theexists_one function name, forcompatibility with the one-variable macro of the same name.
Examples:
[1, 2, 1, 3, 1, 4].existsOne(i, v, i == 1 || v == 1) // returns false[1, 1, 2, 2, 3, 3].existsOne(i, v, i == 2 && v == 2) // returns true{'i': 0, 'j': 1, 'k': 2}.existsOne(i, v, i == 'l' || v == 1) // returns trueTransformList
Comprehension which converts a map or a list into a list value. The outputexpression of the comprehension determines the contents of the output list.Elements in the list may optionally be filtered according to a predicateexpression, where elements that satisfy the predicate are transformed.
<list>.transformList(indexVar, valueVar, <transform>)<list>.transformList(indexVar, valueVar, <filter>, <transform>)<map>.transformList(keyVar, valueVar, <transform>)<map>.transformList(keyVar, valueVar, <filter>, <transform>)Examples:
[1, 2, 3].transformList(indexVar, valueVar, (indexVar * valueVar) + valueVar) // returns [1, 4, 9][1, 2, 3].transformList(indexVar, valueVar, indexVar % 2 == 0 (indexVar * valueVar) + valueVar) // returns [1, 9]{'greeting': 'hello', 'farewell': 'goodbye'} .transformList(k, _, k) // returns ['greeting', 'farewell']{'greeting': 'hello', 'farewell': 'goodbye'} .transformList(_, v, v) // returns ['hello', 'goodbye']TransformMap
Comprehension which converts a map or a list into a map value. The outputexpression of the comprehension determines the value of the output map entry;however, the key remains fixed. Elements in the map may optionally be filteredaccording to a predicate expression, where elements that satisfy the predicateare transformed.
<list>.transformMap(indexVar, valueVar, <transform>)<list>.transformMap(indexVar, valueVar, <filter>, <transform>)<map>.transformMap(keyVar, valueVar, <transform>)<map>.transformMap(keyVar, valueVar, <filter>, <transform>)Examples:
[1, 2, 3].transformMap(indexVar, valueVar, (indexVar * valueVar) + valueVar) // returns {0: 1, 1: 4, 2: 9}[1, 2, 3].transformMap(indexVar, valueVar, indexVar % 2 == 0 (indexVar * valueVar) + valueVar) // returns {0: 1, 2: 9}{'greeting': 'hello'}.transformMap(k, v, v + '!') // returns {'greeting': 'hello!'}TransformMapEntry
Comprehension which converts a map or a list into a map value; however, thistransform expects the entry expression be a map literal. If the transformproduces an entry which duplicates a key in the target map, the comprehensionwill error. Note, that key equality is determined using CEL equality whichasserts that numeric values which are equal, even if they don't have the sametype will cause a key collision.
Elements in the map may optionally be filtered according to a predicateexpression, where elements that satisfy the predicate are transformed.
<list>.transformMap(indexVar, valueVar, <transform>)<list>.transformMap(indexVar, valueVar, <filter>, <transform>)<map>.transformMap(keyVar, valueVar, <transform>)<map>.transformMap(keyVar, valueVar, <filter>, <transform>)Examples:
// returns {'hello': 'greeting'}{'greeting': 'hello'}.transformMapEntry(keyVar, valueVar, {valueVar: keyVar})// reverse lookup, require all values in list be unique[1, 2, 3].transformMapEntry(indexVar, valueVar, {valueVar: indexVar}){'greeting': 'aloha', 'farewell': 'aloha'} .transformMapEntry(keyVar, valueVar, {valueVar: keyVar}) // error, duplicate key
Documentation¶
Overview¶
Package ext contains CEL extension libraries where each library defines a related set ofconstants, functions, macros, or other configuration settings which may not be covered bythe core CEL spec.
Index¶
- func Bindings(options ...BindingsOption) cel.EnvOption
- func Encoders(options ...EncodersOption) cel.EnvOption
- func ExtensionOptionFactory(configElement any) (cel.EnvOption, bool)
- func FormatString(arg ref.Val, locale string) (string, error)
- func Lists(options ...ListsOption) cel.EnvOption
- func Math(options ...MathOption) cel.EnvOption
- func NativeTypes(args ...any) cel.EnvOption
- func NewSetMembershipOptimizer() (cel.ASTOptimizer, error)
- func Protos(options ...ProtosOption) cel.EnvOption
- func Regex(options ...RegexOptions) cel.EnvOption
- func Sets(options ...SetsOption) cel.EnvOption
- func Strings(options ...StringsOption) cel.EnvOption
- func TwoVarComprehensions(options ...TwoVarComprehensionsOption) cel.EnvOption
- type BindingsOption
- type EncodersOption
- type ListsOption
- type MathOption
- type NativeTypesFieldNameHandler
- type NativeTypesOption
- type ProtosOption
- type RegexOptions
- type SetsOption
- type StringsOption
- type TwoVarComprehensionsOption
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
funcBindings¶added inv0.15.0
func Bindings(options ...BindingsOption)cel.EnvOption
Bindings returns a cel.EnvOption to configure support for local variablebindings in expressions.
Cel.Bind¶
Binds a simple identifier to an initialization expression which may be usedin a subsequenct result expression. Bindings may also be nested within eachother.
cel.bind(<varName>, <initExpr>, <resultExpr>)
Examples:
cel.bind(a, 'hello',cel.bind(b, 'world', a + b + b + a)) // "helloworldworldhello"// Avoid a list allocation within the exists comprehension.cel.bind(valid_values, [a, b, c],[d, e, f].exists(elem, elem in valid_values))
Local bindings are not guaranteed to be evaluated before use.
funcEncoders¶added inv0.6.0
func Encoders(options ...EncodersOption)cel.EnvOption
Encoders returns a cel.EnvOption to configure extended functions for string, byte, and objectencodings.
Base64.Decode¶
Decodes base64-encoded string to bytes.
This function will return an error if the string input is not base64-encoded.
base64.decode(<string>) -> <bytes>
Examples:
base64.decode('aGVsbG8=') // return b'hello'base64.decode('aGVsbG8') // return b'hello'Base64.Encode¶
Encodes bytes to a base64-encoded string.
base64.encode(<bytes>) -> <string>
Examples:
base64.encode(b'hello') // return b'aGVsbG8='
funcExtensionOptionFactory¶added inv0.25.0
ExtensionOptionFactory converts an ExtensionConfig value to a CEL environment option.
funcFormatString¶added inv0.14.0
FormatString returns the string representation of a CEL value.
It is used to implement the %s specifier in the (string).format() extension function.
funcLists¶added inv0.17.0
func Lists(options ...ListsOption)cel.EnvOption
Lists returns a cel.EnvOption to configure extended functions for list manipulation.As a general note, all indices are zero-based.
Distinct¶
Introduced in version: 2 (cost support in version 3)
Returns the distinct elements of a list.
<list(T)>.distinct() -> <list(T)>
Examples:
[1, 2, 2, 3, 3, 3].distinct() // return [1, 2, 3]["b", "b", "c", "a", "c"].distinct() // return ["b", "c", "a"][1, "b", 2, "b"].distinct() // return [1, "b", 2]
Range¶
Introduced in version: 2 (cost support in version 3)
Returns a list of integers from 0 to n-1.
lists.range(<int>) -> <list(int)>
Examples:
lists.range(5) -> [0, 1, 2, 3, 4]
Reverse¶
Introduced in version: 2 (cost support in version 3)
Returns the elements of a list in reverse order.
<list(T)>.reverse() -> <list(T)>
Examples:
[5, 3, 1, 2].reverse() // return [2, 1, 3, 5]
Slice¶
Introduced in version: 0 (cost support in version 3)
Returns a new sub-list using the indexes provided.
<list>.slice(<int>, <int>) -> <list>
Examples:
[1,2,3,4].slice(1, 3) // return [2, 3][1,2,3,4].slice(2, 4) // return [3 ,4]
Flatten¶
Introduced in version: 1 (cost support in version 3)
Flattens a list recursively.If an optional depth is provided, the list is flattened to a the specified level.A negative depth value will result in an error.
<list>.flatten() -> <list><list>.flatten(<int>) -> <list>
Examples:
[1,[2,3],[4]].flatten() // return [1, 2, 3, 4][1,[2,[3,4]]].flatten() // return [1, 2, [3, 4]][1,2,[],[],[3,4]].flatten() // return [1, 2, 3, 4][1,[2,[3,[4]]]].flatten(2) // return [1, 2, 3, [4]][1,[2,[3,[4]]]].flatten(-1) // error
Sort¶
Introduced in version: 2 (cost support in version 3)
Sorts a list with comparable elements. If the element type is not comparableor the element types are not the same, the function will produce an error.
<list(T)>.sort() -> <list(T)>T in {int, uint, double, bool, duration, timestamp, string, bytes}Examples:
[3, 2, 1].sort() // return [1, 2, 3]["b", "c", "a"].sort() // return ["a", "b", "c"][1, "b"].sort() // error[[1, 2, 3]].sort() // error
SortBy¶
Introduced in version: 2 (cost support in version 3)
Sorts a list by a key value, i.e., the order is determined by the result ofan expression applied to each element of the list.The output of the key expression must be a comparable type, otherwise thefunction will return an error.
<list(T)>.sortBy(<bindingName>, <keyExpr>) -> <list(T)>keyExpr returns a value in {int, uint, double, bool, duration, timestamp, string, bytes}Examples:
[ Player { name: "foo", score: 0 }, Player { name: "bar", score: -10 }, Player { name: "baz", score: 1000 },].sortBy(e, e.score).map(e, e.name)== ["bar", "foo", "baz"]funcMath¶added inv0.13.0
func Math(options ...MathOption)cel.EnvOption
Math returns a cel.EnvOption to configure namespaced math helper macros andfunctions.
Note, all macros use the 'math' namespace; however, at the time of macroexpansion the namespace looks just like any other identifier. If you arecurrently using a variable named 'math', the macro will likely work just asintended; however, there is some chance for collision.
Math.Greatest¶
Returns the greatest valued number present in the arguments to the macro.
Greatest is a variable argument count macro which must take at least oneargument. Simple numeric and list literals are supported as valid argumenttypes; however, other literals will be flagged as errors during macroexpansion. If the argument expression does not resolve to a numeric orlist(numeric) type during type-checking, or during runtime then an errorwill be produced. If a list argument is empty, this too will produce anerror.
math.greatest(<arg>, ...) -> <double|int|uint>
Examples:
math.greatest(1) // 1math.greatest(1u, 2u) // 2umath.greatest(-42.0, -21.5, -100.0) // -21.5math.greatest([-42.0, -21.5, -100.0]) // -21.5math.greatest(numbers) // numbers must be list(numeric)math.greatest() // parse errormath.greatest('string') // parse errormath.greatest(a, b) // check-time error if a or b is non-numericmath.greatest(dyn('string')) // runtime errorMath.Least¶
Returns the least valued number present in the arguments to the macro.
Least is a variable argument count macro which must take at least oneargument. Simple numeric and list literals are supported as valid argumenttypes; however, other literals will be flagged as errors during macroexpansion. If the argument expression does not resolve to a numeric orlist(numeric) type during type-checking, or during runtime then an errorwill be produced. If a list argument is empty, this too will produce anerror.
math.least(<arg>, ...) -> <double|int|uint>
Examples:
math.least(1) // 1math.least(1u, 2u) // 1umath.least(-42.0, -21.5, -100.0) // -100.0math.least([-42.0, -21.5, -100.0]) // -100.0math.least(numbers) // numbers must be list(numeric)math.least() // parse errormath.least('string') // parse errormath.least(a, b) // check-time error if a or b is non-numericmath.least(dyn('string')) // runtime errorMath.BitOr¶
Introduced at version: 1
Performs a bitwise-OR operation over two int or uint values.
math.bitOr(<int>, <int>) -> <int>math.bitOr(<uint>, <uint>) -> <uint>
Examples:
math.bitOr(1u, 2u) // returns 3umath.bitOr(-2, -4) // returns -2
Math.BitAnd¶
Introduced at version: 1
Performs a bitwise-AND operation over two int or uint values.
math.bitAnd(<int>, <int>) -> <int>math.bitAnd(<uint>, <uint>) -> <uint>
Examples:
math.bitAnd(3u, 2u) // return 2umath.bitAnd(3, 5) // returns 3math.bitAnd(-3, -5) // returns -7
Math.BitXor¶
Introduced at version: 1
math.bitXor(<int>, <int>) -> <int>math.bitXor(<uint>, <uint>) -> <uint>
Performs a bitwise-XOR operation over two int or uint values.
Examples:
math.bitXor(3u, 5u) // returns 6umath.bitXor(1, 3) // returns 2
Math.BitNot¶
Introduced at version: 1
Function which accepts a single int or uint and performs a bitwise-NOTones-complement of the given binary value.
math.bitNot(<int>) -> <int>math.bitNot(<uint>) -> <uint>
Examples
math.bitNot(1) // returns -1math.bitNot(-1) // return 0math.bitNot(0u) // returns 18446744073709551615u
Math.BitShiftLeft¶
Introduced at version: 1
Perform a left shift of bits on the first parameter, by the amount of bitsspecified in the second parameter. The first parameter is either a uint oran int. The second parameter must be an int.
When the second parameter is 64 or greater, 0 will be always be returnedsince the number of bits shifted is greater than or equal to the total bitlength of the number being shifted. Negative valued bit shifts will resultin a runtime error.
math.bitShiftLeft(<int>, <int>) -> <int>math.bitShiftLeft(<uint>, <int>) -> <uint>
Examples
math.bitShiftLeft(1, 2) // returns 4math.bitShiftLeft(-1, 2) // returns -4math.bitShiftLeft(1u, 2) // return 4umath.bitShiftLeft(1u, 200) // returns 0u
Math.BitShiftRight¶
Introduced at version: 1
Perform a right shift of bits on the first parameter, by the amount of bitsspecified in the second parameter. The first parameter is either a uint oran int. The second parameter must be an int.
When the second parameter is 64 or greater, 0 will always be returned sincethe number of bits shifted is greater than or equal to the total bit lengthof the number being shifted. Negative valued bit shifts will result in aruntime error.
The sign bit extension will not be preserved for this operation: vacant bitson the left are filled with 0.
math.bitShiftRight(<int>, <int>) -> <int>math.bitShiftRight(<uint>, <int>) -> <uint>
Examples
math.bitShiftRight(1024, 2) // returns 256math.bitShiftRight(1024u, 2) // returns 256umath.bitShiftRight(1024u, 64) // returns 0u
Math.Ceil¶
Introduced at version: 1
Compute the ceiling of a double value.
math.ceil(<double>) -> <double>
Examples:
math.ceil(1.2) // returns 2.0math.ceil(-1.2) // returns -1.0
Math.Floor¶
Introduced at version: 1
Compute the floor of a double value.
math.floor(<double>) -> <double>
Examples:
math.floor(1.2) // returns 1.0math.floor(-1.2) // returns -2.0
Math.Round¶
Introduced at version: 1
Rounds the double value to the nearest whole number with ties rounding awayfrom zero, e.g. 1.5 -> 2.0, -1.5 -> -2.0.
math.round(<double>) -> <double>
Examples:
math.round(1.2) // returns 1.0math.round(1.5) // returns 2.0math.round(-1.5) // returns -2.0
Math.Trunc¶
Introduced at version: 1
Truncates the fractional portion of the double value.
math.trunc(<double>) -> <double>
Examples:
math.trunc(-1.3) // returns -1.0math.trunc(1.3) // returns 1.0
Math.Abs¶
Introduced at version: 1
Returns the absolute value of the numeric type provided as input. If thevalue is NaN, the output is NaN. If the input is int64 min, the functionwill result in an overflow error.
math.abs(<double>) -> <double>math.abs(<int>) -> <int>math.abs(<uint>) -> <uint>
Examples:
math.abs(-1) // returns 1math.abs(1) // returns 1math.abs(-9223372036854775808) // overflow error
Math.Sign¶
Introduced at version: 1
Returns the sign of the numeric type, either -1, 0, 1 as an int, double, oruint depending on the overload. For floating point values, if NaN isprovided as input, the output is also NaN. The implementation does notdifferentiate between positive and negative zero.
math.sign(<double>) -> <double>math.sign(<int>) -> <int>math.sign(<uint>) -> <uint>
Examples:
math.sign(-42) // returns -1math.sign(0) // returns 0math.sign(42) // returns 1
Math.IsInf¶
Introduced at version: 1
Returns true if the input double value is -Inf or +Inf.
math.isInf(<double>) -> <bool>
Examples:
math.isInf(1.0/0.0) // returns truemath.isInf(1.2) // returns false
Math.IsNaN¶
Introduced at version: 1
Returns true if the input double value is NaN, false otherwise.
math.isNaN(<double>) -> <bool>
Examples:
math.isNaN(0.0/0.0) // returns truemath.isNaN(1.2) // returns false
Math.IsFinite¶
Introduced at version: 1
Returns true if the value is a finite number. Equivalent in behavior to:!math.isNaN(double) && !math.isInf(double)
math.isFinite(<double>) -> <bool>
Examples:
math.isFinite(0.0/0.0) // returns falsemath.isFinite(1.2) // returns true
Math.Sqrt¶
Introduced at version: 2
Returns the square root of the given input as doubleThrows error for negative or non-numeric inputs
math.sqrt(<double>) -> <double>math.sqrt(<int>) -> <double>math.sqrt(<uint>) -> <double>
Examples:
math.sqrt(81) // returns 9.0math.sqrt(985.25) // returns 31.388692231439016 math.sqrt(-15) // returns NaN
funcNativeTypes¶added inv0.13.0
NativeTypes creates a type provider which uses reflect.Type and reflect.Value instancesto produce type definitions that can be used within CEL.
All struct types in Go are exposed to CEL via their simple package name and struct type name:
```gopackage identity
type Account struct { ID int}```
The type `identity.Account` would be exported to CEL using the same qualified name, e.g.`identity.Account{ID: 1234}` would create a new `Account` instance with the `ID` fieldpopulated.
Only exported fields are exposed via NativeTypes, and the type-mapping between Go and CELis as follows:
| Go type | CEL type ||-------------------------------------|-----------|| bool | bool || []byte | bytes || float32, float64 | double || int, int8, int16, int32, int64 | int || string | string || uint, uint8, uint16, uint32, uint64 | uint || time.Duration | duration || time.Time | timestamp || array, slice | list || map | map |
Please note, if you intend to configure support for proto messages in addition to nativetypes, you will need to provide the protobuf types before the golang native types. Thesame advice holds if you are using custom type adapters and type providers. The native typeprovider composes over whichever type adapter and provider is configured in the cel.Env atthe time that it is invoked.
There is also the possibility to rename the fields of native structs by setting the `cel` tagfor fields you want to override. In order to enable this feature, pass in the `ParseStructTags(true)`option. Here is an example to see it in action:
```gopackage identity
type Account struct { ID int OwnerName string `cel:"owner"`}```
The `OwnerName` field is now accessible in CEL via `owner`, e.g. `identity.Account{owner: 'bob'}`.In case there are duplicated field names in the struct, an error will be returned.
funcNewSetMembershipOptimizer¶added inv0.19.0
func NewSetMembershipOptimizer() (cel.ASTOptimizer,error)
NewSetMembershipOptimizer rewrites set membership tests using the `in` operator against a listof constant values of enum, int, uint, string, or boolean type into a set membership test againsta map where the map keys are the elements of the list.
funcProtos¶added inv0.13.0
func Protos(options ...ProtosOption)cel.EnvOption
Protos returns a cel.EnvOption to configure extended macros and functions forproto manipulation.
Note, all macros use the 'proto' namespace; however, at the time of macroexpansion the namespace looks just like any other identifier. If you arecurrently using a variable named 'proto', the macro will likely work just asintended; however, there is some chance for collision.
Protos.GetExt¶
Macro which generates a select expression that retrieves an extension fieldfrom the input proto2 syntax message. If the field is not set, the defaultvalue forthe extension field is returned according to safe-traversal semantics.
proto.getExt(<msg>, <fully.qualified.extension.name>) -> <field-type>
Examples:
proto.getExt(msg, google.expr.proto2.test.int32_ext) // returns int value
Protos.HasExt¶
Macro which generates a test-only select expression that determines whetheran extension field is set on a proto2 syntax message.
proto.hasExt(<msg>, <fully.qualified.extension.name>) -> <bool>
Examples:
proto.hasExt(msg, google.expr.proto2.test.int32_ext) // returns true || false
funcRegex¶added inv0.25.1
func Regex(options ...RegexOptions)cel.EnvOption
Regex returns a cel.EnvOption to configure extended functions for regularexpression operations.
Note: all functions use the 'regex' namespace. If you arecurrently using a variable named 'regex', the functions will likely work asintended, however there is some chance for collision.
This library depends on the CEL optional type. Please ensure that thecel.OptionalTypes() is enabled when using regex extensions.
Replace¶
The `regex.replace` function replaces all non-overlapping substring of a regexpattern in the target string with a replacement string. Optionally, you canlimit the number of replacements by providing a count argument. When the countis a negative number, the function acts as replace all. Only numeric (\N)capture group references are supported in the replacement string, withvalidation for correctness. Backslashed-escaped digits (\1 to \9) within thereplacement argument can be used to insert text matching the correspondingparenthesized group in the regexp pattern. An error will be thrown for invalidregex or replace string.
regex.replace(target: string, pattern: string, replacement: string) -> stringregex.replace(target: string, pattern: string, replacement: string, count: int) -> string
Examples:
regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'regex.replace('banana', 'a', 'x', 0) == 'banana'regex.replace('banana', 'a', 'x', 1) == 'bxnana'regex.replace('banana', 'a', 'x', 2) == 'bxnxna'regex.replace('banana', 'a', 'x', -12) == 'bxnxnx'regex.replace('foo bar', '(fo)o (ba)r', r'\2 \1') == 'ba fo'regex.replace('test', '(.)', r'\2') \\ Runtime Error invalid replace stringregex.replace('foo bar', '(', '$2 $1') \\ Runtime Error invalid regex stringregex.replace('id=123', r'id=(?P<value>\d+)', r'value: \values') \\ Runtime Error invalid replace stringExtract¶
The `regex.extract` function returns the first match of a regex pattern in astring. If no match is found, it returns an optional none value. An error willbe thrown for invalid regex or for multiple capture groups.
regex.extract(target: string, pattern: string) -> optional<string>
Examples:
regex.extract('hello world', 'hello(.*)') == optional.of(' world')regex.extract('item-A, item-B', 'item-(\\w+)') == optional.of('A')regex.extract('HELLO', 'hello') == optional.empty()regex.extract('testuser@testdomain', '(.*)@([^.]*)') // Runtime Error multiple capture groupExtract All¶
The `regex.extractAll` function returns a list of all matches of a regexpattern in a target string. If no matches are found, it returns an empty list. An error willbe thrown for invalid regex or for multiple capture groups.
regex.extractAll(target: string, pattern: string) -> list<string>
Examples:
regex.extractAll('id:123, id:456', 'id:\\d+') == ['id:123', 'id:456']regex.extractAll('id:123, id:456', 'assa') == []regex.extractAll('testuser@testdomain', '(.*)@([^.]*)') // Runtime Error multiple capture groupfuncSets¶added inv0.15.0
func Sets(options ...SetsOption)cel.EnvOption
Sets returns a cel.EnvOption to configure namespaced set relationshipfunctions.
There is no set type within CEL, and while one may be introduced in thefuture, there are cases where a `list` type is known to behave like a set.For such cases, this library provides some basic functionality fordetermining set containment, equivalence, and intersection.
Sets.Contains¶
Returns whether the first list argument contains all elements in the secondlist argument. The list may contain elements of any type and standard CELequality is used to determine whether a value exists in both lists. If thesecond list is empty, the result will always return true.
sets.contains(list(T), list(T)) -> bool
Examples:
sets.contains([], []) // truesets.contains([], [1]) // falsesets.contains([1, 2, 3, 4], [2, 3]) // truesets.contains([1, 2.0, 3u], [1.0, 2u, 3]) // true
Sets.Equivalent¶
Returns whether the first and second list are set equivalent. Lists are setequivalent if for every item in the first list, there is an element in thesecond which is equal. The lists may not be of the same size as they do notguarantee the elements within them are unique, so size does not factor intothe computation.
Examples:
sets.equivalent([], []) // truesets.equivalent([1], [1, 1]) // truesets.equivalent([1], [1u, 1.0]) // truesets.equivalent([1, 2, 3], [3u, 2.0, 1]) // true
Sets.Intersects¶
Returns whether the first list has at least one element whose value is equalto an element in the second list. If either list is empty, the result willbe false.
Examples:
sets.intersects([1], []) // falsesets.intersects([1], [1, 2]) // truesets.intersects([[1], [2, 3]], [[1, 2], [2, 3.0]]) // true
funcStrings¶
func Strings(options ...StringsOption)cel.EnvOption
Strings returns a cel.EnvOption to configure extended functions for string manipulation.As a general note, all indices are zero-based.
CharAt¶
Returns the character at the given position. If the position is negative, or greater thanthe length of the string, the function will produce an error:
<string>.charAt(<int>) -> <string>
Examples:
'hello'.charAt(4) // return 'o''hello'.charAt(5) // return '''hello'.charAt(-1) // error
Format¶
Introduced at version: 1
Returns a new string with substitutions being performed, printf-style.The valid formatting clauses are:
`%s` - substitutes a string. This can also be used on bools, lists, maps, bytes,Duration and Timestamp, in addition to all numerical types (int, uint, and double).Note that the dot/period decimal separator will always be used when printing a listor map that contains a double, and that null can be passed (which results in thestring "null") in addition to types.`%d` - substitutes an integer.`%f` - substitutes a double with fixed-point precision. The default precision is 6, butthis can be adjusted. The strings `Infinity`, `-Infinity`, and `NaN` are also valid inputfor this clause.`%e` - substitutes a double in scientific notation. The default precision is 6, but thiscan be adjusted.`%b` - substitutes an integer with its equivalent binary string. Can also be used on bools.`%x` - substitutes an integer with its equivalent in hexadecimal, or if given a string orbytes, will output each character's equivalent in hexadecimal.`%X` - same as above, but with A-F capitalized.`%o` - substitutes an integer with its equivalent in octal.
<string>.format(<list>) -> <string>
Examples:
"this is a string: %s\nand an integer: %d".format(["str", 42]) // returns "this is a string: str\nand an integer: 42""a double substituted with %%s: %s".format([64.2]) // returns "a double substituted with %s: 64.2""string type: %s".format([type(string)]) // returns "string type: string""timestamp: %s".format([timestamp("2023-02-03T23:31:20+00:00")]) // returns "timestamp: 2023-02-03T23:31:20Z""duration: %s".format([duration("1h45m47s")]) // returns "duration: 6347s""%f".format([3.14]) // returns "3.140000""scientific notation: %e".format([2.71828]) // returns "scientific notation: 2.718280\u202f\u00d7\u202f10\u2070\u2070""5 in binary: %b".format([5]), // returns "5 in binary; 101""26 in hex: %x".format([26]), // returns "26 in hex: 1a""26 in hex (uppercase): %X".format([26]) // returns "26 in hex (uppercase): 1A""30 in octal: %o".format([30]) // returns "30 in octal: 36""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"}]""true bool: %s - false bool: %s\nbinary bool: %b".format([true, false, true]) // returns "true bool: true - false bool: false\nbinary bool: 1"Passing an incorrect type (a string to `%b`) is considered an error, as well as attemptingto use more formatting clauses than there are arguments (`%d %d %d` while passing two ints, for instance).If compile-time checking is enabled, and the formatting string is a constant, and the argument list is a literal,then letting any arguments go unused/unformatted is also considered an error.
IndexOf¶
Returns the integer index of the first occurrence of the search string. If the search string isnot found the function returns -1.
The function also accepts an optional position from which to begin the substring search. If thesubstring is the empty string, the index where the search starts is returned (zero or custom).
<string>.indexOf(<string>) -> <int><string>.indexOf(<string>, <int>) -> <int>
Examples:
'hello mellow'.indexOf('') // returns 0'hello mellow'.indexOf('ello') // returns 1'hello mellow'.indexOf('jello') // returns -1'hello mellow'.indexOf('', 2) // returns 2'hello mellow'.indexOf('ello', 2) // returns 7'hello mellow'.indexOf('ello', 20) // returns -1'hello mellow'.indexOf('ello', -1) // errorJoin¶
Returns a new string where the elements of string list are concatenated.
The function also accepts an optional separator which is placed between elements in the resulting string.
<list<string>>.join() -> <string><list<string>>.join(<string>) -> <string>
Examples:
['hello', 'mellow'].join() // returns 'hellomellow'['hello', 'mellow'].join(' ') // returns 'hello mellow'[].join() // returns ''[].join('/') // returns ''LastIndexOf¶
Returns the integer index at the start of the last occurrence of the search string. If thesearch string is not found the function returns -1.
The function also accepts an optional position which represents the last index to beconsidered as the beginning of the substring match. If the substring is the empty string,the index where the search starts is returned (string length or custom).
<string>.lastIndexOf(<string>) -> <int><string>.lastIndexOf(<string>, <int>) -> <int>
Examples:
'hello mellow'.lastIndexOf('') // returns 12'hello mellow'.lastIndexOf('ello') // returns 7'hello mellow'.lastIndexOf('jello') // returns -1'hello mellow'.lastIndexOf('ello', 6) // returns 1'hello mellow'.lastIndexOf('ello', 20) // returns -1'hello mellow'.lastIndexOf('ello', -1) // errorLowerAscii¶
Returns a new string where all ASCII characters are lower-cased.
This function does not perform Unicode case-mapping for characters outside the ASCII range.
<string>.lowerAscii() -> <string>
Examples:
'TacoCat'.lowerAscii() // returns 'tacocat''TacoCÆt Xii'.lowerAscii() // returns 'tacocÆt xii'
Strings.Quote¶
Introduced in version: 1
Takes the given string and makes it safe to print (without any formatting due to escape sequences).If any invalid UTF-8 characters are encountered, they are replaced with \uFFFD.
strings.quote(<string>)
Examples:
strings.quote('single-quote with "double quote"') // returns '"single-quote with \"double quote\""'strings.quote("two escape sequences \a\n") // returns '"two escape sequences \\a\\n"'
Replace¶
Returns a new string based on the target, which replaces the occurrences of a search stringwith a replacement string if present. The function accepts an optional limit on the number ofsubstring replacements to be made.
When the replacement limit is 0, the result is the original string. When the limit is a negativenumber, the function behaves the same as replace all.
<string>.replace(<string>, <string>) -> <string><string>.replace(<string>, <string>, <int>) -> <string>
Examples:
'hello hello'.replace('he', 'we') // returns 'wello wello''hello hello'.replace('he', 'we', -1) // returns 'wello wello''hello hello'.replace('he', 'we', 1) // returns 'wello hello''hello hello'.replace('he', 'we', 0) // returns 'hello hello''hello hello'.replace('', '_') // returns '_h_e_l_l_o_ _h_e_l_l_o_''hello hello'.replace('h', '') // returns 'ello ello'Split¶
Returns a list of strings split from the input by the given separator. The function acceptsan optional argument specifying a limit on the number of substrings produced by the split.
When the split limit is 0, the result is an empty list. When the limit is 1, the result is thetarget string to split. When the limit is a negative number, the function behaves the same assplit all.
<string>.split(<string>) -> <list<string>><string>.split(<string>, <int>) -> <list<string>>
Examples:
'hello hello hello'.split(' ') // returns ['hello', 'hello', 'hello']'hello hello hello'.split(' ', 0) // returns []'hello hello hello'.split(' ', 1) // returns ['hello hello hello']'hello hello hello'.split(' ', 2) // returns ['hello', 'hello hello']'hello hello hello'.split(' ', -1) // returns ['hello', 'hello', 'hello']Substring¶
Returns the substring given a numeric range corresponding to character positions. Optionallymay omit the trailing range for a substring from a given character position until the end ofa string.
Character offsets are 0-based with an inclusive start range and exclusive end range. It is anerror to specify an end range that is lower than the start range, or for either the start or endindex to be negative or exceed the string length.
<string>.substring(<int>) -> <string><string>.substring(<int>, <int>) -> <string>
Examples:
'tacocat'.substring(4) // returns 'cat''tacocat'.substring(0, 4) // returns 'taco''tacocat'.substring(-1) // error'tacocat'.substring(2, 1) // error
Trim¶
Returns a new string which removes the leading and trailing whitespace in the target string.The trim function uses the Unicode definition of whitespace which does not include thezero-width spaces. See:https://en.wikipedia.org/wiki/Whitespace_character#Unicode
<string>.trim() -> <string>
Examples:
' \ttrim\n '.trim() // returns 'trim'
UpperAscii¶
Returns a new string where all ASCII characters are upper-cased.
This function does not perform Unicode case-mapping for characters outside the ASCII range.
<string>.upperAscii() -> <string>
Examples:
'TacoCat'.upperAscii() // returns 'TACOCAT''TacoCÆt Xii'.upperAscii() // returns 'TACOCÆT XII'
Reverse¶
Introduced at version: 3
Returns a new string whose characters are the same as the target string, only formatted inreverse order.This function relies on converting strings to rune arrays in order to reverse
<string>.reverse() -> <string>
Examples:
'gums'.reverse() // returns 'smug''John Smith'.reverse() // returns 'htimS nhoJ'
Introduced at version: 4
Formatting updated to adhere tohttps://github.com/google/cel-spec/blob/master/doc/extensions/strings.md.
<string>.format(<list>) -> <string>
funcTwoVarComprehensions¶added inv0.22.0
func TwoVarComprehensions(options ...TwoVarComprehensionsOption)cel.EnvOption
TwoVarComprehensions introduces support for two-variable comprehensions.
The two-variable form of comprehensions looks similar to the one-variable counterparts.Where possible, the same macro names were used and additional macro signatures added.The notable distinction for two-variable comprehensions is the introduction of`transformList`, `transformMap`, and `transformMapEntry` support for list and map typesrather than the more traditional `map` and `filter` macros.
All¶
Comprehension which tests whether all elements in the list or map satisfy a givenpredicate. The `all` macro evaluates in a manner consistent with logical AND and willshort-circuit when encountering a `false` value.
<list>.all(indexVar, valueVar, <predicate>) -> bool<map>.all(keyVar, valueVar, <predicate>) -> bool
Examples:
[1, 2, 3].all(i, j, i < j) // returns true{'hello': 'world', 'taco': 'taco'}.all(k, v, k != v) // returns false// Combines two-variable comprehension with single variable{'h': ['hello', 'hi'], 'j': ['joke', 'jog']} .all(k, vals, vals.all(v, v.startsWith(k))) // returns trueExists¶
Comprehension which tests whether any element in a list or map exists which satisfiesa given predicate. The `exists` macro evaluates in a manner consistent with logical ORand will short-circuit when encountering a `true` value.
<list>.exists(indexVar, valueVar, <predicate>) -> bool<map>.exists(keyVar, valueVar, <predicate>) -> bool
Examples:
{'greeting': 'hello', 'farewell': 'goodbye'} .exists(k, v, k.startsWith('good') || v.endsWith('bye')) // returns true[1, 2, 4, 8, 16].exists(i, v, v == 1024 && i == 10) // returns falseExistsOne¶
Comprehension which tests whether exactly one element in a list or map exists whichsatisfies a given predicate expression. This comprehension does not short-circuit inkeeping with the one-variable exists one macro semantics.
<list>.existsOne(indexVar, valueVar, <predicate>)<map>.existsOne(keyVar, valueVar, <predicate>)
This macro may also be used with the `exists_one` function name, for compatibilitywith the one-variable macro of the same name.
Examples:
[1, 2, 1, 3, 1, 4].existsOne(i, v, i == 1 || v == 1) // returns false[1, 1, 2, 2, 3, 3].existsOne(i, v, i == 2 && v == 2) // returns true{'i': 0, 'j': 1, 'k': 2}.existsOne(i, v, i == 'l' || v == 1) // returns trueTransformList¶
Comprehension which converts a map or a list into a list value. The output expressionof the comprehension determines the contents of the output list. Elements in the listmay optionally be filtered according to a predicate expression, where elements thatsatisfy the predicate are transformed.
<list>.transformList(indexVar, valueVar, <transform>)<list>.transformList(indexVar, valueVar, <filter>, <transform>)<map>.transformList(keyVar, valueVar, <transform>)<map>.transformList(keyVar, valueVar, <filter>, <transform>)
Examples:
[1, 2, 3].transformList(indexVar, valueVar, (indexVar * valueVar) + valueVar) // returns [1, 4, 9][1, 2, 3].transformList(indexVar, valueVar, indexVar % 2 == 0 (indexVar * valueVar) + valueVar) // returns [1, 9]{'greeting': 'hello', 'farewell': 'goodbye'} .transformList(k, _, k) // returns ['greeting', 'farewell']{'greeting': 'hello', 'farewell': 'goodbye'} .transformList(_, v, v) // returns ['hello', 'goodbye']TransformMap¶
Comprehension which converts a map or a list into a map value. The output expressionof the comprehension determines the value of the output map entry; however, the keyremains fixed. Elements in the map may optionally be filtered according to a predicateexpression, where elements that satisfy the predicate are transformed.
<list>.transformMap(indexVar, valueVar, <transform>)<list>.transformMap(indexVar, valueVar, <filter>, <transform>)<map>.transformMap(keyVar, valueVar, <transform>)<map>.transformMap(keyVar, valueVar, <filter>, <transform>)
Examples:
[1, 2, 3].transformMap(indexVar, valueVar, (indexVar * valueVar) + valueVar) // returns {0: 1, 1: 4, 2: 9}[1, 2, 3].transformMap(indexVar, valueVar, indexVar % 2 == 0 (indexVar * valueVar) + valueVar) // returns {0: 1, 2: 9}{'greeting': 'hello'}.transformMap(k, v, v + '!') // returns {'greeting': 'hello!'}TransformMapEntry¶
Comprehension which converts a map or a list into a map value; however, this transformexpects the entry expression be a map literal. If the tranform produces an entry whichduplicates a key in the target map, the comprehension will error. Note, that keyequality is determined using CEL equality which asserts that numeric values which areequal, even if they don't have the same type will cause a key collision.
Elements in the map may optionally be filtered according to a predicate expression, whereelements that satisfy the predicate are transformed.
<list>.transformMap(indexVar, valueVar, <transform>)<list>.transformMap(indexVar, valueVar, <filter>, <transform>)<map>.transformMap(keyVar, valueVar, <transform>)<map>.transformMap(keyVar, valueVar, <filter>, <transform>)
Examples:
// returns {'hello': 'greeting'}{'greeting': 'hello'}.transformMapEntry(keyVar, valueVar, {valueVar: keyVar})// reverse lookup, require all values in list be unique[1, 2, 3].transformMapEntry(indexVar, valueVar, {valueVar: indexVar}){'greeting': 'aloha', 'farewell': 'aloha'} .transformMapEntry(keyVar, valueVar, {valueVar: keyVar}) // error, duplicate keyTypes¶
typeBindingsOption¶added inv0.22.0
type BindingsOption func(*celBindings) *celBindings
BindingsOption declares a functional operator for configuring the Bindings library behavior.
funcBindingsVersion¶added inv0.22.0
func BindingsVersion(versionuint32)BindingsOption
BindingsVersion sets the version of the bindings library to an explicit version.
typeEncodersOption¶added inv0.23.0
type EncodersOption func(*encoderLib) *encoderLib
EncodersOption declares a functional operator for configuring encoder extensions.
funcEncodersVersion¶added inv0.23.0
func EncodersVersion(versionuint32)EncodersOption
EncodersVersion sets the library version for encoder extensions.
typeListsOption¶added inv0.22.0
type ListsOption func(*listsLib) *listsLib
ListsOption is a functional interface for configuring the strings library.
funcListsVersion¶added inv0.22.0
func ListsVersion(versionuint32)ListsOption
ListsVersion configures the version of the string library.
The version limits which functions are available. Only functions introducedbelow or equal to the given version included in the library. If this optionis not set, all functions are available.
See the library documentation to determine which version a function was introduced.If the documentation does not state which version a function was introduced, it canbe assumed to be introduced at version 0, when the library was first created.
typeMathOption¶added inv0.21.0
type MathOption func(*mathLib) *mathLib
MathOption declares a functional operator for configuring math extensions.
funcMathVersion¶added inv0.21.0
func MathVersion(versionuint32)MathOption
MathVersion sets the library version for math extensions.
typeNativeTypesFieldNameHandler¶added inv0.22.0
type NativeTypesFieldNameHandler = func(fieldreflect.StructField)string
NativeTypesFieldNameHandler is a handler for mapping a reflect.StructField to a CEL field name.This can be used to override the default Go struct field to CEL field name mapping.
typeNativeTypesOption¶added inv0.21.0
type NativeTypesOption func(*nativeTypeOptions)error
NativeTypesOption is a functional interface for configuring handling of native types.
funcNativeTypesVersion¶added inv0.23.0
func NativeTypesVersion(versionuint32)NativeTypesOption
NativeTypesVersion sets the native types version support for native extensions functions.
funcParseStructField¶added inv0.22.0
func ParseStructField(handlerNativeTypesFieldNameHandler)NativeTypesOption
ParseStructField configures how to parse Go struct fields. It can be used to customize struct field parsing.
funcParseStructTag¶added inv0.22.0
func ParseStructTag(tagstring)NativeTypesOption
ParseStructTag configures the struct tag to parse. The 0th item in the tag is used as the name of the CEL field.For example:If the tag to parse is "cel" and the struct field has tag cel:"foo", the CEL struct field will be "foo".If the tag to parse is "json" and the struct field has tag json:"foo,omitempty", the CEL struct field will be "foo".
funcParseStructTags¶added inv0.21.0
func ParseStructTags(enabledbool)NativeTypesOption
ParseStructTags configures if native types field names should be overridable by CEL struct tags.This is equivalent to ParseStructTag("cel")
typeProtosOption¶added inv0.23.0
type ProtosOption func(*protoLib) *protoLib
ProtosOption declares a functional operator for configuring protobuf utilities.
funcProtosVersion¶added inv0.23.0
func ProtosVersion(versionuint32)ProtosOption
ProtosVersion sets the library version for extensions for protobuf utilities.
typeRegexOptions¶added inv0.25.1
type RegexOptions func(*regexLib) *regexLib
RegexOptions declares a functional operator for configuring regex extension.
funcRegexVersion¶added inv0.25.1
func RegexVersion(versionuint32)RegexOptions
RegexVersion configures the version of the Regex library definitions to use. SeeRegex for supported values.
typeSetsOption¶added inv0.23.0
type SetsOption func(*setsLib) *setsLib
SetsOption declares a functional operator for configuring set extensions.
funcSetsVersion¶added inv0.23.0
func SetsVersion(versionuint32)SetsOption
SetsVersion sets the library version for set extensions.
typeStringsOption¶added inv0.14.0
type StringsOption func(*stringLib) *stringLib
StringsOption is a functional interface for configuring the strings library.
funcStringsLocale¶added inv0.14.0
func StringsLocale(localestring)StringsOption
StringsLocale configures the library with the given locale. The locale tag willbe checked for validity at the time that EnvOptions are configured. If this optionis not passed, string.format will behave as if en_US was passed as the locale.
If StringsVersion is greater than or equal to 4, this option is ignored.
funcStringsValidateFormatCalls¶added inv0.17.2
func StringsValidateFormatCalls(valuebool)StringsOption
StringsValidateFormatCalls validates type-checked ASTs to ensure that string.format() calls havevalid formatting clauses and valid argument types for each clause.
Deprecated
funcStringsVersion¶added inv0.14.0
func StringsVersion(versionuint32)StringsOption
StringsVersion configures the version of the string library.
The version limits which functions are available. Only functions introducedbelow or equal to the given version included in the library. If this optionis not set, all functions are available.
See the library documentation to determine which version a function was introduced.If the documentation does not state which version a function was introduced, it canbe assumed to be introduced at version 0, when the library was first created.
typeTwoVarComprehensionsOption¶added inv0.23.0
type TwoVarComprehensionsOption func(*compreV2Lib) *compreV2Lib
TwoVarComprehensionsOption declares a functional operator for configuring two-variable comprehensions.
funcTwoVarComprehensionsVersion¶added inv0.23.0
func TwoVarComprehensionsVersion(versionuint32)TwoVarComprehensionsOption
TwoVarComprehensionsVersion sets the library version for two-variable comprehensions.