| 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 cel |
| 16 | |
| 17 | import ( |
| 18 | "reflect" |
| 19 | "sort" |
| 20 | "strings" |
| 21 | "testing" |
| 22 | |
| 23 | "google.golang.org/protobuf/encoding/prototext" |
| 24 | "google.golang.org/protobuf/proto" |
| 25 | |
| 26 | "github.com/google/cel-go/common/ast" |
| 27 | "github.com/google/cel-go/common/types" |
| 28 | "github.com/google/cel-go/common/types/ref" |
| 29 | |
| 30 | proto3pb "github.com/google/cel-go/test/proto3pb" |
| 31 | exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" |
| 32 | ) |
| 33 | |
| 34 | func TestConstantFoldingOptimizer(t *testing.T) { |
| 35 | tests := []struct { |
| 36 | expr string |
| 37 | folded string |
| 38 | knownValues map[string]any |
| 39 | }{ |
| 40 | { |
| 41 | expr: `[1, 1 + 2, 1 + (2 + 3)]`, |
| 42 | folded: `[1, 3, 6]`, |
| 43 | }, |
| 44 | { |
| 45 | expr: `6 in [1, 1 + 2, 1 + (2 + 3)]`, |
| 46 | folded: `true`, |
| 47 | }, |
| 48 | { |
| 49 | expr: `5 in [1, 1 + 2, 1 + (2 + 3)]`, |
| 50 | folded: `false`, |
| 51 | }, |
| 52 | { |
| 53 | expr: `x in [1, 1 + 2, 1 + (2 + 3)]`, |
| 54 | folded: `x in [1, 3, 6]`, |
| 55 | }, |
| 56 | { |
| 57 | expr: `1 in [1, x + 2, 1 + (2 + 3)]`, |
| 58 | folded: `true`, |
| 59 | }, |
| 60 | { |
| 61 | expr: `1 in [x, x + 2, 1 + (2 + 3)]`, |
| 62 | folded: `1 in [x, x + 2, 6]`, |
| 63 | }, |
| 64 | { |
| 65 | expr: `x in []`, |
| 66 | folded: `false`, |
| 67 | }, |
| 68 | { |
| 69 | expr: `{'hello': 'world'}.hello == x`, |
| 70 | folded: `"world" == x`, |
| 71 | }, |
| 72 | { |
| 73 | expr: `{'hello': 'world'}.?hello.orValue('default') == x`, |
| 74 | folded: `"world" == x`, |
| 75 | }, |
| 76 | { |
| 77 | expr: `{'hello': 'world'}['hello'] == x`, |
| 78 | folded: `"world" == x`, |
| 79 | }, |
| 80 | { |
| 81 | expr: `optional.of("hello")`, |
| 82 | folded: `optional.of("hello")`, |
| 83 | }, |
| 84 | { |
| 85 | expr: `optional.ofNonZeroValue("")`, |
| 86 | folded: `optional.none()`, |
| 87 | }, |
| 88 | { |
| 89 | expr: `{?'hello': optional.of('world')}['hello'] == x`, |
| 90 | folded: `"world" == x`, |
| 91 | }, |
| 92 | { |
| 93 | expr: `duration(string(7 * 24) + 'h')`, |
| 94 | folded: `duration("604800s")`, |
| 95 | }, |
| 96 | { |
| 97 | expr: `timestamp("1970-01-01T00:00:00Z")`, |
| 98 | folded: `timestamp("1970-01-01T00:00:00Z")`, |
| 99 | }, |
| 100 | { |
| 101 | expr: `[1, 1 + 1, 1 + 2, 2 + 3].exists(i, i < 10)`, |
| 102 | folded: `true`, |
| 103 | }, |
| 104 | { |
| 105 | expr: `[1, 1 + 1, 1 + 2, 2 + 3].exists(i, i < 1 % 2)`, |
| 106 | folded: `false`, |
| 107 | }, |
| 108 | { |
| 109 | expr: `[1, 2, 3].map(i, [1, 2, 3].map(j, i * j))`, |
| 110 | folded: `[[1, 2, 3], [2, 4, 6], [3, 6, 9]]`, |
| 111 | }, |
| 112 | { |
| 113 | expr: `[1, 2, 3].map(i, [1, 2, 3].map(j, i * j).filter(k, k % 2 == 0))`, |
| 114 | folded: `[[2], [2, 4, 6], [6]]`, |
| 115 | }, |
| 116 | { |
| 117 | expr: `[1, 2, 3].map(i, [1, 2, 3].map(j, i * j).filter(k, k % 2 == x))`, |
| 118 | folded: `[1, 2, 3].map(i, [1, 2, 3].map(j, i * j).filter(k, k % 2 == x))`, |
| 119 | }, |
| 120 | { |
| 121 | expr: `[{}, {"a": 1}, {"b": 2}].filter(m, has(m.a))`, |
| 122 | folded: `[{"a": 1}]`, |
| 123 | }, |
| 124 | { |
| 125 | expr: `[{}, {"a": 1}, {"b": 2}].filter(m, has({'a': true}.a))`, |
| 126 | folded: `[{}, {"a": 1}, {"b": 2}]`, |
| 127 | }, |
| 128 | { |
| 129 | expr: `type(1)`, |
| 130 | folded: `int`, |
| 131 | }, |
| 132 | { |
| 133 | expr: `[google.expr.proto3.test.TestAllTypes{single_int32: 2 + 3}].map(i, i)[0]`, |
| 134 | folded: `google.expr.proto3.test.TestAllTypes{single_int32: 5}`, |
| 135 | }, |
| 136 | { |
| 137 | expr: `[?optional.ofNonZeroValue(0)]`, |
| 138 | folded: `[]`, |
| 139 | }, |
| 140 | { |
| 141 | expr: `[1, ?optional.ofNonZeroValue(0)]`, |
| 142 | folded: `[1]`, |
| 143 | }, |
| 144 | { |
| 145 | expr: `[optional.none(), ?x]`, |
| 146 | folded: `[optional.none(), ?x]`, |
| 147 | }, |
| 148 | { |
| 149 | expr: `[?optional.none(), ?x]`, |
| 150 | folded: `[?x]`, |
| 151 | }, |
| 152 | { |
| 153 | expr: `[1, x, ?optional.ofNonZeroValue(0), ?x.?y]`, |
| 154 | folded: `[1, x, ?x.?y]`, |
| 155 | }, |
| 156 | { |
| 157 | expr: `[1, x, ?optional.ofNonZeroValue(3), ?x.?y]`, |
| 158 | folded: `[1, x, 3, ?x.?y]`, |
| 159 | }, |
| 160 | { |
| 161 | expr: `[1, x, ?optional.ofNonZeroValue(3), ?x.?y].size() > 3`, |
| 162 | folded: `[1, x, 3, ?x.?y].size() > 3`, |
| 163 | }, |
| 164 | { |
| 165 | expr: `{?'a': optional.of('hello'), ?x : optional.of(1), ?'b': optional.none()}`, |
| 166 | folded: `{"a": "hello", ?x: optional.of(1)}`, |
| 167 | }, |
| 168 | { |
| 169 | expr: `true ? x + 1 : x + 2`, |
| 170 | folded: `x + 1`, |
| 171 | }, |
| 172 | { |
| 173 | expr: `false ? x + 1 : x + 2`, |
| 174 | folded: `x + 2`, |
| 175 | }, |
| 176 | { |
| 177 | expr: `false ? x + 'world' : 'hello' + 'world'`, |
| 178 | folded: `"helloworld"`, |
| 179 | }, |
| 180 | { |
| 181 | expr: `true && x`, |
| 182 | folded: `x`, |
| 183 | }, |
| 184 | { |
| 185 | expr: `x && true`, |
| 186 | folded: `x`, |
| 187 | }, |
| 188 | { |
| 189 | expr: `false && x`, |
| 190 | folded: `false`, |
| 191 | }, |
| 192 | { |
| 193 | expr: `x && false`, |
| 194 | folded: `false`, |
| 195 | }, |
| 196 | { |
| 197 | expr: `true || x`, |
| 198 | folded: `true`, |
| 199 | }, |
| 200 | { |
| 201 | expr: `x || true`, |
| 202 | folded: `true`, |
| 203 | }, |
| 204 | { |
| 205 | expr: `false || x`, |
| 206 | folded: `x`, |
| 207 | }, |
| 208 | { |
| 209 | expr: `x || false`, |
| 210 | folded: `x`, |
| 211 | }, |
| 212 | { |
| 213 | expr: `true && x && true && x`, |
| 214 | folded: `x && x`, |
| 215 | }, |
| 216 | { |
| 217 | expr: `false || x || false || x`, |
| 218 | folded: `x || x`, |
| 219 | }, |
| 220 | { |
| 221 | expr: `true && true`, |
| 222 | folded: `true`, |
| 223 | }, |
| 224 | { |
| 225 | expr: `true && false`, |
| 226 | folded: `false`, |
| 227 | }, |
| 228 | { |
| 229 | expr: `true || false`, |
| 230 | folded: `true`, |
| 231 | }, |
| 232 | { |
| 233 | expr: `false || false`, |
| 234 | folded: `false`, |
| 235 | }, |
| 236 | { |
| 237 | expr: `true && false || true`, |
| 238 | folded: `true`, |
| 239 | }, |
| 240 | { |
| 241 | expr: `false && true || false`, |
| 242 | folded: `false`, |
| 243 | }, |
| 244 | { |
| 245 | expr: `null`, |
| 246 | folded: `null`, |
| 247 | }, |
| 248 | { |
| 249 | expr: `google.expr.proto3.test.TestAllTypes{?single_int32: optional.ofNonZeroValue(1)}`, |
| 250 | folded: `google.expr.proto3.test.TestAllTypes{single_int32: 1}`, |
| 251 | }, |
| 252 | { |
| 253 | expr: `google.expr.proto3.test.TestAllTypes{?single_int32: optional.ofNonZeroValue(0)}`, |
| 254 | folded: `google.expr.proto3.test.TestAllTypes{}`, |
| 255 | }, |
| 256 | { |
| 257 | expr: `google.expr.proto3.test.TestAllTypes{single_int32: x, repeated_int32: [1, 2, 3]}`, |
| 258 | folded: `google.expr.proto3.test.TestAllTypes{single_int32: x, repeated_int32: [1, 2, 3]}`, |
| 259 | }, |
| 260 | { |
| 261 | expr: `x + dyn([1, 2] + [3, 4])`, |
| 262 | folded: `x + [1, 2, 3, 4]`, |
| 263 | }, |
| 264 | { |
| 265 | expr: `dyn([1, 2]) + [3.0, 4.0]`, |
| 266 | folded: `[1, 2, 3.0, 4.0]`, |
| 267 | }, |
| 268 | { |
| 269 | expr: `{'a': dyn([1, 2]), 'b': x}`, |
| 270 | folded: `{"a": [1, 2], "b": x}`, |
| 271 | }, |
| 272 | { |
| 273 | expr: `1 + x + 2 == 2 + x + 1`, |
| 274 | folded: `1 + x + 2 == 2 + x + 1`, |
| 275 | }, |
| 276 | { |
| 277 | // The order of operations makes it such that the appearance of x in the first means that |
| 278 | // none of the values provided into the addition call will be folded with the current |
| 279 | // implementation. Ideally, the result would be 3 + x == x + 3 (which could be trivially true |
| 280 | // and more easily observed as a result of common subexpression eliminiation) |
| 281 | expr: `1 + 2 + x == x + 2 + 1`, |
| 282 | folded: `3 + x == x + 2 + 1`, |
| 283 | }, |
| 284 | { |
| 285 | expr: `google.expr.proto3.test.ImportedGlobalEnum.IMPORT_BAR`, |
| 286 | folded: `1`, |
| 287 | knownValues: map[string]any{}, |
| 288 | }, |
| 289 | { |
| 290 | expr: `google.expr.proto3.test.ImportedGlobalEnum.IMPORT_BAR`, |
| 291 | folded: `google.expr.proto3.test.ImportedGlobalEnum.IMPORT_BAR`, |
| 292 | }, |
| 293 | { |
| 294 | expr: `c == google.expr.proto3.test.ImportedGlobalEnum.IMPORT_BAZ ? "BAZ" : "Unknown"`, |
| 295 | folded: `"BAZ"`, |
| 296 | knownValues: map[string]any{}, |
| 297 | }, |
| 298 | { |
| 299 | expr: `[ |
| 300 | google.expr.proto3.test.ImportedGlobalEnum.IMPORT_BAR, |
| 301 | c, |
| 302 | google.expr.proto3.test.ImportedGlobalEnum.IMPORT_FOO |
| 303 | ].exists(e, e == google.expr.proto3.test.ImportedGlobalEnum.IMPORT_FOO) |
| 304 | ? "has Foo" : "no Foo"`, |
| 305 | folded: `"has Foo"`, |
| 306 | knownValues: map[string]any{}, |
| 307 | }, |
| 308 | { |
| 309 | expr: `l.exists(e, e == "foo") ? "has Foo" : "no Foo"`, |
| 310 | folded: `"has Foo"`, |
| 311 | knownValues: map[string]any{ |
| 312 | "l": []string{"foo", "bar", "baz"}, |
| 313 | }, |
| 314 | }, |
| 315 | { |
| 316 | expr: `"foo" in l`, |
| 317 | folded: `true`, |
| 318 | knownValues: map[string]any{ |
| 319 | "l": []string{"foo", "bar", "baz"}, |
| 320 | }, |
| 321 | }, |
| 322 | { |
| 323 | expr: `o.repeated_int32`, |
| 324 | folded: `[1, 2, 3]`, |
| 325 | knownValues: map[string]any{ |
| 326 | "o": &proto3pb.TestAllTypes{RepeatedInt32: []int32{1, 2, 3}}, |
| 327 | }, |
| 328 | }, |
| 329 | } |
| 330 | e, err := NewEnv( |
| 331 | OptionalTypes(), |
| 332 | EnableMacroCallTracking(), |
| 333 | Types(&proto3pb.TestAllTypes{}), |
| 334 | Variable("x", DynType), |
| 335 | // work around different package convention in piper vs github. |
| 336 | // google.expr.proto3.test.ImportedGlobalEnum.IMPORT_BAZ |
| 337 | Constant("c", IntType, types.Int(2)), |
| 338 | ) |
| 339 | if err != nil { |
| 340 | t.Fatalf("NewEnv() failed: %v", err) |
| 341 | } |
| 342 | e, err = e.Extend(Variable("l", ListType(StringType))) |
| 343 | if err != nil { |
| 344 | t.Fatalf("Extend() failed: %v", err) |
| 345 | } |
| 346 | e, err = e.Extend(Variable("o", ObjectType("google.expr.proto3.test.TestAllTypes"))) |
| 347 | if err != nil { |
| 348 | t.Fatalf("Extend() failed: %v", err) |
| 349 | } |
| 350 | for _, tst := range tests { |
| 351 | tc := tst |
| 352 | t.Run(tc.expr, func(t *testing.T) { |
| 353 | checked, iss := e.Compile(tc.expr) |
| 354 | if iss.Err() != nil { |
| 355 | t.Fatalf("Compile() failed: %v", iss.Err()) |
| 356 | } |
| 357 | var foldingOpts []ConstantFoldingOption |
| 358 | if tc.knownValues != nil { |
| 359 | knownValues, err := NewActivation(tc.knownValues) |
| 360 | if err != nil { |
| 361 | t.Fatalf("NewActivation() failed: %v", err) |
| 362 | } |
| 363 | foldingOpts = append(foldingOpts, FoldKnownValues(knownValues)) |
| 364 | } |
| 365 | folder, err := NewConstantFoldingOptimizer(foldingOpts...) |
| 366 | if err != nil { |
| 367 | t.Fatalf("NewConstantFoldingOptimizer() failed: %v", err) |
| 368 | } |
| 369 | opt, err := NewStaticOptimizer(folder) |
| 370 | if err != nil { |
| 371 | t.Fatalf("NewStaticOptimizer() failed: %v", err) |
| 372 | } |
| 373 | optimized, iss := opt.Optimize(e, checked) |
| 374 | if iss.Err() != nil { |
| 375 | t.Fatalf("Optimize() generated an invalid AST: %v", iss.Err()) |
| 376 | } |
| 377 | folded, err := AstToString(optimized) |
| 378 | if err != nil { |
| 379 | t.Fatalf("AstToString() failed: %v", err) |
| 380 | } |
| 381 | if folded != tc.folded { |
| 382 | t.Errorf("got %q, wanted %q", folded, tc.folded) |
| 383 | } |
| 384 | }) |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | func TestConstantFoldingCallsWithSideEffects(t *testing.T) { |
| 389 | tests := []struct { |
| 390 | expr string |
| 391 | folded string |
| 392 | error string |
| 393 | }{ |
| 394 | { |
| 395 | expr: `noSideEffect(3)`, |
| 396 | folded: `3`, |
| 397 | }, |
| 398 | { |
| 399 | expr: `withSideEffect(3)`, |
| 400 | folded: `withSideEffect(3)`, |
| 401 | }, |
| 402 | { |
| 403 | expr: `[{}, {"a": 1}, {"b": 2}].exists(i, has(i.b) && withSideEffect(i.b) == 1)`, |
| 404 | folded: `[{}, {"a": 1}, {"b": 2}].exists(i, has(i.b) && withSideEffect(i.b) == 1)`, |
| 405 | }, |
| 406 | { |
| 407 | expr: `[{}, {"a": 1}, {"b": 2}].exists(i, has(i.b) && noSideEffect(i.b) == 2)`, |
| 408 | folded: `true`, |
| 409 | }, |
| 410 | { |
| 411 | expr: `noImpl(3)`, |
| 412 | error: `constant-folding evaluation failed: no such overload: noImpl`, |
| 413 | }, |
| 414 | } |
| 415 | e, err := NewEnv( |
| 416 | OptionalTypes(), |
| 417 | EnableMacroCallTracking(), |
| 418 | Function("noSideEffect", |
| 419 | Overload("noSideEffect_int_int", |
| 420 | []*Type{IntType}, |
| 421 | IntType, FunctionBinding(func(args ...ref.Val) ref.Val { |
| 422 | return args[0] |
| 423 | }))), |
| 424 | Function("withSideEffect", |
| 425 | Overload("withSideEffect_int_int", |
| 426 | []*Type{IntType}, |
| 427 | IntType, LateFunctionBinding())), |
| 428 | Function("noImpl", |
| 429 | Overload("noImpl_int_int", |
| 430 | []*Type{IntType}, |
| 431 | IntType)), |
| 432 | ) |
| 433 | if err != nil { |
| 434 | t.Fatalf("NewEnv() failed: %v", err) |
| 435 | } |
| 436 | for _, tst := range tests { |
| 437 | tc := tst |
| 438 | t.Run(tc.expr, func(t *testing.T) { |
| 439 | checked, iss := e.Compile(tc.expr) |
| 440 | if iss.Err() != nil { |
| 441 | t.Fatalf("Compile() failed: %v", iss.Err()) |
| 442 | } |
| 443 | folder, err := NewConstantFoldingOptimizer() |
| 444 | if err != nil { |
| 445 | t.Fatalf("NewConstantFoldingOptimizer() failed: %v", err) |
| 446 | } |
| 447 | opt, err := NewStaticOptimizer(folder) |
| 448 | if err != nil { |
| 449 | t.Fatalf("NewStaticOptimizer() failed: %v", err) |
| 450 | } |
| 451 | optimized, iss := opt.Optimize(e, checked) |
| 452 | if tc.error != "" { |
| 453 | if iss.Err() == nil { |
| 454 | t.Errorf("got nil, wanted error containing %q", tc.error) |
| 455 | } else if !strings.Contains(iss.Err().Error(), tc.error) { |
| 456 | t.Errorf("got %q, wanted error containing %q", iss.Err().Error(), tc.error) |
| 457 | } |
| 458 | return |
| 459 | } |
| 460 | if iss.Err() != nil { |
| 461 | t.Fatalf("Optimize() generated an invalid AST: %v", iss.Err()) |
| 462 | } |
| 463 | folded, err := AstToString(optimized) |
| 464 | if err != nil { |
| 465 | t.Fatalf("AstToString() failed: %v", err) |
| 466 | } |
| 467 | if folded != tc.folded { |
| 468 | t.Errorf("got %q, wanted %q", folded, tc.folded) |
| 469 | } |
| 470 | }) |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | func TestConstantFoldingOptimizerMacroElimination(t *testing.T) { |
| 475 | tests := []struct { |
| 476 | expr string |
| 477 | folded string |
| 478 | macroCount int |
| 479 | }{ |
| 480 | { |
| 481 | expr: `has({}.key)`, |
| 482 | folded: `false`, |
| 483 | }, |
| 484 | { |
| 485 | expr: `[1, 2, 3].filter(i, i < 1)`, |
| 486 | folded: `[]`, |
| 487 | }, |
| 488 | { |
| 489 | expr: `[{}, {"a": 1}, {"b": 2}].exists(i, has(i.b))`, |
| 490 | folded: `true`, |
| 491 | }, |
| 492 | { |
| 493 | expr: `has(x.b) && [{}, {"a": 1}, {"b": 2}].exists(i, has(i.b))`, |
| 494 | folded: `has(x.b)`, |
| 495 | macroCount: 1, |
| 496 | }, |
| 497 | } |
| 498 | e, err := NewEnv( |
| 499 | OptionalTypes(), |
| 500 | EnableMacroCallTracking(), |
| 501 | Types(&proto3pb.TestAllTypes{}), |
| 502 | Variable("x", DynType)) |
| 503 | if err != nil { |
| 504 | t.Fatalf("NewEnv() failed: %v", err) |
| 505 | } |
| 506 | for _, tst := range tests { |
| 507 | tc := tst |
| 508 | t.Run(tc.expr, func(t *testing.T) { |
| 509 | checked, iss := e.Compile(tc.expr) |
| 510 | if iss.Err() != nil { |
| 511 | t.Fatalf("Compile() failed: %v", iss.Err()) |
| 512 | } |
| 513 | folder, err := NewConstantFoldingOptimizer() |
| 514 | if err != nil { |
| 515 | t.Fatalf("NewConstantFoldingOptimizer() failed: %v", err) |
| 516 | } |
| 517 | opt, err := NewStaticOptimizer(folder) |
| 518 | if err != nil { |
| 519 | t.Fatalf("NewStaticOptimizer() failed: %v", err) |
| 520 | } |
| 521 | optimized, iss := opt.Optimize(e, checked) |
| 522 | if iss.Err() != nil { |
| 523 | t.Fatalf("Optimize() generated an invalid AST: %v", iss.Err()) |
| 524 | } |
| 525 | folded, err := AstToString(optimized) |
| 526 | if err != nil { |
| 527 | t.Fatalf("AstToString() failed: %v", err) |
| 528 | } |
| 529 | if folded != tc.folded { |
| 530 | t.Errorf("folding got %q, wanted %q", folded, tc.folded) |
| 531 | } |
| 532 | if len(optimized.SourceInfo().GetMacroCalls()) != tc.macroCount { |
| 533 | t.Errorf("folding got %d macros, wanted %d macros", len(optimized.SourceInfo().GetMacroCalls()), tc.macroCount) |
| 534 | } |
| 535 | }) |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | func TestConstantFoldingOptimizerWithLimit(t *testing.T) { |
| 540 | tests := []struct { |
| 541 | expr string |
| 542 | limit int |
| 543 | folded string |
| 544 | }{ |
| 545 | { |
| 546 | expr: `[1, 1 + 2, 1 + (2 + 3)]`, |
| 547 | limit: 1, |
| 548 | folded: `[1, 3, 1 + 5]`, |
| 549 | }, |
| 550 | { |
| 551 | expr: `5 in [1, 1 + 2, 1 + (2 + 3)]`, |
| 552 | limit: 2, |
| 553 | folded: `5 in [1, 3, 6]`, |
| 554 | }, |
| 555 | { |
| 556 | // though more complex, the final tryFold() at the end of the optimization pass |
| 557 | // results in this computed output. |
| 558 | expr: `[1, 2, 3].map(i, [1, 2, 3].map(j, i * j))`, |
| 559 | limit: 1, |
| 560 | folded: `[[1, 2, 3], [2, 4, 6], [3, 6, 9]]`, |
| 561 | }, |
| 562 | } |
| 563 | e, err := NewEnv( |
| 564 | OptionalTypes(), |
| 565 | EnableMacroCallTracking(), |
| 566 | Types(&proto3pb.TestAllTypes{}), |
| 567 | Variable("x", DynType)) |
| 568 | if err != nil { |
| 569 | t.Fatalf("NewEnv() failed: %v", err) |
| 570 | } |
| 571 | for _, tst := range tests { |
| 572 | tc := tst |
| 573 | t.Run(tc.expr, func(t *testing.T) { |
| 574 | checked, iss := e.Compile(tc.expr) |
| 575 | if iss.Err() != nil { |
| 576 | t.Fatalf("Compile() failed: %v", iss.Err()) |
| 577 | } |
| 578 | folder, err := NewConstantFoldingOptimizer(MaxConstantFoldIterations(tc.limit)) |
| 579 | if err != nil { |
| 580 | t.Fatalf("NewConstantFoldingOptimizer() failed: %v", err) |
| 581 | } |
| 582 | opt, err := NewStaticOptimizer(folder) |
| 583 | if err != nil { |
| 584 | t.Fatalf("NewStaticOptimizer() failed: %v", err) |
| 585 | } |
| 586 | optimized, iss := opt.Optimize(e, checked) |
| 587 | if iss.Err() != nil { |
| 588 | t.Fatalf("Optimize() generated an invalid AST: %v", iss.Err()) |
| 589 | } |
| 590 | folded, err := AstToString(optimized) |
| 591 | if err != nil { |
| 592 | t.Fatalf("AstToString() failed: %v", err) |
| 593 | } |
| 594 | if folded != tc.folded { |
| 595 | t.Errorf("got %q, wanted %q", folded, tc.folded) |
| 596 | } |
| 597 | }) |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | func TestConstantFoldingNormalizeIDs(t *testing.T) { |
| 602 | tests := []struct { |
| 603 | expr string |
| 604 | ids []int64 |
| 605 | macros map[int64]string |
| 606 | normalizedIDs []int64 |
| 607 | normalizedMacros map[int64]string |
| 608 | }{ |
| 609 | { |
| 610 | expr: `[1, 2, 3]`, |
| 611 | ids: []int64{1, 2, 3, 4}, |
| 612 | normalizedIDs: []int64{1, 2, 3, 4}, |
| 613 | }, |
| 614 | { |
| 615 | expr: `google.expr.proto3.test.TestAllTypes{single_int32: 0}`, |
| 616 | ids: []int64{1, 2, 3}, |
| 617 | normalizedIDs: []int64{1, 2, 3}, |
| 618 | }, |
| 619 | { |
| 620 | expr: `has({x: 'value'}.single_int32)`, |
| 621 | ids: []int64{2, 3, 4, 5, 7}, |
| 622 | macros: map[int64]string{7: ` |
| 623 | call_expr: { |
| 624 | function: "has" |
| 625 | args: { |
| 626 | id: 6 |
| 627 | select_expr: { |
| 628 | operand: { |
| 629 | id: 2 |
| 630 | struct_expr: { |
| 631 | entries: { |
| 632 | id: 3 |
| 633 | map_key: { |
| 634 | id: 4 |
| 635 | ident_expr: { |
| 636 | name: "x" |
| 637 | } |
| 638 | } |
| 639 | value: { |
| 640 | id: 5 |
| 641 | const_expr: { |
| 642 | string_value: "value" |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | } |
| 647 | } |
| 648 | field: "single_int32" |
| 649 | } |
| 650 | } |
| 651 | }`}, |
| 652 | normalizedIDs: []int64{1, 2, 3, 4, 5}, |
| 653 | normalizedMacros: map[int64]string{1: ` |
| 654 | call_expr: { |
| 655 | function: "has" |
| 656 | args: { |
| 657 | id: 6 |
| 658 | select_expr: { |
| 659 | operand: { |
| 660 | id: 2 |
| 661 | struct_expr: { |
| 662 | entries: { |
| 663 | id: 3 |
| 664 | map_key: { |
| 665 | id: 4 |
| 666 | ident_expr: { |
| 667 | name: "x" |
| 668 | } |
| 669 | } |
| 670 | value: { |
| 671 | id: 5 |
| 672 | const_expr: { |
| 673 | string_value: "value" |
| 674 | } |
| 675 | } |
| 676 | } |
| 677 | } |
| 678 | } |
| 679 | field: "single_int32" |
| 680 | } |
| 681 | } |
| 682 | }`, |
| 683 | }, |
| 684 | }, |
| 685 | { |
| 686 | expr: `has(google.expr.proto3.test.TestAllTypes{}.single_int32)`, |
| 687 | ids: []int64{2, 4}, |
| 688 | macros: map[int64]string{ |
| 689 | 4: `call_expr: { |
| 690 | function: "has" |
| 691 | args: { |
| 692 | id: 3 |
| 693 | select_expr: { |
| 694 | operand: { |
| 695 | id: 2 |
| 696 | struct_expr: { |
| 697 | message_name: "google.expr.proto3.test.TestAllTypes" |
| 698 | } |
| 699 | } |
| 700 | field: "single_int32" |
| 701 | } |
| 702 | } |
| 703 | }`, |
| 704 | }, |
| 705 | normalizedIDs: []int64{1}, |
| 706 | }, |
| 707 | { |
| 708 | expr: `[true].exists(i, i)`, |
| 709 | ids: []int64{1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13}, |
| 710 | macros: map[int64]string{ |
| 711 | 13: `call_expr: { |
| 712 | target: { |
| 713 | id: 1 |
| 714 | list_expr: { |
| 715 | elements: { |
| 716 | id: 2 |
| 717 | const_expr: { |
| 718 | bool_value: true |
| 719 | } |
| 720 | } |
| 721 | } |
| 722 | } |
| 723 | function: "exists" |
| 724 | args: { |
| 725 | id: 4 |
| 726 | ident_expr: { |
| 727 | name: "i" |
| 728 | } |
| 729 | } |
| 730 | args: { |
| 731 | id: 5 |
| 732 | ident_expr: { |
| 733 | name: "i" |
| 734 | } |
| 735 | } |
| 736 | }`, |
| 737 | }, |
| 738 | normalizedIDs: []int64{1}, |
| 739 | }, |
| 740 | { |
| 741 | expr: `[x].exists(i, i)`, |
| 742 | ids: []int64{1, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13}, |
| 743 | macros: map[int64]string{ |
| 744 | 13: `call_expr: { |
| 745 | target: { |
| 746 | id: 1 |
| 747 | list_expr: { |
| 748 | elements: { |
| 749 | id: 2 |
| 750 | ident_expr: { |
| 751 | name: "x" |
| 752 | } |
| 753 | } |
| 754 | } |
| 755 | } |
| 756 | function: "exists" |
| 757 | args: { |
| 758 | id: 4 |
| 759 | ident_expr: { |
| 760 | name: "i" |
| 761 | } |
| 762 | } |
| 763 | args: { |
| 764 | id: 5 |
| 765 | ident_expr: { |
| 766 | name: "i" |
| 767 | } |
| 768 | } |
| 769 | }`, |
| 770 | }, |
| 771 | normalizedIDs: []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, |
| 772 | normalizedMacros: map[int64]string{ |
| 773 | 1: `call_expr: { |
| 774 | target: { |
| 775 | id: 2 |
| 776 | list_expr: { |
| 777 | elements: { |
| 778 | id: 3 |
| 779 | ident_expr: { |
| 780 | name: "x" |
| 781 | } |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | function: "exists" |
| 786 | args: { |
| 787 | id: 12 |
| 788 | ident_expr: { |
| 789 | name: "i" |
| 790 | } |
| 791 | } |
| 792 | args: { |
| 793 | id: 10 |
| 794 | ident_expr: { |
| 795 | name: "i" |
| 796 | } |
| 797 | } |
| 798 | }`, |
| 799 | }, |
| 800 | }, |
| 801 | } |
| 802 | e, err := NewEnv( |
| 803 | EnableMacroCallTracking(), |
| 804 | Types(&proto3pb.TestAllTypes{}), |
| 805 | Variable("x", DynType)) |
| 806 | if err != nil { |
| 807 | t.Fatalf("NewEnv() failed: %v", err) |
| 808 | } |
| 809 | for _, tst := range tests { |
| 810 | tc := tst |
| 811 | t.Run(tc.expr, func(t *testing.T) { |
| 812 | checked, iss := e.Compile(tc.expr) |
| 813 | if iss.Err() != nil { |
| 814 | t.Fatalf("Compile() failed: %v", iss.Err()) |
| 815 | } |
| 816 | preOpt := newIDCollector() |
| 817 | ast.PostOrderVisit(checked.NativeRep().Expr(), preOpt) |
| 818 | if !reflect.DeepEqual(preOpt.IDs(), tc.ids) { |
| 819 | t.Errorf("Compile() got ids %v, expected %v", preOpt.IDs(), tc.ids) |
| 820 | } |
| 821 | for id, call := range checked.NativeRep().SourceInfo().MacroCalls() { |
| 822 | macroText, found := tc.macros[id] |
| 823 | if !found { |
| 824 | t.Fatalf("Compile() did not find macro %d", id) |
| 825 | } |
| 826 | pbCall, err := ast.ExprToProto(call) |
| 827 | if err != nil { |
| 828 | t.Fatalf("ast.ExprToProto() failed: %v", err) |
| 829 | } |
| 830 | pbMacro := &exprpb.Expr{} |
| 831 | err = prototext.Unmarshal([]byte(macroText), pbMacro) |
| 832 | if err != nil { |
| 833 | t.Fatalf("prototext.Unmarshal() failed: %v", err) |
| 834 | } |
| 835 | if !proto.Equal(pbCall, pbMacro) { |
| 836 | t.Errorf("Compile() for macro %d got %s, expected %s", id, prototext.Format(pbCall), macroText) |
| 837 | } |
| 838 | } |
| 839 | folder, err := NewConstantFoldingOptimizer() |
| 840 | if err != nil { |
| 841 | t.Fatalf("NewConstantFoldingOptimizer() failed: %v", err) |
| 842 | } |
| 843 | opt, err := NewStaticOptimizer(folder) |
| 844 | if err != nil { |
| 845 | t.Fatalf("NewStaticOptimizer() failed: %v", err) |
| 846 | } |
| 847 | optimized, iss := opt.Optimize(e, checked) |
| 848 | if iss.Err() != nil { |
| 849 | t.Fatalf("Optimize() generated an invalid AST: %v", iss.Err()) |
| 850 | } |
| 851 | postOpt := newIDCollector() |
| 852 | ast.PostOrderVisit(optimized.NativeRep().Expr(), postOpt) |
| 853 | if !reflect.DeepEqual(postOpt.IDs(), tc.normalizedIDs) { |
| 854 | t.Errorf("Optimize() got ids %v, expected %v", postOpt.IDs(), tc.normalizedIDs) |
| 855 | } |
| 856 | for id, call := range optimized.NativeRep().SourceInfo().MacroCalls() { |
| 857 | macroText, found := tc.normalizedMacros[id] |
| 858 | if !found { |
| 859 | t.Fatalf("Optimize() did not find macro %d", id) |
| 860 | } |
| 861 | pbCall, err := ast.ExprToProto(call) |
| 862 | if err != nil { |
| 863 | t.Fatalf("ast.ExprToProto() failed: %v", err) |
| 864 | } |
| 865 | pbMacro := &exprpb.Expr{} |
| 866 | err = prototext.Unmarshal([]byte(macroText), pbMacro) |
| 867 | if err != nil { |
| 868 | t.Fatalf("prototext.Unmarshal() failed: %v", err) |
| 869 | } |
| 870 | if !proto.Equal(pbCall, pbMacro) { |
| 871 | t.Errorf("Optimize() for macro %d got %s, expected %s", id, prototext.Format(pbCall), macroText) |
| 872 | } |
| 873 | } |
| 874 | }) |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | func newIDCollector() *idCollector { |
| 879 | return &idCollector{ |
| 880 | ids: int64Slice{}, |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | type idCollector struct { |
| 885 | ids int64Slice |
| 886 | } |
| 887 | |
| 888 | func (c *idCollector) VisitExpr(e ast.Expr) { |
| 889 | if e.ID() == 0 { |
| 890 | return |
| 891 | } |
| 892 | c.ids = append(c.ids, e.ID()) |
| 893 | } |
| 894 | |
| 895 | // VisitEntryExpr updates the max identifier if the incoming entry id is greater than previously observed. |
| 896 | func (c *idCollector) VisitEntryExpr(e ast.EntryExpr) { |
| 897 | if e.ID() == 0 { |
| 898 | return |
| 899 | } |
| 900 | c.ids = append(c.ids, e.ID()) |
| 901 | } |
| 902 | |
| 903 | func (c *idCollector) IDs() []int64 { |
| 904 | sort.Sort(c.ids) |
| 905 | return c.ids |
| 906 | } |
| 907 | |
| 908 | // int64Slice is an implementation of the sort.Interface |
| 909 | type int64Slice []int64 |
| 910 | |
| 911 | // Len returns the number of elements in the slice. |
| 912 | func (x int64Slice) Len() int { return len(x) } |
| 913 | |
| 914 | // Less indicates whether the value at index i is less than the value at index j. |
| 915 | func (x int64Slice) Less(i, j int) bool { return x[i] < x[j] } |
| 916 | |
| 917 | // Swap swaps the values at indices i and j in place. |
| 918 | func (x int64Slice) Swap(i, j int) { x[i], x[j] = x[j], x[i] } |
| 919 | |
| 920 | // Sort is a convenience method: x.Sort() calls Sort(x). |
| 921 | func (x int64Slice) Sort() { sort.Sort(x) } |