blob: e71988c5705bc4cf95d748333c71a5abb227f097 [file] [log] [blame]
Damien Martin-Guillerezf88f4d82015-09-25 13:56:55 +00001// Copyright 2014 The Bazel Authors. All rights reserved.
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00002//
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
15package com.google.devtools.build.lib.skylark;
16
17import static com.google.common.truth.Truth.assertThat;
michajlo660d17f2020-03-27 09:01:57 -070018import static org.junit.Assert.assertThrows;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000019
20import com.google.common.base.Joiner;
michajlo0a89cef2020-04-06 12:04:12 -070021import com.google.common.base.Strings;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000022import com.google.common.collect.ImmutableList;
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +000023import com.google.common.collect.ImmutableMap;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000024import com.google.common.collect.Iterables;
gregce7fa23ea2018-01-18 12:46:04 -080025import com.google.devtools.build.lib.analysis.config.transitions.NoTransition;
ulfjack35625252017-08-08 19:45:46 +020026import com.google.devtools.build.lib.analysis.skylark.SkylarkAttr;
27import com.google.devtools.build.lib.analysis.skylark.SkylarkAttr.Descriptor;
tomlu72642a22017-10-18 06:23:14 +020028import com.google.devtools.build.lib.analysis.skylark.SkylarkRuleClassFunctions.SkylarkRuleFunction;
ulfjack35625252017-08-08 19:45:46 +020029import com.google.devtools.build.lib.analysis.skylark.SkylarkRuleContext;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000030import com.google.devtools.build.lib.cmdline.Label;
michajlob839a512020-03-11 10:04:23 -070031import com.google.devtools.build.lib.events.Event;
32import com.google.devtools.build.lib.events.EventKind;
Dmitry Lomovf868b3e2017-01-17 10:25:28 +000033import com.google.devtools.build.lib.packages.AdvertisedProviderSet;
Dmitry Lomov0692c7f2016-09-30 16:43:30 +000034import com.google.devtools.build.lib.packages.AspectParameters;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000035import com.google.devtools.build.lib.packages.Attribute;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000036import com.google.devtools.build.lib.packages.BuildType;
juliexxia44e21432020-03-31 08:21:20 -070037import com.google.devtools.build.lib.packages.ExecGroup;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000038import com.google.devtools.build.lib.packages.ImplicitOutputsFunction;
39import com.google.devtools.build.lib.packages.PredicateWithMessage;
Dmitry Lomovf868b3e2017-01-17 10:25:28 +000040import com.google.devtools.build.lib.packages.RequiredProviders;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000041import com.google.devtools.build.lib.packages.RuleClass;
42import com.google.devtools.build.lib.packages.RuleClass.Builder.RuleClassType;
Dmitry Lomov950310f2017-03-01 17:45:12 +000043import com.google.devtools.build.lib.packages.SkylarkAspectClass;
cparsons0d55f4c2017-12-20 14:49:13 -080044import com.google.devtools.build.lib.packages.SkylarkDefinedAspect;
dslomov0667b832017-08-25 09:29:50 +020045import com.google.devtools.build.lib.packages.SkylarkInfo;
dslomovde965ac2017-07-31 21:07:51 +020046import com.google.devtools.build.lib.packages.SkylarkProvider;
gregce74d84d42020-04-17 10:02:03 -070047import com.google.devtools.build.lib.packages.StarlarkProviderIdentifier;
cparsons4ebf6c02018-08-17 14:49:36 -070048import com.google.devtools.build.lib.packages.StructImpl;
cparsons0c5c1c62018-05-24 10:37:03 -070049import com.google.devtools.build.lib.packages.StructProvider;
Googlerc5fcc862019-09-06 16:17:47 -070050import com.google.devtools.build.lib.packages.Type;
gregce1cd84ec2020-04-09 15:45:19 -070051import com.google.devtools.build.lib.skyframe.StarlarkImportLookupFunction;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000052import com.google.devtools.build.lib.skylark.util.SkylarkTestCase;
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +000053import com.google.devtools.build.lib.syntax.ClassObject;
Googlerd21a0d12019-11-21 13:52:30 -080054import com.google.devtools.build.lib.syntax.Depset;
Googlera9c93632019-11-13 10:48:07 -080055import com.google.devtools.build.lib.syntax.Dict;
laurentlb707acfe2018-04-13 06:09:30 -070056import com.google.devtools.build.lib.syntax.EvalException;
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +000057import com.google.devtools.build.lib.syntax.EvalUtils;
adonovan034220a2020-03-24 10:11:26 -070058import com.google.devtools.build.lib.syntax.FileOptions;
59import com.google.devtools.build.lib.syntax.Module;
Googler92578702019-11-21 12:19:31 -080060import com.google.devtools.build.lib.syntax.Mutability;
Googler2abde272019-09-17 12:06:08 -070061import com.google.devtools.build.lib.syntax.ParserInput;
Googler66d099e2019-09-26 08:07:06 -070062import com.google.devtools.build.lib.syntax.StarlarkFile;
Googler942e1c42019-11-12 13:11:44 -080063import com.google.devtools.build.lib.syntax.StarlarkList;
adonovan35c67852020-02-12 14:58:03 -080064import com.google.devtools.build.lib.syntax.StarlarkThread;
Googlerf0890f02019-10-01 07:28:48 -070065import com.google.devtools.build.lib.syntax.SyntaxError;
Googlercfd681f2019-11-11 07:24:02 -080066import com.google.devtools.build.lib.syntax.Tuple;
Dmitry Lomov8ff5a872017-03-04 00:58:14 +000067import com.google.devtools.build.lib.testutil.MoreAsserts;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000068import com.google.devtools.build.lib.util.FileTypeSet;
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +000069import java.util.Collection;
Googler92578702019-11-21 12:19:31 -080070import javax.annotation.Nullable;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000071import org.junit.Before;
Vladimir Moskvaf7c552c2017-01-12 17:17:15 +000072import org.junit.Rule;
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +000073import org.junit.Test;
Vladimir Moskvaf7c552c2017-01-12 17:17:15 +000074import org.junit.rules.ExpectedException;
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +000075import org.junit.runner.RunWith;
76import org.junit.runners.JUnit4;
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000077
Googlerba868542019-10-09 07:26:27 -070078/** Tests for SkylarkRuleClassFunctions. */
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +000079@RunWith(JUnit4.class)
Googlerba868542019-10-09 07:26:27 -070080public final class SkylarkRuleClassFunctionsTest extends SkylarkTestCase {
Vladimir Moskvaf7c552c2017-01-12 17:17:15 +000081 @Rule public ExpectedException thrown = ExpectedException.none();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000082
83 @Before
Taras Tsugrii7fe70472018-07-25 13:58:02 -070084 public final void createBuildFile() throws Exception {
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +000085 scratch.file(
86 "foo/BUILD",
87 "genrule(name = 'foo',",
88 " cmd = 'dummy_cmd',",
89 " srcs = ['a.txt', 'b.img'],",
90 " tools = ['t.exe'],",
91 " outs = ['c.txt'])",
92 "genrule(name = 'bar',",
93 " cmd = 'dummy_cmd',",
94 " srcs = [':jl', ':gl'],",
95 " outs = ['d.txt'])",
96 "java_library(name = 'jl',",
97 " srcs = ['a.java'])",
98 "genrule(name = 'gl',",
99 " cmd = 'touch $(OUTS)',",
100 " srcs = ['a.go'],",
101 " outs = [ 'gl.a', 'gl.gcgox', ],",
102 " output_to_bindir = 1,",
103 ")");
104 }
105
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000106 @Test
Florian Weikerte96b0b82015-09-25 11:35:11 +0000107 public void testCannotOverrideBuiltInAttribute() throws Exception {
Dmitry Lomov950310f2017-03-01 17:45:12 +0000108 ev.setFailFast(false);
brandjon8bd20162017-12-28 08:49:54 -0800109 evalAndExport(
110 "def impl(ctx):",
111 " return",
112 "r = rule(impl, attrs = {'tags': attr.string_list()})");
113 ev.assertContainsError(
114 "There is already a built-in attribute 'tags' which cannot be overridden");
Florian Weikerte96b0b82015-09-25 11:35:11 +0000115 }
116
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000117 @Test
Vladimir Moskvada574922016-10-05 16:36:49 +0000118 public void testCannotOverrideBuiltInAttributeName() throws Exception {
Dmitry Lomov950310f2017-03-01 17:45:12 +0000119 ev.setFailFast(false);
brandjon8bd20162017-12-28 08:49:54 -0800120 evalAndExport(
121 "def impl(ctx):",
122 " return",
123 "r = rule(impl, attrs = {'name': attr.string()})");
124 ev.assertContainsError(
125 "There is already a built-in attribute 'name' which cannot be overridden");
Vladimir Moskvada574922016-10-05 16:36:49 +0000126 }
127
128 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000129 public void testImplicitArgsAttribute() throws Exception {
Dmitry Lomov950310f2017-03-01 17:45:12 +0000130 ev.setFailFast(false);
Dmitry Lomov7b599452015-11-26 10:07:32 +0000131 evalAndExport(
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000132 "def _impl(ctx):",
133 " pass",
134 "exec_rule = rule(implementation = _impl, executable = True)",
135 "non_exec_rule = rule(implementation = _impl)");
lberkiaea56b32017-05-30 12:35:33 +0200136 assertThat(getRuleClass("exec_rule").hasAttr("args", Type.STRING_LIST)).isTrue();
137 assertThat(getRuleClass("non_exec_rule").hasAttr("args", Type.STRING_LIST)).isFalse();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000138 }
139
140 private RuleClass getRuleClass(String name) throws Exception {
tomlu72642a22017-10-18 06:23:14 +0200141 return ((SkylarkRuleFunction) lookup(name)).getRuleClass();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000142 }
143
Googler3fcfbe12019-08-28 08:10:11 -0700144 private void registerDummyStarlarkFunction() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -0700145 exec("def impl():", " pass");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000146 }
147
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000148 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000149 public void testAttrWithOnlyType() throws Exception {
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000150 Attribute attr = buildAttribute("a1", "attr.string_list()");
lberkiaea56b32017-05-30 12:35:33 +0200151 assertThat(attr.getType()).isEqualTo(Type.STRING_LIST);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000152 }
153
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000154 private Attribute buildAttribute(String name, String... lines) throws Exception {
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000155 String[] strings = lines.clone();
156 strings[strings.length - 1] = String.format("%s = %s", name, strings[strings.length - 1]);
157 evalAndExport(strings);
Googleree056632019-10-10 13:04:49 -0700158 Descriptor lookup = (Descriptor) lookup(name);
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000159 return lookup != null ? lookup.build(name) : null;
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000160 }
161
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000162 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000163 public void testOutputListAttr() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000164 Attribute attr = buildAttribute("a1", "attr.output_list()");
lberkiaea56b32017-05-30 12:35:33 +0200165 assertThat(attr.getType()).isEqualTo(BuildType.OUTPUT_LIST);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000166 }
167
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000168 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000169 public void testIntListAttr() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000170 Attribute attr = buildAttribute("a1", "attr.int_list()");
lberkiaea56b32017-05-30 12:35:33 +0200171 assertThat(attr.getType()).isEqualTo(Type.INTEGER_LIST);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000172 }
173
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000174 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000175 public void testOutputAttr() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000176 Attribute attr = buildAttribute("a1", "attr.output()");
lberkiaea56b32017-05-30 12:35:33 +0200177 assertThat(attr.getType()).isEqualTo(BuildType.OUTPUT);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000178 }
179
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000180 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000181 public void testStringDictAttr() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000182 Attribute attr = buildAttribute("a1", "attr.string_dict(default = {'a': 'b'})");
lberkiaea56b32017-05-30 12:35:33 +0200183 assertThat(attr.getType()).isEqualTo(Type.STRING_DICT);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000184 }
185
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000186 @Test
Francois-Rene Rideau028e3192015-10-29 14:26:59 +0000187 public void testStringListDictAttr() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000188 Attribute attr = buildAttribute("a1", "attr.string_list_dict(default = {'a': ['b', 'c']})");
lberkiaea56b32017-05-30 12:35:33 +0200189 assertThat(attr.getType()).isEqualTo(Type.STRING_LIST_DICT);
Francois-Rene Rideau028e3192015-10-29 14:26:59 +0000190 }
191
192 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000193 public void testAttrAllowedFileTypesAnyFile() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000194 Attribute attr = buildAttribute("a1", "attr.label_list(allow_files = True)");
lberkiaea56b32017-05-30 12:35:33 +0200195 assertThat(attr.getAllowedFileTypesPredicate()).isEqualTo(FileTypeSet.ANY_FILE);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000196 }
197
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000198 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000199 public void testAttrAllowedFileTypesWrongType() throws Exception {
Googleree056632019-10-10 13:04:49 -0700200 checkEvalErrorContains(
201 "allow_files should be a boolean or a string list", "attr.label_list(allow_files = 18)");
Laurent Le Brun2445df12016-05-11 14:36:40 +0000202 }
203
204 @Test
laurentlbe6ab3c42019-07-01 10:43:57 -0700205 public void testAttrNameSpecialCharactersAreForbidden() throws Exception {
laurentlbe6ab3c42019-07-01 10:43:57 -0700206 ev.setFailFast(false);
207 evalAndExport("def impl(ctx): return", "r = rule(impl, attrs = {'ab$c': attr.int()})");
laurentlb0fddb302019-08-16 14:02:01 -0700208 ev.assertContainsError("attribute name `ab$c` is not a valid identifier");
laurentlbe6ab3c42019-07-01 10:43:57 -0700209 }
210
211 @Test
212 public void testAttrNameCannotStartWithDigit() throws Exception {
laurentlbe6ab3c42019-07-01 10:43:57 -0700213 ev.setFailFast(false);
214 evalAndExport("def impl(ctx): return", "r = rule(impl, attrs = {'2_foo': attr.int()})");
laurentlb0fddb302019-08-16 14:02:01 -0700215 ev.assertContainsError("attribute name `2_foo` is not a valid identifier");
laurentlbe6ab3c42019-07-01 10:43:57 -0700216 }
217
218 @Test
michajlob839a512020-03-11 10:04:23 -0700219 public void testRuleClassTooManyAttributes() throws Exception {
220 ev.setFailFast(false);
221
222 ImmutableList.Builder<String> linesBuilder =
223 ImmutableList.<String>builder()
224 .add("def impl(ctx): return")
225 .add("r = rule(impl, attrs = {");
michajlo7475b772020-03-12 15:10:11 -0700226 for (int i = 0; i < 200; i++) {
michajlob839a512020-03-11 10:04:23 -0700227 linesBuilder.add(" 'attr" + i + "': attr.int(),");
228 }
229 linesBuilder.add("})");
230
231 evalAndExport(linesBuilder.build().toArray(new String[0]));
232
233 assertThat(ev.getEventCollector()).hasSize(1);
234 Event event = ev.getEventCollector().iterator().next();
235 assertThat(event.getKind()).isEqualTo(EventKind.ERROR);
236 assertThat(event.getMessage()).contains("Rule class r declared too many attributes");
237 }
238
239 @Test
michajlo0a89cef2020-04-06 12:04:12 -0700240 public void testRuleClassTooLongAttributeName() throws Exception {
241 ev.setFailFast(false);
242
243 evalAndExport(
244 "def impl(ctx): return;",
245 "r = rule(impl, attrs = { '" + Strings.repeat("x", 150) + "': attr.int() })");
246
247 assertThat(ev.getEventCollector()).hasSize(1);
248 Event event = ev.getEventCollector().iterator().next();
249 assertThat(event.getKind()).isEqualTo(EventKind.ERROR);
250 assertThat(event.getMessage())
251 .matches("Attribute r\\.x{150}'s name is too long \\(150 > 128\\)");
252 }
253
254 @Test
cparsonse5068582018-07-16 13:33:33 -0700255 public void testDisableDeprecatedParams() throws Exception {
Googleree056632019-10-10 13:04:49 -0700256 setSkylarkSemanticsOptions("--incompatible_disable_deprecated_attr_params=true");
cparsonse5068582018-07-16 13:33:33 -0700257
258 // Verify 'single_file' deprecation.
259 EvalException expected =
260 assertThrows(EvalException.class, () -> eval("attr.label(single_file = True)"));
261 assertThat(expected).hasMessageThat().contains(
262 "'single_file' is no longer supported. use allow_single_file instead.");
263 Attribute attr = buildAttribute("a1", "attr.label(allow_single_file = ['.xml'])");
264 assertThat(attr.isSingleArtifact()).isTrue();
265
266 // Verify 'non_empty' deprecation.
267 expected =
268 assertThrows(EvalException.class, () -> eval("attr.string_list(non_empty=True)"));
269 assertThat(expected).hasMessageThat().contains(
270 "'non_empty' is no longer supported. use allow_empty instead.");
271 attr = buildAttribute("a2", "attr.string_list(allow_empty=False)");
272 assertThat(attr.isNonEmpty()).isTrue();
273 }
274
275 @Test
Laurent Le Brun50681c12016-07-05 10:08:54 +0000276 public void testAttrAllowedSingleFileTypesWrongType() throws Exception {
Googleree056632019-10-10 13:04:49 -0700277 checkEvalErrorContains(
Laurent Le Brun50681c12016-07-05 10:08:54 +0000278 "allow_single_file should be a boolean or a string list",
279 "attr.label(allow_single_file = 18)");
280 }
281
282 @Test
Laurent Le Brun2445df12016-05-11 14:36:40 +0000283 public void testAttrWithList() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000284 Attribute attr = buildAttribute("a1", "attr.label_list(allow_files = ['.xml'])");
lberkiaea56b32017-05-30 12:35:33 +0200285 assertThat(attr.getAllowedFileTypesPredicate().apply("a.xml")).isTrue();
286 assertThat(attr.getAllowedFileTypesPredicate().apply("a.txt")).isFalse();
287 assertThat(attr.isSingleArtifact()).isFalse();
Laurent Le Brun50681c12016-07-05 10:08:54 +0000288 }
289
290 @Test
291 public void testAttrSingleFileWithList() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000292 Attribute attr = buildAttribute("a1", "attr.label(allow_single_file = ['.xml'])");
lberkiaea56b32017-05-30 12:35:33 +0200293 assertThat(attr.getAllowedFileTypesPredicate().apply("a.xml")).isTrue();
294 assertThat(attr.getAllowedFileTypesPredicate().apply("a.txt")).isFalse();
295 assertThat(attr.isSingleArtifact()).isTrue();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000296 }
297
gregce74d84d42020-04-17 10:02:03 -0700298 private static StarlarkProviderIdentifier legacy(String legacyId) {
299 return StarlarkProviderIdentifier.forLegacy(legacyId);
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000300 }
301
gregce74d84d42020-04-17 10:02:03 -0700302 private static StarlarkProviderIdentifier declared(String exportedName) {
303 return StarlarkProviderIdentifier.forKey(
dslomovde965ac2017-07-31 21:07:51 +0200304 new SkylarkProvider.SkylarkKey(FAKE_LABEL, exportedName));
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000305 }
306
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000307 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000308 public void testAttrWithProviders() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000309 Attribute attr =
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000310 buildAttribute("a1",
311 "b = provider()",
312 "attr.label_list(allow_files = True, providers = ['a', b])");
dslomovc13bb392017-08-02 23:29:54 +0200313 assertThat(attr.getRequiredProviders().isSatisfiedBy(set(legacy("a"), declared("b")))).isTrue();
314 assertThat(attr.getRequiredProviders().isSatisfiedBy(set(legacy("a")))).isFalse();
315 }
316
317 @Test
318 public void testAttrWithProvidersOneEmpty() throws Exception {
319 Attribute attr =
320 buildAttribute(
321 "a1",
322 "b = provider()",
323 "attr.label_list(allow_files = True, providers = [['a', b],[]])");
324 assertThat(attr.getRequiredProviders().acceptsAny()).isTrue();
dslomovc32e1b12017-07-31 19:23:52 +0200325 }
326
dslomovc32e1b12017-07-31 19:23:52 +0200327 @Test
Yun Peng83fbb91a2016-02-23 18:37:44 +0000328 public void testAttrWithProvidersList() throws Exception {
329 Attribute attr =
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000330 buildAttribute("a1",
331 "b = provider()",
332 "attr.label_list(allow_files = True, providers = [['a', b], ['c']])");
dslomovc13bb392017-08-02 23:29:54 +0200333 assertThat(attr.getRequiredProviders().isSatisfiedBy(set(legacy("a"), declared("b")))).isTrue();
334 assertThat(attr.getRequiredProviders().isSatisfiedBy(set(legacy("c")))).isTrue();
335 assertThat(attr.getRequiredProviders().isSatisfiedBy(set(legacy("a")))).isFalse();
336 }
337
gregce74d84d42020-04-17 10:02:03 -0700338 private static AdvertisedProviderSet set(StarlarkProviderIdentifier... ids) {
dslomovc13bb392017-08-02 23:29:54 +0200339 AdvertisedProviderSet.Builder builder = AdvertisedProviderSet.builder();
gregce74d84d42020-04-17 10:02:03 -0700340 for (StarlarkProviderIdentifier id : ids) {
dslomovc13bb392017-08-02 23:29:54 +0200341 builder.addSkylark(id);
342 }
343 return builder.build();
Yun Peng83fbb91a2016-02-23 18:37:44 +0000344 }
345
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000346 private void checkAttributeError(String expectedMessage, String... lines) throws Exception {
347 ev.setFailFast(false);
348 buildAttribute("fakeAttribute", lines);
349 MoreAsserts.assertContainsEvent(ev.getEventCollector(), expectedMessage);
350 }
351
Yun Peng83fbb91a2016-02-23 18:37:44 +0000352 @Test
353 public void testAttrWithWrongProvidersList() throws Exception {
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000354 checkAttributeError(
355 "element in 'providers' is of unexpected type. Either all elements should be providers,"
356 + " or all elements should be lists of providers,"
357 + " but got list with an element of type int.",
Yun Pengda9410c2016-03-18 21:14:51 +0000358 "attr.label_list(allow_files = True, providers = [['a', 1], ['c']])");
Yun Peng83fbb91a2016-02-23 18:37:44 +0000359
Dmitry Lomov8ff5a872017-03-04 00:58:14 +0000360 checkAttributeError(
361 "element in 'providers' is of unexpected type. Either all elements should be providers,"
362 + " or all elements should be lists of providers,"
363 + " but got an element of type string.",
364 "b = provider()",
365 "attr.label_list(allow_files = True, providers = [['a', b], 'c'])");
366
367 checkAttributeError(
368 "element in 'providers' is of unexpected type. Either all elements should be providers,"
369 + " or all elements should be lists of providers,"
370 + " but got an element of type string.",
371 "c = provider()",
372 "attr.label_list(allow_files = True, providers = [['a', b], c])");
Yun Peng83fbb91a2016-02-23 18:37:44 +0000373 }
374
375 @Test
Dmitry Lomov5a8f1c02015-11-26 10:49:16 +0000376 public void testLabelListWithAspects() throws Exception {
Dmitry Lomov950310f2017-03-01 17:45:12 +0000377 evalAndExport(
Yun Pengda9410c2016-03-18 21:14:51 +0000378 "def _impl(target, ctx):",
379 " pass",
380 "my_aspect = aspect(implementation = _impl)",
Dmitry Lomov950310f2017-03-01 17:45:12 +0000381 "a = attr.label_list(aspects = [my_aspect])");
Googleree056632019-10-10 13:04:49 -0700382 SkylarkAttr.Descriptor attr = (SkylarkAttr.Descriptor) lookup("a");
383 SkylarkDefinedAspect aspect = (SkylarkDefinedAspect) lookup("my_aspect");
Dmitry Lomov5a8f1c02015-11-26 10:49:16 +0000384 assertThat(aspect).isNotNull();
Dmitry Lomov950310f2017-03-01 17:45:12 +0000385 assertThat(attr.build("xxx").getAspectClasses()).containsExactly(aspect.getAspectClass());
Dmitry Lomov5a8f1c02015-11-26 10:49:16 +0000386 }
387
388 @Test
Dmitry Lomov950310f2017-03-01 17:45:12 +0000389 public void testLabelWithAspects() throws Exception {
390 evalAndExport(
391 "def _impl(target, ctx):",
392 " pass",
393 "my_aspect = aspect(implementation = _impl)",
394 "a = attr.label(aspects = [my_aspect])");
Googleree056632019-10-10 13:04:49 -0700395 SkylarkAttr.Descriptor attr = (SkylarkAttr.Descriptor) lookup("a");
396 SkylarkDefinedAspect aspect = (SkylarkDefinedAspect) lookup("my_aspect");
Dmitry Lomov950310f2017-03-01 17:45:12 +0000397 assertThat(aspect).isNotNull();
398 assertThat(attr.build("xxx").getAspectClasses()).containsExactly(aspect.getAspectClass());
399 }
400
Dmitry Lomov950310f2017-03-01 17:45:12 +0000401 @Test
Dmitry Lomov5a8f1c02015-11-26 10:49:16 +0000402 public void testLabelListWithAspectsError() throws Exception {
Googleree056632019-10-10 13:04:49 -0700403 checkEvalErrorContains(
adonovan85803902020-04-16 14:46:57 -0700404 "at index 0 of aspects, got element of type int, want Aspect",
Dmitry Lomov5a8f1c02015-11-26 10:49:16 +0000405 "def _impl(target, ctx):",
406 " pass",
407 "my_aspect = aspect(implementation = _impl)",
Laurent Le Brunc31f3512016-12-29 21:41:33 +0000408 "attr.label_list(aspects = [my_aspect, 123])");
Dmitry Lomov5a8f1c02015-11-26 10:49:16 +0000409 }
410
411 @Test
Dmitry Lomovc1b1eed2015-11-26 11:18:12 +0000412 public void testAspectExtraDeps() throws Exception {
413 evalAndExport(
414 "def _impl(target, ctx):",
415 " pass",
416 "my_aspect = aspect(_impl,",
Dmitry Lomovace678e2015-12-16 15:10:20 +0000417 " attrs = { '_extra_deps' : attr.label(default = Label('//foo/bar:baz')) }",
418 ")");
Googleree056632019-10-10 13:04:49 -0700419 SkylarkDefinedAspect aspect = (SkylarkDefinedAspect) lookup("my_aspect");
Googler74558fc2016-05-06 21:47:42 +0000420 Attribute attribute = Iterables.getOnlyElement(aspect.getAttributes());
421 assertThat(attribute.getName()).isEqualTo("$extra_deps");
422 assertThat(attribute.getDefaultValue(null))
dannarkda327bb2018-06-22 11:44:27 -0700423 .isEqualTo(
424 Label.parseAbsolute(
425 "//foo/bar:baz",
426 /* defaultToMain= */ false,
427 /* repositoryMapping= */ ImmutableMap.of()));
Dmitry Lomovace678e2015-12-16 15:10:20 +0000428 }
429
430 @Test
Googler74558fc2016-05-06 21:47:42 +0000431 public void testAspectParameter() throws Exception {
432 evalAndExport(
Dmitry Lomovace678e2015-12-16 15:10:20 +0000433 "def _impl(target, ctx):",
434 " pass",
435 "my_aspect = aspect(_impl,",
Googler74558fc2016-05-06 21:47:42 +0000436 " attrs = { 'param' : attr.string(values=['a', 'b']) }",
Dmitry Lomovace678e2015-12-16 15:10:20 +0000437 ")");
Googleree056632019-10-10 13:04:49 -0700438 SkylarkDefinedAspect aspect = (SkylarkDefinedAspect) lookup("my_aspect");
Googler74558fc2016-05-06 21:47:42 +0000439 Attribute attribute = Iterables.getOnlyElement(aspect.getAttributes());
440 assertThat(attribute.getName()).isEqualTo("param");
441 }
Michajlo Matijkiw6d471412016-08-09 20:35:45 +0000442
Googler74558fc2016-05-06 21:47:42 +0000443 @Test
444 public void testAspectParameterRequiresValues() throws Exception {
Googleree056632019-10-10 13:04:49 -0700445 checkEvalErrorContains(
Googler74558fc2016-05-06 21:47:42 +0000446 "Aspect parameter attribute 'param' must have type 'string' and use the 'values' "
Googleree056632019-10-10 13:04:49 -0700447 + "restriction.",
Googler74558fc2016-05-06 21:47:42 +0000448 "def _impl(target, ctx):",
449 " pass",
450 "my_aspect = aspect(_impl,",
451 " attrs = { 'param' : attr.string(default = 'c') }",
452 ")");
453 }
454
455 @Test
456 public void testAspectParameterBadType() throws Exception {
Googleree056632019-10-10 13:04:49 -0700457 checkEvalErrorContains(
Googler74558fc2016-05-06 21:47:42 +0000458 "Aspect parameter attribute 'param' must have type 'string' and use the 'values' "
Googleree056632019-10-10 13:04:49 -0700459 + "restriction.",
Googler74558fc2016-05-06 21:47:42 +0000460 "def _impl(target, ctx):",
461 " pass",
462 "my_aspect = aspect(_impl,",
463 " attrs = { 'param' : attr.label(default = Label('//foo/bar:baz')) }",
464 ")");
465 }
466
467 @Test
468 public void testAspectParameterAndExtraDeps() throws Exception {
469 evalAndExport(
470 "def _impl(target, ctx):",
471 " pass",
472 "my_aspect = aspect(_impl,",
473 " attrs = { 'param' : attr.string(values=['a', 'b']),",
474 " '_extra' : attr.label(default = Label('//foo/bar:baz')) }",
475 ")");
Googleree056632019-10-10 13:04:49 -0700476 SkylarkDefinedAspect aspect = (SkylarkDefinedAspect) lookup("my_aspect");
Googler74558fc2016-05-06 21:47:42 +0000477 assertThat(aspect.getAttributes()).hasSize(2);
478 assertThat(aspect.getParamAttributes()).containsExactly("param");
Dmitry Lomovace678e2015-12-16 15:10:20 +0000479 }
480
481 @Test
482 public void testAspectNoDefaultValueAttribute() throws Exception {
Googleree056632019-10-10 13:04:49 -0700483 checkEvalErrorContains(
Dmitry Lomovace678e2015-12-16 15:10:20 +0000484 "Aspect attribute '_extra_deps' has no default value",
485 "def _impl(target, ctx):",
486 " pass",
487 "my_aspect = aspect(_impl,",
488 " attrs = { '_extra_deps' : attr.label() }",
489 ")");
Dmitry Lomovc1b1eed2015-11-26 11:18:12 +0000490 }
491
492 @Test
John Cater9a8d16e2017-07-05 16:12:07 -0400493 public void testAspectAddToolchain() throws Exception {
494 scratch.file("test/BUILD", "toolchain_type(name = 'my_toolchain_type')");
495 evalAndExport(
496 "def _impl(ctx): pass", "a1 = aspect(_impl, toolchains=['//test:my_toolchain_type'])");
cparsons0d55f4c2017-12-20 14:49:13 -0800497 SkylarkDefinedAspect a = (SkylarkDefinedAspect) lookup("a1");
John Cater9a8d16e2017-07-05 16:12:07 -0400498 assertThat(a.getRequiredToolchains()).containsExactly(makeLabel("//test:my_toolchain_type"));
499 }
500
501 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000502 public void testNonLabelAttrWithProviders() throws Exception {
Googleree056632019-10-10 13:04:49 -0700503 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800504 "unexpected keyword argument 'providers'", "attr.string(providers = ['a'])");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000505 }
506
cparsonse2d200f2018-03-06 16:15:11 -0800507 private static final RuleClass.ConfiguredTargetFactory<Object, Object, Exception>
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000508 DUMMY_CONFIGURED_TARGET_FACTORY =
dslomovc13bb392017-08-02 23:29:54 +0200509 ruleContext -> {
510 throw new IllegalStateException();
511 };
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000512
513 private RuleClass ruleClass(String name) {
514 return new RuleClass.Builder(name, RuleClassType.NORMAL, false)
515 .factory(DUMMY_CONFIGURED_TARGET_FACTORY)
516 .add(Attribute.attr("tags", Type.STRING_LIST))
517 .build();
518 }
vladmos9c787fa2017-07-04 11:45:22 -0400519
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000520 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000521 public void testAttrAllowedRuleClassesSpecificRuleClasses() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000522 Attribute attr = buildAttribute("a",
523 "attr.label_list(allow_rules = ['java_binary'], allow_files = True)");
lberkiaea56b32017-05-30 12:35:33 +0200524 assertThat(attr.getAllowedRuleClassesPredicate().apply(ruleClass("java_binary"))).isTrue();
525 assertThat(attr.getAllowedRuleClassesPredicate().apply(ruleClass("genrule"))).isFalse();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000526 }
vladmos9c787fa2017-07-04 11:45:22 -0400527
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000528 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000529 public void testAttrDefaultValue() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000530 Attribute attr = buildAttribute("a1", "attr.string(default = 'some value')");
juliexxia84d1a662018-12-26 14:07:04 -0800531 assertThat(attr.getDefaultValueUnchecked()).isEqualTo("some value");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000532 }
533
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000534 @Test
vladmos9c787fa2017-07-04 11:45:22 -0400535 public void testLabelAttrDefaultValueAsString() throws Exception {
536 Attribute sligleAttr = buildAttribute("a1", "attr.label(default = '//foo:bar')");
juliexxia84d1a662018-12-26 14:07:04 -0800537 assertThat(sligleAttr.getDefaultValueUnchecked())
dannarkda327bb2018-06-22 11:44:27 -0700538 .isEqualTo(
539 Label.parseAbsolute(
540 "//foo:bar",
541 /* defaultToMain= */ false,
542 /* repositoryMapping= */ ImmutableMap.of()));
vladmos9c787fa2017-07-04 11:45:22 -0400543
544 Attribute listAttr =
545 buildAttribute("a2", "attr.label_list(default = ['//foo:bar', '//bar:foo'])");
juliexxia84d1a662018-12-26 14:07:04 -0800546 assertThat(listAttr.getDefaultValueUnchecked())
vladmos9c787fa2017-07-04 11:45:22 -0400547 .isEqualTo(
548 ImmutableList.of(
dannarkda327bb2018-06-22 11:44:27 -0700549 Label.parseAbsolute(
550 "//foo:bar",
551 /* defaultToMain= */ false,
552 /* repositoryMapping= */ ImmutableMap.of()),
553 Label.parseAbsolute(
554 "//bar:foo",
555 /* defaultToMain= */ false,
556 /*repositoryMapping= */ ImmutableMap.of())));
vladmos9c787fa2017-07-04 11:45:22 -0400557
558 Attribute dictAttr =
559 buildAttribute("a3", "attr.label_keyed_string_dict(default = {'//foo:bar': 'my value'})");
juliexxia84d1a662018-12-26 14:07:04 -0800560 assertThat(dictAttr.getDefaultValueUnchecked())
dannarkda327bb2018-06-22 11:44:27 -0700561 .isEqualTo(
562 ImmutableMap.of(
563 Label.parseAbsolute(
564 "//foo:bar",
565 /* defaultToMain= */ false,
566 /* repositoryMapping= */ ImmutableMap.of()),
567 "my value"));
vladmos9c787fa2017-07-04 11:45:22 -0400568 }
569
570 @Test
571 public void testLabelAttrDefaultValueAsStringBadValue() throws Exception {
Googleree056632019-10-10 13:04:49 -0700572 checkEvalErrorContains(
vladmos9c787fa2017-07-04 11:45:22 -0400573 "invalid label '/foo:bar' in parameter 'default' of attribute 'label': "
janakrd3fe5e72018-03-30 12:49:12 -0700574 + "invalid target name '/foo:bar'",
vladmos9c787fa2017-07-04 11:45:22 -0400575 "attr.label(default = '/foo:bar')");
576
Googleree056632019-10-10 13:04:49 -0700577 checkEvalErrorContains(
vladmos9c787fa2017-07-04 11:45:22 -0400578 "invalid label '/bar:foo' in element 1 of parameter 'default' of attribute "
janakrd3fe5e72018-03-30 12:49:12 -0700579 + "'label_list': invalid target name '/bar:foo'",
vladmos9c787fa2017-07-04 11:45:22 -0400580 "attr.label_list(default = ['//foo:bar', '/bar:foo'])");
581
Googleree056632019-10-10 13:04:49 -0700582 checkEvalErrorContains(
janakrd3fe5e72018-03-30 12:49:12 -0700583 "invalid label '/bar:foo' in dict key element: invalid target name '/bar:foo'",
vladmos9c787fa2017-07-04 11:45:22 -0400584 "attr.label_keyed_string_dict(default = {'//foo:bar': 'a', '/bar:foo': 'b'})");
585 }
586
587 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000588 public void testAttrDefaultValueBadType() throws Exception {
adonovan3f602f22020-01-08 10:28:10 -0800589 checkEvalErrorContains("got value of type 'int', want 'string'", "attr.string(default = 1)");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000590 }
591
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000592 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000593 public void testAttrMandatory() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000594 Attribute attr = buildAttribute("a1", "attr.string(mandatory=True)");
lberkiaea56b32017-05-30 12:35:33 +0200595 assertThat(attr.isMandatory()).isTrue();
596 assertThat(attr.isNonEmpty()).isFalse();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000597 }
598
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000599 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000600 public void testAttrNonEmpty() throws Exception {
Googleree056632019-10-10 13:04:49 -0700601 setSkylarkSemanticsOptions("--incompatible_disable_deprecated_attr_params=false");
602 reset();
laurentlb140c04b2019-05-21 06:56:28 -0700603
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000604 Attribute attr = buildAttribute("a1", "attr.string_list(non_empty=True)");
lberkiaea56b32017-05-30 12:35:33 +0200605 assertThat(attr.isNonEmpty()).isTrue();
606 assertThat(attr.isMandatory()).isFalse();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000607 }
608
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000609 @Test
Laurent Le Brunbc16f722016-07-06 13:40:24 +0000610 public void testAttrAllowEmpty() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000611 Attribute attr = buildAttribute("a1", "attr.string_list(allow_empty=False)");
lberkiaea56b32017-05-30 12:35:33 +0200612 assertThat(attr.isNonEmpty()).isTrue();
613 assertThat(attr.isMandatory()).isFalse();
Laurent Le Brunbc16f722016-07-06 13:40:24 +0000614 }
615
616 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000617 public void testAttrBadKeywordArguments() throws Exception {
Googleree056632019-10-10 13:04:49 -0700618 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800619 "string() got unexpected keyword argument 'bad_keyword'", "attr.string(bad_keyword = '')");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000620 }
621
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000622 @Test
Laurent Le Brunc4ddf6f2016-07-04 13:38:38 +0000623 public void testAttrCfg() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000624 Attribute attr = buildAttribute("a1", "attr.label(cfg = 'host', allow_files = True)");
jcaterb44167f2019-04-02 12:06:26 -0700625 assertThat(attr.getTransitionFactory().isHost()).isTrue();
Laurent Le Brunc4ddf6f2016-07-04 13:38:38 +0000626 }
627
628 @Test
Vladimir Moskva5a510772016-11-23 19:03:38 +0000629 public void testAttrCfgTarget() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000630 Attribute attr = buildAttribute("a1", "attr.label(cfg = 'target', allow_files = True)");
John Cater5adcd3e2019-03-28 10:14:32 -0700631 assertThat(NoTransition.isInstance(attr.getTransitionFactory())).isTrue();
Vladimir Moskva5a510772016-11-23 19:03:38 +0000632 }
633
634 @Test
gregcebceecab2018-06-27 17:44:45 -0700635 public void incompatibleDataTransition() throws Exception {
gregcebceecab2018-06-27 17:44:45 -0700636 EvalException expected =
637 assertThrows(EvalException.class, () -> eval("attr.label(cfg = 'data')"));
laurentlbd576ed02019-03-26 15:35:06 -0700638 assertThat(expected).hasMessageThat().contains("cfg must be either 'host' or 'target'");
gregcebceecab2018-06-27 17:44:45 -0700639 }
640
641 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000642 public void testAttrValues() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000643 Attribute attr = buildAttribute("a1", "attr.string(values = ['ab', 'cd'])");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000644 PredicateWithMessage<Object> predicate = attr.getAllowedValues();
645 assertThat(predicate.apply("ab")).isTrue();
646 assertThat(predicate.apply("xy")).isFalse();
647 }
648
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000649 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000650 public void testAttrIntValues() throws Exception {
Dmitry Lomov460db0f2016-11-24 10:54:19 +0000651 Attribute attr = buildAttribute("a1", "attr.int(values = [1, 2])");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000652 PredicateWithMessage<Object> predicate = attr.getAllowedValues();
653 assertThat(predicate.apply(2)).isTrue();
654 assertThat(predicate.apply(3)).isFalse();
655 }
656
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000657 @Test
allevato45b79e52017-07-07 21:40:50 +0200658 public void testAttrDoc() throws Exception {
659 // We don't actually store the doc in the attr definition; right now it's just meant to be
660 // extracted by documentation generating tools. So we don't have anything to assert and we just
661 // verify that no exceptions were thrown from building them.
662 buildAttribute("a1", "attr.bool(doc='foo')");
663 buildAttribute("a2", "attr.int(doc='foo')");
664 buildAttribute("a3", "attr.int_list(doc='foo')");
665 buildAttribute("a4", "attr.label(doc='foo')");
666 buildAttribute("a5", "attr.label_keyed_string_dict(doc='foo')");
667 buildAttribute("a6", "attr.label_list(doc='foo')");
allevato45b79e52017-07-07 21:40:50 +0200668 buildAttribute("a8", "attr.output(doc='foo')");
669 buildAttribute("a9", "attr.output_list(doc='foo')");
670 buildAttribute("a10", "attr.string(doc='foo')");
671 buildAttribute("a11", "attr.string_dict(doc='foo')");
672 buildAttribute("a12", "attr.string_list(doc='foo')");
673 buildAttribute("a13", "attr.string_list_dict(doc='foo')");
674 }
675
676 @Test
laurentlbd8d37762018-10-26 14:08:33 -0700677 public void testNoAttrLicense() throws Exception {
laurentlbd8d37762018-10-26 14:08:33 -0700678 EvalException expected = assertThrows(EvalException.class, () -> eval("attr.license()"));
679 assertThat(expected)
680 .hasMessageThat()
adonovan4e2b4952019-12-10 12:19:20 -0800681 .contains("'attr (a language module)' value has no field or method 'license'");
laurentlbd8d37762018-10-26 14:08:33 -0700682 }
683
684 @Test
allevato45b79e52017-07-07 21:40:50 +0200685 public void testAttrDocValueBadType() throws Exception {
adonovan3f602f22020-01-08 10:28:10 -0800686 checkEvalErrorContains("got value of type 'int', want 'string'", "attr.string(doc = 1)");
allevato45b79e52017-07-07 21:40:50 +0200687 }
688
689 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000690 public void testRuleImplementation() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000691 evalAndExport("def impl(ctx): return None", "rule1 = rule(impl)");
tomlu72642a22017-10-18 06:23:14 +0200692 RuleClass c = ((SkylarkRuleFunction) lookup("rule1")).getRuleClass();
lberkiaea56b32017-05-30 12:35:33 +0200693 assertThat(c.getConfiguredTargetFunction().getName()).isEqualTo("impl");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000694 }
695
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000696 @Test
allevato45b79e52017-07-07 21:40:50 +0200697 public void testRuleDoc() throws Exception {
698 evalAndExport("def impl(ctx): return None", "rule1 = rule(impl, doc='foo')");
699 }
700
701 @Test
adonovan3f602f22020-01-08 10:28:10 -0800702 public void testFunctionAsAttrDefault() throws Exception {
703 exec("def f(): pass");
704
adonovanaf226dd2019-12-17 12:43:00 -0800705 // Late-bound attributes, which are computed during analysis as a function
706 // of the configuration, are only available for attributes involving labels:
707 // attr.label
708 // attr.label_list
709 // attr.label_keyed_string_dict
710 // attr.output,
711 // attr.output_list
adonovan3f602f22020-01-08 10:28:10 -0800712 // (See testRuleClassImplicitOutputFunctionDependingOnComputedAttribute
713 // for a more detailed positive test.)
714 evalAndExport(
715 "attr.label(default=f)",
716 "attr.label_list(default=f)",
717 "attr.label_keyed_string_dict(default=f)");
718 // Note: the default parameter of attr.output{,_list} is deprecated
719 // (see --incompatible_no_output_attr_default)
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000720
adonovan3f602f22020-01-08 10:28:10 -0800721 // For all other attribute types, the default value may not be a function.
adonovanaf226dd2019-12-17 12:43:00 -0800722 //
adonovan3f602f22020-01-08 10:28:10 -0800723 // (This is a regression test for github.com/bazelbuild/bazel/issues/9463.
724 // The loading-phase feature of "computed attribute defaults" is not exposed
725 // to Starlark; the bug was that the @SkylarkCallable
adonovanaf226dd2019-12-17 12:43:00 -0800726 // annotation was more permissive than the method declaration.)
adonovan3f602f22020-01-08 10:28:10 -0800727 checkEvalErrorContains("got value of type 'function', want 'string'", "attr.string(default=f)");
adonovanaf226dd2019-12-17 12:43:00 -0800728 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800729 "got value of type 'function', want 'sequence of strings'", "attr.string_list(default=f)");
730 checkEvalErrorContains("got value of type 'function', want 'int'", "attr.int(default=f)");
adonovanaf226dd2019-12-17 12:43:00 -0800731 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800732 "got value of type 'function', want 'sequence of ints'", "attr.int_list(default=f)");
733 checkEvalErrorContains("got value of type 'function', want 'bool'", "attr.bool(default=f)");
adonovanaf226dd2019-12-17 12:43:00 -0800734 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800735 "got value of type 'function', want 'dict'", "attr.string_dict(default=f)");
adonovanaf226dd2019-12-17 12:43:00 -0800736 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800737 "got value of type 'function', want 'dict'", "attr.string_list_dict(default=f)");
738 // Note: attr.license appears to be disabled already.
739 // (see --incompatible_no_attr_license)
adonovanaf226dd2019-12-17 12:43:00 -0800740 }
741
Dmitry Lomov7b599452015-11-26 10:07:32 +0000742 private static final Label FAKE_LABEL = Label.parseAbsoluteUnchecked("//fake/label.bzl");
743
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000744 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000745 public void testRuleAddAttribute() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000746 evalAndExport("def impl(ctx): return None", "r1 = rule(impl, attrs={'a1': attr.string()})");
tomlu72642a22017-10-18 06:23:14 +0200747 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
lberkiaea56b32017-05-30 12:35:33 +0200748 assertThat(c.hasAttr("a1", Type.STRING)).isTrue();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000749 }
750
Googlerba868542019-10-09 07:26:27 -0700751 private void evalAndExport(String... lines) throws Exception {
Googler2abde272019-09-17 12:06:08 -0700752 ParserInput input = ParserInput.fromLines(lines);
adonovan35c67852020-02-12 14:58:03 -0800753 StarlarkThread thread = ev.getStarlarkThread();
adonovan034220a2020-03-24 10:11:26 -0700754 Module module = thread.getGlobals();
755 StarlarkFile file = EvalUtils.parseAndValidate(input, FileOptions.DEFAULT, module);
Googlerba868542019-10-09 07:26:27 -0700756 if (!file.ok()) {
adonovanac1c41e2020-04-01 14:28:49 -0700757 throw new SyntaxError.Exception(file.errors());
Googlerf0890f02019-10-01 07:28:48 -0700758 }
gregce1cd84ec2020-04-09 15:45:19 -0700759 StarlarkImportLookupFunction.execAndExport(file, FAKE_LABEL, ev.getEventHandler(), thread);
Dmitry Lomov7b599452015-11-26 10:07:32 +0000760 }
761
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000762 @Test
Jon Brandveinded4fbb2017-01-18 22:21:04 +0000763 public void testExportAliasedName() throws Exception {
764 // When there are multiple names aliasing the same SkylarkExportable, the first one to be
765 // declared should be used. Make sure we're not using lexicographical order, hash order,
766 // non-deterministic order, or anything else.
767 evalAndExport(
768 "def _impl(ctx): pass",
769 "d = rule(implementation = _impl)",
770 "a = d",
771 // Having more names improves the chance that non-determinism will be caught.
772 "b = d",
773 "c = d",
774 "e = d",
775 "f = d",
776 "foo = d",
777 "bar = d",
778 "baz = d",
779 "x = d",
780 "y = d",
781 "z = d");
tomlu72642a22017-10-18 06:23:14 +0200782 String dName = ((SkylarkRuleFunction) lookup("d")).getRuleClass().getName();
783 String fooName = ((SkylarkRuleFunction) lookup("foo")).getRuleClass().getName();
Jon Brandveinded4fbb2017-01-18 22:21:04 +0000784 assertThat(dName).isEqualTo("d");
785 assertThat(fooName).isEqualTo("d");
786 }
787
788 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000789 public void testOutputToGenfiles() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000790 evalAndExport("def impl(ctx): pass", "r1 = rule(impl, output_to_genfiles=True)");
tomlu72642a22017-10-18 06:23:14 +0200791 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
lberkiaea56b32017-05-30 12:35:33 +0200792 assertThat(c.hasBinaryOutput()).isFalse();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000793 }
794
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000795 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000796 public void testRuleAddMultipleAttributes() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000797 evalAndExport(
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000798 "def impl(ctx): return None",
799 "r1 = rule(impl,",
800 " attrs = {",
801 " 'a1': attr.label_list(allow_files=True),",
802 " 'a2': attr.int()",
803 "})");
tomlu72642a22017-10-18 06:23:14 +0200804 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
lberkiaea56b32017-05-30 12:35:33 +0200805 assertThat(c.hasAttr("a1", BuildType.LABEL_LIST)).isTrue();
806 assertThat(c.hasAttr("a2", Type.INTEGER)).isTrue();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000807 }
Taras Tsugrii7fe70472018-07-25 13:58:02 -0700808
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000809 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000810 public void testRuleAttributeFlag() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000811 evalAndExport(
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000812 "def impl(ctx): return None",
813 "r1 = rule(impl, attrs = {'a1': attr.string(mandatory=True)})");
tomlu72642a22017-10-18 06:23:14 +0200814 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
lberkiaea56b32017-05-30 12:35:33 +0200815 assertThat(c.getAttributeByName("a1").isMandatory()).isTrue();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000816 }
817
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000818 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000819 public void testRuleOutputs() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000820 evalAndExport(
821 "def impl(ctx): return None",
822 "r1 = rule(impl, outputs = {'a': 'a.txt'})");
tomlu72642a22017-10-18 06:23:14 +0200823 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
Michajlo Matijkiw6d471412016-08-09 20:35:45 +0000824 ImplicitOutputsFunction function = c.getDefaultImplicitOutputsFunction();
vladmos076977e2017-12-02 14:15:32 -0800825 assertThat(function.getImplicitOutputs(ev.getEventHandler(), null)).containsExactly("a.txt");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000826 }
827
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000828 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000829 public void testRuleUnknownKeyword() throws Exception {
Googler3fcfbe12019-08-28 08:10:11 -0700830 registerDummyStarlarkFunction();
Googleree056632019-10-10 13:04:49 -0700831 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800832 "unexpected keyword argument 'bad_keyword'", "rule(impl, bad_keyword = 'some text')");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000833 }
834
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000835 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000836 public void testRuleImplementationMissing() throws Exception {
Googleree056632019-10-10 13:04:49 -0700837 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800838 "rule() missing 1 required positional argument: implementation", "rule(attrs = {})");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000839 }
840
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000841 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000842 public void testRuleBadTypeForAdd() throws Exception {
Googler3fcfbe12019-08-28 08:10:11 -0700843 registerDummyStarlarkFunction();
Googleree056632019-10-10 13:04:49 -0700844 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -0800845 "in call to rule(), parameter 'attrs' got value of type 'string', want 'dict or NoneType'",
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000846 "rule(impl, attrs = 'some text')");
847 }
848
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000849 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000850 public void testRuleBadTypeInAdd() throws Exception {
Googler3fcfbe12019-08-28 08:10:11 -0700851 registerDummyStarlarkFunction();
Googleree056632019-10-10 13:04:49 -0700852 checkEvalErrorContains(
adonovan07fb6a52020-03-20 14:36:28 -0700853 "got dict<string, string> for 'attrs', want dict<string, Attribute>",
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000854 "rule(impl, attrs = {'a1': 'some text'})");
855 }
856
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000857 @Test
allevato45b79e52017-07-07 21:40:50 +0200858 public void testRuleBadTypeForDoc() throws Exception {
Googler3fcfbe12019-08-28 08:10:11 -0700859 registerDummyStarlarkFunction();
adonovan3f602f22020-01-08 10:28:10 -0800860 checkEvalErrorContains("got value of type 'int', want 'string'", "rule(impl, doc = 1)");
allevato45b79e52017-07-07 21:40:50 +0200861 }
862
863 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000864 public void testLabel() throws Exception {
Googleree056632019-10-10 13:04:49 -0700865 Object result = eval("Label('//foo/foo:foo')");
Dmitry Lomov7b599452015-11-26 10:07:32 +0000866 assertThat(result).isInstanceOf(Label.class);
lberkiaea56b32017-05-30 12:35:33 +0200867 assertThat(result.toString()).isEqualTo("//foo/foo:foo");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000868 }
869
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000870 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000871 public void testLabelSameInstance() throws Exception {
Googleree056632019-10-10 13:04:49 -0700872 Object l1 = eval("Label('//foo/foo:foo')");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000873 // Implicitly creates a new pkgContext and environment, yet labels should be the same.
Googleree056632019-10-10 13:04:49 -0700874 Object l2 = eval("Label('//foo/foo:foo')");
cpovirka4d3da62019-05-02 14:27:33 -0700875 assertThat(l1).isSameInstanceAs(l2);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000876 }
877
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000878 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000879 public void testLabelNameAndPackage() throws Exception {
Googleree056632019-10-10 13:04:49 -0700880 Object result = eval("Label('//foo/bar:baz').name");
lberkiaea56b32017-05-30 12:35:33 +0200881 assertThat(result).isEqualTo("baz");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000882 // NB: implicitly creates a new pkgContext and environments, yet labels should be the same.
Googleree056632019-10-10 13:04:49 -0700883 result = eval("Label('//foo/bar:baz').package");
lberkiaea56b32017-05-30 12:35:33 +0200884 assertThat(result).isEqualTo("foo/bar");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000885 }
886
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000887 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000888 public void testRuleLabelDefaultValue() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000889 evalAndExport(
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000890 "def impl(ctx): return None\n"
891 + "r1 = rule(impl, attrs = {'a1': "
892 + "attr.label(default = Label('//foo:foo'), allow_files=True)})");
tomlu72642a22017-10-18 06:23:14 +0200893 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000894 Attribute a = c.getAttributeByName("a1");
juliexxia84d1a662018-12-26 14:07:04 -0800895 assertThat(a.getDefaultValueUnchecked()).isInstanceOf(Label.class);
896 assertThat(a.getDefaultValueUnchecked().toString()).isEqualTo("//foo:foo");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000897 }
898
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000899 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000900 public void testIntDefaultValue() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000901 evalAndExport(
902 "def impl(ctx): return None",
903 "r1 = rule(impl, attrs = {'a1': attr.int(default = 40+2)})");
tomlu72642a22017-10-18 06:23:14 +0200904 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000905 Attribute a = c.getAttributeByName("a1");
juliexxia84d1a662018-12-26 14:07:04 -0800906 assertThat(a.getDefaultValueUnchecked()).isEqualTo(42);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000907 }
908
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000909 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000910 public void testRuleInheritsBaseRuleAttributes() throws Exception {
Dmitry Lomov7b599452015-11-26 10:07:32 +0000911 evalAndExport("def impl(ctx): return None", "r1 = rule(impl)");
tomlu72642a22017-10-18 06:23:14 +0200912 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
lberkiaea56b32017-05-30 12:35:33 +0200913 assertThat(c.hasAttr("tags", Type.STRING_LIST)).isTrue();
914 assertThat(c.hasAttr("visibility", BuildType.NODEP_LABEL_LIST)).isTrue();
915 assertThat(c.hasAttr("deprecation", Type.STRING)).isTrue();
916 assertThat(c.hasAttr(":action_listener", BuildType.LABEL_LIST))
917 .isTrue(); // required for extra actions
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000918 }
919
920 private void checkTextMessage(String from, String... lines) throws Exception {
fangismed97d842019-04-12 14:19:46 -0700921 String[] strings = lines.clone();
Googleree056632019-10-10 13:04:49 -0700922 Object result = eval(from);
fangismed97d842019-04-12 14:19:46 -0700923 String expect = "";
924 if (strings.length > 0) {
925 expect = Joiner.on("\n").join(lines) + "\n";
926 }
927 assertThat(result).isEqualTo(expect);
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000928 }
929
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000930 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000931 public void testSimpleTextMessagesBooleanFields() throws Exception {
932 checkTextMessage("struct(name=True).to_proto()", "name: true");
933 checkTextMessage("struct(name=False).to_proto()", "name: false");
934 }
935
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +0000936 @Test
cparsons07460fc2018-06-20 10:41:48 -0700937 public void testStructRestrictedOverrides() throws Exception {
Googleree056632019-10-10 13:04:49 -0700938 checkEvalErrorContains(
939 "cannot override built-in struct function 'to_json'", "struct(to_json='foo')");
cparsons07460fc2018-06-20 10:41:48 -0700940
Googleree056632019-10-10 13:04:49 -0700941 checkEvalErrorContains(
942 "cannot override built-in struct function 'to_proto'", "struct(to_proto='foo')");
cparsons07460fc2018-06-20 10:41:48 -0700943 }
944
945 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000946 public void testSimpleTextMessages() throws Exception {
947 checkTextMessage("struct(name='value').to_proto()", "name: \"value\"");
fangismed97d842019-04-12 14:19:46 -0700948 checkTextMessage("struct(name=[]).to_proto()"); // empty lines
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +0000949 checkTextMessage("struct(name=['a', 'b']).to_proto()", "name: \"a\"", "name: \"b\"");
950 checkTextMessage("struct(name=123).to_proto()", "name: 123");
951 checkTextMessage("struct(name=[1, 2, 3]).to_proto()", "name: 1", "name: 2", "name: 3");
952 checkTextMessage("struct(a=struct(b='b')).to_proto()", "a {", " b: \"b\"", "}");
953 checkTextMessage(
954 "struct(a=[struct(b='x'), struct(b='y')]).to_proto()",
955 "a {",
956 " b: \"x\"",
957 "}",
958 "a {",
959 " b: \"y\"",
960 "}");
961 checkTextMessage(
962 "struct(a=struct(b=struct(c='c'))).to_proto()", "a {", " b {", " c: \"c\"", " }", "}");
fangismed97d842019-04-12 14:19:46 -0700963 // dict to_proto tests
964 checkTextMessage("struct(name={}).to_proto()"); // empty lines
965 checkTextMessage(
966 "struct(name={'a': 'b'}).to_proto()", "name {", " key: \"a\"", " value: \"b\"", "}");
967 checkTextMessage(
968 "struct(name={'c': 'd', 'a': 'b'}).to_proto()",
969 "name {",
970 " key: \"c\"",
971 " value: \"d\"",
972 "}",
973 "name {",
974 " key: \"a\"",
975 " value: \"b\"",
976 "}");
977 checkTextMessage(
978 "struct(x=struct(y={'a': 1})).to_proto()",
979 "x {",
980 " y {",
981 " key: \"a\"",
982 " value: 1",
983 " }",
984 "}");
985 checkTextMessage(
986 "struct(name={'a': struct(b=1, c=2)}).to_proto()",
987 "name {",
988 " key: \"a\"",
989 " value {",
990 " b: 1",
991 " c: 2",
992 " }",
993 "}");
994 checkTextMessage(
995 "struct(name={'a': struct(b={4: 'z', 3: 'y'}, c=2)}).to_proto()",
996 "name {",
997 " key: \"a\"",
998 " value {",
999 " b {",
1000 " key: 4",
1001 " value: \"z\"",
1002 " }",
1003 " b {",
1004 " key: 3",
1005 " value: \"y\"",
1006 " }",
1007 " c: 2",
1008 " }",
1009 "}");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001010 }
1011
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +00001012 @Test
Vladimir Moskva76e31d12016-12-05 16:28:37 +00001013 public void testProtoFieldsOrder() throws Exception {
1014 checkTextMessage("struct(d=4, b=2, c=3, a=1).to_proto()", "a: 1", "b: 2", "c: 3", "d: 4");
1015 }
1016
1017 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001018 public void testTextMessageEscapes() throws Exception {
1019 checkTextMessage("struct(name='a\"b').to_proto()", "name: \"a\\\"b\"");
1020 checkTextMessage("struct(name='a\\'b').to_proto()", "name: \"a'b\"");
1021 checkTextMessage("struct(name='a\\nb').to_proto()", "name: \"a\\nb\"");
Googler4489aaf2016-06-17 15:17:37 +00001022
1023 // struct(name="a\\\"b") -> name: "a\\\"b"
1024 checkTextMessage("struct(name='a\\\\\\\"b').to_proto()", "name: \"a\\\\\\\"b\"");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001025 }
1026
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +00001027 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001028 public void testTextMessageInvalidElementInListStructure() throws Exception {
Googleree056632019-10-10 13:04:49 -07001029 checkEvalErrorContains(
fangismed97d842019-04-12 14:19:46 -07001030 "Invalid text format, expected a struct, a dict, a string, a bool, or "
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001031 + "an int but got a list for list element in struct field 'a'",
1032 "struct(a=[['b']]).to_proto()");
1033 }
1034
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +00001035 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001036 public void testTextMessageInvalidStructure() throws Exception {
Googleree056632019-10-10 13:04:49 -07001037 checkEvalErrorContains(
fangismed97d842019-04-12 14:19:46 -07001038 "Invalid text format, expected a struct, a dict, a string, a bool, or an int "
Vladimir Moskvacd12f772017-01-10 12:47:06 +00001039 + "but got a function for struct field 'a'",
1040 "struct(a=rule).to_proto()");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001041 }
1042
Erik Abair927f4592016-02-29 18:57:22 +00001043 private void checkJson(String from, String expected) throws Exception {
Googleree056632019-10-10 13:04:49 -07001044 Object result = eval(from);
lberkiaea56b32017-05-30 12:35:33 +02001045 assertThat(result).isEqualTo(expected);
Erik Abair927f4592016-02-29 18:57:22 +00001046 }
1047
1048 @Test
1049 public void testJsonBooleanFields() throws Exception {
1050 checkJson("struct(name=True).to_json()", "{\"name\":true}");
1051 checkJson("struct(name=False).to_json()", "{\"name\":false}");
1052 }
1053
1054 @Test
Taras Tsugrii7fe70472018-07-25 13:58:02 -07001055 public void testJsonDictFields() throws Exception {
1056 checkJson("struct(config={}).to_json()", "{\"config\":{}}");
1057 checkJson("struct(config={'key': 'value'}).to_json()", "{\"config\":{\"key\":\"value\"}}");
Googleree056632019-10-10 13:04:49 -07001058 checkEvalErrorContains(
Taras Tsugrii7fe70472018-07-25 13:58:02 -07001059 "Keys must be a string but got a int for struct field 'config'",
1060 "struct(config={1:2}).to_json()");
Googleree056632019-10-10 13:04:49 -07001061 checkEvalErrorContains(
Taras Tsugrii7fe70472018-07-25 13:58:02 -07001062 "Keys must be a string but got a int for dict value 'foo'",
1063 "struct(config={'foo':{1:2}}).to_json()");
Googleree056632019-10-10 13:04:49 -07001064 checkEvalErrorContains(
Taras Tsugrii7fe70472018-07-25 13:58:02 -07001065 "Keys must be a string but got a bool for struct field 'config'",
1066 "struct(config={True: False}).to_json()");
1067 }
1068
1069 @Test
Erik Abair927f4592016-02-29 18:57:22 +00001070 public void testJsonEncoding() throws Exception {
1071 checkJson("struct(name='value').to_json()", "{\"name\":\"value\"}");
1072 checkJson("struct(name=['a', 'b']).to_json()", "{\"name\":[\"a\",\"b\"]}");
1073 checkJson("struct(name=123).to_json()", "{\"name\":123}");
1074 checkJson("struct(name=[1, 2, 3]).to_json()", "{\"name\":[1,2,3]}");
1075 checkJson("struct(a=struct(b='b')).to_json()", "{\"a\":{\"b\":\"b\"}}");
1076 checkJson("struct(a=[struct(b='x'), struct(b='y')]).to_json()",
1077 "{\"a\":[{\"b\":\"x\"},{\"b\":\"y\"}]}");
1078 checkJson("struct(a=struct(b=struct(c='c'))).to_json()",
1079 "{\"a\":{\"b\":{\"c\":\"c\"}}}");
1080 }
1081
1082 @Test
1083 public void testJsonEscapes() throws Exception {
1084 checkJson("struct(name='a\"b').to_json()", "{\"name\":\"a\\\"b\"}");
1085 checkJson("struct(name='a\\'b').to_json()", "{\"name\":\"a'b\"}");
Erik Abairec1f2b92016-03-01 00:45:33 +00001086 checkJson("struct(name='a\\\\b').to_json()", "{\"name\":\"a\\\\b\"}");
Erik Abair927f4592016-02-29 18:57:22 +00001087 checkJson("struct(name='a\\nb').to_json()", "{\"name\":\"a\\nb\"}");
Erik Abairec1f2b92016-03-01 00:45:33 +00001088 checkJson("struct(name='a\\rb').to_json()", "{\"name\":\"a\\rb\"}");
1089 checkJson("struct(name='a\\tb').to_json()", "{\"name\":\"a\\tb\"}");
Erik Abair927f4592016-02-29 18:57:22 +00001090 }
1091
1092 @Test
1093 public void testJsonNestedListStructure() throws Exception {
1094 checkJson("struct(a=[['b']]).to_json()", "{\"a\":[[\"b\"]]}");
1095 }
1096
1097 @Test
1098 public void testJsonInvalidStructure() throws Exception {
Googleree056632019-10-10 13:04:49 -07001099 checkEvalErrorContains(
Erik Abair927f4592016-02-29 18:57:22 +00001100 "Invalid text format, expected a struct, a string, a bool, or an int but got a "
Vladimir Moskvacd12f772017-01-10 12:47:06 +00001101 + "function for struct field 'a'",
1102 "struct(a=rule).to_json()");
Erik Abair927f4592016-02-29 18:57:22 +00001103 }
1104
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +00001105 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001106 public void testLabelAttrWrongDefault() throws Exception {
Googleree056632019-10-10 13:04:49 -07001107 checkEvalErrorContains(
adonovan3f602f22020-01-08 10:28:10 -08001108 "got value of type 'int', want 'Label or string or LateBoundDefault or function or"
1109 + " NoneType'",
vladmos9c787fa2017-07-04 11:45:22 -04001110 "attr.label(default = 123)");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001111 }
1112
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +00001113 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001114 public void testLabelGetRelative() throws Exception {
lberkiaea56b32017-05-30 12:35:33 +02001115 assertThat(eval("Label('//foo:bar').relative('baz')").toString()).isEqualTo("//foo:baz");
1116 assertThat(eval("Label('//foo:bar').relative('//baz:qux')").toString()).isEqualTo("//baz:qux");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001117 }
1118
Han-Wen Nienhuys33ce2112015-09-25 14:25:38 +00001119 @Test
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001120 public void testLabelGetRelativeSyntaxError() throws Exception {
Googleree056632019-10-10 13:04:49 -07001121 checkEvalErrorContains(
Damien Martin-Guillerez934c1d52017-03-03 14:44:56 +00001122 "invalid target name 'bad//syntax': target names may not contain '//' path separators",
1123 "Label('//foo:bar').relative('bad//syntax')");
Han-Wen Nienhuysceae8c52015-09-22 16:24:45 +00001124 }
Greg Estren223976c2016-02-04 22:40:56 +00001125
1126 @Test
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001127 public void testStructCreation() throws Exception {
1128 // TODO(fwe): cannot be handled by current testing suite
Googler1a1fca22019-10-14 09:31:22 -07001129 exec("x = struct(a = 1, b = 2)");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001130 assertThat(lookup("x")).isInstanceOf(ClassObject.class);
1131 }
1132
1133 @Test
1134 public void testStructFields() throws Exception {
1135 // TODO(fwe): cannot be handled by current testing suite
Googler1a1fca22019-10-14 09:31:22 -07001136 exec("x = struct(a = 1, b = 2)");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001137 ClassObject x = (ClassObject) lookup("x");
lberkiaea56b32017-05-30 12:35:33 +02001138 assertThat(x.getValue("a")).isEqualTo(1);
1139 assertThat(x.getValue("b")).isEqualTo(2);
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001140 }
1141
1142 @Test
Vladimir Moskvafdfa9882016-11-18 16:24:20 +00001143 public void testStructEquality() throws Exception {
lberkiaea56b32017-05-30 12:35:33 +02001144 assertThat((Boolean) eval("struct(a = 1, b = 2) == struct(b = 2, a = 1)")).isTrue();
1145 assertThat((Boolean) eval("struct(a = 1) == struct(a = 1, b = 2)")).isFalse();
1146 assertThat((Boolean) eval("struct(a = 1, b = 2) == struct(a = 1)")).isFalse();
Vladimir Moskvafdfa9882016-11-18 16:24:20 +00001147 // Compare a recursive object to itself to make sure reference equality is checked
Googler1a1fca22019-10-14 09:31:22 -07001148 exec("s = struct(a = 1, b = []); s.b.append(s)");
1149 assertThat((Boolean) eval("s == s")).isTrue();
lberkiaea56b32017-05-30 12:35:33 +02001150 assertThat((Boolean) eval("struct(a = 1, b = 2) == struct(a = 1, b = 3)")).isFalse();
1151 assertThat((Boolean) eval("struct(a = 1) == [1]")).isFalse();
1152 assertThat((Boolean) eval("[1] == struct(a = 1)")).isFalse();
1153 assertThat((Boolean) eval("struct() == struct()")).isTrue();
1154 assertThat((Boolean) eval("struct() == struct(a = 1)")).isFalse();
Vladimir Moskvafdfa9882016-11-18 16:24:20 +00001155
Googler1a1fca22019-10-14 09:31:22 -07001156 exec("foo = provider(); bar = provider()");
lberkiaea56b32017-05-30 12:35:33 +02001157 assertThat((Boolean) eval("struct(a = 1) == foo(a = 1)")).isFalse();
1158 assertThat((Boolean) eval("foo(a = 1) == struct(a = 1)")).isFalse();
1159 assertThat((Boolean) eval("foo(a = 1) == bar(a = 1)")).isFalse();
1160 assertThat((Boolean) eval("foo(a = 1) == foo(a = 1)")).isTrue();
Vladimir Moskvafdfa9882016-11-18 16:24:20 +00001161 }
1162
1163 @Test
Vladimir Moskva76e31d12016-12-05 16:28:37 +00001164 public void testStructIncomparability() throws Exception {
Googleree056632019-10-10 13:04:49 -07001165 checkEvalErrorContains("Cannot compare structs", "struct(a = 1) < struct(a = 2)");
1166 checkEvalErrorContains("Cannot compare structs", "struct(a = 1) > struct(a = 2)");
1167 checkEvalErrorContains("Cannot compare structs", "struct(a = 1) <= struct(a = 2)");
1168 checkEvalErrorContains("Cannot compare structs", "struct(a = 1) >= struct(a = 2)");
Vladimir Moskva76e31d12016-12-05 16:28:37 +00001169 }
1170
1171 @Test
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001172 public void testStructAccessingFieldsFromSkylark() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001173 exec("x = struct(a = 1, b = 2)", "x1 = x.a", "x2 = x.b");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001174 assertThat(lookup("x1")).isEqualTo(1);
1175 assertThat(lookup("x2")).isEqualTo(2);
1176 }
1177
1178 @Test
1179 public void testStructAccessingUnknownField() throws Exception {
Googleree056632019-10-10 13:04:49 -07001180 checkEvalErrorContains(
adonovan4e2b4952019-12-10 12:19:20 -08001181 "'struct' value has no field or method 'c'\n" + "Available attributes: a, b",
Googleree056632019-10-10 13:04:49 -07001182 "x = struct(a = 1, b = 2)",
1183 "y = x.c");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001184 }
1185
1186 @Test
1187 public void testStructAccessingUnknownFieldWithArgs() throws Exception {
Googleree056632019-10-10 13:04:49 -07001188 checkEvalErrorContains(
adonovan4e2b4952019-12-10 12:19:20 -08001189 "'struct' value has no field or method 'c'", "x = struct(a = 1, b = 2)", "y = x.c()");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001190 }
1191
1192 @Test
1193 public void testStructAccessingNonFunctionFieldWithArgs() throws Exception {
Googleree056632019-10-10 13:04:49 -07001194 checkEvalErrorContains(
1195 "'int' object is not callable", "x = struct(a = 1, b = 2)", "x1 = x.a(1)");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001196 }
1197
1198 @Test
1199 public void testStructAccessingFunctionFieldWithArgs() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001200 exec("def f(x): return x+5", "x = struct(a = f, b = 2)", "x1 = x.a(1)");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001201 assertThat(lookup("x1")).isEqualTo(6);
1202 }
1203
1204 @Test
1205 public void testStructPosArgs() throws Exception {
adonovan3f602f22020-01-08 10:28:10 -08001206 checkEvalErrorContains("struct() got unexpected positional argument", "x = struct(1, b = 2)");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001207 }
1208
1209 @Test
1210 public void testStructConcatenationFieldNames() throws Exception {
1211 // TODO(fwe): cannot be handled by current testing suite
Googler1a1fca22019-10-14 09:31:22 -07001212 exec(
1213 "x = struct(a = 1, b = 2)", //
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001214 "y = struct(c = 1, d = 2)",
1215 "z = x + y\n");
cparsons4ebf6c02018-08-17 14:49:36 -07001216 StructImpl z = (StructImpl) lookup("z");
jcater91ed0f32019-11-07 10:07:16 -08001217 assertThat(z.getFieldNames()).containsExactly("a", "b", "c", "d");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001218 }
1219
1220 @Test
1221 public void testStructConcatenationFieldValues() throws Exception {
1222 // TODO(fwe): cannot be handled by current testing suite
Googler1a1fca22019-10-14 09:31:22 -07001223 exec(
1224 "x = struct(a = 1, b = 2)", //
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001225 "y = struct(c = 1, d = 2)",
1226 "z = x + y\n");
cparsons4ebf6c02018-08-17 14:49:36 -07001227 StructImpl z = (StructImpl) lookup("z");
lberkiaea56b32017-05-30 12:35:33 +02001228 assertThat(z.getValue("a")).isEqualTo(1);
1229 assertThat(z.getValue("b")).isEqualTo(2);
1230 assertThat(z.getValue("c")).isEqualTo(1);
1231 assertThat(z.getValue("d")).isEqualTo(2);
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001232 }
1233
1234 @Test
1235 public void testStructConcatenationCommonFields() throws Exception {
Googleree056632019-10-10 13:04:49 -07001236 checkEvalErrorContains(
adonovan553dc6c2019-12-10 11:22:48 -08001237 "cannot add struct instances with common field 'a'",
Googleree056632019-10-10 13:04:49 -07001238 "x = struct(a = 1, b = 2)",
1239 "y = struct(c = 1, a = 2)",
1240 "z = x + y\n");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001241 }
1242
1243 @Test
1244 public void testConditionalStructConcatenation() throws Exception {
1245 // TODO(fwe): cannot be handled by current testing suite
Googler1a1fca22019-10-14 09:31:22 -07001246 exec(
1247 "def func():",
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001248 " x = struct(a = 1, b = 2)",
1249 " if True:",
1250 " x += struct(c = 1, d = 2)",
1251 " return x",
1252 "x = func()");
cparsons4ebf6c02018-08-17 14:49:36 -07001253 StructImpl x = (StructImpl) lookup("x");
lberkiaea56b32017-05-30 12:35:33 +02001254 assertThat(x.getValue("a")).isEqualTo(1);
1255 assertThat(x.getValue("b")).isEqualTo(2);
1256 assertThat(x.getValue("c")).isEqualTo(1);
1257 assertThat(x.getValue("d")).isEqualTo(2);
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001258 }
1259
1260 @Test
1261 public void testGetattrNoAttr() throws Exception {
Googleree056632019-10-10 13:04:49 -07001262 checkEvalErrorContains(
adonovan4e2b4952019-12-10 12:19:20 -08001263 "'struct' value has no field or method 'b'\nAvailable attributes: a",
Googler055d6c62018-05-22 13:21:04 -07001264 "s = struct(a='val')",
1265 "getattr(s, 'b')");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001266 }
1267
1268 @Test
1269 public void testGetattr() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001270 exec("s = struct(a='val')", "x = getattr(s, 'a')", "y = getattr(s, 'b', 'def')");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001271 assertThat(lookup("x")).isEqualTo("val");
1272 assertThat(lookup("y")).isEqualTo("def");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001273 }
1274
1275 @Test
1276 public void testHasattr() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001277 exec(
1278 "s = struct(a=1)", //
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001279 "x = hasattr(s, 'a')",
1280 "y = hasattr(s, 'b')\n");
1281 assertThat(lookup("x")).isEqualTo(true);
1282 assertThat(lookup("y")).isEqualTo(false);
1283 }
1284
1285 @Test
1286 public void testStructStr() throws Exception {
1287 assertThat(eval("str(struct(x = 2, y = 3, z = 4))"))
1288 .isEqualTo("struct(x = 2, y = 3, z = 4)");
1289 }
1290
1291 @Test
1292 public void testStructsInSets() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001293 exec("depset([struct(a='a')])");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001294 }
1295
1296 @Test
Vladimir Moskva76e31d12016-12-05 16:28:37 +00001297 public void testStructsInDicts() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001298 exec("d = {struct(a = 1): 'aa', struct(b = 2): 'bb'}");
Vladimir Moskva76e31d12016-12-05 16:28:37 +00001299 assertThat(eval("d[struct(a = 1)]")).isEqualTo("aa");
1300 assertThat(eval("d[struct(b = 2)]")).isEqualTo("bb");
1301 assertThat(eval("str([d[k] for k in d])")).isEqualTo("[\"aa\", \"bb\"]");
1302
Googleree056632019-10-10 13:04:49 -07001303 checkEvalErrorContains("unhashable type: 'struct'", "{struct(a = []): 'foo'}");
Vladimir Moskva76e31d12016-12-05 16:28:37 +00001304 }
1305
1306 @Test
Vladimir Moskva10770382016-08-23 15:04:54 +00001307 public void testStructDictMembersAreMutable() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001308 exec(
1309 "s = struct(x = {'a' : 1})", //
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001310 "s.x['b'] = 2\n");
cparsons4ebf6c02018-08-17 14:49:36 -07001311 assertThat(((StructImpl) lookup("s")).getValue("x")).isEqualTo(ImmutableMap.of("a", 1, "b", 2));
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001312 }
1313
1314 @Test
1315 public void testNsetGoodCompositeItem() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001316 exec("def func():", " return depset([struct(a='a')])", "s = func()");
Googlerd21a0d12019-11-21 13:52:30 -08001317 Collection<?> result = ((Depset) lookup("s")).toCollection();
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001318 assertThat(result).hasSize(1);
cparsons4ebf6c02018-08-17 14:49:36 -07001319 assertThat(result.iterator().next()).isInstanceOf(StructImpl.class);
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001320 }
1321
cparsons4ebf6c02018-08-17 14:49:36 -07001322 private static StructImpl makeStruct(String field, Object value) {
cparsons0c5c1c62018-05-24 10:37:03 -07001323 return StructProvider.STRUCT.create(ImmutableMap.of(field, value), "no field '%'");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001324 }
1325
Googler92578702019-11-21 12:19:31 -08001326 private static StructImpl makeBigStruct(@Nullable Mutability mu) {
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001327 // struct(a=[struct(x={1:1}), ()], b=(), c={2:2})
cparsons0c5c1c62018-05-24 10:37:03 -07001328 return StructProvider.STRUCT.create(
Dmitry Lomovea9de072016-08-09 09:35:40 +00001329 ImmutableMap.<String, Object>of(
dslomovde965ac2017-07-31 21:07:51 +02001330 "a",
Googler942e1c42019-11-12 13:11:44 -08001331 StarlarkList.<Object>of(
Googler92578702019-11-21 12:19:31 -08001332 mu,
cparsons0c5c1c62018-05-24 10:37:03 -07001333 StructProvider.STRUCT.create(
Googler92578702019-11-21 12:19:31 -08001334 ImmutableMap.<String, Object>of("x", Dict.<Object, Object>of(mu, 1, 1)),
dslomovde965ac2017-07-31 21:07:51 +02001335 "no field '%s'"),
1336 Tuple.of()),
Dmitry Lomovea9de072016-08-09 09:35:40 +00001337 "b", Tuple.of(),
Googler92578702019-11-21 12:19:31 -08001338 "c", Dict.<Object, Object>of(mu, 2, 2)),
Dmitry Lomovea9de072016-08-09 09:35:40 +00001339 "no field '%s'");
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001340 }
1341
1342 @Test
1343 public void testStructMutabilityShallow() throws Exception {
lberkiaea56b32017-05-30 12:35:33 +02001344 assertThat(EvalUtils.isImmutable(makeStruct("a", 1))).isTrue();
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001345 }
1346
Googler92578702019-11-21 12:19:31 -08001347 private static StarlarkList<Object> makeList(@Nullable Mutability mu) {
1348 return StarlarkList.<Object>of(mu, 1, 2, 3);
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001349 }
1350
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001351 @Test
1352 public void testStructMutabilityDeep() throws Exception {
lberkiaea56b32017-05-30 12:35:33 +02001353 assertThat(EvalUtils.isImmutable(Tuple.<Object>of(makeList(null)))).isTrue();
1354 assertThat(EvalUtils.isImmutable(makeStruct("a", makeList(null)))).isTrue();
1355 assertThat(EvalUtils.isImmutable(makeBigStruct(null))).isTrue();
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001356
Googler92578702019-11-21 12:19:31 -08001357 Mutability mu = ev.getStarlarkThread().mutability();
1358 assertThat(EvalUtils.isImmutable(Tuple.<Object>of(makeList(mu)))).isFalse();
1359 assertThat(EvalUtils.isImmutable(makeStruct("a", makeList(mu)))).isFalse();
1360 assertThat(EvalUtils.isImmutable(makeBigStruct(mu))).isFalse();
Dmitry Lomovcdb6ef52016-08-05 08:38:26 +00001361 }
1362
Dmitry Lomov8a07a952016-08-10 18:29:04 +00001363 @Test
1364 public void declaredProviders() throws Exception {
1365 evalAndExport(
1366 "data = provider()",
1367 "d = data(x = 1, y ='abc')",
1368 "d_x = d.x",
1369 "d_y = d.y"
1370 );
1371 assertThat(lookup("d_x")).isEqualTo(1);
1372 assertThat(lookup("d_y")).isEqualTo("abc");
dslomovde965ac2017-07-31 21:07:51 +02001373 SkylarkProvider dataConstructor = (SkylarkProvider) lookup("data");
cparsons4ebf6c02018-08-17 14:49:36 -07001374 StructImpl data = (StructImpl) lookup("d");
dslomovde965ac2017-07-31 21:07:51 +02001375 assertThat(data.getProvider()).isEqualTo(dataConstructor);
Dmitry Lomov8a07a952016-08-10 18:29:04 +00001376 assertThat(dataConstructor.isExported()).isTrue();
1377 assertThat(dataConstructor.getPrintableName()).isEqualTo("data");
dslomovde965ac2017-07-31 21:07:51 +02001378 assertThat(dataConstructor.getKey())
1379 .isEqualTo(new SkylarkProvider.SkylarkKey(FAKE_LABEL, "data"));
Dmitry Lomov8a07a952016-08-10 18:29:04 +00001380 }
1381
1382 @Test
1383 public void declaredProvidersConcatSuccess() throws Exception {
1384 evalAndExport(
1385 "data = provider()",
1386 "dx = data(x = 1)",
1387 "dy = data(y = 'abc')",
1388 "dxy = dx + dy",
1389 "x = dxy.x",
1390 "y = dxy.y"
1391 );
1392 assertThat(lookup("x")).isEqualTo(1);
1393 assertThat(lookup("y")).isEqualTo("abc");
dslomovde965ac2017-07-31 21:07:51 +02001394 SkylarkProvider dataConstructor = (SkylarkProvider) lookup("data");
cparsons4ebf6c02018-08-17 14:49:36 -07001395 StructImpl dx = (StructImpl) lookup("dx");
dslomovde965ac2017-07-31 21:07:51 +02001396 assertThat(dx.getProvider()).isEqualTo(dataConstructor);
cparsons4ebf6c02018-08-17 14:49:36 -07001397 StructImpl dy = (StructImpl) lookup("dy");
dslomovde965ac2017-07-31 21:07:51 +02001398 assertThat(dy.getProvider()).isEqualTo(dataConstructor);
Dmitry Lomov8a07a952016-08-10 18:29:04 +00001399 }
1400
1401 @Test
1402 public void declaredProvidersConcatError() throws Exception {
1403 evalAndExport(
1404 "data1 = provider()",
1405 "data2 = provider()"
1406 );
1407
Googleree056632019-10-10 13:04:49 -07001408 checkEvalErrorContains(
1409 "Cannot use '+' operator on instances of different providers (data1 and data2)",
Dmitry Lomov8a07a952016-08-10 18:29:04 +00001410 "d1 = data1(x = 1)",
1411 "d2 = data2(y = 2)",
Googleree056632019-10-10 13:04:49 -07001412 "d = d1 + d2");
Dmitry Lomov8a07a952016-08-10 18:29:04 +00001413 }
Dmitry Lomov94b2c882016-09-25 20:24:24 +00001414
1415 @Test
Benjamin Peterson8610d972017-11-27 03:14:43 -08001416 public void declaredProvidersWithFieldsConcatSuccess() throws Exception {
1417 evalAndExport(
1418 "data = provider(fields=['f1', 'f2'])",
1419 "d1 = data(f1 = 4)",
1420 "d2 = data(f2 = 5)",
1421 "d3 = d1 + d2",
1422 "f1 = d3.f1",
1423 "f2 = d3.f2");
1424 assertThat(lookup("f1")).isEqualTo(4);
1425 assertThat(lookup("f2")).isEqualTo(5);
1426 }
1427
1428 @Test
1429 public void declaredProvidersWithFieldsConcatError() throws Exception {
1430 evalAndExport("data1 = provider(fields=['f1', 'f2'])", "data2 = provider(fields=['f3'])");
Googleree056632019-10-10 13:04:49 -07001431 checkEvalErrorContains(
brandjona29648a2018-01-10 08:38:43 -08001432 "Cannot use '+' operator on instances of different providers (data1 and data2)",
Benjamin Peterson8610d972017-11-27 03:14:43 -08001433 "d1 = data1(f1=1, f2=2)",
1434 "d2 = data2(f3=3)",
1435 "d = d1 + d2");
1436 }
1437
1438 @Test
1439 public void declaredProvidersWithOverlappingFieldsConcatError() throws Exception {
1440 evalAndExport("data = provider(fields=['f1', 'f2'])");
Googleree056632019-10-10 13:04:49 -07001441 checkEvalErrorContains(
adonovan553dc6c2019-12-10 11:22:48 -08001442 "cannot add struct instances with common field 'f1'",
Benjamin Peterson8610d972017-11-27 03:14:43 -08001443 "d1 = data(f1 = 4)",
1444 "d2 = data(f1 = 5)",
1445 "d1 + d2");
1446 }
1447
1448 @Test
Dmitry Lomov94b2c882016-09-25 20:24:24 +00001449 public void structsAsDeclaredProvidersTest() throws Exception {
1450 evalAndExport(
1451 "data = struct(x = 1)"
1452 );
cparsons4ebf6c02018-08-17 14:49:36 -07001453 StructImpl data = (StructImpl) lookup("data");
cparsons0c5c1c62018-05-24 10:37:03 -07001454 assertThat(StructProvider.STRUCT.isExported()).isTrue();
1455 assertThat(data.getProvider()).isEqualTo(StructProvider.STRUCT);
1456 assertThat(data.getProvider().getKey()).isEqualTo(StructProvider.STRUCT.getKey());
Dmitry Lomov94b2c882016-09-25 20:24:24 +00001457 }
Dmitry Lomov0692c7f2016-09-30 16:43:30 +00001458
1459 @Test
allevato45b79e52017-07-07 21:40:50 +02001460 public void declaredProvidersDoc() throws Exception {
1461 evalAndExport("data1 = provider(doc='foo')");
1462 }
1463
1464 @Test
1465 public void declaredProvidersBadTypeForDoc() throws Exception {
adonovan3f602f22020-01-08 10:28:10 -08001466 checkEvalErrorContains("got value of type 'int', want 'string'", "provider(doc = 1)");
allevato45b79e52017-07-07 21:40:50 +02001467 }
1468
1469 @Test
Dmitry Lomov0692c7f2016-09-30 16:43:30 +00001470 public void aspectAllAttrs() throws Exception {
1471 evalAndExport(
1472 "def _impl(target, ctx):",
1473 " pass",
1474 "my_aspect = aspect(_impl, attr_aspects=['*'])");
1475
cparsons0d55f4c2017-12-20 14:49:13 -08001476 SkylarkDefinedAspect myAspect = (SkylarkDefinedAspect) lookup("my_aspect");
lberki3bd28392019-02-05 01:01:02 -08001477 assertThat(myAspect.getDefinition(AspectParameters.EMPTY).propagateAlong("foo")).isTrue();
Dmitry Lomov0692c7f2016-09-30 16:43:30 +00001478 }
1479
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001480 @Test
1481 public void aspectRequiredAspectProvidersSingle() throws Exception {
1482 evalAndExport(
1483 "def _impl(target, ctx):",
1484 " pass",
Dmitry Lomov8ff5a872017-03-04 00:58:14 +00001485 "cc = provider()",
1486 "my_aspect = aspect(_impl, required_aspect_providers=['java', cc])"
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001487 );
cparsons0d55f4c2017-12-20 14:49:13 -08001488 SkylarkDefinedAspect myAspect = (SkylarkDefinedAspect) lookup("my_aspect");
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001489 RequiredProviders requiredProviders = myAspect.getDefinition(AspectParameters.EMPTY)
1490 .getRequiredProvidersForAspects();
1491 assertThat(requiredProviders.isSatisfiedBy(AdvertisedProviderSet.ANY)).isTrue();
1492 assertThat(requiredProviders.isSatisfiedBy(AdvertisedProviderSet.EMPTY)).isFalse();
1493 assertThat(requiredProviders.isSatisfiedBy(
1494 AdvertisedProviderSet.builder()
Dmitry Lomov8ff5a872017-03-04 00:58:14 +00001495 .addSkylark(declared("cc"))
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001496 .addSkylark("java")
1497 .build()))
1498 .isTrue();
1499 assertThat(requiredProviders.isSatisfiedBy(
1500 AdvertisedProviderSet.builder()
1501 .addSkylark("cc")
1502 .build()))
1503 .isFalse();
1504 }
1505
1506 @Test
1507 public void aspectRequiredAspectProvidersAlternatives() throws Exception {
1508 evalAndExport(
1509 "def _impl(target, ctx):",
1510 " pass",
Dmitry Lomov8ff5a872017-03-04 00:58:14 +00001511 "cc = provider()",
1512 "my_aspect = aspect(_impl, required_aspect_providers=[['java'], [cc]])"
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001513 );
cparsons0d55f4c2017-12-20 14:49:13 -08001514 SkylarkDefinedAspect myAspect = (SkylarkDefinedAspect) lookup("my_aspect");
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001515 RequiredProviders requiredProviders = myAspect.getDefinition(AspectParameters.EMPTY)
1516 .getRequiredProvidersForAspects();
1517 assertThat(requiredProviders.isSatisfiedBy(AdvertisedProviderSet.ANY)).isTrue();
1518 assertThat(requiredProviders.isSatisfiedBy(AdvertisedProviderSet.EMPTY)).isFalse();
1519 assertThat(requiredProviders.isSatisfiedBy(
1520 AdvertisedProviderSet.builder()
1521 .addSkylark("java")
1522 .build()))
1523 .isTrue();
1524 assertThat(requiredProviders.isSatisfiedBy(
1525 AdvertisedProviderSet.builder()
Dmitry Lomov8ff5a872017-03-04 00:58:14 +00001526 .addSkylark(declared("cc"))
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001527 .build()))
1528 .isTrue();
1529 assertThat(requiredProviders.isSatisfiedBy(
1530 AdvertisedProviderSet.builder()
1531 .addSkylark("prolog")
1532 .build()))
1533 .isFalse();
1534 }
1535
1536 @Test
1537 public void aspectRequiredAspectProvidersEmpty() throws Exception {
1538 evalAndExport(
1539 "def _impl(target, ctx):",
1540 " pass",
1541 "my_aspect = aspect(_impl, required_aspect_providers=[])"
1542 );
cparsons0d55f4c2017-12-20 14:49:13 -08001543 SkylarkDefinedAspect myAspect = (SkylarkDefinedAspect) lookup("my_aspect");
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001544 RequiredProviders requiredProviders = myAspect.getDefinition(AspectParameters.EMPTY)
1545 .getRequiredProvidersForAspects();
1546 assertThat(requiredProviders.isSatisfiedBy(AdvertisedProviderSet.ANY)).isFalse();
1547 assertThat(requiredProviders.isSatisfiedBy(AdvertisedProviderSet.EMPTY)).isFalse();
1548 }
1549
1550 @Test
1551 public void aspectRequiredAspectProvidersDefault() throws Exception {
1552 evalAndExport(
1553 "def _impl(target, ctx):",
1554 " pass",
1555 "my_aspect = aspect(_impl)"
1556 );
cparsons0d55f4c2017-12-20 14:49:13 -08001557 SkylarkDefinedAspect myAspect = (SkylarkDefinedAspect) lookup("my_aspect");
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001558 RequiredProviders requiredProviders = myAspect.getDefinition(AspectParameters.EMPTY)
1559 .getRequiredProvidersForAspects();
1560 assertThat(requiredProviders.isSatisfiedBy(AdvertisedProviderSet.ANY)).isFalse();
1561 assertThat(requiredProviders.isSatisfiedBy(AdvertisedProviderSet.EMPTY)).isFalse();
1562 }
1563
Dmitry Lomov950310f2017-03-01 17:45:12 +00001564 @Test
Dmitry Lomov8ff5a872017-03-04 00:58:14 +00001565 public void aspectProvides() throws Exception {
1566 evalAndExport(
1567 "def _impl(target, ctx):",
1568 " pass",
1569 "y = provider()",
1570 "my_aspect = aspect(_impl, provides = ['x', y])"
1571 );
cparsons0d55f4c2017-12-20 14:49:13 -08001572 SkylarkDefinedAspect myAspect = (SkylarkDefinedAspect) lookup("my_aspect");
Dmitry Lomov8ff5a872017-03-04 00:58:14 +00001573 AdvertisedProviderSet advertisedProviders = myAspect.getDefinition(AspectParameters.EMPTY)
1574 .getAdvertisedProviders();
1575 assertThat(advertisedProviders.canHaveAnyProvider()).isFalse();
1576 assertThat(advertisedProviders.getSkylarkProviders())
1577 .containsExactly(legacy("x"), declared("y"));
1578 }
1579
1580 @Test
1581 public void aspectProvidesError() throws Exception {
1582 ev.setFailFast(false);
1583 evalAndExport(
1584 "def _impl(target, ctx):",
1585 " pass",
1586 "y = provider()",
1587 "my_aspect = aspect(_impl, provides = ['x', 1])"
1588 );
1589 MoreAsserts.assertContainsEvent(ev.getEventCollector(),
1590 " Illegal argument: element in 'provides' is of unexpected type."
cparsonsaab98682018-04-27 13:04:59 -07001591 + " Should be list of providers, but got item of type int. ");
Dmitry Lomov8ff5a872017-03-04 00:58:14 +00001592 }
1593
allevato45b79e52017-07-07 21:40:50 +02001594 @Test
1595 public void aspectDoc() throws Exception {
1596 evalAndExport(
1597 "def _impl(target, ctx):",
1598 " pass",
1599 "my_aspect = aspect(_impl, doc='foo')");
1600 }
1601
1602 @Test
1603 public void aspectBadTypeForDoc() throws Exception {
Googler3fcfbe12019-08-28 08:10:11 -07001604 registerDummyStarlarkFunction();
adonovan3f602f22020-01-08 10:28:10 -08001605 checkEvalErrorContains("got value of type 'int', want 'string'", "aspect(impl, doc = 1)");
allevato45b79e52017-07-07 21:40:50 +02001606 }
1607
Dmitry Lomov8ff5a872017-03-04 00:58:14 +00001608 @Test
Dmitry Lomov950310f2017-03-01 17:45:12 +00001609 public void fancyExports() throws Exception {
1610 evalAndExport(
1611 "def _impla(target, ctx): pass",
1612 "p, (a, p1) = [",
1613 " provider(),",
1614 " [ aspect(_impla),",
1615 " provider() ]",
1616 "]"
1617 );
dslomovde965ac2017-07-31 21:07:51 +02001618 SkylarkProvider p = (SkylarkProvider) lookup("p");
cparsons0d55f4c2017-12-20 14:49:13 -08001619 SkylarkDefinedAspect a = (SkylarkDefinedAspect) lookup("a");
dslomovde965ac2017-07-31 21:07:51 +02001620 SkylarkProvider p1 = (SkylarkProvider) lookup("p1");
Dmitry Lomov950310f2017-03-01 17:45:12 +00001621 assertThat(p.getPrintableName()).isEqualTo("p");
dslomovde965ac2017-07-31 21:07:51 +02001622 assertThat(p.getKey()).isEqualTo(new SkylarkProvider.SkylarkKey(FAKE_LABEL, "p"));
Dmitry Lomov950310f2017-03-01 17:45:12 +00001623 assertThat(p1.getPrintableName()).isEqualTo("p1");
dslomovde965ac2017-07-31 21:07:51 +02001624 assertThat(p1.getKey()).isEqualTo(new SkylarkProvider.SkylarkKey(FAKE_LABEL, "p1"));
Dmitry Lomov950310f2017-03-01 17:45:12 +00001625 assertThat(a.getAspectClass()).isEqualTo(
1626 new SkylarkAspectClass(FAKE_LABEL, "a")
1627 );
1628 }
1629
1630 @Test
1631 public void multipleTopLevels() throws Exception {
1632 evalAndExport(
1633 "p = provider()",
1634 "p1 = p"
1635 );
dslomovde965ac2017-07-31 21:07:51 +02001636 SkylarkProvider p = (SkylarkProvider) lookup("p");
1637 SkylarkProvider p1 = (SkylarkProvider) lookup("p1");
Dmitry Lomov950310f2017-03-01 17:45:12 +00001638 assertThat(p).isEqualTo(p1);
dslomovde965ac2017-07-31 21:07:51 +02001639 assertThat(p.getKey()).isEqualTo(new SkylarkProvider.SkylarkKey(FAKE_LABEL, "p"));
1640 assertThat(p1.getKey()).isEqualTo(new SkylarkProvider.SkylarkKey(FAKE_LABEL, "p"));
Dmitry Lomov950310f2017-03-01 17:45:12 +00001641 }
Dmitry Lomovf868b3e2017-01-17 10:25:28 +00001642
dslomov0667b832017-08-25 09:29:50 +02001643 @Test
1644 public void providerWithFields() throws Exception {
1645 evalAndExport(
1646 "p = provider(fields = ['x', 'y'])",
1647 "p1 = p(x = 1, y = 2)",
1648 "x = p1.x",
1649 "y = p1.y"
1650 );
1651 SkylarkProvider p = (SkylarkProvider) lookup("p");
1652 SkylarkInfo p1 = (SkylarkInfo) lookup("p1");
1653
dslomov0667b832017-08-25 09:29:50 +02001654 assertThat(p1.getProvider()).isEqualTo(p);
1655 assertThat(lookup("x")).isEqualTo(1);
1656 assertThat(lookup("y")).isEqualTo(2);
1657 }
1658
1659 @Test
1660 public void providerWithFieldsDict() throws Exception {
1661 evalAndExport(
1662 "p = provider(fields = { 'x' : 'I am x', 'y' : 'I am y'})",
1663 "p1 = p(x = 1, y = 2)",
1664 "x = p1.x",
1665 "y = p1.y"
1666 );
1667 SkylarkProvider p = (SkylarkProvider) lookup("p");
1668 SkylarkInfo p1 = (SkylarkInfo) lookup("p1");
1669
dslomov0667b832017-08-25 09:29:50 +02001670 assertThat(p1.getProvider()).isEqualTo(p);
1671 assertThat(lookup("x")).isEqualTo(1);
1672 assertThat(lookup("y")).isEqualTo(2);
1673 }
1674
1675 @Test
1676 public void providerWithFieldsOptional() throws Exception {
1677 evalAndExport(
1678 "p = provider(fields = ['x', 'y'])",
1679 "p1 = p(y = 2)",
1680 "y = p1.y"
1681 );
1682 SkylarkProvider p = (SkylarkProvider) lookup("p");
1683 SkylarkInfo p1 = (SkylarkInfo) lookup("p1");
1684
dslomov0667b832017-08-25 09:29:50 +02001685 assertThat(p1.getProvider()).isEqualTo(p);
1686 assertThat(lookup("y")).isEqualTo(2);
1687 }
1688
1689 @Test
1690 public void providerWithFieldsOptionalError() throws Exception {
1691 ev.setFailFast(false);
1692 evalAndExport(
1693 "p = provider(fields = ['x', 'y'])",
1694 "p1 = p(y = 2)",
1695 "x = p1.x"
1696 );
adonovan4e2b4952019-12-10 12:19:20 -08001697 MoreAsserts.assertContainsEvent(
1698 ev.getEventCollector(), " 'p' value has no field or method 'x'");
dslomov0667b832017-08-25 09:29:50 +02001699 }
1700
1701 @Test
1702 public void providerWithExtraFieldsError() throws Exception {
1703 ev.setFailFast(false);
1704 evalAndExport(
1705 "p = provider(fields = ['x', 'y'])",
1706 "p1 = p(x = 1, y = 2, z = 3)"
1707 );
1708 MoreAsserts.assertContainsEvent(ev.getEventCollector(),
1709 "unexpected keyword 'z' in call to p(*, x = ?, y = ?)");
1710 }
1711
1712 @Test
1713 public void providerWithEmptyFieldsError() throws Exception {
1714 ev.setFailFast(false);
1715 evalAndExport(
1716 "p = provider(fields = [])",
1717 "p1 = p(x = 1, y = 2, z = 3)"
1718 );
1719 MoreAsserts.assertContainsEvent(ev.getEventCollector(),
1720 "unexpected keywords 'x', 'y', 'z' in call to p()");
1721 }
1722
Dmitry Lomov0692c7f2016-09-30 16:43:30 +00001723 @Test
1724 public void starTheOnlyAspectArg() throws Exception {
Googleree056632019-10-10 13:04:49 -07001725 checkEvalErrorContains(
1726 "'*' must be the only string in 'attr_aspects' list",
Dmitry Lomov0692c7f2016-09-30 16:43:30 +00001727 "def _impl(target, ctx):",
1728 " pass",
1729 "aspect(_impl, attr_aspects=['*', 'foo'])");
1730 }
Vladimir Moskvaf7c552c2017-01-12 17:17:15 +00001731
1732 @Test
1733 public void testMandatoryConfigParameterForExecutableLabels() throws Exception {
1734 scratch.file("third_party/foo/extension.bzl",
1735 "def _main_rule_impl(ctx):",
1736 " pass",
1737 "my_rule = rule(_main_rule_impl,",
1738 " attrs = { ",
1739 " 'exe' : attr.label(executable = True, allow_files = True),",
1740 " },",
1741 ")"
1742 );
1743 scratch.file("third_party/foo/BUILD",
laurentlb5ddd8042017-11-30 12:03:31 -08001744 "load(':extension.bzl', 'my_rule')",
Vladimir Moskvaf7c552c2017-01-12 17:17:15 +00001745 "my_rule(name = 'main', exe = ':tool.sh')"
1746 );
1747
cushon978cb002018-02-24 14:05:37 -08001748 AssertionError expected =
1749 assertThrows(AssertionError.class, () -> createRuleContext("//third_party/foo:main"));
brandjon8bd20162017-12-28 08:49:54 -08001750 assertThat(expected).hasMessageThat()
1751 .contains("cfg parameter is mandatory when executable=True is provided.");
Vladimir Moskvaf7c552c2017-01-12 17:17:15 +00001752 }
Vladimir Moskvaf7c552c2017-01-12 17:17:15 +00001753
John Catereca28402017-05-17 21:44:12 +02001754 @Test
1755 public void testRuleAddToolchain() throws Exception {
John Cater9a8d16e2017-07-05 16:12:07 -04001756 scratch.file("test/BUILD", "toolchain_type(name = 'my_toolchain_type')");
John Catereca28402017-05-17 21:44:12 +02001757 evalAndExport(
John Cater9a8d16e2017-07-05 16:12:07 -04001758 "def impl(ctx): return None", "r1 = rule(impl, toolchains=['//test:my_toolchain_type'])");
tomlu72642a22017-10-18 06:23:14 +02001759 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
John Cater9a8d16e2017-07-05 16:12:07 -04001760 assertThat(c.getRequiredToolchains()).containsExactly(makeLabel("//test:my_toolchain_type"));
John Catereca28402017-05-17 21:44:12 +02001761 }
vladmos2f32e382017-06-19 12:44:21 -04001762
1763 @Test
John Caterd79e9772018-06-14 02:24:57 -07001764 public void testRuleAddExecutionConstraints() throws Exception {
Googler3fcfbe12019-08-28 08:10:11 -07001765 registerDummyStarlarkFunction();
John Caterd79e9772018-06-14 02:24:57 -07001766 scratch.file("test/BUILD", "toolchain_type(name = 'my_toolchain_type')");
1767 evalAndExport(
1768 "r1 = rule(",
1769 " implementation = impl,",
1770 " toolchains=['//test:my_toolchain_type'],",
1771 " exec_compatible_with=['//constraint:cv1', '//constraint:cv2'],",
1772 ")");
1773 RuleClass c = ((SkylarkRuleFunction) lookup("r1")).getRuleClass();
1774 assertThat(c.getExecutionPlatformConstraints())
1775 .containsExactly(makeLabel("//constraint:cv1"), makeLabel("//constraint:cv2"));
1776 }
1777
1778 @Test
juliexxia693048d2020-04-01 06:41:42 -07001779 public void testRuleAddExecGroup() throws Exception {
1780 setSkylarkSemanticsOptions("--experimental_exec_groups=true");
1781 reset();
1782
1783 registerDummyStarlarkFunction();
1784 scratch.file("test/BUILD", "toolchain_type(name = 'my_toolchain_type')");
1785 evalAndExport(
1786 "plum = rule(",
1787 " implementation = impl,",
1788 " exec_groups = {",
1789 " 'group': exec_group(",
1790 " toolchains=['//test:my_toolchain_type'],",
1791 " exec_compatible_with=['//constraint:cv1', '//constraint:cv2'],",
1792 " ),",
1793 " },",
1794 ")");
1795 RuleClass plum = ((SkylarkRuleFunction) lookup("plum")).getRuleClass();
1796 assertThat(plum.getRequiredToolchains()).isEmpty();
1797 assertThat(plum.getExecGroups().get("group").getRequiredToolchains())
1798 .containsExactly(makeLabel("//test:my_toolchain_type"));
1799 assertThat(plum.getExecutionPlatformConstraints()).isEmpty();
1800 assertThat(plum.getExecGroups().get("group").getExecutionPlatformConstraints())
1801 .containsExactly(makeLabel("//constraint:cv1"), makeLabel("//constraint:cv2"));
1802 }
1803
1804 @Test
vladmos2f32e382017-06-19 12:44:21 -04001805 public void testRuleFunctionReturnsNone() throws Exception {
1806 scratch.file("test/rule.bzl",
1807 "def _impl(ctx):",
1808 " pass",
1809 "foo_rule = rule(",
1810 " implementation = _impl,",
1811 " attrs = {'params': attr.string_list()},",
1812 ")");
1813 scratch.file("test/BUILD",
1814 "load(':rule.bzl', 'foo_rule')",
1815 "r = foo_rule(name='foo')", // Custom rule should return None
1816 "c = cc_library(name='cc')", // Native rule should return None
1817 "",
1818 "foo_rule(",
1819 " name='check',",
1820 " params = [type(r), type(c)]",
1821 ")");
1822 invalidatePackages();
1823 SkylarkRuleContext context = createRuleContext("//test:check");
1824 @SuppressWarnings("unchecked")
Googler942e1c42019-11-12 13:11:44 -08001825 StarlarkList<Object> params = (StarlarkList<Object>) context.getAttr().getValue("params");
vladmos2f32e382017-06-19 12:44:21 -04001826 assertThat(params.get(0)).isEqualTo("NoneType");
1827 assertThat(params.get(1)).isEqualTo("NoneType");
1828 }
cparsons0c5c1c62018-05-24 10:37:03 -07001829
1830 @Test
1831 public void testTypeOfStruct() throws Exception {
Googler1a1fca22019-10-14 09:31:22 -07001832 exec("p = type(struct)", "s = type(struct())");
cparsons0c5c1c62018-05-24 10:37:03 -07001833
1834 assertThat(lookup("p")).isEqualTo("Provider");
1835 assertThat(lookup("s")).isEqualTo("struct");
1836 }
juliexxia44e21432020-03-31 08:21:20 -07001837
1838 @Test
1839 public void testCreateExecGroup() throws Exception {
1840 setSkylarkSemanticsOptions("--experimental_exec_groups=true");
1841 reset();
1842
1843 scratch.file("test/BUILD", "toolchain_type(name = 'my_toolchain_type')");
1844 evalAndExport(
1845 "group = exec_group(",
1846 " toolchains=['//test:my_toolchain_type'],",
1847 " exec_compatible_with=['//constraint:cv1', '//constraint:cv2'],",
1848 ")");
1849 ExecGroup group = ((ExecGroup) lookup("group"));
1850 assertThat(group.getRequiredToolchains())
1851 .containsExactly(makeLabel("//test:my_toolchain_type"));
1852 assertThat(group.getExecutionPlatformConstraints())
1853 .containsExactly(makeLabel("//constraint:cv1"), makeLabel("//constraint:cv2"));
1854 }
John Catereca28402017-05-17 21:44:12 +02001855}