File: ast_test.go

package info (click to toggle)
golang-github-google-cel-go 0.18.2%2Bds-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,888 kB
  • sloc: sh: 93; makefile: 12
file content (348 lines) | stat: -rw-r--r-- 11,725 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ast_test

import (
	"fmt"
	"reflect"
	"testing"

	"github.com/google/cel-go/common"
	"github.com/google/cel-go/common/ast"
	"github.com/google/cel-go/common/overloads"
	"github.com/google/cel-go/common/types"
	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/proto"
)

func TestASTCopy(t *testing.T) {
	tests := []string{
		`'a' == 'b'`,
		`'a'.size()`,
		`size('a')`,
		`has({'a': 1}.a)`,
		`{'a': 1}`,
		`{'a': 1}['a']`,
		`[1, 2, 3].exists(i, i % 2 == 1)`,
		`google.expr.proto3.test.TestAllTypes{}`,
		`google.expr.proto3.test.TestAllTypes{repeated_int32: [1, 2]}`,
	}

	for _, tst := range tests {
		checked := mustTypeCheck(t, tst)
		copyChecked := ast.Copy(checked)
		if !reflect.DeepEqual(copyChecked.Expr(), checked.Expr()) {
			t.Errorf("Copy() got expr %v, wanted %v", copyChecked.Expr(), checked.Expr())
		}
		if !reflect.DeepEqual(copyChecked.SourceInfo(), checked.SourceInfo()) {
			t.Errorf("Copy() got source info %v, wanted %v", copyChecked.SourceInfo(), checked.SourceInfo())
		}
		copyParsed := ast.Copy(ast.NewAST(checked.Expr(), checked.SourceInfo()))
		if !reflect.DeepEqual(copyParsed.Expr(), checked.Expr()) {
			t.Errorf("Copy() got expr %v, wanted %v", copyParsed.Expr(), checked.Expr())
		}
		if !reflect.DeepEqual(copyParsed.SourceInfo(), checked.SourceInfo()) {
			t.Errorf("Copy() got source info %v, wanted %v", copyParsed.SourceInfo(), checked.SourceInfo())
		}
		checkedPB, err := ast.ToProto(checked)
		if err != nil {
			t.Errorf("ast.ToProto() failed: %v", err)
		}
		copyCheckedPB, err := ast.ToProto(copyChecked)
		if err != nil {
			t.Errorf("ast.ToProto() failed: %v", err)
		}
		if !proto.Equal(checkedPB, copyCheckedPB) {
			t.Errorf("Copy() produced different proto results, got %v, wanted %v",
				prototext.Format(checkedPB), prototext.Format(copyCheckedPB))
		}
		checkedRoundtrip, err := ast.ToAST(checkedPB)
		if err != nil {
			t.Errorf("ast.ToAST() failed: %v", err)
		}
		if !reflect.DeepEqual(checked, checkedRoundtrip) {
			t.Errorf("Roundtrip got %v, wanted %v", checkedRoundtrip, checked)
		}
	}
}

func TestASTNilSafety(t *testing.T) {
	ex, err := ast.ProtoToExpr(nil)
	if err != nil {
		t.Fatalf("ast.ProtoToExpr() failed: %v", err)
	}
	info, err := ast.ProtoToSourceInfo(nil)
	if err != nil {
		t.Fatalf("ast.ProtoToSourceInfo() failed: %v", err)
	}
	tests := []*ast.AST{
		nil,
		ast.NewAST(nil, nil),
		ast.NewCheckedAST(nil, nil, nil),
		ast.NewCheckedAST(ast.NewAST(nil, nil), nil, nil),
		ast.NewAST(ex, info),
		ast.NewCheckedAST(ast.NewAST(ex, info), map[int64]*types.Type{}, map[int64]*ast.ReferenceInfo{}),
	}
	for _, tst := range tests {
		a := tst
		asts := []*ast.AST{a, ast.Copy(a)}
		for _, testAST := range asts {
			if testAST.Expr().ID() != 0 {
				t.Errorf("Expr().ID() got %v, wanted 0", testAST.Expr().ID())
			}
			if testAST.SourceInfo().SyntaxVersion() != "" {
				t.Errorf("SourceInfo().SyntaxVersion() got %s, wanted empty string", testAST.SourceInfo().SyntaxVersion())
			}
			if testAST.IsChecked() {
				t.Error("IsChecked() returned true, wanted false")
			}
			if testAST.GetType(testAST.Expr().ID()) != types.DynType {
				t.Errorf("GetType() got %v, wanted dyn", testAST.GetType(testAST.Expr().ID()))
			}
			if len(testAST.GetOverloadIDs(testAST.Expr().ID())) != 0 {
				t.Errorf("GetOverloadIDs() got %v, wanted empty set", testAST.GetOverloadIDs(testAST.Expr().ID()))
			}
		}
	}
}

