blob: 2ab108f0a72cd939543161e318aaf587801aa84d [file] [log] [blame]
Dmitry Lomovf4cd4752015-11-23 17:50:57 +00001// Copyright 2014 The Bazel Authors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package com.google.devtools.build.lib.analysis;
16
mstaib16514d32017-12-07 15:18:52 -080017import static com.google.common.collect.ImmutableList.toImmutableList;
lberkiaea56b32017-05-30 12:35:33 +020018import static com.google.common.truth.Truth.assertThat;
mstaib16514d32017-12-07 15:18:52 -080019import static com.google.devtools.build.lib.packages.Attribute.attr;
20import static com.google.devtools.build.lib.packages.BuildType.LABEL;
21import static com.google.devtools.build.lib.packages.BuildType.NODEP_LABEL;
Googlerc5fcc862019-09-06 16:17:47 -070022import static com.google.devtools.build.lib.packages.Type.STRING;
michajlo660d17f2020-03-27 09:01:57 -070023import static org.junit.Assert.assertThrows;
Florian Weikert10df9522015-11-26 15:00:59 +000024
Googler19226b72020-02-06 12:58:43 -080025import com.google.common.collect.ImmutableMap;
gregce06b76c92020-06-19 14:46:56 -070026import com.google.common.collect.ImmutableSet;
jhorvitz33f76482021-10-28 10:13:26 -070027import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
mstaib16514d32017-12-07 15:18:52 -080028import com.google.devtools.build.lib.analysis.config.BuildOptions;
gregce06b76c92020-06-19 14:46:56 -070029import com.google.devtools.build.lib.analysis.config.BuildOptionsView;
gregcee495e6b2019-04-30 14:07:06 -070030import com.google.devtools.build.lib.analysis.config.CoreOptions;
gregce06b76c92020-06-19 14:46:56 -070031import com.google.devtools.build.lib.analysis.config.FragmentOptions;
cparsons21e25182019-01-15 16:00:26 -080032import com.google.devtools.build.lib.analysis.config.transitions.SplitTransition;
John Cater0a9e1ed2019-03-27 11:02:01 -070033import com.google.devtools.build.lib.analysis.config.transitions.TransitionFactory;
Florian Weikertcca703a2015-12-07 09:56:38 +000034import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
mstaib16514d32017-12-07 15:18:52 -080035import com.google.devtools.build.lib.analysis.util.MockRule;
Dmitry Lomovf4cd4752015-11-23 17:50:57 +000036import com.google.devtools.build.lib.events.Event;
gregcef0a40ac2020-03-31 14:11:30 -070037import com.google.devtools.build.lib.events.EventHandler;
janakra56a6ad2018-02-02 15:52:22 -080038import com.google.devtools.build.lib.packages.Attribute.LabelLateBoundDefault;
John Cater2c0dece2019-04-02 09:18:18 -070039import com.google.devtools.build.lib.packages.AttributeTransitionData;
Dmitry Lomovf4cd4752015-11-23 17:50:57 +000040import com.google.devtools.build.lib.packages.NoSuchTargetException;
41import com.google.devtools.build.lib.packages.Package;
mstaib16514d32017-12-07 15:18:52 -080042import com.google.devtools.build.lib.testutil.TestRuleClassProvider;
gregceecb61ee2020-05-19 10:56:29 -070043import java.util.Map;
John Cater660e8a52021-04-20 08:00:56 -070044import java.util.regex.Pattern;
Florian Weikert10df9522015-11-26 15:00:59 +000045import org.junit.Test;
46import org.junit.runner.RunWith;
47import org.junit.runners.JUnit4;
48
Googlere10873c2021-10-20 09:09:01 -070049/** Tests that check that dependency cycles are reported correctly. */
Florian Weikert10df9522015-11-26 15:00:59 +000050@RunWith(JUnit4.class)
Florian Weikertcca703a2015-12-07 09:56:38 +000051public class CircularDependencyTest extends BuildViewTestCase {
Dmitry Lomovf4cd4752015-11-23 17:50:57 +000052
Florian Weikert10df9522015-11-26 15:00:59 +000053 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +000054 public void testOneRuleCycle() throws Exception {
55 checkError(
56 "cycle",
57 "foo.g",
Googlere10873c2021-10-20 09:09:01 -070058 // error message
Dmitry Lomovf4cd4752015-11-23 17:50:57 +000059 selfEdgeMsg("//cycle:foo.g"),
60 // Rule
61 "genrule(name = 'foo.g',",
62 " outs = ['Foo.java'],",
63 " srcs = ['foo.g'],",
64 " cmd = 'cat $(SRCS) > $<' )");
65 }
66
Florian Weikert10df9522015-11-26 15:00:59 +000067 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +000068 public void testDirectPackageGroupCycle() throws Exception {
69 checkError(
70 "cycle",
71 "melon",
72 selfEdgeMsg("//cycle:moebius"),
73 "package_group(name='moebius', packages=[], includes=['//cycle:moebius'])",
74 "sh_library(name='melon', visibility=[':moebius'])");
75 }
76
Florian Weikert10df9522015-11-26 15:00:59 +000077 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +000078 public void testThreeLongPackageGroupCycle() throws Exception {
John Cater660e8a52021-04-20 08:00:56 -070079 @SuppressWarnings("ConstantPatternCompile")
80 Pattern expectedEvent =
81 Pattern.compile(
82 "cycle in dependency graph:\n"
83 + " //cycle:superman \\([a-f0-9]+\\)\n"
84 + ".-> //cycle:rock \\(null\\)\n"
85 + "| //cycle:paper \\(null\\)\n"
86 + "| //cycle:scissors \\(null\\)\n"
87 + "`-- //cycle:rock \\(null\\)");
Dmitry Lomovf4cd4752015-11-23 17:50:57 +000088 checkError(
89 "cycle",
90 "superman",
91 expectedEvent,
92 "# dummy line",
93 "package_group(name='paper', includes=['//cycle:scissors'])",
94 "package_group(name='rock', includes=['//cycle:paper'])",
95 "package_group(name='scissors', includes=['//cycle:rock'])",
96 "sh_library(name='superman', visibility=[':rock'])");
97
John Cater660e8a52021-04-20 08:00:56 -070098 Event foundEvent = assertContainsEvent(expectedEvent);
adonovan07b15e62020-04-09 18:32:33 -070099 assertThat(foundEvent.getLocation().toString()).isEqualTo("/workspace/cycle/BUILD:3:14");
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000100 }
101
Googlere10873c2021-10-20 09:09:01 -0700102 /** Test to detect implicit input/output file overlap in rules. */
Florian Weikert10df9522015-11-26 15:00:59 +0000103 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000104 public void testOneRuleImplicitCycleJava() throws Exception {
105 Package pkg =
106 createScratchPackageForImplicitCycle(
107 "cycle", "java_library(name='jcyc',", " srcs = ['libjcyc.jar', 'foo.java'])");
jcater42edea62019-05-01 08:46:18 -0700108 assertThrows(NoSuchTargetException.class, () -> pkg.getTarget("jcyc"));
lberkiaea56b32017-05-30 12:35:33 +0200109 assertThat(pkg.containsErrors()).isTrue();
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000110 assertContainsEvent("rule 'jcyc' has file 'libjcyc.jar' as both an" + " input and an output");
111 }
112
113 /**
Googlere10873c2021-10-20 09:09:01 -0700114 * Test not to detect implicit input/output file overlap in rules, when coming from a different
115 * package.
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000116 */
Florian Weikert10df9522015-11-26 15:00:59 +0000117 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000118 public void testInputOutputConflictDifferentPackage() throws Exception {
119 Package pkg =
120 createScratchPackageForImplicitCycle(
121 "googledata/xxx",
122 "genrule(name='geo',",
123 " srcs = ['//googledata/geo:geo_info.txt'],",
124 " outs = ['geoinfo.txt'],",
125 " cmd = '$(SRCS) > $@')");
lberkiaea56b32017-05-30 12:35:33 +0200126 assertThat(pkg.containsErrors()).isFalse();
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000127 }
128
Florian Weikert10df9522015-11-26 15:00:59 +0000129 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000130 public void testTwoRuleCycle() throws Exception {
131 scratchRule("b", "rule2", "cc_library(name='rule2',", " deps=['//a:rule1'])");
132
133 checkError(
134 "a",
135 "rule1",
John Cater660e8a52021-04-20 08:00:56 -0700136 Pattern.compile(
137 "in cc_library rule //a:rule1: cycle in dependency graph:\n"
138 + ".-> //a:rule1 \\([a-f0-9]+\\)\n"
139 + "| //b:rule2 \\([a-f0-9]+\\)\n"
140 + "`-- //a:rule1 \\([a-f0-9]+\\)"),
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000141 "cc_library(name='rule1',",
142 " deps=['//b:rule2'])");
143 }
144
Florian Weikert10df9522015-11-26 15:00:59 +0000145 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000146 public void testTwoRuleCycle2() throws Exception {
147 reporter.removeHandler(failFastHandler); // expect errors
148 scratch.file(
149 "x/BUILD", "java_library(name='x', deps=['y'])", "java_library(name='y', deps=['x'])");
150 getConfiguredTarget("//x");
151 assertContainsEvent("in java_library rule //x:x: cycle in dependency graph");
152 }
153
Florian Weikert10df9522015-11-26 15:00:59 +0000154 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000155 public void testIndirectOneRuleCycle() throws Exception {
156 scratchRule(
157 "cycle",
158 "foo.h",
159 "genrule(name = 'foo.h',",
160 " outs = ['bar.h'],",
161 " srcs = ['foo.h'],",
162 " cmd = 'cp $< $@')");
163 checkError(
164 "main",
165 "mygenrule",
Googlere10873c2021-10-20 09:09:01 -0700166 // error message
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000167 selfEdgeMsg("//cycle:foo.h"),
168 // Rule
169 "genrule(name='mygenrule',",
170 " outs = ['baz.h'],",
171 " srcs = ['//cycle:foo.h'],",
172 " cmd = 'cp $< $@')");
173 }
174
John Cater660e8a52021-04-20 08:00:56 -0700175 private Pattern selfEdgeMsg(String label) {
176 return Pattern.compile(label + " \\([a-f0-9]+|null\\) \\[self-edge\\]");
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000177 }
178
179 // Regression test for: "IllegalStateException in
180 // AbstractConfiguredTarget.initialize()".
181 // Failure to mark all cycle-forming nodes when there are *two* cycles led to
182 // an attempt to initialise a node we'd already visited.
Florian Weikert10df9522015-11-26 15:00:59 +0000183 @Test
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000184 public void testTwoCycles() throws Exception {
185 reporter.removeHandler(failFastHandler); // expect errors
186 scratch.file(
187 "x/BUILD",
188 "genrule(name='b', srcs=['c'], tools=['c'], outs=['b.out'], cmd=':')",
189 "genrule(name='c', srcs=['b.out'], outs=[], cmd=':')");
190 getConfiguredTarget("//x:b"); // doesn't crash!
Lukacs Berkibba75d82016-06-14 09:08:29 +0000191 assertContainsEvent("cycle in dependency graph");
192 }
193
194 @Test
195 public void testAspectCycle() throws Exception {
196 reporter.removeHandler(failFastHandler);
Googlere10873c2021-10-20 09:09:01 -0700197 scratch.file(
198 "x/BUILD",
Lukacs Berkibba75d82016-06-14 09:08:29 +0000199 "load('//x:x.bzl', 'aspected', 'plain')",
200 // Using data= makes the dependency graph clearer because then the aspect does not propagate
201 // from aspectdep through a to b (and c)
202 "plain(name = 'a', noaspect_deps = [':b'])",
203 "aspected(name = 'b', aspect_deps = ['c'])",
204 "plain(name = 'c')",
205 "plain(name = 'aspectdep', aspect_deps = ['a'])");
206
cparsons0f22a962019-04-18 10:25:37 -0700207 scratch.file(
208 "x/x.bzl",
Lukacs Berkibba75d82016-06-14 09:08:29 +0000209 "def _impl(ctx):",
cparsons0f22a962019-04-18 10:25:37 -0700210 " return []",
Lukacs Berkibba75d82016-06-14 09:08:29 +0000211 "",
212 "rule_aspect = aspect(",
213 " implementation = _impl,",
214 " attr_aspects = ['aspect_deps'],",
215 " attrs = { '_implicit': attr.label(default = Label('//x:aspectdep')) })",
216 "",
217 "plain = rule(",
218 " implementation = _impl,",
219 " attrs = { 'aspect_deps': attr.label_list(), 'noaspect_deps': attr.label_list() })",
220 "",
221 "aspected = rule(",
222 " implementation = _impl,",
223 " attrs = { 'aspect_deps': attr.label_list(aspects = [rule_aspect]) })");
224
225 getConfiguredTarget("//x:a");
226 assertContainsEvent("cycle in dependency graph");
227 assertContainsEvent("//x:c with aspect //x:x.bzl%rule_aspect");
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000228 }
mstaib16514d32017-12-07 15:18:52 -0800229
230 /** A late bound dependency which depends on the 'dep' label if the 'define' is in --defines. */
231 // TODO(b/65746853): provide a way to do this without passing the entire configuration
jhorvitz33f76482021-10-28 10:13:26 -0700232 private static final LabelLateBoundDefault<BuildConfigurationValue> LATE_BOUND_DEP =
janakra56a6ad2018-02-02 15:52:22 -0800233 LabelLateBoundDefault.fromTargetConfiguration(
jhorvitz33f76482021-10-28 10:13:26 -0700234 BuildConfigurationValue.class,
mstaib16514d32017-12-07 15:18:52 -0800235 null,
236 (rule, attributes, config) ->
237 config.getCommandLineBuildVariables().containsKey(attributes.get("define", STRING))
238 ? attributes.get("dep", NODEP_LABEL)
239 : null);
240
241 /** A rule which always depends on the given label. */
242 private static final MockRule NORMAL_DEPENDER =
243 () -> MockRule.define("normal_dep", attr("dep", LABEL).allowedFileTypes());
244
245 /** A rule which depends on a given label only if the given define is set. */
246 private static final MockRule LATE_BOUND_DEPENDER =
247 () ->
248 MockRule.define(
249 "late_bound_dep",
250 attr("define", STRING).mandatory(),
251 attr("dep", NODEP_LABEL).mandatory(),
252 attr(":late_bound_dep", LABEL).value(LATE_BOUND_DEP));
253
254 /** A rule which removes a define from the configuration of its dependency. */
255 private static final MockRule DEFINE_CLEARER =
256 () ->
257 MockRule.define(
258 "define_clearer",
259 attr("define", STRING).mandatory(),
260 attr("dep", LABEL)
261 .mandatory()
262 .allowedFileTypes()
263 .cfg(
John Cater2c0dece2019-04-02 09:18:18 -0700264 new TransitionFactory<AttributeTransitionData>() {
cparsons21e25182019-01-15 16:00:26 -0800265 @Override
John Cater2c0dece2019-04-02 09:18:18 -0700266 public SplitTransition create(AttributeTransitionData data) {
gregceecb61ee2020-05-19 10:56:29 -0700267 return new SplitTransition() {
gregce06b76c92020-06-19 14:46:56 -0700268
269 @Override
270 public ImmutableSet<Class<? extends FragmentOptions>>
271 requiresOptionFragments() {
272 return ImmutableSet.of(CoreOptions.class);
273 }
274
gregceecb61ee2020-05-19 10:56:29 -0700275 @Override
276 public Map<String, BuildOptions> split(
gregce06b76c92020-06-19 14:46:56 -0700277 BuildOptionsView options, EventHandler eventHandler) {
gregceecb61ee2020-05-19 10:56:29 -0700278 String define = data.attributes().get("define", STRING);
gregce06b76c92020-06-19 14:46:56 -0700279 BuildOptionsView newOptions = options.clone();
gregceecb61ee2020-05-19 10:56:29 -0700280 CoreOptions optionsFragment = newOptions.get(CoreOptions.class);
281 optionsFragment.commandLineBuildVariables =
282 optionsFragment.commandLineBuildVariables.stream()
283 .filter((pair) -> !pair.getKey().equals(define))
284 .collect(toImmutableList());
gregce06b76c92020-06-19 14:46:56 -0700285 return ImmutableMap.of("define_cleaner", newOptions.underlying());
gregceecb61ee2020-05-19 10:56:29 -0700286 }
cparsons21e25182019-01-15 16:00:26 -0800287 };
288 }
John Cater0a9e1ed2019-03-27 11:02:01 -0700289
290 @Override
291 public boolean isSplit() {
292 return true;
293 }
cparsons21e25182019-01-15 16:00:26 -0800294 }));
mstaib16514d32017-12-07 15:18:52 -0800295
296 @Override
brandjon232a6b82020-06-08 12:32:49 -0700297 protected ConfiguredRuleClassProvider createRuleClassProvider() {
mstaib16514d32017-12-07 15:18:52 -0800298 ConfiguredRuleClassProvider.Builder builder =
299 new ConfiguredRuleClassProvider.Builder()
300 .addRuleDefinition(NORMAL_DEPENDER)
301 .addRuleDefinition(LATE_BOUND_DEPENDER)
302 .addRuleDefinition(DEFINE_CLEARER);
303 TestRuleClassProvider.addStandardRules(builder);
304 return builder.build();
305 }
306
307 @Test
308 public void testLateBoundTargetCycleNotConfiguredTargetCycle() throws Exception {
309 // Target graph: //a -> //b -?> //c -> //a (loop)
310 // Configured target graph: //a -> //b -> //c -> //a (2) -> //b (2)
311 scratch.file("a/BUILD", "normal_dep(name = 'a', dep = '//b')");
312 scratch.file("b/BUILD", "late_bound_dep(name = 'b', dep = '//c', define = 'CYCLE_ON')");
313 scratch.file("c/BUILD", "define_clearer(name = 'c', dep = '//a', define = 'CYCLE_ON')");
314
315 useConfiguration("--define=CYCLE_ON=yes");
316 getConfiguredTarget("//a");
317 assertNoEvents();
318 }
319
320 @Test
321 public void testSelectTargetCycleNotConfiguredTargetCycle() throws Exception {
322 // Target graph: //a -> //b -?> //c -> //a (loop)
323 // Configured target graph: //a -> //b -> //c -> //a (2) -> //b (2) -> //b:stop (2)
324 scratch.file("a/BUILD", "normal_dep(name = 'a', dep = '//b')");
Googlere10873c2021-10-20 09:09:01 -0700325 scratch.file(
326 "b/BUILD",
mstaib16514d32017-12-07 15:18:52 -0800327 "config_setting(name = 'cycle', define_values = {'CYCLE_ON': 'yes'})",
328 "normal_dep(name = 'stop')",
329 "normal_dep(name = 'b', dep = select({':cycle': '//c', '//conditions:default': ':stop'}))");
330 scratch.file("c/BUILD", "define_clearer(name = 'c', dep = '//a', define = 'CYCLE_ON')");
331
332 useConfiguration("--define=CYCLE_ON=yes");
333 getConfiguredTarget("//a");
334 assertNoEvents();
335 }
Googlere10873c2021-10-20 09:09:01 -0700336
337 @Test
338 public void testInvalidVisibility() throws Exception {
339 scratch.file(
340 "a/BUILD",
341 "cc_library(name='rule1',",
342 " deps=['//b:rule2'],",
343 " visibility=['//b:rule2'])");
344 scratch.file("b/BUILD", "cc_library(name='rule2')");
345
346 AssertionError expected =
347 assertThrows(AssertionError.class, () -> getConfiguredTarget("//a:rule1"));
348
349 assertThat(expected)
350 .hasMessageThat()
351 .contains("Label '//b:rule2' does not refer to a package group.");
352 }
353
354 @Test
355 public void testInvalidVisibilityWithSelect() throws Exception {
356 scratch.file(
357 "a/BUILD",
358 "cc_library(name='rule1',",
359 " deps=['//b:rule2'],",
360 " visibility=['//b:rule2'])");
361 scratch.file(
362 "b/BUILD",
363 "config_setting(name = 'fastbuild', values = {'compilation_mode': 'fastbuild'})",
364 "cc_library(name='rule2',",
365 " hdrs = select({",
366 " ':fastbuild': glob([",
367 " '*.h',",
368 " ]),",
369 " }),",
370 ")");
371
372 AssertionError expected =
373 assertThrows(AssertionError.class, () -> getConfiguredTarget("//a:rule1"));
374
375 assertThat(expected)
376 .hasMessageThat()
377 .contains("Label '//b:rule2' does not refer to a package group.");
378 }
Dmitry Lomovf4cd4752015-11-23 17:50:57 +0000379}