| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package ext |
| 16 |
|
| 17 |
import ( |
| 18 |
"errors" |
| 19 |
"fmt" |
| 20 |
"math" |
| 21 |
"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 |
|
| 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 |
|
| 64 |
|
| 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 |
|
| 188 |
|
| 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 |
|
| 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 |
|
| 208 |
|
| 209 |
|
| 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 |
|
| 272 |
func (c *stringFormatter) String(arg ref.Val, locale string) (string, error) { |
| 273 |
return FormatString(arg, locale) |
| 274 |
} |
| 275 |
|
| 276 |
|
| 277 |
func (c *stringFormatter) Decimal(arg ref.Val, locale string) (string, error) { |
| 278 |
return formatDecimal(arg, locale) |
| 279 |
} |
| 280 |
|
| 281 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 350 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 412 |
|
| 413 |
type stringFormatValidator struct{} |
| 414 |
|
| 415 |
|
| 416 |
func (stringFormatValidator) Name() string { |
| 417 |
return "cel.validator.string_format" |
| 418 |
} |
| 419 |
|
| 420 |
|
| 421 |
|
| 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 |
|
| 429 |
|
| 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 |
|
| 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 |
|
| 456 |
|
| 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 |
|
| 470 |
|
| 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 |
|
| 507 |
type stringFormatChecker struct { |
| 508 |
args []ast.Expr |
| 509 |
argsRequested int |
| 510 |
currArgIndex int64 |
| 511 |
ast *ast.AST |
| 512 |
} |
| 513 |
|
| 514 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 592 |
func (c *stringFormatChecker) Arg(index int64) (ref.Val, error) { |
| 593 |
c.argsRequested++ |
| 594 |
c.currArgIndex = index |
| 595 |
|
| 596 |
|
| 597 |
return types.Int(0), nil |
| 598 |
} |
| 599 |
|
| 600 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 663 |
|
| 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 |
|
| 706 |
func (e formatError) Error() string { |
| 707 |
return e.msg |
| 708 |
} |
| 709 |
|
| 710 |
|
| 711 |
func (e formatError) Is(target error) bool { |
| 712 |
return e.msg == target.Error() |
| 713 |
} |
| 714 |
|
| 715 |
|
| 716 |
type stringArgList struct { |
| 717 |
args traits.Lister |
| 718 |
} |
| 719 |
|
| 720 |
|
| 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 |
|
| 729 |
func (c *stringArgList) Size() int64 { |
| 730 |
return c.args.Size().Value().(int64) |
| 731 |
} |
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
type formatStringInterpolator interface { |
| 738 |
|
| 739 |
|
| 740 |
String(ref.Val, string) (string, error) |
| 741 |
|
| 742 |
|
| 743 |
|
| 744 |
Decimal(ref.Val, string) (string, error) |
| 745 |
|
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
Fixed(*int) func(ref.Val, string) (string, error) |
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
Scientific(*int) func(ref.Val, string) (string, error) |
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
Binary(ref.Val, string) (string, error) |
| 759 |
|
| 760 |
|
| 761 |
|
| 762 |
Hex(bool) func(ref.Val, string) (string, error) |
| 763 |
|
| 764 |
|
| 765 |
|
| 766 |
Octal(ref.Val, string) (string, error) |
| 767 |
} |
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
type formatListArgs interface { |
| 772 |
|
| 773 |
Arg(int64) (ref.Val, error) |
| 774 |
|
| 775 |
|
| 776 |
Size() int64 |
| 777 |
} |
| 778 |
|
| 779 |
|
| 780 |
|
| 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 |
|
| 828 |
|
| 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 |
|
| 911 |
func (e parseFormatError) Error() string { |
| 912 |
return fmt.Sprintf("%s: %s", e.msg, e.wrapped.Error()) |
| 913 |
} |
| 914 |
|
| 915 |
|
| 916 |
func (e parseFormatError) Is(target error) bool { |
| 917 |
return e.Error() == target.Error() |
| 918 |
} |
| 919 |
|
| 920 |
|
| 921 |
func (e parseFormatError) Unwrap() error { |
| 922 |
return e.wrapped |
| 923 |
} |
| 924 |
|
| 925 |
const ( |
| 926 |
runtimeID = int64(-1) |
| 927 |
) |