using clang’s libTooling to rewrite nested ternary expressions

The following ‘C’ source code containing a nested ternary statement fails to be rewritten correctly using libTooling’s clang::Rewriter with a RecursiveASTVisitor.

I cannot figure out why. I added diagnostic code to examine the edit buffer after rewriting at each stage, unfortunately rewriting the nested ternary causes the entire rewrite buffer to become corrupted.

Starting with the following C source file which contains a recursive ConditionalOperator:

void nestedTernaryDeclStmt() {
    int ii, jj, kk, ll, mm;
    int foo =  ii > jj  ? ( kk <= ll ) ? mm : 4123 : 5321 ;
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^ (outer ternary)
                          ^~~~~~~~~~~~~~~~~~~~~~~^        (nested ternary)
}

At the end of the first bool VisitConditionalOperator(clang::ConditionalOperator *CO) const callback, the contents of the file’s edit buffer is correctly rewritten as:

void nestedTernaryDeclStmt() {
    int ii, jj, kk, ll, mm;
    int foo =  'REPLACEMENT 0' ;
}

This is what I expected as the outermost ternary is completely rewritten. Then when the bool VisitConditionalOperator(clang::ConditionalOperator *CO) const is called for the second time containing the nested ternary expression ( kk <= ll ) ? mm : 4123, dumping the rewritten rewrite buffer has the following corrupted content.

void nestedTernaryDeclStmt() {
    int ii, jj, kk, ll, mm;'REPLACEMENT 1'MENT 0' ;
}

Instead of using the getSourceRange from the CO parameter, I adjusted this to span the range up to the end of the last token (a frequently asked question about clang range locations). I also tried many other combinations of type of tokened and non tokened character ranges but nothing I try seems to work.

Here is the problematic visitor:

// Experimental recursive visitor class.
class MyVisitor : public clang::RecursiveASTVisitor<MyVisitor> {
public:
    explicit MyVisitor(
        clang::ASTContext& rContext,
        clang::Rewriter& rRewriter)
        : mContext{rContext}
        , mRewriter{rRewriter}
    {}

#if 0
    // default behavior is to traverse the AST in pre-order (override to true to force post-order).
    // @JC note that since this uses CRTP pattern (i.e. class Derived : public Base<Derived>),
    // the method is not virtual & bypasses the need for a VTable - very clever!
    bool shouldTraversePostOrder() const {
        return false;
    }
#endif

    //! Visitor pattern callback for 'ConditionalOperator'.
    bool VisitConditionalOperator(clang::ConditionalOperator *CO) const {
        // This method is called for every 'ConditionalOperator' in the code.
        // You can examine 'CO' to extract information about it.
        const auto& SM = mContext.getSourceManager();
        const auto& LO = mContext.getLangOpts();
        const auto sourceRange = CO->getSourceRange();

        // Assume SM is a clang::SourceManager object and Range is a clang::SourceRange for the range
        const auto BLoc = sourceRange.getBegin();
        const auto ELoc = sourceRange.getEnd();

        // Adjust the end location to the end of the last token
        const auto AdjustedELoc = clang::Lexer::getLocForEndOfToken(
            ELoc, 0, SM, LO);

        // Create adjusted range that includes the length of the last token
        clang::SourceRange AdjustedRange(BLoc, AdjustedELoc);

        auto CSR1 = clang::CharSourceRange::getCharRange(BLoc, AdjustedELoc);
        //CSR1.setTokenRange(true);

        unsigned BLine = SM.getSpellingLineNumber(BLoc);
        unsigned BCol = SM.getSpellingColumnNumber(BLoc);
        unsigned ELine = SM.getSpellingLineNumber(ELoc);
        unsigned ECol = SM.getSpellingColumnNumber(ELoc);

        auto cond = gStmtToString(&mContext, CO->getCond());
        auto lhs = gStmtToString(&mContext, CO->getLHS());
        auto rhs = gStmtToString(&mContext, CO->getRHS());

        // Rewrite as follows:
        const auto probeText = std::format(
            "'REPLACEMENT {}'"
            , gProbeIndex++);

        mRewriter.ReplaceText(/*sourceRange*/CSR1, probeText);

        // Get the RewriteBuffer for the main file.
        std::string str;
        llvm::raw_string_ostream rso(str);
        clang::RewriteBuffer &RB = mRewriter.getEditBuffer(SM.getMainFileID());
        RB.write(rso);
        rso.flush();

        // returning false aborts the traversal
        return true;
    }

private:
    clang::ASTContext& mContext;
    clang::Rewriter& mRewriter;
};

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật