mgartmann updated this revision to Diff 334632.
mgartmann marked an inline comment as done.
mgartmann added a comment.

Add isInStdNamespace to matcher so that only global objects in namespace `std` 
are matched and add corresponding tests.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D99646/new/

https://reviews.llvm.org/D99646

Files:
  clang-tools-extra/clang-tidy/misc/CMakeLists.txt
  clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
  clang-tools-extra/clang-tidy/misc/StdStreamObjectsOutsideMainCheck.cpp
  clang-tools-extra/clang-tidy/misc/StdStreamObjectsOutsideMainCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  
clang-tools-extra/docs/clang-tidy/checks/misc-std-stream-objects-outside-main.rst
  
clang-tools-extra/test/clang-tidy/checkers/misc-std-stream-objects-outside-main.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/misc-std-stream-objects-outside-main.cpp
===================================================================
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/misc-std-stream-objects-outside-main.cpp
@@ -0,0 +1,64 @@
+// RUN: %check_clang_tidy %s misc-std-stream-objects-outside-main %t
+
+namespace std {
+struct string {
+  string(const char *);
+  ~string();
+};
+
+struct Ostream {
+  Ostream &operator<<(string Message);
+};
+
+struct Istream {
+  Istream &operator>>(string Message);
+};
+
+Ostream cout{}, wcout{}, cerr{}, wcerr{};
+Istream cin{}, wcin{};
+
+} // namespace std
+
+namespace arbitrary_namespace {
+std::Ostream cout{};
+std::Istream cin{};
+} // namespace arbitrary_namespace
+
+void problematic() {
+  // CHECK-MESSAGES: :[[@LINE+1]]:8: warning: predefined standard stream objects should not be used outside the main function [misc-std-stream-objects-outside-main]
+  std::cout << "This should trigger the check";
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:8: warning: predefined standard stream objects should not be used outside the main function [misc-std-stream-objects-outside-main]
+  std::wcout << "This should trigger the check";
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:8: warning: predefined standard stream objects should not be used outside the main function [misc-std-stream-objects-outside-main]
+  std::cerr << "This should trigger the check";
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:8: warning: predefined standard stream objects should not be used outside the main function [misc-std-stream-objects-outside-main]
+  std::wcerr << "This should trigger the check";
+
+  arbitrary_namespace::cout << "This should not trigger the check"; // OK
+
+  std::string Foo{"bar"};
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:8: warning: predefined standard stream objects should not be used outside the main function [misc-std-stream-objects-outside-main]
+  std::cin >> Foo;
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:8: warning: predefined standard stream objects should not be used outside the main function [misc-std-stream-objects-outside-main]
+  std::wcin >> Foo;
+
+  arbitrary_namespace::cin >> Foo; // OK
+}
+
+int main() {
+  std::cout << "This should not trigger the check";                 // OK
+  std::wcout << "This should not trigger the check";                // OK
+  std::cerr << "This should not trigger the check";                 // OK
+  std::wcerr << "This should not trigger the check";                // OK
+  arbitrary_namespace::cout << "This should not trigger the check"; // OK
+
+  std::string Foo{"bar"};
+  std::cin >> Foo;                 // OK
+  std::wcin >> Foo;                // OK
+  arbitrary_namespace::cin >> Foo; // OK
+}
Index: clang-tools-extra/docs/clang-tidy/checks/misc-std-stream-objects-outside-main.rst
===================================================================
--- /dev/null
+++ clang-tools-extra/docs/clang-tidy/checks/misc-std-stream-objects-outside-main.rst
@@ -0,0 +1,45 @@
+.. title:: clang-tidy - misc-std-stream-objects-outside-main
+
+misc-std-stream-objects-outside-main
+=============
+
+Diagnoses if a predefined standard stream object (``cin``, ``wcin``,
+``cout``, ``wcout``, ``cerr`` or ``wcerr``) is used outside the ``main`` function.
+
+For instance, in the following code, the use of ``std::cout`` outside of ``main()`` would get
+flagged whereas the use of ``std::cout`` inside ``main()`` is not flagged:
+
+.. code-block:: c++
+
+  #include <iostream>
+
+  void some_function() {
+    std::cout << "This triggers the check.";
+         ~~~~
+  }
+
+  int main() {
+    std::cout << "This does not trigger the check.";
+  }
+
+Since the predefined standard stream objects are global objects, their use outside of ``main()`` worsens a
+program's testability and is thus discouraged. Instead, those objects should only be used inside ``main()``.
+They can then be passed as arguments to other functions like so:
+
+.. code-block:: c++
+
+  #include <iostream>
+
+  void some_function(std::istream & in, std::ostream & out) {
+    out << "This does not trigger the check.";
+
+    int i{0};
+    in >> i;
+  }
+
+  int main() {
+    some_function(std::cin, std::cout);
+  }
+
+In contrast to using ``std::cin`` and ``std::cout`` directly, in the above example, it is possible to inject 
+mocked stream objects into ``some_function()`` during testing.
Index: clang-tools-extra/docs/clang-tidy/checks/list.rst
===================================================================
--- clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -210,6 +210,7 @@
    `misc-non-private-member-variables-in-classes <misc-non-private-member-variables-in-classes.html>`_,
    `misc-redundant-expression <misc-redundant-expression.html>`_, "Yes"
    `misc-static-assert <misc-static-assert.html>`_, "Yes"
