与不同变量类型相比,用于变量的 Clang AST 匹配器
Clang AST matcher for variables compared to different variable types
我是clang-tidy的新手,以下是练习,所以我可以转向更复杂的匹配器和工具。
假设我们有
typedef int my_type;
void foo()
{
int x = 0;//this should be identified as need to be fixed
my_type z = 0;
if( x == z){
//match this case
}
}
我的目标是确定与"my_type"进行比较的变量,以便通过将其类型更改为my_type来修复其声明。
现在我正在尝试执行以下操作
auto my_type_decl = varDecl(hasType(asString("my_type")));
auto my_type_decl_exp= declRefExpr(to(my_type_decl));
auto binop = binaryOperator(has(implicitCastExpr(has(my_type_decl_exp))));
auto other_decl_exp = declRefExpr(hasAncestor(binop), unless(to(my_type_decl)));
//get ancestor functionDecl
//get descendant varDecls that match the other_decl_exp
这里的问题是我忽略了上下文。 做这样的事情的正确方法是什么?
您可以将节点匹配器绑定到名称,然后从匹配结果中检索这些节点。
例如:
// Match binary operators
binaryOperator(
// that are equality comparisons,
hasOperatorName("=="),
// where one side refers to a variable
hasEitherOperand(ignoringImpCasts(declRefExpr(to(varDecl(
// whose type is a typedef or type alias
hasType(typedefNameDecl(
// named "::my_type"
hasName("::my_type"),
// that aliases any type, which is bound to the name "aliased",
hasType(type().bind("aliased"))))))))),
// and where one side refers to a variable
hasEitherOperand(ignoringImpCasts(declRefExpr(to(varDecl(
// whose type is the same as the type bound to "aliased",
// which is bound to the name "declToChange".
hasType(type(equalsBoundNode("aliased")))).bind("declToChange"))))));
然后:
const auto *declToChange = result.Nodes.getNodeAs<VarDecl>("declToChange");
请注意,这与相等比较匹配,因此declToChange
可能会在多个匹配项中指向相同的VarDecl
。
在下面的示例中,此匹配器将生成两个declToChange
绑定到x
的匹配项,而没有一个declToChange
绑定到y
的匹配项:
typedef int my_type;
void foo() {
int x = 0;
int y = 0;
my_type z = 0;
if (x == z) {
}
if (z == x) {
}
}
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- Visual C++: MSVC vs. GCC+CLANG: 处理 lambda 捕获类成员变量,正确的方法是什么?
- 使用 clang++ 和 g++ 在C++中初始化变量
- 使用变量模板的递归计算 - gcc 与 clang
- 与不同变量类型相比,用于变量的 Clang AST 匹配器
- Clang++ 6.0 内存清理器未报告返回值指示条件分支的函数中的未初始化局部变量
- C :动态分配的变量未在clang中删除
- 如果Constexpr - clang vs.GCC,则非constexpr变量
- GCC和Clang不警告未使用的异常变量
- Clang 在编译时不会计算非 constexpr 变量的 constexpr 函数的值
- gcc 和 clang 中 constexpr 静态成员变量的链接器错误
- Clang AST 匹配器:如何在 lambda 捕获的变量上进行匹配
- 未定义的引用指针的变量模板在clang中功能,而不是GCC
- constexpr 表达式和变量生存期,G++ 和 Clang 不同意的一个例子
- "constexpr"变量"used in its own initializer":Clang与GCC
- clang vs gcc CRTP:constexpr 变量不能有非文字类型
- 声明一个在clang中的非偏见的变量
- 单行多变量声明的clang ast访问者
- 初始化全局变量时,Clang-4.0会生成冗余方法
- CLang 3.5 LibTooling:获取CLang::VarDecl中变量的文件名