Skip to content

Commit

Permalink
Delete the depset.union() method
Browse files Browse the repository at this point in the history
    It has been deprecated for a long time.
    bazelbuild/bazel#5817

    RELNOTES: None.
    PiperOrigin-RevId: 283060975
  • Loading branch information
Luca Di Grazia committed Sep 4, 2022
1 parent 3b56733 commit d48786b
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,10 @@ private static Depset create(
itemsBuilder.add(x);
}
} else {
throw Starlark.errorf(
"cannot union value of type '%s' to a depset", EvalUtils.getDataTypeName(item));
throw new EvalException(
null,
String.format(
"cannot union value of type '%s' to a depset", EvalUtils.getDataTypeName(item)));
}
ImmutableList<Object> items = itemsBuilder.build();
ImmutableList<NestedSet<?>> transitiveItems = transitiveItemsBuilder.build();
Expand All @@ -146,7 +148,7 @@ private static Depset create(
}
} catch (IllegalArgumentException e) {
// Order mismatch between item and builder.
throw Starlark.errorf("%s", e.getMessage());
throw new EvalException(null, e.getMessage());
}
return new Depset(contentType, builder.build(), items, transitiveItems);
}
Expand All @@ -171,13 +173,14 @@ private static void checkElement(Object x, boolean strict) throws EvalException
// which are Starlark-unhashable even if frozen.
// TODO(adonovan): also remove StarlarkList.hashCode.
if (strict && !EvalUtils.isImmutable(x)) {
throw Starlark.errorf("depset elements must not be mutable values");
throw new EvalException(null, "depset elements must not be mutable values");
}

// Even the looser regime forbids the toplevel constructor to be list or dict.
if (x instanceof StarlarkList || x instanceof Dict) {
throw Starlark.errorf(
"depsets cannot contain items of type '%s'", EvalUtils.getDataTypeName(x));
throw new EvalException(
null,
String.format("depsets cannot contain items of type '%s'", EvalUtils.getDataTypeName(x)));
}
}

Expand Down Expand Up @@ -227,8 +230,9 @@ private static SkylarkType checkType(SkylarkType depsetType, SkylarkType itemTyp
if (depsetType == SkylarkType.TOP || depsetType.equals(itemType)) {
return itemType;
}
throw Starlark.errorf(
"cannot add an item of type '%s' to a depset of '%s'", itemType, depsetType);
throw new EvalException(
null,
String.format("cannot add an item of type '%s' to a depset of '%s'", itemType, depsetType));
}

