[clang-tools-extra] [tidy] add new check bugprone-return-const-ref-from-parameter (PR #89497)

Congcong Cai via cfe-commits cfe-commits at lists.llvm.org
Mon Apr 22 03:40:49 PDT 2024


================
@@ -0,0 +1,34 @@
+//===--- ReturnConstRefFromParameterCheck.cpp - clang-tidy ----------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ReturnConstRefFromParameterCheck.h"
+#include "../utils/Matchers.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void ReturnConstRefFromParameterCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+      returnStmt(hasReturnValue(declRefExpr(to(parmVarDecl(hasType(
+                     hasCanonicalType(matchers::isReferenceToConst())))))))
+          .bind("ret"),
+      this);
----------------
HerrCai0907 wrote:

clang will create `CXXConstructExpr` for object and `ImplicitCastExpr` for builtin type. just like
```
`-FunctionDecl 0x13d8cf548 <line:3:1, col:36> col:9 fn 'const S (const S &)'
  |-ParmVarDecl 0x13d8cf450 <col:12, col:21> col:21 used a 'const S &'
  `-CompoundStmt 0x13d8ee1a0 <col:24, col:36>
    `-ReturnStmt 0x13d8ee190 <col:26, col:33>
      `-CXXConstructExpr 0x13d8ee160 <col:33> 'const S':'const S' 'void (const S &) noexcept'
        `-DeclRefExpr 0x13d8cf640 <col:33> 'const S':'const S' lvalue ParmVar 0x13d8cf450 'a' 'const S &'
```
and 
```
`-FunctionDecl 0x1410d9ac0 <line:3:1, col:40> col:11 fn 'const int (const int &)'
  |-ParmVarDecl 0x1410d99f0 <col:14, col:25> col:25 used a 'const int &'
  `-CompoundStmt 0x1410d9c00 <col:28, col:40>
    `-ReturnStmt 0x1410d9bf0 <col:30, col:37>
      `-ImplicitCastExpr 0x1410d9bd8 <col:37> 'int' <LValueToRValue>
        `-DeclRefExpr 0x1410d9bb8 <col:37> 'const int' lvalue ParmVar 0x1410d99f0 'a' 'const int &'
```


https://github.com/llvm/llvm-project/pull/89497


More information about the cfe-commits mailing list