Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Non-Semantic rule can break semantic rules #91

Open
alefhar opened this issue Dec 8, 2019 · 0 comments
Open

Non-Semantic rule can break semantic rules #91

alefhar opened this issue Dec 8, 2019 · 0 comments

Comments

@alefhar
Copy link

alefhar commented Dec 8, 2019

Applying a non-semantic rule before a semantic rule can break that semantic rule. For the source

public class Main {

  public int get() {
    int a = 1, b = 2;
    if (a == 1) {
      if (b == 2) {
        int c = b + a;
        return c;
      }
    }
    return -1;
  }
}

the transformation chain

<walkmod>
    <chain name="default">
        <transformation type="sonar:CollapsibleIfStatements"/>
        <transformation type="sonar:RemoveUselessVariables"/>
    </chain>
</walkmod>

results in the source code

public class Main {

  public int get() {
    int a = 1, b = 2;
    if ((a == 1) && (b == 2)) {
      return c;
    }
    return -1;
  }
}

The declaration of the variable c was removed, the transformation causes compilation errors. Changing the order of the applied rules yields the correct results.
I debugged the problem and the rule RemoveUselessVariables does not find any usages for the variable c. I then had a look at the rule CollapsibleIfStatements, where the then-block of the inner if is cloned and set as then-block of the parent-if:

if (stmt instanceof BlockStmt) {
  BlockStmt block = (BlockStmt) stmt;
  List<Statement> stmts = block.getStmts();
  if (stmts.size() == 1) {
    parentIf.setThenStmt(n.getThenStmt().clone());
    parentIf.setCondition(condition);
  }
}

In clone() the child statements and expressions are cloned as well. When the VariableDeclaration for c is cloned only the variable name and the definition are taken over; the usages however are not cloned (this seems to be the case for all sibling classes). The then-block then contains statements with erased semantic analysis. The block seems to get passed to the next rules which then lacks the required information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant