Issue |
138735
|
Summary |
[clang-tidy] Check request: modernize-use-structured-binding
|
Labels |
|
Assignees |
|
Reporter |
denzor200
|
C++17 suggests us structured binding feature as a convenient way to decompose composite objects into individual variables.
Needs a check that will find creations of a tuple-like which was assigned from a returned value. The check will show warning to change it to use structured binding.
Also the check will provide fix-it in the case when it's possible to deduce names for future decomposed variables.
BEFORE:
```
const auto results = mapping.try_emplace("hello!"); // WARNING AND FIX-IT
const iterator& it = results.first;
const bool succeed = results.second;
```
AFTER:
```
const auto [it, succeed] = mapping.try_emplace("hello!");
```
The check should also cover `for` statements:
BEFORE:
```
for (const auto& node : mapping) { // WARNING AND FIX-IT
const std::string& key = node.first;
const A& value = node.second;
// ...
}
```
AFTER:
```
for (const auto& [key, value] : mapping) {
// ...
}
```
The check must respect original result's cv-ref modifiers.
BEFORE:
```
const auto& results = mapping.try_emplace("hello!"); // WARNING AND FIX-IT
const iterator& it = results.first;
bool succeed = results.second;
```
AFTER:
```
const auto& [it, succeed] = mapping.try_emplace("hello!");
```
Keep in mind that the check will not provide fix-it in the case when the changed code will not be compiled - just a warning would be enough:
BEFORE:
```
const auto results = mapping.try_emplace("hello!"); // WARNING
const iterator& it = results.first;
bool succeed = results.second;
succeed = true;
```
INCORRECT AFTER:
```
const auto [it, succeed] = mapping.try_emplace("hello!");
succeed = true; // BAD - assignment of read-only variable 'succeed'
```
Also the check will not provide fix-it in the case when it's impossible to deduce names - just a warning would be enough:
```
const auto results = mapping.try_emplace("hello!"); // WARNING
if (results.second) {
handle_inserted(results.first);
}
// no name deduced
```
In the case when it's impossible to use structured-binding no warning must be provided:
```
const auto results = mapping.try_emplace("hello!");
handle_inserted(results);
```
Reassignment of potentially decomposed variables must be considered as impossibility to use structured binding - no warning, this is a job for [modernize-use-std-tie-to-decompose-result](https://github.com/llvm/llvm-project/issues/138732).
BEFORE:
```
const auto pos1 = get_position(); // WARNING AND FIX-IT
float x = pos.1first;
float y = pos1.second;
// ...
const auto pos2 = get_position2();
x = pos2.first;
y = pos2.second;
```
AFTER:
```
auto [x, y] = get_position();
// ...
const auto pos2 = get_position2();
x = pos2.first;
y = pos2.second;
```
_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs