915просмотров
16 марта 2025 г.
Score: 1.0K
Это мэтч Следующим шагом в задании было написание того же на ast_matchers. Для упрощения своей жизни я предварительно проверил работу в clang-query и получил запрос:
match namedDecl(hasName("fisting")) Примерно то же самое делает и MatchFinder
int main(int argc, const char **argv) { // ... command line processing ... clang::ast_matchers::DeclarationMatcher fistingMatcher = clang::ast_matchers::namedDecl(clang::ast_matchers::hasName("fisting")) .bind("fistingId"); FistingPrinter printer; clang::ast_matchers::MatchFinder finder; finder.addMatcher(fistingMatcher, &printer); return tool.run(clang::tooling::newFrontendActionFactory(&finder).get()) ? EXIT_FAILURE : EXIT_SUCCESS;
}
При этом в случае совпадения вызывается определенный пользователем callback для дальнейшей более сложной для общей реализации обработки:
class FistingPrinter final : public clang::ast_matchers::MatchFinder::MatchCallback { void run(const clang::ast_matchers::MatchFinder::MatchResult &result) override { clang::ASTContext context = result.Context; const clang::NamedDecl decl = result.Nodes.getNodeAs<clang::NamedDecl>("fistingId"); if (decl == nullptr) return; llvm::outs() << "hint: fisting detected on " << context->getFullLoc((decl->getBeginLoc())).getLineNumber() << ":" << context->getFullLoc((decl->getBeginLoc())).getColumnNumber() << "\n"; }
}; #compiler #llvm