Skip to content

[Clang Libtooling] Unexpected Word Splitting #108821

Open
@bajinsheng

Description

@bajinsheng

I wrote a code based on libtooling to add a simple printf in each IF statement as follows:

  bool VisitIfStmt(IfStmt *If) {
    FullSourceLoc FullLocation = Context->getFullLoc(If->getBeginLoc());
    if (FullLocation.isValid()) {
      if (Stmt *Then = If->getThen()) {
        SourceLocation StartLoc = Then->getBeginLoc();
        SourceLocation EndLoc = Then->getEndLoc().getLocWithOffset(1);
        IfCounter++;
        std::string NewIfStmt = "";
        // Check if the body is a compound statement
        if (isa<CompoundStmt>(Then)) {
          NewIfStmt += "  printf(\"Executing code block " + std::to_string(IfCounter) + "\\n\");\n";
          NewIfStmt += TheRewriter.getRewrittenText(SourceRange(StartLoc, EndLoc));
        } else {
          NewIfStmt += "{\n";
          NewIfStmt += "  printf(\"Executing code block " + std::to_string(IfCounter) + "\\n\");\n";
          NewIfStmt += TheRewriter.getRewrittenText(SourceRange(StartLoc, EndLoc));
          NewIfStmt += "\n}";
        }
        NewIfStmt += "\n}";
        TheRewriter.ReplaceText(SourceRange(StartLoc, EndLoc), NewIfStmt);
      }
    }
    return true;
  }

However, for this target code:

int main (){
    int a = 1;
    if (a == 1)
        if (a > 0) 
            return true;
}

It will be changed into
image

The return is incorrectly split.

Full test case, please see here: test.txt

LLVM version: 36adf8e

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions