[PATCH] D99646: [clang-tidy] misc-std-stream-objects-outside-main: a new check

Marco Gartmann via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed Mar 31 03:09:12 PDT 2021


mgartmann created this revision.
mgartmann added reviewers: aaron.ballman, njames93, alexfh.
mgartmann added a project: clang-tools-extra.
Herald added subscribers: xazax.hun, mgorny.
mgartmann requested review of this revision.

**Problem Description**

The `iostream` header file defines multiple global objects like `std:cin`, `std::cout`, etc.

The pitfall of using these global objects outside of the `main` function is that it negatively affects the code's testability. They cannot be replaced with a mocked input stream during testing. Therefore,  `std::cin`, `std::cout` etc. should only be used inside the main function. If other functions need an input or an output stream, one is encouraged to use the `std::istream` and `std::ostream` interfaces and to receive the stream object files as function parameters. 
Thus, during testing, mocked stream objects can be handed to the function.

**What this Check Does**

The goal of this check is to find any uses of predefined standard stream objects (i.e., `cout, wcout, cerr, wcerr, cin, wcin`) and to check whether they are used inside the `main` function or not. If any uses are found outside the `main` function, they get flagged.

The use of `clog` and `wclog` does not get flagged by this check. The rationale for this is that code with logging functionality rarely needs to be tested.

**Context**

The idea for this check is adopted from the checks implemented in Cevelop IDE <https://www.cevelop.com/>.

This contribution is part of a project which aims to port Cevelop's built-in checks to other IDEs.

We are happy to receive any suggestions for improvement.


Repository:
  rG LLVM Github Monorepo

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

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D99646.334382.patch
Type: text/x-patch
Size: 10982 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20210331/f78a975a/attachment-0001.bin>


More information about the cfe-commits mailing list