blob: bc5b35341f249262818b508c49809b2b91e65683 [file] [log] [blame]
Aaron Ballmane4b17652015-10-08 19:54:43 +00001//===--- SetLongJmpCheck.cpp - clang-tidy----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "SetLongJmpCheck.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Lex/PPCallbacks.h"
15#include "clang/Lex/Preprocessor.h"
16
17using namespace clang::ast_matchers;
18
19namespace clang {
20namespace tidy {
21
22const char SetLongJmpCheck::DiagWording[] =
23 "do not call %0; consider using exception handling instead";
24
25namespace {
26class SetJmpMacroCallbacks : public PPCallbacks {
27 SetLongJmpCheck &Check;
28
29public:
30 explicit SetJmpMacroCallbacks(SetLongJmpCheck &Check) : Check(Check) {}
31
32 void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
33 SourceRange Range, const MacroArgs *Args) override {
34 const auto *II = MacroNameTok.getIdentifierInfo();
35 if (!II)
36 return;
37
38 if (II->getName() == "setjmp")
39 Check.diag(Range.getBegin(), Check.DiagWording) << II;
40 }
41};
42} // namespace
43
44void SetLongJmpCheck::registerPPCallbacks(CompilerInstance &Compiler) {
45 // This checker only applies to C++, where exception handling is a superior
46 // solution to setjmp/longjmp calls.
47 if (!getLangOpts().CPlusPlus)
48 return;
49
50 // Per [headers]p5, setjmp must be exposed as a macro instead of a function,
51 // despite the allowance in C for setjmp to also be an extern function.
52 Compiler.getPreprocessor().addPPCallbacks(
53 llvm::make_unique<SetJmpMacroCallbacks>(*this));
54}
55
56void SetLongJmpCheck::registerMatchers(MatchFinder *Finder) {
57 // This checker only applies to C++, where exception handling is a superior
58 // solution to setjmp/longjmp calls.
59 if (!getLangOpts().CPlusPlus)
60 return;
61
62 // In case there is an implementation that happens to define setjmp as a
63 // function instead of a macro, this will also catch use of it. However, we
64 // are primarily searching for uses of longjmp.
65 Finder->addMatcher(callExpr(callee(functionDecl(anyOf(hasName("setjmp"),
66 hasName("longjmp")))))
67 .bind("expr"),
68 this);
69}
70
71void SetLongJmpCheck::check(const MatchFinder::MatchResult &Result) {
72 const auto *E = Result.Nodes.getNodeAs<CallExpr>("expr");
73 diag(E->getExprLoc(), DiagWording) << cast<NamedDecl>(E->getCalleeDecl());
74}
75
76} // namespace tidy
77} // namespace clang