+   `misc-std-stream-objects-outside-main <misc-std-stream-objects-outside-main.html>`_, "Yes"
    `misc-throw-by-value-catch-by-reference <misc-throw-by-value-catch-by-reference.html>`_,
    `misc-unconventional-assign-operator <misc-unconventional-assign-operator.html>`_,
    `misc-uniqueptr-reset-release <misc-uniqueptr-reset-release.html>`_, "Yes"
Index: clang-tools-extra/docs/ReleaseNotes.rst
===================================================================
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -95,6 +95,12 @@
   Finds member initializations in the constructor body which can be placed into
   the initialization list instead.
 
+- New :doc:`misc-std-stream-objects-outside-main
+  <clang-tidy/checks/misc-std-stream-objects-outside-main>` check.
+
+  Diagnoses if a predefined standard stream object (``cin``, ``wcin``,
+  ``cout``, ``wcout``, ``cerr`` or ``wcerr``) is used outside the ``main`` function.
+
 New check aliases
 ^^^^^^^^^^^^^^^^^
 
Index: clang-tools-extra/clang-tidy/misc/StdStreamObjectsOutsideMainCheck.h
===================================================================
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/StdStreamObjectsOutsideMainCheck.h
@@ -0,0 +1,40 @@
+//===--- StdStreamObjectsOutsideMainCheck.h - clang-tidy --------*- C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_STDSTREAMOBJECTSOUTSIDEMAINCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_STDSTREAMOBJECTSOUTSIDEMAINCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+namespace misc {
+
+/// Diagnoses if a predefined standard stream object (`cin`, `wcin`,
+/// `cout`, `wcout`, `cerr` or `wcerr`) is used outside the `main` function.
+///
+/// For the user-facing documentation and examples see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/misc-std-stream-objects-outside-main.html
+class StdStreamObjectsOutsideMainCheck : public ClangTidyCheck {
+public:
+  StdStreamObjectsOutsideMainCheck(StringRef Name, ClangTidyContext *Context)
+      : ClangTidyCheck(Name, Context) {}
+
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+    return LangOpts.CPlusPlus;
+  }
+
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+};
+
+} // namespace misc
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_STDSTREAMOBJECTSOUTSIDEMAINCHECK_H
Index: clang-tools-extra/clang-tidy/misc/StdStreamObjectsOutsideMainCheck.cpp
===================================================================
--- /dev/null
+++ clang-tools-extra/clang-tidy/misc/StdStreamObjectsOutsideMainCheck.cpp
@@ -0,0 +1,40 @@
+//===--- StdStreamObjectsOutsideMainCheck.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 "StdStreamObjectsOutsideMainCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace misc {
+
+void StdStreamObjectsOutsideMainCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+      declRefExpr(to(namedDecl(hasAnyName("cin", "wcin", "cout", "wcout",
+                                          "cerr", "wcerr"),
+                               isInStdNamespace())),
+                  unless(forFunction(isMain())))
+          .bind("match"),
+      this);
+}
+
+void StdStreamObjectsOutsideMainCheck::check(
+    const MatchFinder::MatchResult &Result) {
+  const auto *MatchedDecl = Result.Nodes.getNodeAs<DeclRefExpr>("match");
+
+  diag(MatchedDecl->getLocation(), "predefined standard stream objects should "
+                                   "not be used outside the main function");
+}
+
+} // namespace misc
+} // namespace tidy
+} // namespace clang
Index: clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
===================================================================
--- clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
+++ clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp
@@ -17,6 +17,7 @@
 #include "NonPrivateMemberVariablesInClassesCheck.h"
 #include "RedundantExpressionCheck.h"
 #include "StaticAssertCheck.h"
+#include "StdStreamObjectsOutsideMainCheck.h"
 #include "ThrowByValueCatchByReferenceCheck.h"
 #include "UnconventionalAssignOperatorCheck.h"
 #include "UniqueptrResetReleaseCheck.h"
@@ -44,6 +45,8 @@
     CheckFactories.registerCheck<RedundantExpressionCheck>(
         "misc-redundant-expression");
     CheckFactories.registerCheck<StaticAssertCheck>("misc-static-assert");
+    CheckFactories.registerCheck<StdStreamObjectsOutsideMainCheck>(
+        "misc-std-stream-objects-outside-main");
     CheckFactories.registerCheck<ThrowByValueCatchByReferenceCheck>(
         "misc-throw-by-value-catch-by-reference");
     CheckFactories.registerCheck<UnconventionalAssignOperatorCheck>(
Index: clang-tools-extra/clang-tidy/misc/CMakeLists.txt
===================================================================
--- clang-tools-extra/clang-tidy/misc/CMakeLists.txt
+++ clang-tools-extra/clang-tidy/misc/CMakeLists.txt
@@ -13,6 +13,7 @@
   NonPrivateMemberVariablesInClassesCheck.cpp
   RedundantExpressionCheck.cpp
   StaticAssertCheck.cpp
+  StdStreamObjectsOutsideMainCheck.cpp
   ThrowByValueCatchByReferenceCheck.cpp
   UnconventionalAssignOperatorCheck.cpp
   UniqueptrResetReleaseCheck.cpp
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to