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
|
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// 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 com.google.devtools.build.lib.syntax;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.packages.Info;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.syntax.SkylarkList.MutableList;
import com.google.devtools.build.lib.syntax.SkylarkList.Tuple;
import com.google.devtools.build.lib.syntax.util.EvaluationTestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Tests for the validation process of Skylark files.
*/
@RunWith(JUnit4.class)
public class ValidationTest extends EvaluationTestCase {
@Test
public void testAssignmentNotValidLValue() {
checkError("cannot assign to '\"a\"'", "'a' = 1");
}
@Test
public void testAugmentedAssignmentWithMultipleLValues() {
checkError("cannot perform augmented assignment on a list or tuple expression", "a, b += 2, 3");
}
@Test
public void testReturnOutsideFunction() throws Exception {
checkError("return statements must be inside a function", "return 2\n");
}
@Test
public void testLoadAfterStatement() throws Exception {
env = newEnvironmentWithSkylarkOptions("--incompatible_bzl_disallow_load_after_statement=true");
checkError(
"load() statements must be called before any other statement",
"a = 5",
"load(':b.bzl', 'c')");
}
@Test
public void testAllowLoadAfterStatement() throws Exception {
env =
newEnvironmentWithSkylarkOptions("--incompatible_bzl_disallow_load_after_statement=false");
parse("a = 5", "load(':b.bzl', 'c')");
}
@Test
public void testForbiddenToplevelIfStatement() throws Exception {
env = newEnvironmentWithSkylarkOptions("--incompatible_disallow_toplevel_if_statement=true");
checkError("if statements are not allowed at the top level", "if True: a = 2");
}
@Test
public void testAllowedToplevelIfStatement() throws Exception {
env = newEnvironmentWithSkylarkOptions("--incompatible_disallow_toplevel_if_statement=false");
parse("if True: a = 5");
}
@Test
public void testTwoFunctionsWithTheSameName() throws Exception {
checkError(
"Variable foo is read only", "def foo():", " return 1", "def foo(x, y):", " return 1");
}
@Test
public void testFunctionLocalVariable() throws Exception {
checkError(
"name 'a' is not defined",
"def func2(b):",
" c = b",
" c = a",
"def func1():",
" a = 1",
" func2(2)");
}
@Test
public void testFunctionLocalVariableDoesNotEffectGlobalValidationEnv() throws Exception {
checkError("name 'a' is not defined", "def func1():", " a = 1", "def func2(b):", " b = a");
}
@Test
public void testFunctionParameterDoesNotEffectGlobalValidationEnv() throws Exception {
checkError("name 'a' is not defined", "def func1(a):", " return a", "def func2():", " b = a");
}
@Test
public void testDefinitionByItself() throws Exception {
checkError("name 'a' is not defined", "a = a");
checkError("name 'a' is not defined", "a += a");
checkError("name 'a' is not defined", "[[] for a in a]");
checkError("name 'a' is not defined", "def f():", " for a in a: pass");
}
@Test
public void testLocalValidationEnvironmentsAreSeparated() throws Exception {
parse("def func1():", " a = 1", "def func2():", " a = 'abc'\n");
}
@Test
public void testBuiltinSymbolsAreReadOnly() throws Exception {
checkError("Variable repr is read only", "repr = 1");
}
@Test
public void testSkylarkGlobalVariablesAreReadonly() throws Exception {
checkError("Variable a is read only", "a = 1", "a = 2");
}
@Test
public void testFunctionDefRecursion() throws Exception {
parse("def func():", " func()\n");
}
@Test
public void testMutualRecursion() throws Exception {
parse("def foo(i):", " bar(i)", "def bar(i):", " foo(i)", "foo(4)");
}
@Test
public void testFunctionDefinedBelow() {
parse("def bar(): a = foo() + 'a'", "def foo(): return 1\n");
}
@Test
public void testFunctionDoesNotExist() {
checkError("name 'foo' is not defined", "def bar(): a = foo() + 'a'");
}
@Test
public void testTupleLiteralWorksForDifferentTypes() throws Exception {
parse("('a', 1)");
}
@Test
public void testDictLiteralDifferentValueTypeWorks() throws Exception {
parse("{'a': 1, 'b': 'c'}");
}
@Test
public void testNoneAssignment() throws Exception {
parse("def func():", " a = None", " a = 2", " a = None\n");
}
@Test
public void testNoneIsAnyType() throws Exception {
parse("None + None");
parse("2 == None");
parse("None > 'a'");
parse("[] in None");
parse("5 * None");
}
// Skylark built-in functions specific tests
@Test
public void testFuncReturningDictAssignmentAsLValue() throws Exception {
parse(
"def my_dict():",
" return {'a': 1}",
"def func():",
" my_dict()['b'] = 2");
}
@Test
public void testEmptyLiteralGenericIsSetInLaterConcatWorks() {
parse("def func():", " s = {}", " s['a'] = 'b'\n");
}
@Test
public void testModulesReadOnlyInFuncDefBody() {
parse("def func():", " cmd_helper = depset()");
}
@Test
public void testBuiltinGlobalFunctionsReadOnlyInFuncDefBody() {
parse("def func():", " rule = 'abc'");
}
@Test
public void testBuiltinGlobalFunctionsReadOnlyAsFuncDefArg() {
parse("def func(rule):", " return rule");
}
@Test
public void testFunctionReturnsFunction() {
parse(
"def rule(*, implementation): return None",
"def impl(ctx): return None",
"",
"skylark_rule = rule(implementation = impl)",
"",
"def macro(name):",
" skylark_rule(name = name)");
}
@Test
public void testTypeForBooleanLiterals() {
parse("len([1, 2]) == 0 and True");
parse("len([1, 2]) == 0 and False");
}
@Test
public void testDollarErrorDoesNotLeak() throws Exception {
setFailFast(false);
parseFile(
"def GenerateMapNames():", " a = 2", " b = [3, 4]", " if a not b:", " print(a)");
assertContainsError("syntax error at 'b': expected in");
// Parser uses "$error" symbol for error recovery.
// It should not be used in error messages.
for (Event event : getEventCollector()) {
assertThat(event.getMessage()).doesNotContain("$error$");
}
}
@Test
public void testGetSkylarkType() throws Exception {
Class<?> emptyTupleClass = Tuple.empty().getClass();
Class<?> tupleClass = Tuple.of(1, "a", "b").getClass();
Class<?> mutableListClass = MutableList.copyOf(env, Tuple.of(1, 2, 3)).getClass();
assertThat(EvalUtils.getSkylarkType(mutableListClass)).isEqualTo(MutableList.class);
assertThat(MutableList.class.isAnnotationPresent(SkylarkModule.class)).isTrue();
assertThat(EvalUtils.getSkylarkType(emptyTupleClass)).isEqualTo(Tuple.class);
assertThat(EvalUtils.getSkylarkType(tupleClass)).isEqualTo(Tuple.class);
assertThat(EvalUtils.getSkylarkType(Info.class)).isEqualTo(Info.class);
try {
EvalUtils.getSkylarkType(ClassObject.class);
throw new Exception("Should have raised IllegalArgumentException exception");
} catch (IllegalArgumentException e) {
assertThat(e)
.hasMessageThat()
.contains(
"interface com.google.devtools.build.lib.syntax.ClassObject is not allowed "
+ "as a Skylark value");
}
}
@Test
public void testSkylarkTypeEquivalence() throws Exception {
Class<?> emptyTupleClass = Tuple.empty().getClass();
Class<?> tupleClass = Tuple.of(1, "a", "b").getClass();
Class<?> mutableListClass = MutableList.copyOf(env, Tuple.of(1, 2, 3)).getClass();
assertThat(SkylarkType.of(mutableListClass)).isEqualTo(SkylarkType.LIST);
assertThat(SkylarkType.of(emptyTupleClass)).isEqualTo(SkylarkType.TUPLE);
assertThat(SkylarkType.of(tupleClass)).isEqualTo(SkylarkType.TUPLE);
assertThat(SkylarkType.TUPLE).isNotEqualTo(SkylarkType.LIST);
try {
SkylarkType.of(ClassObject.class);
throw new Exception("foo");
} catch (Exception e) {
assertThat(e)
.hasMessageThat()
.contains(
"interface com.google.devtools.build.lib.syntax.ClassObject "
+ "is not allowed as a Skylark value");
}
// Also test for these bazel classes, to avoid some regression.
// TODO(bazel-team): move to some other place to remove dependency of syntax tests on Artifact?
assertThat(SkylarkType.of(Artifact.SpecialArtifact.class))
.isEqualTo(SkylarkType.of(Artifact.class));
assertThat(SkylarkType.of(RuleConfiguredTarget.class)).isNotEqualTo(SkylarkType.of(Info.class));
}
@Test
public void testSkylarkTypeInclusion() throws Exception {
assertThat(SkylarkType.INT.includes(SkylarkType.BOTTOM)).isTrue();
assertThat(SkylarkType.BOTTOM.includes(SkylarkType.INT)).isFalse();
assertThat(SkylarkType.TOP.includes(SkylarkType.INT)).isTrue();
SkylarkType combo1 = SkylarkType.Combination.of(SkylarkType.LIST, SkylarkType.INT);
assertThat(SkylarkType.LIST.includes(combo1)).isTrue();
SkylarkType union1 =
SkylarkType.Union.of(SkylarkType.DICT, SkylarkType.LIST);
assertThat(union1.includes(SkylarkType.DICT)).isTrue();
assertThat(union1.includes(combo1)).isTrue();
assertThat(union1.includes(SkylarkType.STRING)).isFalse();
SkylarkType union2 =
SkylarkType.Union.of(
SkylarkType.LIST, SkylarkType.DICT, SkylarkType.STRING, SkylarkType.INT);
SkylarkType inter1 = SkylarkType.intersection(union1, union2);
assertThat(inter1.includes(SkylarkType.DICT)).isTrue();
assertThat(inter1.includes(SkylarkType.LIST)).isTrue();
assertThat(inter1.includes(combo1)).isTrue();
assertThat(inter1.includes(SkylarkType.INT)).isFalse();
}
private void parse(String... lines) {
parseFile(lines);
assertNoWarningsOrErrors();
}
private void checkError(String errorMsg, String... lines) {
setFailFast(false);
parseFile(lines);
assertContainsError(errorMsg);
}
}
|