llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

False report modernize-return-braced-init-list with std::string and incorrect fix is applied

Open jackua22 opened this issue 2 years ago • 3 comments

The issue is reproducible with clang 17 and 18. This file

#include <string>
std::string space(size_t n) {
    return std::string(n, ' ');
}

generates a warning warning: avoid repeating the return type from the declaration; use a braced initializer list instead [modernize-return-braced-init-list] And with auto-fix, tidy modifies it with the following diff

<     return std::string(n, ' ');
---
>     return {n, ' '};

Then the compilation fails: error: non-constant-expression cannot be narrowed from type 'size_t' (aka 'unsigned long') to 'char' in initializer list [-Wc++11-narrowing]

To reproduce: clang-tidy '--checks=modernize-return-braced-init-list' --fix str.cpp -- -std=c++17 -stdlib=libc++

jackua22 avatar Apr 02 '24 01:04 jackua22

@llvm/issue-subscribers-clang-tidy

Author: None (jackua22)

The issue is reproducible with clang 17 and 18. This file ``` #include <string> std::string space(size_t n) { return std::string(n, ' '); } ``` generates a warning `warning: avoid repeating the return type from the declaration; use a braced initializer list instead [modernize-return-braced-init-list]` And with auto-fix, tidy modifies it with the following diff ``` < return std::string(n, ' '); --- > return {n, ' '}; ``` Then the compilation fails: `error: non-constant-expression cannot be narrowed from type 'size_t' (aka 'unsigned long') to 'char' in initializer list [-Wc++11-narrowing]`

To reproduce: clang-tidy '--checks=modernize-return-braced-init-list' --fix str.cpp -- -std=c++17 -stdlib=libc++

llvmbot avatar Apr 02 '24 01:04 llvmbot

Please assign it to me.

divyaxdv avatar Apr 02 '24 02:04 divyaxdv

Furthermore, fixing the compilation error according to the suggestion introduces a bug:

<source>:3:13: error: non-constant-expression cannot be narrowed from type 'size_t' (aka 'unsigned long') to 'char' in initializer list [-Wc++11-narrowing]
    3 |     return {n, ' '};
      |             ^
<source>:3:13: note: insert an explicit cast to silence this issue
    3 |     return {n, ' '};
      |             ^
      |             static_cast<char>( )

Related: https://github.com/llvm/llvm-project/issues/39728

chrchr-github avatar Sep 25 '24 16:09 chrchr-github