How to use AST for both custom front-end action and clang static analysis

Viewed 388

I am working on a libTooling based project where I have written a custom frontend action class by referring this. Now I want to run clang static analysis in the same tool. Currently, I am running the tool again for clang static analysis (after modifying compiler options). But this will parse the files and create AST again.

I want to create AST once and use for custom frontend action and clang static analysis.

How can I achieve this? Is MultiplexConsumer is of any help here?

1 Answers

It seems that MultiplexConsumer is the way to go.

Here's what worked for me, in my frontend action class:

std::unique_ptr<ASTConsumer> CreateASTConsumer(
    CompilerInstance& compiler, StringRef inFile) override {

    std::unique_ptr<ASTConsumer> consumer1 =
        std::make_unique<MyConsumer1>(compiler);

    std::unique_ptr<ASTConsumer> consumer2 =
        std::make_unique<MyConsumer2>(compiler);

    std::vector<std::unique_ptr<ASTConsumer>> consumers;
    consumers.emplace_back(std::move(consumer1));
    consumers.emplace_back(std::move(consumer2));
    return std::make_unique<MultiplexConsumer>(std::move(consumers));
}

Note, though, that if consumer1 returns any errors, then consumer2 will not run. If consumer1 returns only warnings, or no diagnostics, then consumer2 will run.

Related