Skip to content
On this page

来源: 2020 LLVM Developers’ Meeting: “Using Clang-tidy for Customized Checkers and Large Scale Source...” - YouTube

Austin LLVM Meetup

cpp
binaryOperator(hasOperatorName("/"), 
hasRHS(integerLiteral(equals(0)).bind(KEY_NODE)));

image-20230414191046966

Clang-tidy

  • Now with this perspective, shifting focus to clang-tidy
  • A Clang based C++ Linting tool framework
  • Full access to the AST and preprocessor
  • Clang-tidy is extensible – custom checks are possible
  • More than 200 existing checks
    • Readability, efficiency, correctness, modernization
    • Highly configurable
    • Can automatically fix the code in many place

usage

  • Dump AST : clang –cc1 –ast-dump init.cpp
  • clang-tidy –list-checks ▪ clang-tidy –list-checks –checks=*
  • clang-tidy --checks=-*,cppcoreguidelines-init-variables init.cpp 禁用所有的规则,只启用cppcoreguidelines-init-variables
  • clang-tidy --checks=-,cppcoreguidelines-init-variables --fix init.cpp

如何添加check

  1. ./add_new_check.py misc change-malloc

  2. rubuild

  3. clang-tidy --list-checks –checks=* | grep change

手册:AST Matcher Reference (llvm.org)

如何手工测试matcher

clang-query test.cpp --

使用体验

labelStmt指的是紧跟的那一条语句

EXPECT_FALSE(
    matches("void f() { while (1) { bar: 1+2;break; foo: return; } }",
            traverse(TK_AsIs, labelStmt(hasSubstatement(breakStmt())))));