[clang-tidy] Don't issue most google-readability-casting warnings on .c files included in other files.

This is done sometimes for testing purposes, and the check needs to handle this
consistently.

llvm-svn: 238193
This commit is contained in:
Alexander Kornienko 2015-05-26 10:47:48 +00:00
parent db0712f986
commit 2b56649cd2
2 changed files with 22 additions and 8 deletions

View File

@ -97,15 +97,19 @@ void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
// compiled as C++.
if (getCurrentMainFile().endswith(".c"))
return;
// Ignore code in .c files #included in other files (which shouldn't be done,
// but people still do this for test and other purposes).
SourceManager &SM = *Result.SourceManager;
if (SM.getFilename(SM.getSpellingLoc(CastExpr->getLocStart())).endswith(".c"))
return;
// Leave type spelling exactly as it was (unlike
// getTypeAsWritten().getAsString() which would spell enum types 'enum X').
StringRef DestTypeString = Lexer::getSourceText(
CharSourceRange::getTokenRange(
CastExpr->getLParenLoc().getLocWithOffset(1),
CastExpr->getRParenLoc().getLocWithOffset(-1)),
*Result.SourceManager, Result.Context->getLangOpts());
StringRef DestTypeString =
Lexer::getSourceText(CharSourceRange::getTokenRange(
CastExpr->getLParenLoc().getLocWithOffset(1),
CastExpr->getRParenLoc().getLocWithOffset(-1)),
SM, Result.Context->getLangOpts());
auto diag_builder =
diag(CastExpr->getLocStart(), "C-style casts are discouraged. %0");
@ -118,8 +122,7 @@ void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) {
if (!isa<ParenExpr>(SubExpr)) {
CastText.push_back('(');
diag_builder << FixItHint::CreateInsertion(
Lexer::getLocForEndOfToken(SubExpr->getLocEnd(), 0,
*Result.SourceManager,
Lexer::getLocForEndOfToken(SubExpr->getLocEnd(), 0, SM,
Result.Context->getLangOpts()),
")");
}

View File

@ -2,11 +2,22 @@
// The testing script always adds .cpp extension to the input file name, so we
// need to run clang-tidy directly in order to verify handling of .c files:
// RUN: clang-tidy --checks=-*,google-readability-casting %s -- -x c++ | FileCheck %s -check-prefix=CHECK-MESSAGES -implicit-check-not='{{warning|error}}:'
// RUN: cp %s %t.main_file.cpp
// RUN: clang-tidy --checks=-*,google-readability-casting -header-filter='.*' %t.main_file.cpp -- -I%S -DTEST_INCLUDE -x c++ | FileCheck %s -check-prefix=CHECK-MESSAGES -implicit-check-not='{{warning|error}}:'
// REQUIRES: shell
#ifdef TEST_INCLUDE
#undef TEST_INCLUDE
#include "google-readability-casting.c"
#else
void f(const char *cpc) {
const char *cpc2 = (const char*)cpc;
// CHECK-MESSAGES: :[[@LINE-1]]:22: warning: redundant cast to the same type [google-readability-casting]
// CHECK-FIXES: const char *cpc2 = cpc;
char *pc = (char*)cpc;
}
#endif