func TestSourceInfo(t *testing.T) {
	src := common.NewStringSource("a\n? b\n: c", "custom description")
	info := ast.NewSourceInfo(src)
	if info.Description() != "custom description" {
		t.Errorf("Description() got %s, wanted 'custom description'", info.Description())
	}
	if len(info.LineOffsets()) != 3 {
		t.Errorf("LineOffsets() got %v, wanted 3 offsets", info.LineOffsets())
	}
	info.SetOffsetRange(1, ast.OffsetRange{Start: 0, Stop: 1}) // a
	info.SetOffsetRange(2, ast.OffsetRange{Start: 4, Stop: 5}) // b
	info.SetOffsetRange(3, ast.OffsetRange{Start: 8, Stop: 9}) // c
	if !reflect.DeepEqual(info.GetStartLocation(1), common.NewLocation(1, 0)) {
		t.Errorf("info.GetStartLocation(1) got %v, wanted line 1, col 0", info.GetStartLocation(1))
	}
	if !reflect.DeepEqual(info.GetStopLocation(1), common.NewLocation(1, 1)) {
		t.Errorf("info.GetStopLocation(1) got %v, wanted line 1, col 1", info.GetStopLocation(1))
	}
	if !reflect.DeepEqual(info.GetStartLocation(2), common.NewLocation(2, 2)) {
		t.Errorf("info.GetStartLocation(2) got %v, wanted line 2, col 2", info.GetStartLocation(2))
	}
	if !reflect.DeepEqual(info.GetStopLocation(2), common.NewLocation(2, 3)) {
		t.Errorf("info.GetStopLocation(2) got %v, wanted line 2, col 3", info.GetStopLocation(2))
	}
	if !reflect.DeepEqual(info.GetStartLocation(3), common.NewLocation(3, 2)) {
		t.Errorf("info.GetStartLocation(3) got %v, wanted line 2, col 2", info.GetStartLocation(3))
	}
	if !reflect.DeepEqual(info.GetStopLocation(3), common.NewLocation(3, 3)) {
		t.Errorf("info.GetStopLocation(3) got %v, wanted line 2, col 3", info.GetStopLocation(3))
	}
	if info.ComputeOffset(3, 2) != 8 {
		t.Errorf("info.ComputeOffset(3, 2) got %d, wanted 8", info.ComputeOffset(3, 2))
	}
}

func TestSourceInfoNilSafety(t *testing.T) {
	info, err := ast.ProtoToSourceInfo(nil)
	if err != nil {
		t.Fatalf("ast.ProtoToSourceInfo() failed: %v", err)
	}
	tests := []*ast.SourceInfo{
		nil,
		info,
		ast.NewSourceInfo(nil),
	}
	for i, tst := range tests {
		tc := tst
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			testInfo := tc
			if testInfo.SyntaxVersion() != "" {
				t.Errorf("SyntaxVersion() got %s, wanted empty string", testInfo.SyntaxVersion())
			}
			if testInfo.Description() != "" {
				t.Errorf("Description() got %s, wanted empty string", testInfo.Description())
			}
			if len(testInfo.LineOffsets()) != 0 {
				t.Errorf("LineOffsets() got %v, wanted empty list", testInfo.LineOffsets())
			}
			if len(testInfo.MacroCalls()) != 0 {
				t.Errorf("MacroCalls() got %v, wanted empty map", testInfo.MacroCalls())
			}
			if call, found := testInfo.GetMacroCall(0); found {
				t.Errorf("GetMacroCall(0) got %v, wanted not found", call)
			}
			if r, found := testInfo.GetOffsetRange(0); found {
				t.Errorf("GetOffsetRange(0) got %v, wanted not found", r)
			}
			if loc := testInfo.GetStartLocation(0); loc != common.NoLocation {
				t.Errorf("GetStartLocation(0) got %v, wanted no location", loc)
			}
			if loc := testInfo.GetStopLocation(0); loc != common.NoLocation {
				t.Errorf("GetStopLocation(0) got %v, wanted no location", loc)
			}
			if off := testInfo.ComputeOffset(1, 0); off != 0 {
				t.Errorf("ComputeOffset(1, 0) got %d, wanted 0", off)
			}
			if off := testInfo.ComputeOffset(-2, 0); off != -1 {
				t.Errorf("ComputeOffset(-2, 0) got %d, wanted -1", off)
			}
			if off := testInfo.ComputeOffset(2, 0); off != -1 {
				t.Errorf("ComputeOffset(2, 0) got %d, wanted -1", off)
			}
		})
	}
}

