| 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 ast_test |
| 16 | |
| 17 | import ( |
| 18 | "fmt" |
| 19 | "maps" |
| 20 | "reflect" |
| 21 | "testing" |
| 22 | |
| 23 | "github.com/google/cel-go/common" |
| 24 | "github.com/google/cel-go/common/ast" |
| 25 | "github.com/google/cel-go/common/overloads" |
| 26 | "github.com/google/cel-go/common/types" |
| 27 | "google.golang.org/protobuf/encoding/prototext" |
| 28 | "google.golang.org/protobuf/proto" |
| 29 | ) |
| 30 | |
| 31 | func TestASTCopy(t *testing.T) { |
| 32 | tests := []string{ |
| 33 | `'a' == 'b'`, |
| 34 | `'a'.size()`, |
| 35 | `size('a')`, |
| 36 | `has({'a': 1}.a)`, |
| 37 | `{'a': 1}`, |
| 38 | `{'a': 1}['a']`, |
| 39 | `[1, 2, 3].exists(i, i % 2 == 1)`, |
| 40 | `google.expr.proto3.test.TestAllTypes{}`, |
| 41 | `google.expr.proto3.test.TestAllTypes{repeated_int32: [1, 2]}`, |
| 42 | } |
| 43 | |
| 44 | for _, tst := range tests { |
| 45 | checked := mustTypeCheck(t, tst) |
| 46 | copyChecked := ast.Copy(checked) |
| 47 | if !reflect.DeepEqual(copyChecked.Expr(), checked.Expr()) { |
| 48 | t.Errorf("Copy() got expr %v, wanted %v", copyChecked.Expr(), checked.Expr()) |
| 49 | } |
| 50 | if !reflect.DeepEqual(copyChecked.SourceInfo(), checked.SourceInfo()) { |
| 51 | t.Errorf("Copy() got source info %v, wanted %v", copyChecked.SourceInfo(), checked.SourceInfo()) |
| 52 | } |
| 53 | copyParsed := ast.Copy(ast.NewAST(checked.Expr(), checked.SourceInfo())) |
| 54 | if !reflect.DeepEqual(copyParsed.Expr(), checked.Expr()) { |
| 55 | t.Errorf("Copy() got expr %v, wanted %v", copyParsed.Expr(), checked.Expr()) |
| 56 | } |
| 57 | if !reflect.DeepEqual(copyParsed.SourceInfo(), checked.SourceInfo()) { |
| 58 | t.Errorf("Copy() got source info %v, wanted %v", copyParsed.SourceInfo(), checked.SourceInfo()) |
| 59 | } |
| 60 | checkedPB, err := ast.ToProto(checked) |
| 61 | if err != nil { |
| 62 | t.Errorf("ast.ToProto() failed: %v", err) |
| 63 | } |
| 64 | copyCheckedPB, err := ast.ToProto(copyChecked) |
| 65 | if err != nil { |
| 66 | t.Errorf("ast.ToProto() failed: %v", err) |
| 67 | } |
| 68 | if !proto.Equal(checkedPB, copyCheckedPB) { |
| 69 | t.Errorf("Copy() produced different proto results, got %v, wanted %v", |
| 70 | prototext.Format(checkedPB), prototext.Format(copyCheckedPB)) |
| 71 | } |
| 72 | checkedRoundtrip, err := ast.ToAST(checkedPB) |
| 73 | if err != nil { |
| 74 | t.Errorf("ast.ToAST() failed: %v", err) |
| 75 | } |
| 76 | same := reflect.DeepEqual(checked.Expr(), checkedRoundtrip.Expr()) && |
| 77 | reflect.DeepEqual(checked.ReferenceMap(), checkedRoundtrip.ReferenceMap()) && |
| 78 | reflect.DeepEqual(checked.TypeMap(), checkedRoundtrip.TypeMap()) && |
| 79 | reflect.DeepEqual(checked.SourceInfo().MacroCalls(), checkedRoundtrip.SourceInfo().MacroCalls()) |
| 80 | if !same { |
| 81 | t.Errorf("Roundtrip got %v, wanted %v", checkedRoundtrip, checked) |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | func TestASTNilSafety(t *testing.T) { |
| 87 | ex, err := ast.ProtoToExpr(nil) |
| 88 | if err != nil { |
| 89 | t.Fatalf("ast.ProtoToExpr() failed: %v", err) |
| 90 | } |
| 91 | info, err := ast.ProtoToSourceInfo(nil) |
| 92 | if err != nil { |
| 93 | t.Fatalf("ast.ProtoToSourceInfo() failed: %v", err) |
| 94 | } |
| 95 | tests := []*ast.AST{ |
| 96 | nil, |
| 97 | ast.NewAST(nil, nil), |
| 98 | ast.NewCheckedAST(nil, nil, nil), |
| 99 | ast.NewCheckedAST(ast.NewAST(nil, nil), nil, nil), |
| 100 | ast.NewAST(ex, info), |
| 101 | ast.NewCheckedAST(ast.NewAST(ex, info), map[int64]*types.Type{}, map[int64]*ast.ReferenceInfo{}), |
| 102 | } |
| 103 | for _, tst := range tests { |
| 104 | a := tst |
| 105 | asts := []*ast.AST{a, ast.Copy(a)} |
| 106 | for _, testAST := range asts { |
| 107 | if testAST.Expr().ID() != 0 { |
| 108 | t.Errorf("Expr().ID() got %v, wanted 0", testAST.Expr().ID()) |
| 109 | } |
| 110 | if testAST.SourceInfo().SyntaxVersion() != "" { |
| 111 | t.Errorf("SourceInfo().SyntaxVersion() got %s, wanted empty string", testAST.SourceInfo().SyntaxVersion()) |
| 112 | } |
| 113 | if testAST.IsChecked() { |
| 114 | t.Error("IsChecked() returned true, wanted false") |
| 115 | } |
| 116 | if testAST.GetType(testAST.Expr().ID()) != types.DynType { |
| 117 | t.Errorf("GetType() got %v, wanted dyn", testAST.GetType(testAST.Expr().ID())) |
| 118 | } |
| 119 | if len(testAST.GetOverloadIDs(testAST.Expr().ID())) != 0 { |
| 120 | t.Errorf("GetOverloadIDs() got %v, wanted empty set", testAST.GetOverloadIDs(testAST.Expr().ID())) |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | func TestSourceInfo(t *testing.T) { |
| 127 | src := common.NewStringSource("a\n? b\n: c", "custom description") |
| 128 | info := ast.NewSourceInfo(src) |
| 129 | if info.Description() != "custom description" { |
| 130 | t.Errorf("Description() got %s, wanted 'custom description'", info.Description()) |
| 131 | } |
| 132 | if len(info.LineOffsets()) != 3 { |
| 133 | t.Errorf("LineOffsets() got %v, wanted 3 offsets", info.LineOffsets()) |
| 134 | } |
| 135 | info.SetOffsetRange(1, ast.OffsetRange{Start: 0, Stop: 1}) // a |
| 136 | info.SetOffsetRange(2, ast.OffsetRange{Start: 4, Stop: 5}) // b |
| 137 | info.SetOffsetRange(3, ast.OffsetRange{Start: 8, Stop: 9}) // c |
| 138 | if !reflect.DeepEqual(info.GetStartLocation(1), common.NewLocation(1, 0)) { |
| 139 | t.Errorf("info.GetStartLocation(1) got %v, wanted line 1, col 0", info.GetStartLocation(1)) |
| 140 | } |
| 141 | if !reflect.DeepEqual(info.GetStopLocation(1), common.NewLocation(1, 1)) { |
| 142 | t.Errorf("info.GetStopLocation(1) got %v, wanted line 1, col 1", info.GetStopLocation(1)) |
| 143 | } |
| 144 | if !reflect.DeepEqual(info.GetStartLocation(2), common.NewLocation(2, 2)) { |
| 145 | t.Errorf("info.GetStartLocation(2) got %v, wanted line 2, col 2", info.GetStartLocation(2)) |
| 146 | } |
| 147 | if !reflect.DeepEqual(info.GetStopLocation(2), common.NewLocation(2, 3)) { |
| 148 | t.Errorf("info.GetStopLocation(2) got %v, wanted line 2, col 3", info.GetStopLocation(2)) |
| 149 | } |
| 150 | if !reflect.DeepEqual(info.GetStartLocation(3), common.NewLocation(3, 2)) { |
| 151 | t.Errorf("info.GetStartLocation(3) got %v, wanted line 2, col 2", info.GetStartLocation(3)) |
| 152 | } |
| 153 | if !reflect.DeepEqual(info.GetStopLocation(3), common.NewLocation(3, 3)) { |
| 154 | t.Errorf("info.GetStopLocation(3) got %v, wanted line 2, col 3", info.GetStopLocation(3)) |
| 155 | } |
| 156 | if info.ComputeOffset(3, 2) != 8 { |
| 157 | t.Errorf("info.ComputeOffset(3, 2) got %d, wanted 8", info.ComputeOffset(3, 2)) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func TestSourceInfoNilSafety(t *testing.T) { |
| 162 | info, err := ast.ProtoToSourceInfo(nil) |
| 163 | if err != nil { |
| 164 | t.Fatalf("ast.ProtoToSourceInfo() failed: %v", err) |
| 165 | } |
| 166 | tests := []*ast.SourceInfo{ |
| 167 | nil, |
| 168 | info, |
| 169 | ast.NewSourceInfo(nil), |
| 170 | } |
| 171 | for i, tst := range tests { |
| 172 | tc := tst |
| 173 | t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { |
| 174 | testInfo := tc |
| 175 | if testInfo.SyntaxVersion() != "" { |
| 176 | t.Errorf("SyntaxVersion() got %s, wanted empty string", testInfo.SyntaxVersion()) |
| 177 | } |
| 178 | if testInfo.Description() != "" { |
| 179 | t.Errorf("Description() got %s, wanted empty string", testInfo.Description()) |
| 180 | } |
| 181 | if len(testInfo.LineOffsets()) != 0 { |
| 182 | t.Errorf("LineOffsets() got %v, wanted empty list", testInfo.LineOffsets()) |
| 183 | } |
| 184 | if len(testInfo.MacroCalls()) != 0 { |
| 185 | t.Errorf("MacroCalls() got %v, wanted empty map", testInfo.MacroCalls()) |
| 186 | } |
| 187 | if call, found := testInfo.GetMacroCall(0); found { |
| 188 | t.Errorf("GetMacroCall(0) got %v, wanted not found", call) |
| 189 | } |
| 190 | if r, found := testInfo.GetOffsetRange(0); found { |
| 191 | t.Errorf("GetOffsetRange(0) got %v, wanted not found", r) |
| 192 | } |
| 193 | if loc := testInfo.GetStartLocation(0); loc != common.NoLocation { |
| 194 | t.Errorf("GetStartLocation(0) got %v, wanted no location", loc) |
| 195 | } |
| 196 | if loc := testInfo.GetStopLocation(0); loc != common.NoLocation { |
| 197 | t.Errorf("GetStopLocation(0) got %v, wanted no location", loc) |
| 198 | } |
| 199 | if off := testInfo.ComputeOffset(1, 0); off != 0 { |
| 200 | t.Errorf("ComputeOffset(1, 0) got %d, wanted 0", off) |
| 201 | } |
| 202 | if off := testInfo.ComputeOffset(-2, 0); off != -1 { |
| 203 | t.Errorf("ComputeOffset(-2, 0) got %d, wanted -1", off) |
| 204 | } |
| 205 | if off := testInfo.ComputeOffset(2, 0); off != -1 { |
| 206 | t.Errorf("ComputeOffset(2, 0) got %d, wanted -1", off) |
| 207 | } |
| 208 | }) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | func TestReferenceInfoEquals(t *testing.T) { |
| 213 | tests := []struct { |
| 214 | name string |
| 215 | a *ast.ReferenceInfo |
| 216 | b *ast.ReferenceInfo |
| 217 | equal bool |
| 218 | }{ |
| 219 | { |
| 220 | name: "single overload equal", |
| 221 | a: ast.NewFunctionReference(overloads.AddBytes), |
| 222 | b: ast.NewFunctionReference(overloads.AddBytes), |
| 223 | equal: true, |
| 224 | }, |
| 225 | { |
| 226 | name: "single overload not equal", |
| 227 | a: ast.NewFunctionReference(overloads.AddBytes), |
| 228 | b: ast.NewFunctionReference(overloads.AddDouble), |
| 229 | equal: false, |
| 230 | }, |
| 231 | { |
| 232 | name: "single and multiple overload not equal", |
| 233 | a: ast.NewFunctionReference(overloads.AddBytes), |
| 234 | b: ast.NewFunctionReference(overloads.AddBytes, overloads.AddDouble), |
| 235 | equal: false, |
| 236 | }, |
| 237 | { |
| 238 | name: "multiple overloads equal", |
| 239 | a: ast.NewFunctionReference(overloads.AddBytes, overloads.AddDouble), |
| 240 | b: ast.NewFunctionReference(overloads.AddDouble, overloads.AddBytes), |
| 241 | equal: true, |
| 242 | }, |
| 243 | { |
| 244 | name: "identifier reference equal", |
| 245 | a: ast.NewIdentReference("BYTES", nil), |
| 246 | b: ast.NewIdentReference("BYTES", nil), |
| 247 | equal: true, |
| 248 | }, |
| 249 | { |
| 250 | name: "identifier reference not equal", |
| 251 | a: ast.NewIdentReference("BYTES", nil), |
| 252 | b: ast.NewIdentReference("TRUE", nil), |
| 253 | equal: false, |
| 254 | }, |
| 255 | { |
| 256 | name: "identifier and constant reference not equal", |
| 257 | a: ast.NewIdentReference("BYTES", nil), |
| 258 | b: ast.NewIdentReference("BYTES", types.Bytes("bytes")), |
| 259 | equal: false, |
| 260 | }, |
| 261 | { |
| 262 | name: "constant references equal", |
| 263 | a: ast.NewIdentReference("BYTES", types.Bytes("bytes")), |
| 264 | b: ast.NewIdentReference("BYTES", types.Bytes("bytes")), |
| 265 | equal: true, |
| 266 | }, |
| 267 | { |
| 268 | name: "constant references not equal", |
| 269 | a: ast.NewIdentReference("BYTES", types.Bytes("bytes")), |
| 270 | b: ast.NewIdentReference("BYTES", types.Bytes("bytes-other")), |
| 271 | equal: false, |
| 272 | }, |
| 273 | { |
| 274 | name: "constant and overload reference not equal", |
| 275 | a: ast.NewIdentReference("BYTES", types.Bytes("bytes")), |
| 276 | b: ast.NewFunctionReference(overloads.AddDouble, overloads.AddBytes), |
| 277 | equal: false, |
| 278 | }, |
| 279 | } |
| 280 | for _, tst := range tests { |
| 281 | tc := tst |
| 282 | t.Run(tc.name, func(t *testing.T) { |
| 283 | out := tc.a.Equals(tc.b) |
| 284 | if out != tc.equal { |
| 285 | t.Errorf("%v.Equals(%v) got %v, wanted %v", tc.a, tc.b, out, tc.equal) |
| 286 | } |
| 287 | }) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | func TestReferenceInfoAddOverload(t *testing.T) { |
| 292 | add := ast.NewFunctionReference(overloads.AddBytes) |
| 293 | add.AddOverload(overloads.AddDouble) |
| 294 | if !add.Equals(ast.NewFunctionReference(overloads.AddBytes, overloads.AddDouble)) { |
| 295 | t.Error("AddOverload() did not produce equal references") |
| 296 | } |
| 297 | add.AddOverload(overloads.AddDouble) |
| 298 | if !add.Equals(ast.NewFunctionReference(overloads.AddBytes, overloads.AddDouble)) { |
| 299 | t.Error("repeated AddOverload() did not produce equal references") |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | func TestNewSourceInfoRelative(t *testing.T) { |
| 304 | sourceInfo := ast.NewSourceInfo( |
| 305 | mockRelativeSource(t, |
| 306 | "\n \n a || b ?\n cond1 :\n cond2", |
| 307 | []int32{1, 2, 13, 25}, |
| 308 | common.NewLocation(2, 1))) |
| 309 | tests := []struct { |
| 310 | loc common.Location |
| 311 | offset int32 |
| 312 | }{ |
| 313 | // All locations specify a line number starting at 1 |
| 314 | // The location of line 2, offset 1 is the same as the |
| 315 | // relative offset at location 1, 0 (offset 2) |
| 316 | {loc: common.NewLocation(1, 0), offset: 2}, |
| 317 | // Equivalent to line 3, column 4 |
| 318 | {loc: common.NewLocation(2, 3), offset: 6}, |
| 319 | // Equivalent to line 4, column 2 |
| 320 | {loc: common.NewLocation(3, 1), offset: 15}, |
| 321 | } |
| 322 | for _, tst := range tests { |
| 323 | gotOffset := sourceInfo.ComputeOffset(int32(tst.loc.Line()), int32(tst.loc.Column())) |
| 324 | if gotOffset != tst.offset { |
| 325 | t.Errorf("ComputeOffset() got %v, wanted %v", gotOffset, tst.offset) |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | func TestMaxID(t *testing.T) { |
| 331 | checked := mustTypeCheck(t, `has({'a':'key'}.key)`) |
| 332 | maxID := ast.MaxID(checked) |
| 333 | checked.SourceInfo().SetMacroCall( |
| 334 | maxID+2, |
| 335 | ast.NewExprFactory().NewIdent(maxID+1, "dummy")) |
| 336 | // Max ID always pads by 1 between invocations, and it's called twice here |
| 337 | // due to the presence of the macro which was injected after the fact. |
| 338 | if ast.MaxID(checked) != maxID+4 { |
| 339 | t.Errorf("ast.MaxID() got %v, wanted %d", ast.MaxID(checked), maxID+4) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | func TestHeights(t *testing.T) { |
| 344 | tests := []struct { |
| 345 | expr string |
| 346 | height int |
| 347 | }{ |
| 348 | {`'a' == 'b'`, 1}, |
| 349 | {`'a'.size()`, 1}, |
| 350 | {`[1, 2].size()`, 2}, |
| 351 | {`size('a')`, 1}, |
| 352 | {`has({'a': 1}.a)`, 2}, |
| 353 | {`{'a': 1}`, 1}, |
| 354 | {`{'a': 1}['a']`, 2}, |
| 355 | {`[1, 2, 3].exists(i, i % 2 == 1)`, 4}, |
| 356 | {`google.expr.proto3.test.TestAllTypes{}`, 1}, |
| 357 | {`google.expr.proto3.test.TestAllTypes{repeated_int32: [1, 2]}`, 2}, |
| 358 | } |
| 359 | for _, tst := range tests { |
| 360 | checked := mustTypeCheck(t, tst.expr) |
| 361 | maxHeight := ast.Heights(checked)[checked.Expr().ID()] |
| 362 | if maxHeight != tst.height { |
| 363 | t.Errorf("ast.Heights(%q) got max height %d, wanted %d", tst.expr, maxHeight, tst.height) |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | func mockRelativeSource(t testing.TB, text string, lineOffsets []int32, baseLocation common.Location) common.Source { |
| 369 | t.Helper() |
| 370 | return &mockSource{ |
| 371 | Source: common.NewTextSource(text), |
| 372 | lineOffsets: lineOffsets, |
| 373 | baseLocation: baseLocation} |
| 374 | } |
| 375 | |
| 376 | type mockSource struct { |
| 377 | common.Source |
| 378 | lineOffsets []int32 |
| 379 | baseLocation common.Location |
| 380 | } |
| 381 | |
| 382 | func (src *mockSource) LineOffsets() []int32 { |
| 383 | return src.lineOffsets |
| 384 | } |
| 385 | |
| 386 | func (src *mockSource) OffsetLocation(offset int32) (common.Location, bool) { |
| 387 | if offset == 0 { |
| 388 | return src.baseLocation, true |
| 389 | } |
| 390 | return src.Source.OffsetLocation(offset) |
| 391 | } |
| 392 | |
| 393 | func TestSourceInfoRenumberIDs(t *testing.T) { |
| 394 | info := ast.NewSourceInfo(nil) |
| 395 | for old := int64(1); old <= 5; old++ { |
| 396 | info.SetOffsetRange(old, ast.OffsetRange{Start: int32(old), Stop: int32(old) + 1}) |
| 397 | } |
| 398 | original := make(map[int64]ast.OffsetRange) |
| 399 | maps.Copy(original, info.OffsetRanges()) |
| 400 | |
| 401 | // Verify the renumbering is stable. |
| 402 | var next int64 = 101 |
| 403 | idMap := make(map[int64]int64) |
| 404 | idGen := func(old int64) int64 { |
| 405 | if _, found := idMap[old]; !found { |
| 406 | idMap[old] = next |
| 407 | next = next + 1 |
| 408 | } |
| 409 | return idMap[old] |
| 410 | } |
| 411 | info.RenumberIDs(idGen) |
| 412 | |
| 413 | if len(info.OffsetRanges()) != 5 { |
| 414 | t.Errorf("got %d offset ranges, wanted 5", len(info.OffsetRanges())) |
| 415 | } |
| 416 | |
| 417 | for old := int64(1); old <= 5; old++ { |
| 418 | want := original[old] |
| 419 | new := old + 100 |
| 420 | got, found := info.GetOffsetRange(new) |
| 421 | if !found { |
| 422 | t.Errorf("offset range for ID %d not found", new) |
| 423 | } |
| 424 | if got != want { |
| 425 | t.Errorf("offset range for ID %d incorrect; got %v, want %v", new, got, want) |
| 426 | } |
| 427 | } |
| 428 | } |