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

Danny Mösch via cfe-commits cfe-commits at lists.llvm.org
Sun Apr 21 23:34:02 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);
----------------
SimplyDanny wrote:

Does this need to check that the function's return type is a constant reference as well? For example, is
```c++
const S fn(const S &a) {
    return a;
}
```
without the reference return type okay? The documentation of this check says so:

> Detects return statements that return a constant reference parameter **as constant reference**.

As I understand the AUTOSAR rule, it's about pointers or references to automatic variables returned from a function. So

```c++
int *f(int i) { return &i; }
```

and

```c++
int *g() {
    int i = 1;
    return &i;
}
```

would be violations of the rule too.

I know that we are not allowed to cite the rules literally, but only checking constant reference parameters might be too restricted. Or are there other checks implementing the other cases already? If so, should they be extended instead of having a new separate check?

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


More information about the cfe-commits mailing list