Index: clang-tidy/modernize/CMakeLists.txt =================================================================== --- clang-tidy/modernize/CMakeLists.txt +++ clang-tidy/modernize/CMakeLists.txt @@ -15,6 +15,7 @@ ShrinkToFitCheck.cpp UseAutoCheck.cpp UseDefaultCheck.cpp + UseNoexceptCheck.cpp UseNullptrCheck.cpp UseOverrideCheck.cpp Index: clang-tidy/modernize/ModernizeTidyModule.cpp =================================================================== --- clang-tidy/modernize/ModernizeTidyModule.cpp +++ clang-tidy/modernize/ModernizeTidyModule.cpp @@ -21,6 +21,7 @@ #include "ShrinkToFitCheck.h" #include "UseAutoCheck.h" #include "UseDefaultCheck.h" +#include "UseNoexceptCheck.h" #include "UseNullptrCheck.h" #include "UseOverrideCheck.h" @@ -48,6 +49,7 @@ CheckFactories.registerCheck("modernize-shrink-to-fit"); CheckFactories.registerCheck("modernize-use-auto"); CheckFactories.registerCheck("modernize-use-default"); + CheckFactories.registerCheck("modernize-use-noexcept"); CheckFactories.registerCheck("modernize-use-nullptr"); CheckFactories.registerCheck("modernize-use-override"); } Index: clang-tidy/modernize/UseNoexceptCheck.h =================================================================== --- /dev/null +++ clang-tidy/modernize/UseNoexceptCheck.h @@ -0,0 +1,52 @@ +//===--- UseNoexceptCheck.h - clang-tidy-------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USE_NOEXCEPT_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USE_NOEXCEPT_H + +#include "../ClangTidy.h" + +namespace clang { +namespace tidy { +namespace modernize { + +using CandidateSet = llvm::StringSet; + +/// \brief Replace dynamic exception specifications, with +/// `noexcept` (or user-defined macro) or `noexcept(true)`. +/// \code +/// void foo() throw(); +/// \endcode +/// Is converted to: +/// \code +/// void foo() noexcept; +/// \endcode +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/modernize-use-noexcept.html +class UseNoexceptCheck : public ClangTidyCheck { +public: + UseNoexceptCheck(StringRef Name, ClangTidyContext *Context); + void storeOptions(ClangTidyOptions::OptionMap &Opts) override; + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + +private: + bool checkHelper(const ast_matchers::MatchFinder::MatchResult &Result, + const SourceRange &Range, CharSourceRange &FileMoveRange, + unsigned &Len); + const std::string ReplacementStr; + StringRef Replacement; +}; + +} // namespace modernize +} // namespace tidy +} // namespace clang + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MODERNIZE_USE_NOEXCEPT_H Index: clang-tidy/modernize/UseNoexceptCheck.cpp =================================================================== --- /dev/null +++ clang-tidy/modernize/UseNoexceptCheck.cpp @@ -0,0 +1,127 @@ +//===--- UseNoexceptCheck.cpp - clang-tidy---------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "UseNoexceptCheck.h" +#include "../utils/LexerUtils.h" +#include "clang/AST/ASTContext.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace modernize { + +UseNoexceptCheck::UseNoexceptCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context), + ReplacementStr(Options.get("ReplacementString", "noexcept")) {} + +void UseNoexceptCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "ReplacementString", ReplacementStr); +} + +void UseNoexceptCheck::registerMatchers(MatchFinder *Finder) { + if (!getLangOpts().CPlusPlus) + return; + Finder->addMatcher( + functionDecl(hasDynamicExceptionSpec()).bind("functionDecl"), this); +} + +bool UseNoexceptCheck::checkHelper(const MatchFinder::MatchResult &Result, + const SourceRange &Range, + CharSourceRange &FileMoveRange, + unsigned &Len) { + SourceManager &SM = *Result.SourceManager; + const ASTContext &Context = *Result.Context; + SourceLocation CurrentLoc = Range.getEnd(); + CharSourceRange MoveRange; + unsigned TokenLength = 0; + + SmallVector Tokens = + utils::lexer::ParseTokens(Context, SM, CharSourceRange(Range, true)); + auto TokensEnd = Tokens.rend(); + for (auto I = Tokens.rbegin(); I != TokensEnd; ++I) { + SourceLocation Loc = I->getLocation(); + TokenLength = I->getLength(); + + // Looking for throw(), throw([,...]), or throw(...). + if (I->is(tok::r_paren)) { + if (++I == TokensEnd) + return false; + bool Empty = true; + // Found ')', now loop till we find '('. + while (I->isNot(tok::l_paren)) { + Empty = false; + if (++I == TokensEnd) + return false; + } + if (++I == TokensEnd) + return false; + if (StringRef(SM.getCharacterData(I->getLocation()), I->getLength()) == + "throw") { + if (!Empty) { + // We only support macro replacement for "throw()". + if (Replacement != "noexcept") + return false; + Replacement = "noexcept(false)"; + } + MoveRange.setEnd(Loc); + MoveRange.setBegin(I->getLocation()); + break; + } + } else if (++I == TokensEnd) { + return false; + } + CurrentLoc = I->getLocation(); + } + + FileMoveRange = Lexer::makeFileCharRange(MoveRange, SM, getLangOpts()); + if (FileMoveRange.isValid()) { + std::pair BeginInfo = + SM.getDecomposedLoc(FileMoveRange.getBegin()); + std::pair EndInfo = + SM.getDecomposedLoc(FileMoveRange.getEnd()); + Len = EndInfo.second - BeginInfo.second + TokenLength; + return true; + } + return false; +} + +void UseNoexceptCheck::check(const MatchFinder::MatchResult &Result) { + auto FuncDecl = Result.Nodes.getNodeAs("functionDecl"); + if (!FuncDecl) + return; + + auto Range = FuncDecl->getSourceRange(); + if (!Range.isValid()) + return; + + Replacement = ReplacementStr; + CharSourceRange FileMoveRange; + unsigned Len = 0; + + if (!checkHelper(Result, Range, FileMoveRange, Len)) + return; + + diag(FuncDecl->getLocation(), "function '%0' uses dynamic exception " + "specification '%1'; use '%2' instead") + << FuncDecl->getNameInfo().getAsString() + << StringRef( + Result.SourceManager->getCharacterData(FileMoveRange.getBegin()), + Len) + << Replacement + << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(FileMoveRange.getBegin(), + FileMoveRange.getEnd()), + Replacement); +} + +} // namespace modernize +} // namespace tidy +} // namespace clang Index: clang-tidy/modernize/UseOverrideCheck.cpp =================================================================== --- clang-tidy/modernize/UseOverrideCheck.cpp +++ clang-tidy/modernize/UseOverrideCheck.cpp @@ -10,7 +10,7 @@ #include "UseOverrideCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" -#include "clang/Lex/Lexer.h" +#include "../utils/LexerUtils.h" using namespace clang::ast_matchers; @@ -24,36 +24,6 @@ Finder->addMatcher(cxxMethodDecl(isOverride()).bind("method"), this); } -// Re-lex the tokens to get precise locations to insert 'override' and remove -// 'virtual'. -static SmallVector -ParseTokens(CharSourceRange Range, const MatchFinder::MatchResult &Result) { - const SourceManager &Sources = *Result.SourceManager; - std::pair LocInfo = - Sources.getDecomposedLoc(Range.getBegin()); - StringRef File = Sources.getBufferData(LocInfo.first); - const char *TokenBegin = File.data() + LocInfo.second; - Lexer RawLexer(Sources.getLocForStartOfFile(LocInfo.first), - Result.Context->getLangOpts(), File.begin(), TokenBegin, - File.end()); - SmallVector Tokens; - Token Tok; - while (!RawLexer.LexFromRawLexer(Tok)) { - if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) - break; - if (Sources.isBeforeInTranslationUnit(Range.getEnd(), Tok.getLocation())) - break; - if (Tok.is(tok::raw_identifier)) { - IdentifierInfo &Info = Result.Context->Idents.get(StringRef( - Sources.getCharacterData(Tok.getLocation()), Tok.getLength())); - Tok.setIdentifierInfo(&Info); - Tok.setKind(Info.getTokenID()); - } - Tokens.push_back(Tok); - } - return Tokens; -} - static StringRef GetText(const Token &Tok, const SourceManager &Sources) { return StringRef(Sources.getCharacterData(Tok.getLocation()), Tok.getLength()); @@ -112,7 +82,8 @@ // FIXME: Instead of re-lexing and looking for specific macros such as // 'ABSTRACT', properly store the location of 'virtual' and '= 0' in each // FunctionDecl. - SmallVector Tokens = ParseTokens(FileRange, Result); + SmallVector Tokens = utils::lexer::ParseTokens( + *Result.Context, *Result.SourceManager, FileRange); // Add 'override' on inline declarations that don't already have it. if (!HasFinal && !HasOverride) { Index: clang-tidy/utils/LexerUtils.h =================================================================== --- clang-tidy/utils/LexerUtils.h +++ clang-tidy/utils/LexerUtils.h @@ -12,6 +12,7 @@ #include "clang/AST/ASTContext.h" #include "clang/Lex/Lexer.h" +#include "llvm/ADT/SmallVector.h" namespace clang { namespace tidy { @@ -23,6 +24,10 @@ Token getPreviousNonCommentToken(const ASTContext &Context, SourceLocation Location); +SmallVector ParseTokens(const ASTContext &Context, + const SourceManager &Sources, + CharSourceRange Range); + } // namespace lexer } // namespace utils } // namespace tidy Index: clang-tidy/utils/LexerUtils.cpp =================================================================== --- clang-tidy/utils/LexerUtils.cpp +++ clang-tidy/utils/LexerUtils.cpp @@ -35,6 +35,33 @@ return Token; } +SmallVector ParseTokens(const ASTContext &Context, + const SourceManager &Sources, + CharSourceRange Range) { + std::pair LocInfo = + Sources.getDecomposedLoc(Range.getBegin()); + StringRef File = Sources.getBufferData(LocInfo.first); + const char *TokenBegin = File.data() + LocInfo.second; + Lexer RawLexer(Sources.getLocForStartOfFile(LocInfo.first), + Context.getLangOpts(), File.begin(), TokenBegin, File.end()); + SmallVector Tokens; + Token Tok; + while (!RawLexer.LexFromRawLexer(Tok)) { + if (Tok.is(tok::semi) || Tok.is(tok::l_brace)) + break; + if (Sources.isBeforeInTranslationUnit(Range.getEnd(), Tok.getLocation())) + break; + if (Tok.is(tok::raw_identifier)) { + IdentifierInfo &Info = Context.Idents.get(StringRef( + Sources.getCharacterData(Tok.getLocation()), Tok.getLength())); + Tok.setIdentifierInfo(&Info); + Tok.setKind(Info.getTokenID()); + } + Tokens.push_back(Tok); + } + return Tokens; +} + } // namespace lexer } // namespace utils } // namespace tidy Index: docs/ReleaseNotes.rst =================================================================== --- docs/ReleaseNotes.rst +++ docs/ReleaseNotes.rst @@ -191,6 +191,11 @@ Selectively replaces string literals containing escaped characters with raw string literals. +- New `modernize-use-noexcept + `_ check + + Replaces dynamic exception specifications with ``noexcept`` or a user defined macro. + - New `performance-faster-string-find `_ check Index: docs/clang-tidy/checks/modernize-use-noexcept.rst =================================================================== --- /dev/null +++ docs/clang-tidy/checks/modernize-use-noexcept.rst @@ -0,0 +1,50 @@ +.. title:: clang-tidy - modernize-use-noexcept + +modernize-use-noexcept +====================== + +The check converts dynamic exception specifications, e.g., ``throw()``, +``throw([,...])``, or ``throw(...)`` to ``noexcept``, ``noexcept(false)``, +or a user defined macro. + +Example +------- + +.. code-block:: c++ + + void foo() throw(); + void bar() throw(int) {} + +transforms to: + +.. code-block:: c++ + + void foo() noexcept; + void bar() noexcept(false) {} + + +User defined macros +------------------- + +By default this check will only replace ``throw()`` with ``noexcept``, +and ``throw([,...])`` or ``throw(...)`` with +``noexcept(false)``. Additionally, users can also use +:option:`ReplacementString` to specify a macro to use instead of +``noexcept``. This is useful when maintaining source code that must +be compiled with older compilers that don't support the ``noexcept`` +keyword. + +Example +^^^^^^^ + +.. code-block:: c++ + + void foo() throw() {} + +transforms to: + +.. code-block:: c++ + + void foo() NOEXCEPT {} + +if the `ReplacementString` option is set to `NOEXCEPT`. Index: test/clang-tidy/modernize-use-noexcept-macro.cpp =================================================================== --- /dev/null +++ test/clang-tidy/modernize-use-noexcept-macro.cpp @@ -0,0 +1,13 @@ +// RUN: %check_clang_tidy %s modernize-use-noexcept %t -- \ +// RUN: -config="{CheckOptions: [{key: modernize-use-noexcept.ReplacementString, value: 'NOEXCEPT'}]}" \ +// RUN: -- -std=c++11 + +#define NOEXCEPT noexcept + +void bar() throw() {} +// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'bar' uses dynamic exception specification 'throw()'; use 'NOEXCEPT' instead [modernize-use-noexcept] +// CHECK-FIXES: void bar() NOEXCEPT {} + +// Should not trigger a replacement. +void foo() noexcept(true); + Index: test/clang-tidy/modernize-use-noexcept.cpp =================================================================== --- /dev/null +++ test/clang-tidy/modernize-use-noexcept.cpp @@ -0,0 +1,22 @@ +// RUN: %check_clang_tidy %s modernize-use-noexcept %t -- \ +// RUN: -- -std=c++11 + +class A{}; +class B{}; + +void foo() throw(); +// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'foo' uses dynamic exception specification 'throw()'; use 'noexcept' instead [modernize-use-noexcept] +// CHECK-FIXES: void foo() noexcept; + +void bar() throw(...); +// CHECK-MESSAGES: :[[@LINE-1]]:6: warning: function 'bar' uses dynamic exception specification 'throw(...)'; use 'noexcept(false)' instead [modernize-use-noexcept] +// CHECK-FIXES: void bar() noexcept(false); + +void foobar() throw(A, B) +{} +// CHECK-MESSAGES: :[[@LINE-2]]:6: warning: function 'foobar' uses dynamic exception specification 'throw(A, B)'; use 'noexcept(false)' instead [modernize-use-noexcept] +// CHECK-FIXES: void foobar() noexcept(false) + +// Should not trigger a replacement. +void titi() noexcept {} +void toto() noexcept(true) {}