llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
29.09k stars 12k forks source link

new check: use C++17 if-init, switch-init #38471

Open kirillbobyrev opened 6 years ago

kirillbobyrev commented 6 years ago
Bugzilla Link 39123
Version unspecified
OS All
CC @JonasToth

Extended Description

C++17 offers a handful of great features, one of which allows variable initializations within if and switch blocks:

Patterns like

T Value = maybeReturnValue(); if (Value.hasValue()) // Value is never used again doSomething();

seem to be pretty common (consider llvm::Optional, std::optional, set/map::find(...) and similar operations) and it would be great to detect these (at least the easiest cases) to enforce better readability via C++17 language features.

Examples from my own code in Dex.cpp:

std::vector<std::unique_ptr> TrigramIterators; for (const auto &Trigram : TrigramTokens) { const auto It = InvertedIndex.find(Trigram); if (It != InvertedIndex.end()) TrigramIterators.push_back(It->second.iterator()); }

...

std::vector<std::unique_ptr> ScopeIterators; for (const auto &Scope : Req.Scopes) { const auto It = InvertedIndex.find(Token(Token::Kind::Scope, Scope)); if (It != InvertedIndex.end()) ScopeIterators.push_back(It->second.iterator()); }

There's a nice blog post featuring this new language concept: https://skebanga.github.io/if-with-initializer/

JonasToth commented 6 years ago

This could/should be done with a check initialize late that tries to reduce the scope of variables as much as possible.

The 'readability-isolate-decl' could serve as a utility function to split up declarations that can be moved to a later point

llvmbot commented 2 years ago

@llvm/issue-subscribers-c-17