| 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 | "time" |
| 25 | "unicode" |
| 26 | |
| 27 | "github.com/google/cel-go/cel" |
| 28 | "github.com/google/cel-go/common/ast" |
| 29 | "github.com/google/cel-go/common/types" |
| 30 | "github.com/google/cel-go/common/types/ref" |
| 31 | "github.com/google/cel-go/common/types/traits" |
| 32 | ) |
| 33 | |
| 34 | type clauseImplV2 func(ref.Val) (string, error) |
| 35 | |
| 36 | type appendingFormatterV2 struct { |
| 37 | buf []byte |
| 38 | } |
| 39 | |
| 40 | type formattedMapEntryV2 struct { |
| 41 | key string |
| 42 | val string |
| 43 | } |
| 44 | |
| 45 | func (af *appendingFormatterV2) format(arg ref.Val) error { |
| 46 | switch arg.Type() { |
| 47 | case types.BoolType: |
| 48 | argBool, ok := arg.Value().(bool) |
| 49 | if !ok { |
| 50 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.BoolType) |
| 51 | } |
| 52 | af.buf = strconv.AppendBool(af.buf, argBool) |
| 53 | return nil |
| 54 | case types.IntType: |
| 55 | argInt, ok := arg.Value().(int64) |
| 56 | if !ok { |
| 57 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.IntType) |
| 58 | } |
| 59 | af.buf = strconv.AppendInt(af.buf, argInt, 10) |
| 60 | return nil |
| 61 | case types.UintType: |
| 62 | argUint, ok := arg.Value().(uint64) |
| 63 | if !ok { |
| 64 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.UintType) |
| 65 | } |
| 66 | af.buf = strconv.AppendUint(af.buf, argUint, 10) |
| 67 | return nil |
| 68 | case types.DoubleType: |
| 69 | argDbl, ok := arg.Value().(float64) |
| 70 | if !ok { |
| 71 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.DoubleType) |
| 72 | } |
| 73 | if math.IsNaN(argDbl) { |
| 74 | af.buf = append(af.buf, "NaN"...) |
| 75 | return nil |
| 76 | } |
| 77 | if math.IsInf(argDbl, -1) { |
| 78 | af.buf = append(af.buf, "-Infinity"...) |
| 79 | return nil |
| 80 | } |
| 81 | if math.IsInf(argDbl, 1) { |
| 82 | af.buf = append(af.buf, "Infinity"...) |
| 83 | return nil |
| 84 | } |
| 85 | af.buf = strconv.AppendFloat(af.buf, argDbl, 'f', -1, 64) |
| 86 | return nil |
| 87 | case types.BytesType: |
| 88 | argBytes, ok := arg.Value().([]byte) |
| 89 | if !ok { |
| 90 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.BytesType) |
| 91 | } |
| 92 | af.buf = append(af.buf, argBytes...) |
| 93 | return nil |
| 94 | case types.StringType: |
| 95 | argStr, ok := arg.Value().(string) |
| 96 | if !ok { |
| 97 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.StringType) |
| 98 | } |
| 99 | af.buf = append(af.buf, argStr...) |
| 100 | return nil |
| 101 | case types.DurationType: |
| 102 | argDur, ok := arg.Value().(time.Duration) |
| 103 | if !ok { |
| 104 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.DurationType) |
| 105 | } |
| 106 | af.buf = strconv.AppendFloat(af.buf, argDur.Seconds(), 'f', -1, 64) |
| 107 | af.buf = append(af.buf, "s"...) |
| 108 | return nil |
| 109 | case types.TimestampType: |
| 110 | argTime, ok := arg.Value().(time.Time) |
| 111 | if !ok { |
| 112 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.TimestampType) |
| 113 | } |
| 114 | af.buf = argTime.UTC().AppendFormat(af.buf, time.RFC3339Nano) |
| 115 | return nil |
| 116 | case types.NullType: |
| 117 | af.buf = append(af.buf, "null"...) |
| 118 | return nil |
| 119 | case types.TypeType: |
| 120 | argType, ok := arg.Value().(string) |
| 121 | if !ok { |
| 122 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.TypeType) |
| 123 | } |
| 124 | af.buf = append(af.buf, argType...) |
| 125 | return nil |
| 126 | case types.ListType: |
| 127 | argList, ok := arg.(traits.Lister) |
| 128 | if !ok { |
| 129 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.ListType) |
| 130 | } |
| 131 | argIter := argList.Iterator() |
| 132 | af.buf = append(af.buf, "["...) |
| 133 | if argIter.HasNext() == types.True { |
| 134 | if err := af.format(argIter.Next()); err != nil { |
| 135 | return err |
| 136 | } |
| 137 | for argIter.HasNext() == types.True { |
| 138 | af.buf = append(af.buf, ", "...) |
| 139 | if err := af.format(argIter.Next()); err != nil { |
| 140 | return err |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | af.buf = append(af.buf, "]"...) |
| 145 | return nil |
| 146 | case types.MapType: |
| 147 | argMap, ok := arg.(traits.Mapper) |
| 148 | if !ok { |
| 149 | return fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.MapType) |
| 150 | } |
| 151 | argIter := argMap.Iterator() |
| 152 | ents := []formattedMapEntryV2{} |
| 153 | for argIter.HasNext() == types.True { |
| 154 | key := argIter.Next() |
| 155 | val, ok := argMap.Find(key) |
| 156 | if !ok { |
| 157 | return fmt.Errorf("key missing from map: '%s'", key) |
| 158 | } |
| 159 | keyStr, err := formatStringV2(key) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | valStr, err := formatStringV2(val) |
| 164 | if err != nil { |
| 165 | return err |
| 166 | } |
| 167 | ents = append(ents, formattedMapEntryV2{keyStr, valStr}) |
| 168 | } |
| 169 | sort.SliceStable(ents, func(x, y int) bool { |
| 170 | return ents[x].key < ents[y].key |
| 171 | }) |
| 172 | af.buf = append(af.buf, "{"...) |
| 173 | for i, e := range ents { |
| 174 | if i > 0 { |
| 175 | af.buf = append(af.buf, ", "...) |
| 176 | } |
| 177 | af.buf = append(af.buf, e.key...) |
| 178 | af.buf = append(af.buf, ": "...) |
| 179 | af.buf = append(af.buf, e.val...) |
| 180 | } |
| 181 | af.buf = append(af.buf, "}"...) |
| 182 | return nil |
| 183 | default: |
| 184 | return stringFormatErrorV2(runtimeID, arg.Type().TypeName()) |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | func formatStringV2(arg ref.Val) (string, error) { |
| 189 | var fmter appendingFormatterV2 |
| 190 | if err := fmter.format(arg); err != nil { |
| 191 | return "", err |
| 192 | } |
| 193 | return string(fmter.buf), nil |
| 194 | } |
| 195 | |
| 196 | type stringFormatterV2 struct{} |
| 197 | |
| 198 | // String implements formatStringInterpolatorV2.String. |
| 199 | func (c *stringFormatterV2) String(arg ref.Val) (string, error) { |
| 200 | return formatStringV2(arg) |
| 201 | } |
| 202 | |
| 203 | // Decimal implements formatStringInterpolatorV2.Decimal. |
| 204 | func (c *stringFormatterV2) Decimal(arg ref.Val) (string, error) { |
| 205 | switch arg.Type() { |
| 206 | case types.IntType: |
| 207 | argInt, ok := arg.Value().(int64) |
| 208 | if !ok { |
| 209 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.IntType) |
| 210 | } |
| 211 | return strconv.FormatInt(argInt, 10), nil |
| 212 | case types.UintType: |
| 213 | argUint, ok := arg.Value().(uint64) |
| 214 | if !ok { |
| 215 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.UintType) |
| 216 | } |
| 217 | return strconv.FormatUint(argUint, 10), nil |
| 218 | case types.DoubleType: |
| 219 | argDbl, ok := arg.Value().(float64) |
| 220 | if !ok { |
| 221 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.DoubleType) |
| 222 | } |
| 223 | if math.IsNaN(argDbl) { |
| 224 | return "NaN", nil |
| 225 | } |
| 226 | if math.IsInf(argDbl, -1) { |
| 227 | return "-Infinity", nil |
| 228 | } |
| 229 | if math.IsInf(argDbl, 1) { |
| 230 | return "Infinity", nil |
| 231 | } |
| 232 | return strconv.FormatFloat(argDbl, 'f', -1, 64), nil |
| 233 | default: |
| 234 | return "", decimalFormatErrorV2(runtimeID, arg.Type().TypeName()) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | // Fixed implements formatStringInterpolatorV2.Fixed. |
| 239 | func (c *stringFormatterV2) Fixed(precision int) func(ref.Val) (string, error) { |
| 240 | return func(arg ref.Val) (string, error) { |
| 241 | fmtStr := fmt.Sprintf("%%.%df", precision) |
| 242 | switch arg.Type() { |
| 243 | case types.IntType: |
| 244 | argInt, ok := arg.Value().(int64) |
| 245 | if !ok { |
| 246 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.IntType) |
| 247 | } |
| 248 | return fmt.Sprintf(fmtStr, float64(argInt)), nil |
| 249 | case types.UintType: |
| 250 | argUint, ok := arg.Value().(uint64) |
| 251 | if !ok { |
| 252 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.UintType) |
| 253 | } |
| 254 | return fmt.Sprintf(fmtStr, float64(argUint)), nil |
| 255 | case types.DoubleType: |
| 256 | argDbl, ok := arg.Value().(float64) |
| 257 | if !ok { |
| 258 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.DoubleType) |
| 259 | } |
| 260 | if math.IsNaN(argDbl) { |
| 261 | return "NaN", nil |
| 262 | } |
| 263 | if math.IsInf(argDbl, -1) { |
| 264 | return "-Infinity", nil |
| 265 | } |
| 266 | if math.IsInf(argDbl, 1) { |
| 267 | return "Infinity", nil |
| 268 | } |
| 269 | return fmt.Sprintf(fmtStr, argDbl), nil |
| 270 | default: |
| 271 | return "", fixedPointFormatErrorV2(runtimeID, arg.Type().TypeName()) |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | // Scientific implements formatStringInterpolatorV2.Scientific. |
| 277 | func (c *stringFormatterV2) Scientific(precision int) func(ref.Val) (string, error) { |
| 278 | return func(arg ref.Val) (string, error) { |
| 279 | fmtStr := fmt.Sprintf("%%1.%de", precision) |
| 280 | switch arg.Type() { |
| 281 | case types.IntType: |
| 282 | argInt, ok := arg.Value().(int64) |
| 283 | if !ok { |
| 284 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.IntType) |
| 285 | } |
| 286 | return fmt.Sprintf(fmtStr, float64(argInt)), nil |
| 287 | case types.UintType: |
| 288 | argUint, ok := arg.Value().(uint64) |
| 289 | if !ok { |
| 290 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.UintType) |
| 291 | } |
| 292 | return fmt.Sprintf(fmtStr, float64(argUint)), nil |
| 293 | case types.DoubleType: |
| 294 | argDbl, ok := arg.Value().(float64) |
| 295 | if !ok { |
| 296 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.DoubleType) |
| 297 | } |
| 298 | if math.IsNaN(argDbl) { |
| 299 | return "NaN", nil |
| 300 | } |
| 301 | if math.IsInf(argDbl, -1) { |
| 302 | return "-Infinity", nil |
| 303 | } |
| 304 | if math.IsInf(argDbl, 1) { |
| 305 | return "Infinity", nil |
| 306 | } |
| 307 | return fmt.Sprintf(fmtStr, argDbl), nil |
| 308 | default: |
| 309 | return "", scientificFormatErrorV2(runtimeID, arg.Type().TypeName()) |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | |
| 314 | // Binary implements formatStringInterpolatorV2.Binary. |
| 315 | func (c *stringFormatterV2) Binary(arg ref.Val) (string, error) { |
| 316 | switch arg.Type() { |
| 317 | case types.BoolType: |
| 318 | argBool, ok := arg.Value().(bool) |
| 319 | if !ok { |
| 320 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.BoolType) |
| 321 | } |
| 322 | if argBool { |
| 323 | return "1", nil |
| 324 | } |
| 325 | return "0", nil |
| 326 | case types.IntType: |
| 327 | argInt, ok := arg.Value().(int64) |
| 328 | if !ok { |
| 329 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.IntType) |
| 330 | } |
| 331 | return strconv.FormatInt(argInt, 2), nil |
| 332 | case types.UintType: |
| 333 | argUint, ok := arg.Value().(uint64) |
| 334 | if !ok { |
| 335 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.UintType) |
| 336 | } |
| 337 | return strconv.FormatUint(argUint, 2), nil |
| 338 | default: |
| 339 | return "", binaryFormatErrorV2(runtimeID, arg.Type().TypeName()) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | // Hex implements formatStringInterpolatorV2.Hex. |
| 344 | func (c *stringFormatterV2) Hex(useUpper bool) func(ref.Val) (string, error) { |
| 345 | return func(arg ref.Val) (string, error) { |
| 346 | var fmtStr string |
| 347 | if useUpper { |
| 348 | fmtStr = "%X" |
| 349 | } else { |
| 350 | fmtStr = "%x" |
| 351 | } |
| 352 | switch arg.Type() { |
| 353 | case types.IntType: |
| 354 | argInt, ok := arg.Value().(int64) |
| 355 | if !ok { |
| 356 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.IntType) |
| 357 | } |
| 358 | return fmt.Sprintf(fmtStr, argInt), nil |
| 359 | case types.UintType: |
| 360 | argUint, ok := arg.Value().(uint64) |
| 361 | if !ok { |
| 362 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.UintType) |
| 363 | } |
| 364 | return fmt.Sprintf(fmtStr, argUint), nil |
| 365 | case types.StringType: |
| 366 | argStr, ok := arg.Value().(string) |
| 367 | if !ok { |
| 368 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.StringType) |
| 369 | } |
| 370 | return fmt.Sprintf(fmtStr, argStr), nil |
| 371 | case types.BytesType: |
| 372 | argBytes, ok := arg.Value().([]byte) |
| 373 | if !ok { |
| 374 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.BytesType) |
| 375 | } |
| 376 | return fmt.Sprintf(fmtStr, argBytes), nil |
| 377 | default: |
| 378 | return "", hexFormatErrorV2(runtimeID, arg.Type().TypeName()) |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | // Octal implements formatStringInterpolatorV2.Octal. |
| 384 | func (c *stringFormatterV2) Octal(arg ref.Val) (string, error) { |
| 385 | switch arg.Type() { |
| 386 | case types.IntType: |
| 387 | argInt, ok := arg.Value().(int64) |
| 388 | if !ok { |
| 389 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.IntType) |
| 390 | } |
| 391 | return strconv.FormatInt(argInt, 8), nil |
| 392 | case types.UintType: |
| 393 | argUint, ok := arg.Value().(uint64) |
| 394 | if !ok { |
| 395 | return "", fmt.Errorf("type conversion error from '%s' to '%s'", arg.Type(), types.UintType) |
| 396 | } |
| 397 | return strconv.FormatUint(argUint, 8), nil |
| 398 | default: |
| 399 | return "", octalFormatErrorV2(runtimeID, arg.Type().TypeName()) |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | // stringFormatValidatorV2 implements the cel.ASTValidator interface allowing for static validation |
| 404 | // of string.format calls. |
| 405 | type stringFormatValidatorV2 struct{} |
| 406 | |
| 407 | // Name returns the name of the validator. |
| 408 | func (stringFormatValidatorV2) Name() string { |
| 409 | return "cel.validator.string_format" |
| 410 | } |
| 411 | |
| 412 | // Configure implements the ASTValidatorConfigurer interface and augments the list of functions to skip |
| 413 | // during homogeneous aggregate literal type-checks. |
| 414 | func (stringFormatValidatorV2) Configure(config cel.MutableValidatorConfig) error { |
| 415 | functions := config.GetOrDefault(cel.HomogeneousAggregateLiteralExemptFunctions, []string{}).([]string) |
| 416 | functions = append(functions, "format") |
| 417 | return config.Set(cel.HomogeneousAggregateLiteralExemptFunctions, functions) |
| 418 | } |
| 419 | |
| 420 | // Validate parses all literal format strings and type checks the format clause against the argument |
| 421 | // at the corresponding ordinal within the list literal argument to the function, if one is specified. |
| 422 | func (stringFormatValidatorV2) Validate(env *cel.Env, _ cel.ValidatorConfig, a *ast.AST, iss *cel.Issues) { |
| 423 | root := ast.NavigateAST(a) |
| 424 | formatCallExprs := ast.MatchDescendants(root, matchConstantFormatStringWithListLiteralArgs(a)) |
| 425 | for _, e := range formatCallExprs { |
| 426 | call := e.AsCall() |
| 427 | formatStr := call.Target().AsLiteral().Value().(string) |
| 428 | args := call.Args()[0].AsList().Elements() |
| 429 | formatCheck := &stringFormatCheckerV2{ |
| 430 | args: args, |
| 431 | ast: a, |
| 432 | } |
| 433 | // use a placeholder locale, since locale doesn't affect syntax |
| 434 | _, err := parseFormatStringV2(formatStr, formatCheck, formatCheck) |
| 435 | if err != nil { |
| 436 | iss.ReportErrorAtID(getErrorExprID(e.ID(), err), "%v", err) |
| 437 | continue |
| 438 | } |
| 439 | seenArgs := formatCheck.argsRequested |
| 440 | if len(args) > seenArgs { |
| 441 | iss.ReportErrorAtID(e.ID(), |
| 442 | "too many arguments supplied to string.format (expected %d, got %d)", seenArgs, len(args)) |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | // stringFormatCheckerV2 implements the formatStringInterpolater interface |
| 448 | type stringFormatCheckerV2 struct { |
| 449 | args []ast.Expr |
| 450 | argsRequested int |
| 451 | currArgIndex int64 |
| 452 | ast *ast.AST |
| 453 | } |
| 454 | |
| 455 | // String implements formatStringInterpolatorV2.String. |
| 456 | func (c *stringFormatCheckerV2) String(arg ref.Val) (string, error) { |
| 457 | formatArg := c.args[c.currArgIndex] |
| 458 | valid, badID := c.verifyString(formatArg) |
| 459 | if !valid { |
| 460 | return "", stringFormatErrorV2(badID, c.typeOf(badID).TypeName()) |
| 461 | } |
| 462 | return "", nil |
| 463 | } |
| 464 | |
| 465 | // Decimal implements formatStringInterpolatorV2.Decimal. |
| 466 | func (c *stringFormatCheckerV2) Decimal(arg ref.Val) (string, error) { |
| 467 | id := c.args[c.currArgIndex].ID() |
| 468 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType, types.DoubleType) |
| 469 | if !valid { |
| 470 | return "", decimalFormatErrorV2(id, c.typeOf(id).TypeName()) |
| 471 | } |
| 472 | return "", nil |
| 473 | } |
| 474 | |
| 475 | // Fixed implements formatStringInterpolatorV2.Fixed. |
| 476 | func (c *stringFormatCheckerV2) Fixed(precision int) func(ref.Val) (string, error) { |
| 477 | return func(arg ref.Val) (string, error) { |
| 478 | id := c.args[c.currArgIndex].ID() |
| 479 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType, types.DoubleType) |
| 480 | if !valid { |
| 481 | return "", fixedPointFormatErrorV2(id, c.typeOf(id).TypeName()) |
| 482 | } |
| 483 | return "", nil |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | // Scientific implements formatStringInterpolatorV2.Scientific. |
| 488 | func (c *stringFormatCheckerV2) Scientific(precision int) func(ref.Val) (string, error) { |
| 489 | return func(arg ref.Val) (string, error) { |
| 490 | id := c.args[c.currArgIndex].ID() |
| 491 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType, types.DoubleType) |
| 492 | if !valid { |
| 493 | return "", scientificFormatErrorV2(id, c.typeOf(id).TypeName()) |
| 494 | } |
| 495 | return "", nil |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | // Binary implements formatStringInterpolatorV2.Binary. |
| 500 | func (c *stringFormatCheckerV2) Binary(arg ref.Val) (string, error) { |
| 501 | id := c.args[c.currArgIndex].ID() |
| 502 | valid := c.verifyTypeOneOf(id, types.BoolType, types.IntType, types.UintType) |
| 503 | if !valid { |
| 504 | return "", binaryFormatErrorV2(id, c.typeOf(id).TypeName()) |
| 505 | } |
| 506 | return "", nil |
| 507 | } |
| 508 | |
| 509 | // Hex implements formatStringInterpolatorV2.Hex. |
| 510 | func (c *stringFormatCheckerV2) Hex(useUpper bool) func(ref.Val) (string, error) { |
| 511 | return func(arg ref.Val) (string, error) { |
| 512 | id := c.args[c.currArgIndex].ID() |
| 513 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType, types.StringType, types.BytesType) |
| 514 | if !valid { |
| 515 | return "", hexFormatErrorV2(id, c.typeOf(id).TypeName()) |
| 516 | } |
| 517 | return "", nil |
| 518 | } |
| 519 | } |
| 520 | |
| 521 | // Octal implements formatStringInterpolatorV2.Octal. |
| 522 | func (c *stringFormatCheckerV2) Octal(arg ref.Val) (string, error) { |
| 523 | id := c.args[c.currArgIndex].ID() |
| 524 | valid := c.verifyTypeOneOf(id, types.IntType, types.UintType) |
| 525 | if !valid { |
| 526 | return "", octalFormatErrorV2(id, c.typeOf(id).TypeName()) |
| 527 | } |
| 528 | return "", nil |
| 529 | } |
| 530 | |
| 531 | // Arg implements formatListArgs.Arg. |
| 532 | func (c *stringFormatCheckerV2) Arg(index int64) (ref.Val, error) { |
| 533 | c.argsRequested++ |
| 534 | c.currArgIndex = index |
| 535 | // return a dummy value - this is immediately passed to back to us |
| 536 | // through one of the FormatCallback functions, so anything will do |
| 537 | return types.Int(0), nil |
| 538 | } |
| 539 | |
| 540 | // Size implements formatListArgs.Size. |
| 541 | func (c *stringFormatCheckerV2) Size() int64 { |
| 542 | return int64(len(c.args)) |
| 543 | } |
| 544 | |
| 545 | func (c *stringFormatCheckerV2) typeOf(id int64) *cel.Type { |
| 546 | return c.ast.GetType(id) |
| 547 | } |
| 548 | |
| 549 | func (c *stringFormatCheckerV2) verifyTypeOneOf(id int64, validTypes ...*cel.Type) bool { |
| 550 | t := c.typeOf(id) |
| 551 | if t == cel.DynType { |
| 552 | return true |
| 553 | } |
| 554 | for _, vt := range validTypes { |
| 555 | // Only check runtime type compatibility without delving deeper into parameterized types |
| 556 | if t.Kind() == vt.Kind() { |
| 557 | return true |
| 558 | } |
| 559 | } |
| 560 | return false |
| 561 | } |
| 562 | |
| 563 | func (c *stringFormatCheckerV2) verifyString(sub ast.Expr) (bool, int64) { |
| 564 | paramA := cel.TypeParamType("A") |
| 565 | paramB := cel.TypeParamType("B") |
| 566 | subVerified := c.verifyTypeOneOf(sub.ID(), |
| 567 | cel.ListType(paramA), cel.MapType(paramA, paramB), |
| 568 | cel.IntType, cel.UintType, cel.DoubleType, cel.BoolType, cel.StringType, |
| 569 | cel.TimestampType, cel.BytesType, cel.DurationType, cel.TypeType, cel.NullType) |
| 570 | if !subVerified { |
| 571 | return false, sub.ID() |
| 572 | } |
| 573 | switch sub.Kind() { |
| 574 | case ast.ListKind: |
| 575 | for _, e := range sub.AsList().Elements() { |
| 576 | // recursively verify if we're dealing with a list/map |
| 577 | verified, id := c.verifyString(e) |
| 578 | if !verified { |
| 579 | return false, id |
| 580 | } |
| 581 | } |
| 582 | return true, sub.ID() |
| 583 | case ast.MapKind: |
| 584 | for _, e := range sub.AsMap().Entries() { |
| 585 | // recursively verify if we're dealing with a list/map |
| 586 | entry := e.AsMapEntry() |
| 587 | verified, id := c.verifyString(entry.Key()) |
| 588 | if !verified { |
| 589 | return false, id |
| 590 | } |
| 591 | verified, id = c.verifyString(entry.Value()) |
| 592 | if !verified { |
| 593 | return false, id |
| 594 | } |
| 595 | } |
| 596 | return true, sub.ID() |
| 597 | default: |
| 598 | return true, sub.ID() |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | // helper routines for reporting common errors during string formatting static validation and |
| 603 | // runtime execution. |
| 604 | |
| 605 | func binaryFormatErrorV2(id int64, badType string) error { |
| 606 | return newFormatError(id, "only ints, uints, and bools can be formatted as binary, was given %s", badType) |
| 607 | } |
| 608 | |
| 609 | func decimalFormatErrorV2(id int64, badType string) error { |
| 610 | return newFormatError(id, "decimal clause can only be used on ints, uints, and doubles, was given %s", badType) |
| 611 | } |
| 612 | |
| 613 | func fixedPointFormatErrorV2(id int64, badType string) error { |
| 614 | return newFormatError(id, "fixed-point clause can only be used on ints, uints, and doubles, was given %s", badType) |
| 615 | } |
| 616 | |
| 617 | func hexFormatErrorV2(id int64, badType string) error { |
| 618 | return newFormatError(id, "only ints, uints, bytes, and strings can be formatted as hex, was given %s", badType) |
| 619 | } |
| 620 | |
| 621 | func octalFormatErrorV2(id int64, badType string) error { |
| 622 | return newFormatError(id, "octal clause can only be used on ints and uints, was given %s", badType) |
| 623 | } |
| 624 | |
| 625 | func scientificFormatErrorV2(id int64, badType string) error { |
| 626 | return newFormatError(id, "scientific clause can only be used on ints, uints, and doubles, was given %s", badType) |
| 627 | } |
| 628 | |
| 629 | func stringFormatErrorV2(id int64, badType string) error { |
| 630 | 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) |
| 631 | } |
| 632 | |
| 633 | // formatStringInterpolatorV2 is an interface that allows user-defined behavior |
| 634 | // for formatting clause implementations, as well as argument retrieval. |
| 635 | // Each function is expected to support the appropriate types as laid out in |
| 636 | // the string.format documentation, and to return an error if given an inappropriate type. |
| 637 | type formatStringInterpolatorV2 interface { |
| 638 | // String takes a ref.Val and a string representing the current locale identifier |
| 639 | // and returns the Val formatted as a string, or an error if one occurred. |
| 640 | String(ref.Val) (string, error) |
| 641 | |
| 642 | // Decimal takes a ref.Val and a string representing the current locale identifier |
| 643 | // and returns the Val formatted as a decimal integer, or an error if one occurred. |
| 644 | Decimal(ref.Val) (string, error) |
| 645 | |
| 646 | // Fixed takes an int pointer representing precision (or nil if none was given) and |
| 647 | // returns a function operating in a similar manner to String and Decimal, taking a |
| 648 | // ref.Val and locale and returning the appropriate string. A closure is returned |
| 649 | // so precision can be set without needing an additional function call/configuration. |
| 650 | Fixed(int) func(ref.Val) (string, error) |
| 651 | |
| 652 | // Scientific functions identically to Fixed, except the string returned from the closure |
| 653 | // is expected to be in scientific notation. |
| 654 | Scientific(int) func(ref.Val) (string, error) |
| 655 | |
| 656 | // Binary takes a ref.Val and a string representing the current locale identifier |
| 657 | // and returns the Val formatted as a binary integer, or an error if one occurred. |
| 658 | Binary(ref.Val) (string, error) |
| 659 | |
| 660 | // Hex takes a boolean that, if true, indicates the hex string output by the returned |
| 661 | // closure should use uppercase letters for A-F. |
| 662 | Hex(bool) func(ref.Val) (string, error) |
| 663 | |
| 664 | // Octal takes a ref.Val and a string representing the current locale identifier and |
| 665 | // returns the Val formatted in octal, or an error if one occurred. |
| 666 | Octal(ref.Val) (string, error) |
| 667 | } |
| 668 | |
| 669 | // parseFormatString formats a string according to the string.format syntax, taking the clause implementations |
| 670 | // from the provided FormatCallback and the args from the given FormatList. |
| 671 | func parseFormatStringV2(formatStr string, callback formatStringInterpolatorV2, list formatListArgs) (string, error) { |
| 672 | i := 0 |
| 673 | argIndex := 0 |
| 674 | var builtStr strings.Builder |
| 675 | for i < len(formatStr) { |
| 676 | if formatStr[i] == '%' { |
| 677 | if i+1 < len(formatStr) && formatStr[i+1] == '%' { |
| 678 | err := builtStr.WriteByte('%') |
| 679 | if err != nil { |
| 680 | return "", fmt.Errorf("error writing format string: %w", err) |
| 681 | } |
| 682 | i += 2 |
| 683 | continue |
| 684 | } else { |
| 685 | argAny, err := list.Arg(int64(argIndex)) |
| 686 | if err != nil { |
| 687 | return "", err |
| 688 | } |
| 689 | if i+1 >= len(formatStr) { |
| 690 | return "", errors.New("unexpected end of string") |
| 691 | } |
| 692 | if int64(argIndex) >= list.Size() { |
| 693 | return "", fmt.Errorf("index %d out of range", argIndex) |
| 694 | } |
| 695 | numRead, val, refErr := parseAndFormatClauseV2(formatStr[i:], argAny, callback, list) |
| 696 | if refErr != nil { |
| 697 | return "", refErr |
| 698 | } |
| 699 | _, err = builtStr.WriteString(val) |
| 700 | if err != nil { |
| 701 | return "", fmt.Errorf("error writing format string: %w", err) |
| 702 | } |
| 703 | i += numRead |
| 704 | argIndex++ |
| 705 | } |
| 706 | } else { |
| 707 | err := builtStr.WriteByte(formatStr[i]) |
| 708 | if err != nil { |
| 709 | return "", fmt.Errorf("error writing format string: %w", err) |
| 710 | } |
| 711 | i++ |
| 712 | } |
| 713 | } |
| 714 | return builtStr.String(), nil |
| 715 | } |
| 716 | |
| 717 | // parseAndFormatClause parses the format clause at the start of the given string with val, and returns |
| 718 | // how many characters were consumed and the substituted string form of val, or an error if one occurred. |
| 719 | func parseAndFormatClauseV2(formatStr string, val ref.Val, callback formatStringInterpolatorV2, list formatListArgs) (int, string, error) { |
| 720 | i := 1 |
| 721 | read, formatter, err := parseFormattingClauseV2(formatStr[i:], callback) |
| 722 | i += read |
| 723 | if err != nil { |
| 724 | return -1, "", newParseFormatError("could not parse formatting clause", err) |
| 725 | } |
| 726 | |
| 727 | valStr, err := formatter(val) |
| 728 | if err != nil { |
| 729 | return -1, "", newParseFormatError("error during formatting", err) |
| 730 | } |
| 731 | return i, valStr, nil |
| 732 | } |
| 733 | |
| 734 | func parseFormattingClauseV2(formatStr string, callback formatStringInterpolatorV2) (int, clauseImplV2, error) { |
| 735 | i := 0 |
| 736 | read, precision, err := parsePrecisionV2(formatStr[i:]) |
| 737 | i += read |
| 738 | if err != nil { |
| 739 | return -1, nil, fmt.Errorf("error while parsing precision: %w", err) |
| 740 | } |
| 741 | r := rune(formatStr[i]) |
| 742 | i++ |
| 743 | switch r { |
| 744 | case 's': |
| 745 | return i, callback.String, nil |
| 746 | case 'd': |
| 747 | return i, callback.Decimal, nil |
| 748 | case 'f': |
| 749 | return i, callback.Fixed(precision), nil |
| 750 | case 'e': |
| 751 | return i, callback.Scientific(precision), nil |
| 752 | case 'b': |
| 753 | return i, callback.Binary, nil |
| 754 | case 'x', 'X': |
| 755 | return i, callback.Hex(unicode.IsUpper(r)), nil |
| 756 | case 'o': |
| 757 | return i, callback.Octal, nil |
| 758 | default: |
| 759 | return -1, nil, fmt.Errorf("unrecognized formatting clause \"%c\"", r) |
| 760 | } |
| 761 | } |
| 762 | |
| 763 | func parsePrecisionV2(formatStr string) (int, int, error) { |
| 764 | i := 0 |
| 765 | if formatStr[i] != '.' { |
| 766 | return i, defaultPrecision, nil |
| 767 | } |
| 768 | i++ |
| 769 | var buffer strings.Builder |
| 770 | for { |
| 771 | if i >= len(formatStr) { |
| 772 | return -1, -1, errors.New("could not find end of precision specifier") |
| 773 | } |
| 774 | if !isASCIIDigit(rune(formatStr[i])) { |
| 775 | break |
| 776 | } |
| 777 | buffer.WriteByte(formatStr[i]) |
| 778 | i++ |
| 779 | } |
| 780 | precision, err := strconv.Atoi(buffer.String()) |
| 781 | if err != nil { |
| 782 | return -1, -1, fmt.Errorf("error while converting precision to integer: %w", err) |
| 783 | } |
| 784 | if precision < 0 { |
| 785 | return -1, -1, fmt.Errorf("negative precision: %d", precision) |
| 786 | } |
| 787 | return i, precision, nil |
| 788 | } |