Skip to content

Commit

Permalink
Remove side-effect free expressions from MultiExpressions, if not the…
Browse files Browse the repository at this point in the history
… last

All but the last expression are non-observable, so if they are side-effect free
they can safely be removed.

PiperOrigin-RevId: 718431223
  • Loading branch information
kevinoconnor7 authored and copybara-github committed Jan 22, 2025
1 parent 1bf4ca4 commit 9b1df00
Showing 1 changed file with 12 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,8 @@ public boolean shouldProcessMethod(Method method) {
@Override
public Statement rewriteExpressionStatement(ExpressionStatement statement) {
if (statement.getExpression() instanceof MultiExpression) {
// Since we're looking at MultiExpressions that are the primary expression of an
// ExpressionStatement, we know that the return value isn't used.
// That makes it safe to remove any subexpressions that don't have side effects.
List<Expression> expressions =
((MultiExpression) statement.getExpression())
.getExpressions().stream()
.filter(Expression::hasSideEffects)
.collect(toImmutableList());
((MultiExpression) statement.getExpression()).getExpressions();

if (expressions.isEmpty()) {
// No expressions with side effects in this top level multexpression, remove completely.
Expand Down Expand Up @@ -101,13 +95,23 @@ public Statement rewriteExpressionStatement(ExpressionStatement statement) {
@Override
public Expression rewriteMultiExpression(MultiExpression multiExpression) {
List<Expression> flattenedExpressions = new ArrayList<>();
for (Expression expression : multiExpression.getExpressions()) {
for (int i = 0; i < multiExpression.getExpressions().size(); i++) {
Expression expression = multiExpression.getExpressions().get(i);

// Any side-effect free expression can be removed as it's not observable, expect for the
// last expression.
boolean isLastExpression = i == multiExpression.getExpressions().size() - 1;
if (!isLastExpression && !expression.hasSideEffects()) {
continue;
}

if (expression instanceof MultiExpression) {
flattenedExpressions.addAll(((MultiExpression) expression).getExpressions());
} else {
flattenedExpressions.add(expression);
}
}

return MultiExpression.newBuilder().setExpressions(flattenedExpressions).build();
}
}
Expand Down

0 comments on commit 9b1df00

Please sign in to comment.