在编写 clang-tidy 检查和修复时如何获取 ref 限定符的源位置?

问题描述 投票:0回答:1

我想编写一个

clang-tidy
检查,为某些 C++ 方法添加左值引用限定符。我已经设法检测到要修复的方法,但我很难找到正确的源位置来添加限定符。

我的尝试是这个:

void MyCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXMethodDecl>("x");

  if (RQ_None != MatchedDecl->getRefQualifier()) {
    return;
  }

  diag(MatchedDecl->getBeginLoc(),
       "Member Function %0 should have lvalue ref qualifier.")
      << MatchedDecl
      << FixItHint::CreateInsertion(
             MatchedDecl->getTypeSpecEndLoc().getLocWithOffset(1), " &");
  diag(MatchedDecl->getTypeSpecEndLoc().getLocWithOffset(1),
       "Add ref-qualifier for lvalues.", DiagnosticIDs::Note);
}

如果已找到的 C++ 方法在方法名称之前指定了返回值,则效果很好:

Test& modify1();

正在这样修复:

Test& modify1() &;

但是如果该方法具有尾随返回类型,则我的插入源位置不正确。

auto modify2() -> Test&

正在这样修复:

auto modify2() -> Test& &;

有语法错误。

而不是

getTypeSpecEndLoc().getLocWithOffset(1)
我应该使用需要 ref 限定符的源代码位置。如何从 AST 匹配器中找出位置?

c++ clang-tidy clang-ast-matchers
1个回答
0
投票

如第 dcl.fct 节所述 C++ 标准中,ref 限定符位于 cv 限定符之后:

D1(参数声明子句)cv-限定符-seqopt ref-限定符opt noexcept-说明符opt 属性说明符-seqopt 尾随返回类型opt

Clang 不记录精确标识的源位置 位置“cv 限定符之后”,即 ref 限定符所在的位置。 它记录的最接近的是右括号的位置 参数列表的末尾。 这可以从

FunctionDecl
通过拨打
getFunctionTypeLoc()
获取
FunctionTypeLoc
, 并在该对象上调用
getRParenLoc()

从那里,您必须检查该位置的令牌以检查 并跳过

const
volatile
。 看问题 从 clang AST 节点获取 token 序列 有关如何检索和检查令牌的信息。

© www.soinside.com 2019 - 2024. All rights reserved.