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

[clang-tidy] readability-redundant-preprocessor false positive on builtin preprocessor checks

Open philnik777 opened this issue 3 years ago • 3 comments

#if __has_builtin(__remove_cvref)
#  if __has_cpp_attribute(no_unique_address)
#  endif
#endif

(Godbolt) generates

1 warning generated.
<source>:2:4: warning: nested redundant #if; consider removing it [readability-redundant-preprocessor]
    2 | #  if __has_cpp_attribute(no_unique_address)
      |    ^
<source>:1:2: note: previous #if was here
    1 | #if __has_builtin(__remove_cvref)
      |  ^
1 warning generated.

which is obviously wrong.

philnik777 avatar Aug 19 '23 15:08 philnik777

@llvm/issue-subscribers-clang-tidy

llvmbot avatar Aug 19 '23 16:08 llvmbot

What I found is that ConditionRange point to ')' character only, and we compare later ')' with ')', oryginal issue is probably somewhere in clang preprocessor, but still easiest fix would be simply to take as a begining of range a token after 'if'.

PiotrZSL avatar Aug 19 '23 19:08 PiotrZSL

Following up on @PiotrZSL's finding - the issue is that ConditionRange points to incomplete token locations after macro expansion. For builtin expressions like __has_builtin(__remove_cvref), the preprocessor's ExpandBuiltinMacro replaces the entire expression with a single numeric token, causing the condition range to collapse.

The fix reads the condition text directly from the source buffer by:

  1. Using Lexer::getLocForEndOfToken() on the Loc parameter (which points to the if keyword token) to find where the condition starts
  2. Reading forward to end-of-line, handling \ continuations
  3. This recovers the original source text regardless of macro expansion

I have this implemented and tested. Ready to submit a PR if this approach looks good!

Aditya26189 avatar Feb 15 '26 08:02 Aditya26189