How to clone or create AST stmt node clang?

I want to change AST with clang LibTooling. How can I clone an AST node or add a new one, for example. I would like to create BinaryOperatorwith ADD opcode

0
source share
2 answers

Creating new AST nodes is rather cumbersome in Clang, and this is not the recommended way to use libTooling. Rather, you should “read” the AST and release the code back, or code changes (rewriting, replacing, etc.).

See this article and other articles (and code samples) related to it for more information on the correct path for this.

+3
source

() clang AST , node, ASTContext, . . clang:: DeclRefExpr.

, , . , , . new/delete, ASTContext .

clang ASTContext , ( ASTContext).

, clang ASTContext:

#ifndef CLANG_ALLOCATOR_H
#define CLANG_ALLOCATOR_H

#include <clang/AST/ASTContext.h>

/// Allocator that relies on clang AST context for actual memory
/// allocation. Any class that wishes to allocated an AST node may
/// create an instance of this class for that purpose
class ClangAllocator
{
public:

    explicit ClangAllocator(clang::ASTContext& ast_context)
        : m_ast_context(ast_context)
    {
    }

    template<class ClassType, class ... Args>
    inline ClassType* Alloc(Args&& ... args)
    {
        return new (m_ast_context) ClassType(std::forward<Args&&>(args)...);
    }

private:

    clang::ASTContext& m_ast_context;
};

#endif /// CLANG_ALLOCATOR_H

AST, , , - TreeTransform Rebuild, .

AST node , - , std:: replace . :

/// immediate_parent is immediate parent of the old_stmt
std::replace(
    immediate_parent->child_begin()
    , immediate_parent->child_end()
    , old_stmt
    , new_stmt);
0

Source: https://habr.com/ru/post/1666268/


All Articles