/**
Expand Down Expand Up @@ -346,9 +350,10 @@ public static <T> NestedSet<T> getSetFromNoneableParam(
Depset depset = (Depset) depsetOrNone;
return depset.getSetFromParam(expectedType, fieldName);
} else {
throw Starlark.errorf(
"expected a depset of '%s' but got '%s' for parameter '%s'",
EvalUtils.getDataTypeNameFromClass(expectedType), depsetOrNone, fieldName);
throw new EvalException(
String.format(
"expected a depset of '%s' but got '%s' for parameter '%s'",
EvalUtils.getDataTypeNameFromClass(expectedType), depsetOrNone, fieldName));
}
}

Expand Down Expand Up @@ -382,7 +387,7 @@ public boolean isImmutable() {
@Override
public void repr(Printer printer) {
printer.append("depset(");
printer.printList(set.toList(), "[", ", ", "]", null);
printer.printList(set, "[", ", ", "]", null);
Order order = getOrder();
if (order != Order.STABLE_ORDER) {
printer.append(", order = ");
Expand Down Expand Up @@ -448,9 +453,11 @@ static Depset fromDirectAndTransitive(
if (!x.isEmpty()) {
type = checkType(type, x.getContentType());
if (!order.isCompatible(x.getOrder())) {
throw Starlark.errorf(
"Order '%s' is incompatible with order '%s'",
order.getSkylarkName(), x.getOrder().getSkylarkName());
throw new EvalException(
null,
String.format(
"Order '%s' is incompatible with order '%s'",
order.getSkylarkName(), x.getOrder().getSkylarkName()));
}
builder.addTransitive(x.getSet());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

/** Tests for Depset. */
@RunWith(JUnit4.class)
public final class DepsetTest extends EvaluationTestCase {
public class DepsetTest extends EvaluationTestCase {

@Test
public void testConstructor() throws Exception {
Expand All @@ -53,38 +53,38 @@ public void testTuples() throws Exception {
assertThat(get("s_three").getContentType()).isEqualTo(SkylarkType.TUPLE);
assertThat(get("s_eight").getContentType()).isEqualTo(SkylarkType.TUPLE);

assertThat(get("s_four").getSet(Tuple.class).toList())
assertThat(get("s_four").getSet(Tuple.class))
.containsExactly(
Tuple.of("1", "3"), Tuple.of("1", "2"), Tuple.of("3", "4"), Tuple.of("5", "6"));
assertThat(get("s_five").getSet(Tuple.class).toList())
assertThat(get("s_five").getSet(Tuple.class))
.containsExactly(
Tuple.of("1", "3", "5"), Tuple.of("1", "2"), Tuple.of("3", "4"), Tuple.of("5", "6"));
assertThat(get("s_eight").getSet(Tuple.class).toList())
assertThat(get("s_eight").getSet(Tuple.class))
.containsExactly(
Tuple.of(1, 3), Tuple.of("1", "2"), Tuple.of("3", "4"), Tuple.of("5", "6"));
}

@Test
public void testGetSet() throws Exception {
exec("s = depset(['a', 'b'])");
assertThat(get("s").getSet(String.class).toList()).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(Object.class).toList()).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(String.class)).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(Object.class)).containsExactly("a", "b").inOrder();
assertThrows(Depset.TypeException.class, () -> get("s").getSet(Integer.class));
}

@Test
public void testGetSetDirect() throws Exception {
exec("s = depset(direct = ['a', 'b'])");
assertThat(get("s").getSet(String.class).toList()).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(Object.class).toList()).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(String.class)).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(Object.class)).containsExactly("a", "b").inOrder();
assertThrows(Depset.TypeException.class, () -> get("s").getSet(Integer.class));
}

@Test
public void testGetSetItems() throws Exception {
exec("s = depset(items = ['a', 'b'])");
assertThat(get("s").getSet(String.class).toList()).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(Object.class).toList()).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(String.class)).containsExactly("a", "b").inOrder();
assertThat(get("s").getSet(Object.class)).containsExactly("a", "b").inOrder();
assertThrows(Depset.TypeException.class, () -> get("s").getSet(Integer.class));
}

