Skip to content

Commit ba93722

Browse files
authored
[ggj] fix(ast): Prevent post-increment ops on declared variables (#712)
* chore(engx): Remove obsolete TODOs in codegen src * chore(build, engx): Check license only on src/ files in pre-commit * fix(ast): Prevent post-increment ops on declared variables
1 parent 69cd9f8 commit ba93722

2 files changed

Lines changed: 20 additions & 6 deletions

File tree

src/main/java/com/google/api/generator/engine/ast/UnaryOperationExpr.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,15 +73,18 @@ private UnaryOperationExpr build() {
7373
TypeNode exprType = unaryOperationExpr.expr().type();
7474
OperatorKind operator = unaryOperationExpr.operatorKind();
7575

76-
// TODO: (summerji) Add Decl Check for variable.
7776
// Add final keyword checking for post/prefix ++, -- when needed.
7877
if (operator.equals(OperatorKind.UNARY_POST_INCREMENT)
7978
&& unaryOperationExpr.expr() instanceof VariableExpr) {
79+
VariableExpr varExpr = (VariableExpr) unaryOperationExpr.expr();
8080
Preconditions.checkState(
81-
!((VariableExpr) unaryOperationExpr.expr()).isFinal(),
81+
!varExpr.isFinal(),
82+
String.format("Cannot increment the final variable '%s'.", varExpr.variable().name()));
83+
84+
Preconditions.checkState(
85+
!varExpr.isDecl(),
8286
String.format(
83-
"Cannot assign a value to final variable '%s'.",
84-
((VariableExpr) unaryOperationExpr.expr()).variable().name()));
87+
"Cannot increment the declaration of variable %s", varExpr.variable().name()));
8588
}
8689

8790
final String errorMsg =

src/test/java/com/google/api/generator/engine/ast/UnaryOperationExprTest.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,19 @@ public void invalidPostIncrement_referenceType() {
9595

9696
@Test
9797
public void invalidPostIncrement_finalVariable() {
98-
Variable var = Variable.builder().setName("i").setType(TypeNode.INT).build();
99-
VariableExpr variableExpr = VariableExpr.builder().setIsFinal(true).setVariable(var).build();
98+
Variable variable = Variable.builder().setName("i").setType(TypeNode.INT).build();
99+
VariableExpr variableExpr =
100+
VariableExpr.builder().setIsFinal(true).setVariable(variable).build();
101+
assertThrows(
102+
IllegalStateException.class,
103+
() -> UnaryOperationExpr.postfixIncrementWithExpr(variableExpr));
104+
}
105+
106+
@Test
107+
public void invalidPostIncrement_declaredVariable() {
108+
Variable variable = Variable.builder().setName("i").setType(TypeNode.INT).build();
109+
VariableExpr variableExpr =
110+
VariableExpr.builder().setIsDecl(true).setVariable(variable).build();
100111
assertThrows(
101112
IllegalStateException.class,
102113
() -> UnaryOperationExpr.postfixIncrementWithExpr(variableExpr));

0 commit comments

Comments
 (0)