| 1 | // Copyright 2023 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package ext |
| 16 | |
| 17 | import ( |
| 18 | "errors" |
| 19 | "fmt" |
| 20 | "math" |
| 21 | "sort" |
| 22 | "strconv" |
| 23 | "strings" |
| 24 | "unicode" |
| 25 | |
| 26 | "golang.org/x/text/language" |
| 27 | "golang.org/x/text/message" |
| 28 | |
| 29 | "github.com/google/cel-go/cel" |
| 30 | "github.com/google/cel-go/common/ast" |
| 31 | "github.com/google/cel-go/common/overloads" |
| 32 | "github.com/google/cel-go/common/types" |
| 33 | "github.com/google/cel-go/common/types/ref" |
| 34 | "github.com/google/cel-go/common/types/traits" |
| 35 | ) |
| 36 | |
| 37 | type clauseImpl func(ref.Val, string) (string, error) |
| 38 | |
| 39 | func clauseForType(argType ref.Type) (clauseImpl, error) { |
| 40 | switch argType { |
| 41 | case types.IntType, types.UintType: |
| 42 | return formatDecimal, nil |
| 43 | case types.StringType, types.BytesType, types.BoolType, types.NullType, types.TypeType: |
| 44 | return FormatString, nil |
| 45 | case types.TimestampType, types.DurationType: |
| 46 | // special case to ensure timestamps/durations get printed as CEL literals |
| 47 | return func(arg ref.Val, locale string) (string, error) { |
| 48 | argStrVal := arg.ConvertToType(types.StringType) |
| 49 | argStr := argStrVal.Value().(string) |
| 50 | if arg.Type() == types.TimestampType { |
| 51 | return fmt.Sprintf("timestamp(%q)", argStr), nil |
| 52 | } |
| 53 | if arg.Type() == types.DurationType { |
| 54 | return fmt.Sprintf("duration(%q)", argStr), nil |
| 55 | } |
| 56 | return "", fmt.Errorf("cannot convert argument of type %s to timestamp/duration", arg.Type().TypeName()) |
| 57 | }, nil |
| 58 | case types.ListType: |
| 59 | return formatList, nil |
| 60 | case types.MapType: |
| 61 | return formatMap, nil |
| 62 | case types.DoubleType: |
| 63 | // avoid formatFixed so we can output a period as the decimal separator in order |
| 64 | // to always be a valid CEL literal |
| 65 | return func(arg ref.Val, locale string) (string, error) { |
| 66 | argDouble, ok := arg.Value().(float64) |
| 67 | if !ok { |
| 68 | return "", fmt.Errorf("couldn't convert %s to float64", arg.Type().TypeName()) |
| 69 | } |
| 70 | fmtStr := fmt.Sprintf("%%.%df", defaultPrecision) |
| 71 | return fmt.Sprintf(fmtStr, argDouble), nil |
| 72 | }, nil |
| 73 | case types.TypeType: |
| 74 | return func(arg ref.Val, locale string) (string, error) { |
| 75 | return fmt.Sprintf("type(%s)", arg.Value().(string)), nil |
| 76 | }, nil |
| 77 | default: |
| 78 | return nil, fmt.Errorf("no formatting function for %s", argType.TypeName()) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | func formatList(arg ref.Val, locale string) (string, error) { |
| 83 | argList := arg.(traits.Lister) |
| 84 | argIterator := argList.Iterator() |
| 85 | var listStrBuilder strings.Builder |
| 86 | _, err := listStrBuilder.WriteRune('[') |
| 87 | if err != nil { |
| 88 | return "", fmt.Errorf("error writing to list string: %w", err) |
| 89 | } |
| 90 | for argIterator.HasNext() == types.True { |
| 91 | member := argIterator.Next() |
| 92 | memberFormat, err := clauseForType(member.Type()) |
| 93 | if err != nil { |
| 94 | return "", err |
| 95 | } |
| 96 | unquotedStr, err := memberFormat(member, locale) |
| 97 | if err != nil { |
| 98 | return "", err |
| 99 | } |
| 100 | str := quoteForCEL(member, unquotedStr) |
| 101 | _, err = listStrBuilder.WriteString(str) |
| 102 | if err != nil { |
| 103 | return "", fmt.Errorf("error writing to list string: %w", err) |
| 104 | } |
| 105 | if argIterator.HasNext() == types.True { |
| 106 | _, err = listStrBuilder.WriteString(", ") |
| 107 | if err != nil { |
| 108 | return "", fmt.Errorf("error writing to list string: %w", err) |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | _, err = listStrBuilder.WriteRune(']') |
| 113 | if err != nil { |
| 114 | return "", fmt.Errorf("error writing to list string: %w", err) |
| 115 | } |
| 116 | return listStrBuilder.String(), nil |
| 117 | } |
| 118 | |
| 119 | func formatMap(arg ref.Val, locale string) (string, error) { |
| 120 | argMap := arg.(traits.Mapper) |
| 121 | argIterator := argMap.Iterator() |
| 122 | type mapPair struct { |
| 123 | key string |
| 124 | value string |
| 125 | } |
| 126 | argPairs := make([]mapPair, argMap.Size().Value().(int64)) |
| 127 | i := 0 |
| 128 | for argIterator.HasNext() == types.True { |
| 129 | key := argIterator.Next() |
| 130 | var keyFormat clauseImpl |
| 131 | switch key.Type() { |
| 132 | case types.StringType, types.BoolType: |
| 133 | keyFormat = FormatString |
| 134 | case types.IntType, types.UintType: |
| 135 | keyFormat = formatDecimal |
| 136 | default: |
| 137 | return "", fmt.Errorf("no formatting function for map key of type %s", key.Type().TypeName()) |
| 138 | } |
| 139 | unquotedKeyStr, err := keyFormat(key, locale) |
| 140 | if err != nil { |
| 141 | return "", err |
| 142 | } |
| 143 | keyStr := quoteForCEL(key, unquotedKeyStr) |
| 144 | value, found := argMap.Find(key) |
| 145 | if !found { |
| 146 | return "", fmt.Errorf("could not find key: %q", key) |
| 147 | } |
| 148 | valueFormat, err := clauseForType(value.Type()) |
| 149 | if err != nil { |
| 150 | return "", err |
| 151 | } |
| 152 | unquotedValueStr, err := valueFormat(value, locale) |
| 153 | if err != nil { |
| 154 | return "", err |
| 155 | } |
| 156 | valueStr := quoteForCEL(value, unquotedValueStr) |
| 157 | argPairs[i] = mapPair{keyStr, valueStr} |
| 158 | i++ |
| 159 | } |
| 160 | sort.SliceStable(argPairs, func(x, y int) bool { |
| 161 | return argPairs[x].key < argPairs[y].key |
| 162 | }) |
| 163 | var mapStrBuilder strings.Builder |
| 164 | _, err := mapStrBuilder.WriteRune('{') |
| 165 | if err != nil { |
| 166 | return "", fmt.Errorf("error writing to map string: %w", err) |
| 167 | } |
| 168 | for i, entry := range argPairs { |
| 169 | _, err = mapStrBuilder.WriteString(fmt.Sprintf("%s:%s", entry.key, entry.value)) |
| 170 | if err != nil { |
| 171 | return "", fmt.Errorf("error writing to map string: %w", err) |
| 172 | } |
| 173 | if i < len(argPairs)-1 { |
| 174 | _, err = mapStrBuilder.WriteString(", ") |
| 175 | if err != nil { |
| 176 | return "", fmt.Errorf("error writing to map string: %w", err) |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | _, err = mapStrBuilder.WriteRune('}') |
| 181 | if err != nil { |
| 182 | return "", fmt.Errorf("error writing to map string: %w", err) |
| 183 | } |
| 184 | return mapStrBuilder.String(), nil |
| 185 | } |
| 186 | |
| 187 | // quoteForCEL takes a formatted, unquoted value and quotes it in a manner suitable |
| 188 | // for embedding directly in CEL. |
| 189 | func quoteForCEL(refVal ref.Val, unquotedValue string) string { |
| 190 | switch refVal.Type() { |
| 191 | case types.StringType: |
| 192 | return fmt.Sprintf("%q", unquotedValue) |
| 193 | case types.BytesType: |
| 194 | return fmt.Sprintf("b%q", unquotedValue) |
| 195 | case types.DoubleType: |
| 196 | // special case to handle infinity/NaN |
| 197 | num := refVal.Value().(float64) |
| 198 | if math.IsInf(num, 1) || math.IsInf(num, -1) || math.IsNaN(num) { |
| 199 | return fmt.Sprintf("%q", unquotedValue) |
| 200 | } |
| 201 | return unquotedValue |
| 202 | default: |
| 203 | return unquotedValue |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | // FormatString returns the string representation of a CEL value. |
| 208 | // |
| 209 | // It is used to implement the %s specifier in the (string).format() extension function. |
| 210 | func FormatString(arg ref.Val, locale string) (string, error) { |
| 211 | switch arg.Type() { |
| 212 | case types.ListType: |
| 213 | return formatList(arg, locale) |
| 214 | case types.MapType: |
| 215 | return formatMap(arg, locale) |
| 216 | case types.IntType, types.UintType, types.DoubleType, |
| 217 | types.BoolType, types.StringType, types.TimestampType, types.BytesType, types.DurationType, types.TypeType: |
| 218 | argStrVal := arg.ConvertToType(types.StringType) |
| 219 | argStr, ok := argStrVal.Value().(string) |
| 220 | if !ok { |
| 221 | return "", fmt.Errorf("could not convert argument %q to string", argStrVal) |
| 222 | } |
| 223 | return argStr, nil |
| 224 | case types.NullType: |
| 225 | return "null", nil |
| 226 | default: |
| 227 | return "", stringFormatError(runtimeID, arg.Type().TypeName()) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | func formatDecimal(arg ref.Val, locale string) (string, error) { |
| 232 | switch arg.Type() { |
| 233 | case types.IntType: |
| 234 | argInt, ok := arg.ConvertToType(types.IntType).Value().(int64) |
| 235 | if !ok { |
| 236 | return "", fmt.Errorf("could not convert \"%s\" to int64", arg.Value()) |
| 237 | } |
| 238 | return fmt.Sprintf("%d", argInt), nil |
| 239 | case types.UintType: |
| 240 | argInt, ok := arg.ConvertToType(types.UintType).Value().(uint64) |
| 241 | if !ok { |
| 242 | return "", fmt.Errorf("could not convert \"%s\" to uint64", arg.Value()) |
| 243 | } |
| 244 | return fmt.Sprintf("%d", argInt), nil |
| 245 | default: |
| 246 | return "", decimalFormatError(runtimeID, arg.Type().TypeName()) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | func matchLanguage(locale string) (language.Tag, error) { |
| 251 | matcher, err := makeMatcher(locale) |
| 252 | if err != nil { |
| 253 | return language.Und, err |
| 254 | } |
| 255 | tag, _ := language.MatchStrings(matcher, locale) |
| 256 | return tag, nil |
| 257 | } |
| 258 | |
| 259 | func makeMatcher(locale string) (language.Matcher, error) { |
| 260 | tags := make([]language.Tag, 0) |
| 261 | tag, err := language.Parse(locale) |
| 262 | if err != nil { |
| 263 | return nil, err |
| 264 | } |
| 265 | tags = append(tags, tag) |
| 266 | return language.NewMatcher(tags), nil |
| 267 | } |
| 268 | |
| 269 | type stringFormatter struct{} |
| 270 | |
| 271 | // String implements formatStringInterpolator.String. |
| 272 | func (c *stringFormatter) String(arg ref.Val, locale string) (string, error) { |
| 273 | return FormatString(arg, locale) |
| 274 | } |
| 275 | |
| 276 | // Decimal implements formatStringInterpolator.Decimal. |
| 277 | func (c *stringFormatter) Decimal(arg ref.Val, locale string) (string, error) { |
| 278 | return formatDecimal(arg, locale) |
| 279 | } |
| 280 | |
| 281 | // Fixed implements formatStringInterpolator.Fixed. |
| 282 | func (c *stringFormatter) Fixed(precision *int) func(ref.Val, string) (string, error) { |
| 283 | if precision == nil { |
| 284 | precision = new(int) |
| 285 | *precision = defaultPrecision |
| 286 | } |
| 287 | return func(arg ref.Val, locale string) (string, error) { |
| 288 | strException := false |
| 289 | if arg.Type() == types.StringType { |
| 290 | argStr := arg.Value().(string) |
| 291 | if argStr == "NaN" || argStr == "Infinity" || argStr == "-Infinity" { |
| 292 | strException = true |
| 293 | } |
| 294 | } |
| 295 | if arg.Type() != types.DoubleType && !strException { |
| 296 | return "", fixedPointFormatError(runtimeID, arg.Type().TypeName()) |
| 297 | } |
| 298 | argFloatVal := arg.ConvertToType(types.DoubleType) |
| 299 | argFloat, ok := argFloatVal.Value().(float64) |
| 300 | if !ok { |
| 301 | return "", fmt.Errorf("could not convert \"%s\" to float64", argFloatVal.Value()) |
| 302 | } |
| 303 | fmtStr := fmt.Sprintf("%%.%df", *precision) |
| 304 | |
| 305 | matchedLocale, err := matchLanguage(locale) |
| 306 | if err != nil { |
| 307 | return "", fmt.Errorf("error matching locale: %w", err) |
| 308 | } |
| 309 | return message.NewPrinter(matchedLocale).Sprintf(fmtStr, argFloat), nil |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // Scientific implements formatStringInterpolator.Scientific. |
| 314 | func (c *stringFormatter) Scientific(precision *int) func(ref.Val, string) (string, error) { |
| 315 | if precision == nil { |
| 316 | precision = new(int) |
| 317 | *precision = defaultPrecision |
| 318 | } |
| 319 | return func(arg ref.Val, locale string) (string, error) { |
| 320 | strException := false |
| 321 | if arg.Type() == types.StringType { |
| 322 | argStr := arg.Value().(string) |
| 323 | if argStr == "NaN" || argStr == "Infinity" || argStr == "-Infinity" { |
| 324 | strException = true |
| 325 | } |
| 326 | } |
| 327 | if arg.Type() != types.DoubleType && !strException { |
| 328 | return "", scientificFormatError(runtimeID, arg.Type().TypeName()) |
| 329 | } |
| 330 | argFloatVal := arg.ConvertToType(types.DoubleType) |
| 331 | argFloat, ok := argFloatVal.Value().(float64) |
| 332 | if !ok { |
| 333 | return "", fmt.Errorf("could not convert \"%v\" to float64", argFloatVal.Value()) |
| 334 | } |
| 335 | matchedLocale, err := matchLanguage(locale) |
| 336 | if err != nil { |
| 337 | return "", fmt.Errorf("error matching locale: %w", err) |
| 338 | } |
| 339 | fmtStr := fmt.Sprintf("%%%de", *precision) |
| 340 | return message.NewPrinter(matchedLocale).Sprintf(fmtStr, argFloat), nil |
| 341 | } |
| 342 | } |
| 343 | |
| 344 | // Binary implements formatStringInterpolator.Binary. |
| 345 | func (c *stringFormatter) Binary(arg ref.Val, locale string) (string, error) { |
| 346 | switch arg.Type() { |
| 347 | case types.IntType: |
| 348 | argInt := arg.Value().(int64) |
| 349 | // locale is intentionally unused as integers formatted as binary |
| 350 | // strings are locale-independent |
| 351 | return fmt.Sprintf("%b", argInt), nil |
| 352 | case types.UintType: |
| 353 | argInt := arg.Value().(uint64) |
| 354 | return fmt.Sprintf("%b", argInt), nil |
| 355 | case types.BoolType: |
| 356 | argBool := arg.Value().(bool) |
| 357 | if argBool { |
| 358 | return "1", nil |
| 359 | } |
| 360 | return "0", nil |
| 361 | default: |
| 362 | return "", binaryFormatError(runtimeID, arg.Type().TypeName()) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | // Hex implements formatStringInterpolator.Hex. |
| 367 | func (c *stringFormatter) Hex(useUpper bool) func(ref.Val, string) (string, error) { |
| 368 | return func(arg ref.Val, locale string) (string, error) { |
| 369 | fmtStr := "%x" |
| 370 | if useUpper { |
| 371 | fmtStr = "%X" |
| 372 | } |
| 373 | switch arg.Type() { |
| 374 | case types.StringType, types.BytesType: |
| 375 | if arg.Type() == types.BytesType { |
| 376 | return fmt.Sprintf(fmtStr, arg.Value().([]byte)), nil |
| 377 | } |
| 378 | return fmt.Sprintf(fmtStr, arg.Value().(string)), nil |
| 379 | case types.IntType: |
| 380 | argInt, ok := arg.Value().(int64) |
| 381 | if !ok { |
| 382 | return "", fmt.Errorf("could not convert \"%s\" to int64", arg.Value()) |
| 383 | } |
| 384 | return fmt.Sprintf(fmtStr, argInt), nil |
| 385 | case types.UintType: |
| 386 | argInt, ok := arg.Value().(uint64) |
| 387 | if !ok { |
| 388 | return "", fmt.Errorf("could not convert \"%s\" to uint64", arg.Value()) |
| 389 | } |
| 390 | return fmt.Sprintf(fmtStr, argInt), nil |
| 391 | default: |
| 392 | return "", hexFormatError(runtimeID, arg.Type().TypeName()) |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | // Octal implements formatStringInterpolator.Octal. |
| 398 | func (c *stringFormatter) Octal(arg ref.Val, locale string) (string, error) { |
| 399 | switch arg.Type() { |
| 400 | case types.IntType: |
| 401 | argInt := arg.Value().(int64) |
| 402 | return fmt.Sprintf("%o", argInt), nil |
| 403 | case types.UintType: |
| 404 | argInt := arg.Value().(uint64) |
| 405 | return fmt.Sprintf("%o", argInt), nil |
| 406 | default: |
| 407 | return "", octalFormatError(runtimeID, arg.Type().TypeName()) |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | // stringFormatValidator implements the cel.ASTValidator interface allowing for static validation |
| 412 | // of string.format calls. |
| 413 | type stringFormatValidator struct{} |
| 414 | |
| 415 | // Name returns the name of the validator. |
| 416 | func (stringFormatValidator) Name() string { |
| 417 | return "cel.validator.string_format" |
| 418 | } |
| 419 | |
| 420 | // Configure implements the ASTValidatorConfigurer interface and augments the list of functions to skip |
| 421 | // during homogeneous aggregate literal type-checks. |
| 422 | func (stringFormatValidator) Configure(config cel.MutableValidatorConfig) error { |
| 423 | functions := config.GetOrDefault(cel.HomogeneousAggregateLiteralExemptFunctions, []string{}).([]string) |
| 424 | functions = append(functions, "format") |
| 425 | return config.Set(cel.HomogeneousAggregateLiteralExemptFunctions, functions) |
| 426 | } |
| 427 | |
| 428 | // Validate parses all literal format strings and type checks the format clause against the argument |
| 429 | // at the corresponding ordinal within the list literal argument to the function, if one is specified. |
| 430 | func (stringFormatValidator) Validate(env *cel.Env, _ cel.ValidatorConfig, a *ast.AST, iss *cel.Issues) { |
| 431 | root := ast.NavigateAST(a) |
| 432 | formatCallExprs := ast.MatchDescendants(root, matchConstantFormatStringWithListLiteralArgs(a)) |
| 433 | for _, e := range formatCallExprs { |
| 434 | call := e.AsCall() |
| 435 | formatStr := call.Target().AsLiteral().Value().(string) |
| 436 | args := call.Args()[0].AsList().Elements() |
| 437 | formatCheck := &stringFormatChecker{ |
| 438 | args: args, |
| 439 | ast: a, |
| 440 | } |
| 441 | // use a placeholder locale, since locale doesn't affect syntax |
| 442 | _, err := parseFormatString(formatStr, formatCheck, formatCheck, "en_US") |
| 443 | if err != nil { |
| 444 | iss.ReportErrorAtID(getErrorExprID(e.ID(), err), "%v", err) |
| 445 | continue |
| 446 | } |
| 447 | seenArgs := formatCheck.argsRequested |
| 448 | if len(args) > seenArgs { |
| 449 | iss.ReportErrorAtID(e.ID(), |
| 450 | "too many arguments supplied to string.format (expected %d, got %d)", seenArgs, len(args)) |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | // getErrorExprID determines which list literal argument triggered a type-disagreement for the |
| 456 | // purposes of more accurate error message reports. |
| 457 | func getErrorExprID(id int64, err error) int64 { |
| 458 | fmtErr, ok := err.(formatError) |
| 459 | if ok { |
| 460 | return fmtErr.id |
| 461 | } |
| 462 | wrapped := errors.Unwrap(err) |
| 463 | if wrapped != nil { |
| 464 | return getErrorExprID(id, wrapped) |
| 465 | } |
| 466 | return id |
| 467 | } |
| 468 | |
| 469 | // matchConstantFormatStringWithListLiteralArgs matches all valid expression nodes for string |
| 470 | // format checking. |
| 471 | func matchConstantFormatStringWithListLiteralArgs(a *ast.AST) ast.ExprMatcher { |
| 472 | return func(e ast.NavigableExpr) bool { |
| 473 | if e.Kind() != ast.CallKind { |
| 474 | return false |
| 475 | } |
| 476 | call := e.AsCall() |
| 477 | if !call.IsMemberFunction() || call.FunctionName() != "format" { |
| 478 | return false |
| 479 | } |
| 480 | overloadIDs := a.GetOverloadIDs(e.ID()) |
| 481 | if len(overloadIDs) != 0 { |
| 482 | found := false |
| 483 | for _, overload := range overloadIDs { |
| 484 | if overload == overloads.ExtFormatString { |
| 485 | found = true |
| 486 | break |
| 487 | } |
| 488 | } |
| 489 | if !found { |
| 490 | return false |
| 491 | } |
| 492 | } |
| 493 | formatString := call.Target() |
| 494 | if formatString.Kind() != ast.LiteralKind || formatString.AsLiteral().Type() != cel.StringType { |
| 495 | return false |
| 496 | } |
| 497 | args := call.Args() |
| 498 | if len(args) != 1 { |
| 499 | return false |
| 500 | } |
| 501 | formatArgs := args[0] |
| 502 | return formatArgs.Kind() == ast.ListKind |
| 503 | } |
| 504 | } |
| 505 | |
| 506 | // stringFormatChecker implements the formatStringInterpolater interface |
| 507 | type stringFormatChecker struct { |
| 508 | args []ast.Expr |
| 509 | argsRequested int |
| 510 | currArgIndex int64 |
| 511 | ast *ast.AST |
| 512 | } |
| 513 | |
| 514 | // String implements formatStringInterpolator.String. |
| 515 | func (c *stringFormatChecker) String(arg ref.Val, locale string) (string, error) { |
| 516 | formatArg := c.args[c.currArgIndex] |
| 517 | valid, badID := c.verifyString(formatArg) |
| 518 | if !valid { |
| 519 | return "", stringFormatError(badID, c.typeOf(badID).TypeName()) |
| 520 | } |
| 521 | return "", nil |
| 522 | } |
| 523 | |
| 524 | // Decimal implements formatStringInterpolator.Decimal. |
| 525 | func (c *stringFormatChecker) Decimal(arg ref.Val, locale string) (string, error) { |
| 526 | id := c.args[c.currArgIndex].ID() |
| 527 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType) |
| 528 | if !valid { |
| 529 | return "", decimalFormatError(id, c.typeOf(id).TypeName()) |
| 530 | } |
| 531 | return "", nil |
| 532 | } |
| 533 | |
| 534 | // Fixed implements formatStringInterpolator.Fixed. |
| 535 | func (c *stringFormatChecker) Fixed(precision *int) func(ref.Val, string) (string, error) { |
| 536 | return func(arg ref.Val, locale string) (string, error) { |
| 537 | id := c.args[c.currArgIndex].ID() |
| 538 | // we allow StringType since "NaN", "Infinity", and "-Infinity" are also valid values |
| 539 | valid := c.verifyTypeOneOf(id, types.DoubleType, types.StringType) |
| 540 | if !valid { |
| 541 | return "", fixedPointFormatError(id, c.typeOf(id).TypeName()) |
| 542 | } |
| 543 | return "", nil |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | // Scientific implements formatStringInterpolator.Scientific. |
| 548 | func (c *stringFormatChecker) Scientific(precision *int) func(ref.Val, string) (string, error) { |
| 549 | return func(arg ref.Val, locale string) (string, error) { |
| 550 | id := c.args[c.currArgIndex].ID() |
| 551 | valid := c.verifyTypeOneOf(id, types.DoubleType, types.StringType) |
| 552 | if !valid { |
| 553 | return "", scientificFormatError(id, c.typeOf(id).TypeName()) |
| 554 | } |
| 555 | return "", nil |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | // Binary implements formatStringInterpolator.Binary. |
| 560 | func (c *stringFormatChecker) Binary(arg ref.Val, locale string) (string, error) { |
| 561 | id := c.args[c.currArgIndex].ID() |
| 562 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType, types.BoolType) |
| 563 | if !valid { |
| 564 | return "", binaryFormatError(id, c.typeOf(id).TypeName()) |
| 565 | } |
| 566 | return "", nil |
| 567 | } |
| 568 | |
| 569 | // Hex implements formatStringInterpolator.Hex. |
| 570 | func (c *stringFormatChecker) Hex(useUpper bool) func(ref.Val, string) (string, error) { |
| 571 | return func(arg ref.Val, locale string) (string, error) { |
| 572 | id := c.args[c.currArgIndex].ID() |
| 573 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType, types.StringType, types.BytesType) |
| 574 | if !valid { |
| 575 | return "", hexFormatError(id, c.typeOf(id).TypeName()) |
| 576 | } |
| 577 | return "", nil |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | // Octal implements formatStringInterpolator.Octal. |
| 582 | func (c *stringFormatChecker) Octal(arg ref.Val, locale string) (string, error) { |
| 583 | id := c.args[c.currArgIndex].ID() |
| 584 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType) |
| 585 | if !valid { |
| 586 | return "", octalFormatError(id, c.typeOf(id).TypeName()) |
| 587 | } |
| 588 | return "", nil |
| 589 | } |
| 590 | |
| 591 | // Arg implements formatListArgs.Arg. |
| 592 | func (c *stringFormatChecker) Arg(index int64) (ref.Val, error) { |
| 593 | c.argsRequested++ |
| 594 | c.currArgIndex = index |
| 595 | // return a dummy value - this is immediately passed to back to us |
| 596 | // through one of the FormatCallback functions, so anything will do |
| 597 | return types.Int(0), nil |
| 598 | } |
| 599 | |
| 600 | // Size implements formatListArgs.Size. |
| 601 | func (c *stringFormatChecker) Size() int64 { |
| 602 | return int64(len(c.args)) |
| 603 | } |
| 604 | |
| 605 | func (c *stringFormatChecker) typeOf(id int64) *cel.Type { |
| 606 | return c.ast.GetType(id) |
| 607 | } |
| 608 | |
| 609 | func (c *stringFormatChecker) verifyTypeOneOf(id int64, validTypes ...*cel.Type) bool { |
| 610 | t := c.typeOf(id) |
| 611 | if t == cel.DynType { |
| 612 | return true |
| 613 | } |
| 614 | for _, vt := range validTypes { |
| 615 | // Only check runtime type compatibility without delving deeper into parameterized types |
| 616 | if t.Kind() == vt.Kind() { |
| 617 | return true |
| 618 | } |
| 619 | } |
| 620 | return false |
| 621 | } |
| 622 | |
| 623 | func (c *stringFormatChecker) verifyString(sub ast.Expr) (bool, int64) { |
| 624 | paramA := cel.TypeParamType("A") |
| 625 | paramB := cel.TypeParamType("B") |
| 626 | subVerified := c.verifyTypeOneOf(sub.ID(), |
| 627 | cel.ListType(paramA), cel.MapType(paramA, paramB), |
| 628 | cel.IntType, cel.UintType, cel.DoubleType, cel.BoolType, cel.StringType, |
| 629 | cel.TimestampType, cel.BytesType, cel.DurationType, cel.TypeType, cel.NullType) |
| 630 | if !subVerified { |
| 631 | return false, sub.ID() |
| 632 | } |
| 633 | switch sub.Kind() { |
| 634 | case ast.ListKind: |
| 635 | for _, e := range sub.AsList().Elements() { |
| 636 | // recursively verify if we're dealing with a list/map |
| 637 | verified, id := c.verifyString(e) |
| 638 | if !verified { |
| 639 | return false, id |
| 640 | } |
| 641 | } |
| 642 | return true, sub.ID() |
| 643 | case ast.MapKind: |
| 644 | for _, e := range sub.AsMap().Entries() { |
| 645 | // recursively verify if we're dealing with a list/map |
| 646 | entry := e.AsMapEntry() |
| 647 | verified, id := c.verifyString(entry.Key()) |
| 648 | if !verified { |
| 649 | return false, id |
| 650 | } |
| 651 | verified, id = c.verifyString(entry.Value()) |
| 652 | if !verified { |
| 653 | return false, id |
| 654 | } |
| 655 | } |
| 656 | return true, sub.ID() |
| 657 | default: |
| 658 | return true, sub.ID() |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | // helper routines for reporting common errors during string formatting static validation and |
| 663 | // runtime execution. |
| 664 | |
| 665 | func binaryFormatError(id int64, badType string) error { |
| 666 | return newFormatError(id, "only integers and bools can be formatted as binary, was given %s", badType) |
| 667 | } |
| 668 | |
| 669 | func decimalFormatError(id int64, badType string) error { |
| 670 | return newFormatError(id, "decimal clause can only be used on integers, was given %s", badType) |
| 671 | } |
| 672 | |
| 673 | func fixedPointFormatError(id int64, badType string) error { |
| 674 | return newFormatError(id, "fixed-point clause can only be used on doubles, was given %s", badType) |
| 675 | } |
| 676 | |
| 677 | func hexFormatError(id int64, badType string) error { |
| 678 | return newFormatError(id, "only integers, byte buffers, and strings can be formatted as hex, was given %s", badType) |
| 679 | } |
| 680 | |
| 681 | func octalFormatError(id int64, badType string) error { |
| 682 | return newFormatError(id, "octal clause can only be used on integers, was given %s", badType) |
| 683 | } |
| 684 | |
| 685 | func scientificFormatError(id int64, badType string) error { |
| 686 | return newFormatError(id, "scientific clause can only be used on doubles, was given %s", badType) |
| 687 | } |
| 688 | |
| 689 | func stringFormatError(id int64, badType string) error { |
| 690 | return newFormatError(id, "string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given %s", badType) |
| 691 | } |
| 692 | |
| 693 | type formatError struct { |
| 694 | id int64 |
| 695 | msg string |
| 696 | } |
| 697 | |
| 698 | func newFormatError(id int64, msg string, args ...any) error { |
| 699 | return formatError{ |
| 700 | id: id, |
| 701 | msg: fmt.Sprintf(msg, args...), |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | // Error implements error. |
| 706 | func (e formatError) Error() string { |
| 707 | return e.msg |
| 708 | } |
| 709 | |
| 710 | // Is implements errors.Is. |
| 711 | func (e formatError) Is(target error) bool { |
| 712 | return e.msg == target.Error() |
| 713 | } |
| 714 | |
| 715 | // stringArgList implements the formatListArgs interface. |
| 716 | type stringArgList struct { |
| 717 | args traits.Lister |
| 718 | } |
| 719 | |
| 720 | // Arg implements formatListArgs.Arg. |
| 721 | func (c *stringArgList) Arg(index int64) (ref.Val, error) { |
| 722 | if index >= c.args.Size().Value().(int64) { |
| 723 | return nil, fmt.Errorf("index %d out of range", index) |
| 724 | } |
| 725 | return c.args.Get(types.Int(index)), nil |
| 726 | } |
| 727 | |
| 728 | // Size implements formatListArgs.Size. |
| 729 | func (c *stringArgList) Size() int64 { |
| 730 | return c.args.Size().Value().(int64) |
| 731 | } |
| 732 | |
| 733 | // formatStringInterpolator is an interface that allows user-defined behavior |
| 734 | // for formatting clause implementations, as well as argument retrieval. |
| 735 | // Each function is expected to support the appropriate types as laid out in |
| 736 | // the string.format documentation, and to return an error if given an inappropriate type. |
| 737 | type formatStringInterpolator interface { |
| 738 | // String takes a ref.Val and a string representing the current locale identifier |
| 739 | // and returns the Val formatted as a string, or an error if one occurred. |
| 740 | String(ref.Val, string) (string, error) |
| 741 | |
| 742 | // Decimal takes a ref.Val and a string representing the current locale identifier |
| 743 | // and returns the Val formatted as a decimal integer, or an error if one occurred. |
| 744 | Decimal(ref.Val, string) (string, error) |
| 745 | |
| 746 | // Fixed takes an int pointer representing precision (or nil if none was given) and |
| 747 | // returns a function operating in a similar manner to String and Decimal, taking a |
| 748 | // ref.Val and locale and returning the appropriate string. A closure is returned |
| 749 | // so precision can be set without needing an additional function call/configuration. |
| 750 | Fixed(*int) func(ref.Val, string) (string, error) |
| 751 | |
| 752 | // Scientific functions identically to Fixed, except the string returned from the closure |
| 753 | // is expected to be in scientific notation. |
| 754 | Scientific(*int) func(ref.Val, string) (string, error) |
| 755 | |
| 756 | // Binary takes a ref.Val and a string representing the current locale identifier |
| 757 | // and returns the Val formatted as a binary integer, or an error if one occurred. |
| 758 | Binary(ref.Val, string) (string, error) |
| 759 | |
| 760 | // Hex takes a boolean that, if true, indicates the hex string output by the returned |
| 761 | // closure should use uppercase letters for A-F. |
| 762 | Hex(bool) func(ref.Val, string) (string, error) |
| 763 | |
| 764 | // Octal takes a ref.Val and a string representing the current locale identifier and |
| 765 | // returns the Val formatted in octal, or an error if one occurred. |
| 766 | Octal(ref.Val, string) (string, error) |
| 767 | } |
| 768 | |
| 769 | // formatListArgs is an interface that allows user-defined list-like datatypes to be used |
| 770 | // for formatting clause implementations. |
| 771 | type formatListArgs interface { |
| 772 | // Arg returns the ref.Val at the given index, or an error if one occurred. |
| 773 | Arg(int64) (ref.Val, error) |
| 774 | |
| 775 | // Size returns the length of the argument list. |
| 776 | Size() int64 |
| 777 | } |
| 778 | |
| 779 | // parseFormatString formats a string according to the string.format syntax, taking the clause implementations |
| 780 | // from the provided FormatCallback and the args from the given FormatList. |
| 781 | func parseFormatString(formatStr string, callback formatStringInterpolator, list formatListArgs, locale string) (string, error) { |
| 782 | i := 0 |
| 783 | argIndex := 0 |
| 784 | var builtStr strings.Builder |
| 785 | for i < len(formatStr) { |
| 786 | if formatStr[i] == '%' { |
| 787 | if i+1 < len(formatStr) && formatStr[i+1] == '%' { |
| 788 | err := builtStr.WriteByte('%') |
| 789 | if err != nil { |
| 790 | return "", fmt.Errorf("error writing format string: %w", err) |
| 791 | } |
| 792 | i += 2 |
| 793 | continue |
| 794 | } else { |
| 795 | argAny, err := list.Arg(int64(argIndex)) |
| 796 | if err != nil { |
| 797 | return "", err |
| 798 | } |
| 799 | if i+1 >= len(formatStr) { |
| 800 | return "", errors.New("unexpected end of string") |
| 801 | } |
| 802 | if int64(argIndex) >= list.Size() { |
| 803 | return "", fmt.Errorf("index %d out of range", argIndex) |
| 804 | } |
| 805 | numRead, val, refErr := parseAndFormatClause(formatStr[i:], argAny, callback, list, locale) |
| 806 | if refErr != nil { |
| 807 | return "", refErr |
| 808 | } |
| 809 | _, err = builtStr.WriteString(val) |
| 810 | if err != nil { |
| 811 | return "", fmt.Errorf("error writing format string: %w", err) |
| 812 | } |
| 813 | i += numRead |
| 814 | argIndex++ |
| 815 | } |
| 816 | } else { |
| 817 | err := builtStr.WriteByte(formatStr[i]) |
| 818 | if err != nil { |
| 819 | return "", fmt.Errorf("error writing format string: %w", err) |
| 820 | } |
| 821 | i++ |
| 822 | } |
| 823 | } |
| 824 | return builtStr.String(), nil |
| 825 | } |
| 826 | |
| 827 | // parseAndFormatClause parses the format clause at the start of the given string with val, and returns |
| 828 | // how many characters were consumed and the substituted string form of val, or an error if one occurred. |
| 829 | func parseAndFormatClause(formatStr string, val ref.Val, callback formatStringInterpolator, list formatListArgs, locale string) (int, string, error) { |
| 830 | i := 1 |
| 831 | read, formatter, err := parseFormattingClause(formatStr[i:], callback) |
| 832 | i += read |
| 833 | if err != nil { |
| 834 | return -1, "", newParseFormatError("could not parse formatting clause", err) |
| 835 | } |
| 836 | |
| 837 | valStr, err := formatter(val, locale) |
| 838 | if err != nil { |
| 839 | return -1, "", newParseFormatError("error during formatting", err) |
| 840 | } |
| 841 | return i, valStr, nil |
| 842 | } |
| 843 | |
| 844 | func parseFormattingClause(formatStr string, callback formatStringInterpolator) (int, clauseImpl, error) { |
| 845 | i := 0 |
| 846 | read, precision, err := parsePrecision(formatStr[i:]) |
| 847 | i += read |
| 848 | if err != nil { |
| 849 | return -1, nil, fmt.Errorf("error while parsing precision: %w", err) |
| 850 | } |
| 851 | r := rune(formatStr[i]) |
| 852 | i++ |
| 853 | switch r { |
| 854 | case 's': |
| 855 | return i, callback.String, nil |
| 856 | case 'd': |
| 857 | return i, callback.Decimal, nil |
| 858 | case 'f': |
| 859 | return i, callback.Fixed(precision), nil |
| 860 | case 'e': |
| 861 | return i, callback.Scientific(precision), nil |
| 862 | case 'b': |
| 863 | return i, callback.Binary, nil |
| 864 | case 'x', 'X': |
| 865 | return i, callback.Hex(unicode.IsUpper(r)), nil |
| 866 | case 'o': |
| 867 | return i, callback.Octal, nil |
| 868 | default: |
| 869 | return -1, nil, fmt.Errorf("unrecognized formatting clause \"%c\"", r) |
| 870 | } |
| 871 | } |
| 872 | |
| 873 | func parsePrecision(formatStr string) (int, *int, error) { |
| 874 | i := 0 |
| 875 | if formatStr[i] != '.' { |
| 876 | return i, nil, nil |
| 877 | } |
| 878 | i++ |
| 879 | var buffer strings.Builder |
| 880 | for { |
| 881 | if i >= len(formatStr) { |
| 882 | return -1, nil, errors.New("could not find end of precision specifier") |
| 883 | } |
| 884 | if !isASCIIDigit(rune(formatStr[i])) { |
| 885 | break |
| 886 | } |
| 887 | buffer.WriteByte(formatStr[i]) |
| 888 | i++ |
| 889 | } |
| 890 | precision, err := strconv.Atoi(buffer.String()) |
| 891 | if err != nil { |
| 892 | return -1, nil, fmt.Errorf("error while converting precision to integer: %w", err) |
| 893 | } |
| 894 | return i, &precision, nil |
| 895 | } |
| 896 | |
| 897 | func isASCIIDigit(r rune) bool { |
| 898 | return r <= unicode.MaxASCII && unicode.IsDigit(r) |
| 899 | } |
| 900 | |
| 901 | type parseFormatError struct { |
| 902 | msg string |
| 903 | wrapped error |
| 904 | } |
| 905 | |
| 906 | func newParseFormatError(msg string, wrapped error) error { |
| 907 | return parseFormatError{msg: msg, wrapped: wrapped} |
| 908 | } |
| 909 | |
| 910 | // Error implements error. |
| 911 | func (e parseFormatError) Error() string { |
| 912 | return fmt.Sprintf("%s: %s", e.msg, e.wrapped.Error()) |
| 913 | } |
| 914 | |
| 915 | // Is implements errors.Is. |
| 916 | func (e parseFormatError) Is(target error) bool { |
| 917 | return e.Error() == target.Error() |
| 918 | } |
| 919 | |
| 920 | // Is implements errors.Unwrap. |
| 921 | func (e parseFormatError) Unwrap() error { |
| 922 | return e.wrapped |
| 923 | } |
| 924 | |
| 925 | const ( |
| 926 | runtimeID = int64(-1) |
| 927 | ) |