Expand Down Expand Up @@ -239,8 +239,7 @@ public void testItemsAndTransitive() throws Exception {
public void testTooManyPositionals() throws Exception {
new BothModesTest()
.testIfErrorContains(
"depset() accepts no more than 2 positional arguments but got 3",
"depset([], 'default', [])");
"expected no more than 2 positional arguments, but got 3", "depset([], 'default', [])");
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@

package com.google.devtools.build.lib.syntax;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.syntax.util.EvaluationTestCase;
Expand All @@ -24,9 +27,11 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for MethodLibrary. */
/**
* Tests for MethodLibrary.
*/
@RunWith(JUnit4.class)
public final class MethodLibraryTest extends EvaluationTestCase {
public class MethodLibraryTest extends EvaluationTestCase {

private static final String LINE_SEPARATOR = System.lineSeparator();

Expand Down Expand Up @@ -92,7 +97,7 @@ public void testStackTraceWithAugmentedAssignment() throws Exception {
+ LINE_SEPARATOR
+ "\t\ts += \"2\""
+ LINE_SEPARATOR
+ "unsupported binary operation: int + string",
+ "unsupported operand type(s) for +: 'int' and 'string'",
"def foo():",
" s = 1",
" s += '2'",
Expand All @@ -105,7 +110,8 @@ public void testStackTraceSkipBuiltInOnly() throws Exception {
// only one built-in function.
new BothModesTest()
.testIfExactError(
"in call to index(), parameter 'sub' got value of type 'int', want 'string'",
"expected value of type 'string' for parameter 'sub', "
+ "for call to method index(sub, start = 0, end = None) of 'string'",
"'test'.index(1)");
}

Expand All @@ -129,7 +135,8 @@ public void testStackTrace() throws Exception {
+ LINE_SEPARATOR
+ "\t\t\"test\".index(x)"
+ LINE_SEPARATOR
+ "in call to index(), parameter 'sub' got value of type 'int', want 'string'",
+ "expected value of type 'string' for parameter 'sub', "
+ "for call to method index(sub, start = 0, end = None) of 'string'",
"def foo():",
" bar(1)",
"def bar(x):",
Expand All @@ -143,8 +150,8 @@ public void testBuiltinFunctionErrorMessage() throws Exception {
new BothModesTest()
.testIfErrorContains("substring \"z\" not found in \"abc\"", "'abc'.index('z')")
.testIfErrorContains(
"in call to startswith(), parameter 'sub' got value of type 'int', want 'string or"
+ " tuple of strings'",
"expected value of type 'string or tuple of strings' for parameter 'sub', "
+ "for call to method startswith(sub, start = 0, end = None) of 'string'",
"'test'.startswith(1)")
.testIfErrorContains("in dict, got string, want iterable", "dict('a')");
}
Expand All @@ -162,7 +169,8 @@ public void testHasAttr() throws Exception {
public void testGetAttrMissingField() throws Exception {
new SkylarkTest()
.testIfExactError(
"'string' value has no field or method 'not_there'", "getattr('a string', 'not_there')")
"object of type 'string' has no attribute 'not_there'",
"getattr('a string', 'not_there')")
.testExpression("getattr('a string', 'not_there', 'use this')", "use this")
.testExpression("getattr('a string', 'not there', None)", Starlark.NONE);
}
Expand Down Expand Up @@ -195,13 +203,13 @@ public void testGetAttrMissingField_typoDetection() throws Exception {
new SkylarkTest()
.update("s", new AStruct())
.testIfExactError(
"'AStruct' value has no field or method 'feild' (did you mean 'field'?)",
"object of type 'AStruct' has no attribute 'feild' (did you mean 'field'?)",
"getattr(s, 'feild')");
}

@Test
public void testGetAttrWithMethods() throws Exception {
String msg = "'string' value has no field or method 'cnt'";
String msg = "object of type 'string' has no attribute 'cnt'";
new SkylarkTest()
.testIfExactError(msg, "getattr('a string', 'cnt')")
.testExpression("getattr('a string', 'cnt', 'default')", "default");
Expand All @@ -224,7 +232,7 @@ public void testBoolean() throws Exception {
@Test
public void testBooleanUnsupportedOperationFails() throws Exception {
new BothModesTest()
.testIfErrorContains("unsupported binary operation: bool + bool", "True + True");
.testIfErrorContains("unsupported operand type(s) for +: 'bool' and 'bool'", "True + True");
}

@Test
Expand Down Expand Up @@ -327,8 +335,7 @@ public void testDictionaryCreationInvalidPositional() throws Exception {
"in dict, dictionary update sequence element #0 is not iterable (string)",
"dict([('a')])")
.testIfErrorContains(
"dict() accepts no more than 1 positional argument but got 3",
"dict((3,4), (3,2), (1,2))")
"expected no more than 1 positional arguments, but got 3", "dict((3,4), (3,2), (1,2))")
.testIfErrorContains(
"item #0 has length 3, but exactly two elements are required",
"dict([('a', 'b', 'c')])");
Expand Down Expand Up @@ -455,7 +462,8 @@ public void testHash() throws Exception {
.testExpression("hash('skylark')", "skylark".hashCode())
.testExpression("hash('google')", "google".hashCode())
.testIfErrorContains(
"in call to hash(), parameter 'value' got value of type 'NoneType', want 'string'",
"expected value of type 'string' for parameter 'value', "
+ "for call to function hash(value)",
"hash(None)");
}

Expand All @@ -469,8 +477,8 @@ public void testRangeType() throws Exception {
.testExpression("repr(a)", "range(0, 3)")
.testExpression("repr(range(1,2,3))", "range(1, 2, 3)")
.testExpression("type(a)", "range")
.testIfErrorContains("unsupported binary operation: range + range", "a + a")
.testIfErrorContains("'range' value has no field or method 'append'", "a.append(3)")
.testIfErrorContains("unsupported operand type(s) for +: 'range' and 'range'", "a + a")
.testIfErrorContains("type 'range' has no method append()", "a.append(3)")
.testExpression("str(list(range(5)))", "[0, 1, 2, 3, 4]")
.testExpression("str(list(range(0)))", "[]")
.testExpression("str(list(range(1)))", "[0]")
Expand Down Expand Up @@ -499,7 +507,7 @@ public void testRangeType() throws Exception {
.testExpression("str(range(0, 10, 2)[::-2])", "range(8, -2, -4)")
.testExpression("str(range(5)[1::-1])", "range(1, -1, -1)")
.testIfErrorContains("step cannot be 0", "range(2, 3, 0)")
.testIfErrorContains("unsupported binary operation: range * int", "range(3) * 3")
.testIfErrorContains("unsupported operand type(s) for *: 'range' and 'int'", "range(3) * 3")
.testIfErrorContains("Cannot compare range objects", "range(3) < range(5)")
.testIfErrorContains("Cannot compare range objects", "range(4) > [1]")
.testExpression("4 in range(1, 10)", true)
Expand Down Expand Up @@ -578,7 +586,7 @@ public void testLenOnBadType() throws Exception {
public void testIndexOnFunction() throws Exception {
new BothModesTest()
.testIfErrorContains("type 'function' has no operator [](int)", "len[1]")
.testIfErrorContains("invalid slice operand: function", "len[1:4]");
.testIfErrorContains("type 'function' has no operator [:](int, int, NoneType)", "len[1:4]");
}

@Test
Expand Down Expand Up @@ -620,6 +628,16 @@ public void testType() throws Exception {
.testExpression("type(str)", "function");
}

// TODO(bazel-team): Move select and this test into lib/packages.
@Test
public void testSelectFunction() throws Exception {
enableSkylarkMode();
exec("a = select({'a': 1})");
SelectorList result = (SelectorList) lookup("a");
assertThat(((SelectorValue) Iterables.getOnlyElement(result.getElements())).getDictionary())
.containsExactly("a", 1);
}

@Test
public void testZipFunction() throws Exception {
new BothModesTest()
Expand Down Expand Up @@ -742,7 +760,8 @@ public void testLegacyNamed() throws Exception {
public void testExperimentalStarlarkConfig() throws Exception {
new SkylarkTest("--incompatible_restrict_named_params")
.testIfErrorContains(
"join() got named argument for positional-only parameter 'elements'",
"parameter 'elements' may not be specified by name, "
+ "for call to method join(elements) of 'string'",
"','.join(elements=['foo', 'bar'])");
}

Expand Down Expand Up @@ -778,7 +797,7 @@ public void testDisableDepsetItems() throws Exception {
"parameter 'direct' cannot be specified both positionally and by keyword",
"depset([0, 1], 'default', direct=[0,1])")
.testIfErrorContains(
"in call to depset(), parameter 'items' is deprecated and will be removed soon. "
"parameter 'items' is deprecated and will be removed soon. "
+ "It may be temporarily re-enabled by setting "
+ "--incompatible_disable_depset_inputs=false",
"depset(items=[0,1])");
Expand Down

0 comments on commit d48786b

Please sign in to comment.