Skip to content

Commit

Permalink
Fix repr of dict-valued select expressions
Browse files Browse the repository at this point in the history
We need to print `select({'x': {...}}) | {...}` - but were printing the operator
as '+' instead of '|'.

PiperOrigin-RevId: 676478492
Change-Id: I93a1c6d28f3cc7b768c219d999fc1c347c97c4ff
  • Loading branch information
tetromino authored and copybara-github committed Sep 19, 2024
1 parent 1c1dd49 commit d661d7d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,14 @@ static SelectorList concat(Object x, Object y) throws EvalException {
return of(Arrays.asList(x, y));
}

private static TokenKind binaryOpToken(Object value) {
return getNativeType(value).equals(Dict.class) ? TokenKind.PIPE : TokenKind.PLUS;
}

@Override
@Nullable
public SelectorList binaryOp(TokenKind op, Object that, boolean thisLeft) throws EvalException {
if (getNativeType(that).equals(Dict.class)) {
if (op == TokenKind.PIPE) {
return thisLeft ? concat(this, that) : concat(that, this);
}
} else if (op == TokenKind.PLUS) {
if (op == binaryOpToken(that)) {
return thisLeft ? concat(this, that) : concat(that, this);
}
return null;
Expand Down Expand Up @@ -206,7 +206,7 @@ public String toString() {

@Override
public void repr(Printer printer) {
printer.printList(elements, "", " + ", "");
printer.printList(elements, "", String.format(" %s ", binaryOpToken(this)), "");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,25 @@ public void testUnionIncompatibleType() throws Exception {
"{'a': 'a'} | select({'foo': ['FOO']})",
"Cannot combine incompatible types (dict, select of list)");
}

@Test
public void testRepr() throws Exception {
assertThat(eval("repr(select({'foo': ['FOO']})+['BAR'])"))
.isEqualTo("select({\"foo\": [\"FOO\"]}) + [\"BAR\"]");

assertThat(eval("repr(['FOO']+select({'bar': ['BAR']}))"))
.isEqualTo("[\"FOO\"] + select({\"bar\": [\"BAR\"]})");

assertThat(eval("repr(select({'foo': ['FOO']})+select({'bar': ['BAR']}))"))
.isEqualTo("select({\"foo\": [\"FOO\"]}) + select({\"bar\": [\"BAR\"]})");

assertThat(eval("repr(select({'foo': {'FOO': 123}})|{'BAR': 456})"))
.isEqualTo("select({\"foo\": {\"FOO\": 123}}) | {\"BAR\": 456}");

assertThat(eval("repr({'FOO': 123}|select({'bar': {'BAR': 456}}))"))
.isEqualTo("{\"FOO\": 123} | select({\"bar\": {\"BAR\": 456}})");

assertThat(eval("repr(select({'foo': {'FOO': 123}})|select({'bar': {'BAR': 456}}))"))
.isEqualTo("select({\"foo\": {\"FOO\": 123}}) | select({\"bar\": {\"BAR\": 456}})");
}
}

0 comments on commit d661d7d

Please sign in to comment.