11 #include "../utils/LexerUtils.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
15 using namespace clang::ast_matchers;
21 void SuspiciousSemicolonCheck::registerMatchers(MatchFinder *
Finder) {
23 stmt(anyOf(ifStmt(hasThen(nullStmt().bind(
"semi")),
24 unless(hasElse(stmt()))),
25 forStmt(hasBody(nullStmt().bind(
"semi"))),
26 cxxForRangeStmt(hasBody(nullStmt().bind(
"semi"))),
27 whileStmt(hasBody(nullStmt().bind(
"semi")))))
32 void SuspiciousSemicolonCheck::check(
const MatchFinder::MatchResult &
Result) {
33 if (Result.Context->getDiagnostics().hasErrorOccurred())
36 const auto *Semicolon = Result.Nodes.getNodeAs<NullStmt>(
"semi");
37 SourceLocation LocStart = Semicolon->getLocStart();
39 if (LocStart.isMacroID())
42 ASTContext &Ctxt = *Result.Context;
44 auto &
SM = *Result.SourceManager;
45 unsigned SemicolonLine =
SM.getSpellingLineNumber(LocStart);
47 const auto *Statement = Result.Nodes.getNodeAs<Stmt>(
"stmt");
48 const bool IsIfStmt = isa<IfStmt>(Statement);
51 SM.getSpellingLineNumber(Token.getLocation()) != SemicolonLine)
54 SourceLocation LocEnd = Semicolon->getLocEnd();
55 FileID FID =
SM.getFileID(LocEnd);
56 llvm::MemoryBuffer *Buffer =
SM.getBuffer(FID, LocEnd);
57 Lexer Lexer(
SM.getLocForStartOfFile(FID), Ctxt.getLangOpts(),
58 Buffer->getBufferStart(),
SM.getCharacterData(LocEnd) + 1,
59 Buffer->getBufferEnd());
60 if (Lexer.LexFromRawLexer(Token))
63 unsigned BaseIndent =
SM.getSpellingColumnNumber(Statement->getLocStart());
64 unsigned NewTokenIndent =
SM.getSpellingColumnNumber(Token.getLocation());
65 unsigned NewTokenLine =
SM.getSpellingLineNumber(Token.getLocation());
67 if (!IsIfStmt && NewTokenIndent <= BaseIndent &&
68 Token.getKind() != tok::l_brace && NewTokenLine != SemicolonLine)
71 diag(LocStart,
"potentially unintended semicolon")
72 << FixItHint::CreateRemoval(SourceRange(LocStart, LocEnd));
std::unique_ptr< ast_matchers::MatchFinder > Finder
Token getPreviousNonCommentToken(const ASTContext &Context, SourceLocation Location)
Returns previous non-comment token skipping over any comment text or tok::unknown if not found...