func TestReferenceInfoEquals(t *testing.T) {
	tests := []struct {
		name  string
		a     *ast.ReferenceInfo
		b     *ast.ReferenceInfo
		equal bool
	}{
		{
			name:  "single overload equal",
			a:     ast.NewFunctionReference(overloads.AddBytes),
			b:     ast.NewFunctionReference(overloads.AddBytes),
			equal: true,
		},
		{
			name:  "single overload not equal",
			a:     ast.NewFunctionReference(overloads.AddBytes),
			b:     ast.NewFunctionReference(overloads.AddDouble),
			equal: false,
		},
		{
			name:  "single and multiple overload not equal",
			a:     ast.NewFunctionReference(overloads.AddBytes),
			b:     ast.NewFunctionReference(overloads.AddBytes, overloads.AddDouble),
			equal: false,
		},
		{
			name:  "multiple overloads equal",
			a:     ast.NewFunctionReference(overloads.AddBytes, overloads.AddDouble),
			b:     ast.NewFunctionReference(overloads.AddDouble, overloads.AddBytes),
			equal: true,
		},
		{
			name:  "identifier reference equal",
			a:     ast.NewIdentReference("BYTES", nil),
			b:     ast.NewIdentReference("BYTES", nil),
			equal: true,
		},
		{
			name:  "identifier reference not equal",
			a:     ast.NewIdentReference("BYTES", nil),
			b:     ast.NewIdentReference("TRUE", nil),
			equal: false,
		},
		{
			name:  "identifier and constant reference not equal",
			a:     ast.NewIdentReference("BYTES", nil),
			b:     ast.NewIdentReference("BYTES", types.Bytes("bytes")),
			equal: false,
		},
		{
			name:  "constant references equal",
			a:     ast.NewIdentReference("BYTES", types.Bytes("bytes")),
			b:     ast.NewIdentReference("BYTES", types.Bytes("bytes")),
			equal: true,
		},
		{
			name:  "constant references not equal",
			a:     ast.NewIdentReference("BYTES", types.Bytes("bytes")),
			b:     ast.NewIdentReference("BYTES", types.Bytes("bytes-other")),
			equal: false,
		},
		{
			name:  "constant and overload reference not equal",
			a:     ast.NewIdentReference("BYTES", types.Bytes("bytes")),
			b:     ast.NewFunctionReference(overloads.AddDouble, overloads.AddBytes),
			equal: false,
		},
	}
	for _, tst := range tests {
		tc := tst
		t.Run(tc.name, func(t *testing.T) {
			out := tc.a.Equals(tc.b)
			if out != tc.equal {
				t.Errorf("%v.Equals(%v) got %v, wanted %v", tc.a, tc.b, out, tc.equal)
			}
		})
	}
}

func TestReferenceInfoAddOverload(t *testing.T) {
	add := ast.NewFunctionReference(overloads.AddBytes)
	add.AddOverload(overloads.AddDouble)
	if !add.Equals(ast.NewFunctionReference(overloads.AddBytes, overloads.AddDouble)) {
		t.Error("AddOverload() did not produce equal references")
	}
	add.AddOverload(overloads.AddDouble)
	if !add.Equals(ast.NewFunctionReference(overloads.AddBytes, overloads.AddDouble)) {
		t.Error("repeated AddOverload() did not produce equal references")
	}
}

func TestNewSourceInfoRelative(t *testing.T) {
	sourceInfo := ast.NewSourceInfo(
		mockRelativeSource(t,
			"\n \n a || b ?\n cond1 :\n cond2",
			[]int32{1, 2, 13, 25},
			common.NewLocation(2, 1)))
	tests := []struct {
		loc    common.Location
		offset int32
	}{
		// All locations specify a line number starting at 1
		// The location of line 2, offset 1 is the same as the
		// relative offset at location 1, 0 (offset 2)
		{loc: common.NewLocation(1, 0), offset: 2},
		// Equivalent to line 3, column 4
		{loc: common.NewLocation(2, 3), offset: 6},
		// Equivalent to line 4, column 2
		{loc: common.NewLocation(3, 1), offset: 15},
	}
	for _, tst := range tests {
		gotOffset := sourceInfo.ComputeOffset(int32(tst.loc.Line()), int32(tst.loc.Column()))
		if gotOffset != tst.offset {
			t.Errorf("ComputeOffset() got %v, wanted %v", gotOffset, tst.offset)
		}
	}
}

func mockRelativeSource(t testing.TB, text string, lineOffsets []int32, baseLocation common.Location) common.Source {
	t.Helper()
	return &mockSource{
		Source:       common.NewTextSource(text),
		lineOffsets:  lineOffsets,
		baseLocation: baseLocation}
}

type mockSource struct {
	common.Source
	lineOffsets  []int32
	baseLocation common.Location
}

func (src *mockSource) LineOffsets() []int32 {
	return src.lineOffsets
}

func (src *mockSource) OffsetLocation(offset int32) (common.Location, bool) {
	if offset == 0 {
		return src.baseLocation, true
	}
	return src.Source.OffsetLocation(offset)
}