[clang-tools-extra] [clang-tidy] Add a new check 'modernize-use-string-view' (PR #172170)

Baranov Victor via cfe-commits cfe-commits at lists.llvm.org
Tue Dec 30 10:39:27 PST 2025


================
@@ -0,0 +1,119 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "UseStringViewCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTDiagnostic.h"
+#include "clang/AST/Stmt.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/Diagnostic.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+static StringRef toStringViewTypeStr(StringRef Type) {
+  if (Type.contains("wchar_t"))
+    return "std::wstring_view";
+  if (Type.contains("char8_t"))
+    return "std::u8string_view";
+  if (Type.contains("char16_t"))
+    return "std::u16string_view";
+  if (Type.contains("char32_t"))
+    return "std::u32string_view";
+  return "std::string_view";
+}
+
+static auto getStringTypeMatcher(StringRef CharType) {
+  return hasCanonicalType(hasDeclaration(cxxRecordDecl(hasName(CharType))));
+}
+
+static void fixReturns(Stmt *Stmt, DiagnosticBuilder &Diag) {
----------------
vbvictor wrote:

This will not work in general case because you need to traverse recursively into sub-statements. consider example
```cpp
void foo() {
 if (1) {
   return string{} // is not a child of body-stmt
 }
```
you need logic similar to `allDeclRef` in https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clang-tidy/utils/DeclRefExprUtils.h

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


More information about the cfe-commits mailing list