Index: change-namespace/ChangeNamespace.cpp =================================================================== --- change-namespace/ChangeNamespace.cpp +++ change-namespace/ChangeNamespace.cpp @@ -345,7 +345,8 @@ } else if (const auto *TLoc = Result.Nodes.getNodeAs("type")) { fixTypeLoc(Result, startLocationForType(*TLoc), EndLocationForType(*TLoc), *TLoc); - } else if (const auto *VarRef = Result.Nodes.getNodeAs("var_ref")){ + } else if (const auto *VarRef = + Result.Nodes.getNodeAs("var_ref")) { const auto *Var = Result.Nodes.getNodeAs("var_decl"); assert(Var); if (Var->getCanonicalDecl()->isStaticDataMember()) @@ -358,8 +359,8 @@ VarRefRange.getEnd(), Name); } else { const auto *Call = Result.Nodes.getNodeAs("call"); - assert(Call != nullptr &&"Expecting callback for CallExpr."); - const clang::FunctionDecl* Func = Call->getDirectCallee(); + assert(Call != nullptr && "Expecting callback for CallExpr."); + const clang::FunctionDecl *Func = Call->getDirectCallee(); assert(Func != nullptr); // Ignore out-of-line static methods since they will be handled by nested // name specifiers. @@ -548,7 +549,8 @@ const UsingDecl *UsingDeclaration) { SourceLocation Start = UsingDeclaration->getLocStart(); SourceLocation End = UsingDeclaration->getLocEnd(); - if (Start.isInvalid() || End.isInvalid()) return; + if (Start.isInvalid() || End.isInvalid()) + return; assert(UsingDeclaration->shadow_size() > 0); // FIXME: it might not be always accurate to use the first using-decl. Index: clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp =================================================================== --- clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp +++ clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp @@ -30,17 +30,14 @@ using namespace llvm; using namespace clang; - static void eatDiagnostics(const SMDiagnostic &, void *) {} namespace clang { namespace replace { -std::error_code -collectReplacementsFromDirectory(const llvm::StringRef Directory, - TUReplacements &TUs, - TUReplacementFiles & TURFiles, - clang::DiagnosticsEngine &Diagnostics) { +std::error_code collectReplacementsFromDirectory( + const llvm::StringRef Directory, TUReplacements &TUs, + TUReplacementFiles &TURFiles, clang::DiagnosticsEngine &Diagnostics) { using namespace llvm::sys::fs; using namespace llvm::sys::path; @@ -128,7 +125,7 @@ Rewriter &Rewrite) { bool Result = true; for (std::vector::const_iterator I = Replaces.begin(), - E = Replaces.end(); + E = Replaces.end(); I != E; ++I) { if (I->isApplicable()) { Result = I->apply(Rewrite) && Result; @@ -139,11 +136,10 @@ return Result; } - // FIXME: moved from libToolingCore. remove this when std::vector // is replaced with tooling::Replacements class. static void deduplicate(std::vector &Replaces, - std::vector &Conflicts) { + std::vector &Conflicts) { if (Replaces.empty()) return; Index: clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp =================================================================== --- clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp +++ clang-apply-replacements/tool/ClangApplyReplacementsMain.cpp @@ -43,7 +43,6 @@ "merging/replacing."), cl::init(false), cl::cat(ReplacementCategory)); - static cl::opt DoFormat( "format", cl::desc("Enable formatting of code changed by applying replacements.\n" @@ -63,8 +62,8 @@ cl::init(""), cl::cat(FormattingCategory)); static cl::opt -FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription), - cl::init("LLVM"), cl::cat(FormattingCategory)); + FormatStyleOpt("style", cl::desc(format::StyleOptionHelpDescription), + cl::init("LLVM"), cl::cat(FormattingCategory)); namespace { // Helper object to remove the TUReplacement files (triggered by @@ -75,9 +74,7 @@ clang::DiagnosticsEngine &Diagnostics) : TURFiles(Files), Diag(Diagnostics) {} - ~ScopedFileRemover() { - deleteReplacementFiles(TURFiles, Diag); - } + ~ScopedFileRemover() { deleteReplacementFiles(TURFiles, Diag); } private: const TUReplacementFiles &TURFiles; @@ -106,7 +103,8 @@ static bool getRewrittenData(const std::vector &Replacements, Rewriter &Rewrites, std::string &Result) { - if (Replacements.empty()) return true; + if (Replacements.empty()) + return true; if (!applyAllReplacements(Replacements, Rewrites)) return false; @@ -206,8 +204,7 @@ IntrusiveRefCntPtr DiagOpts(new DiagnosticOptions()); DiagnosticsEngine Diagnostics( - IntrusiveRefCntPtr(new DiagnosticIDs()), - DiagOpts.get()); + IntrusiveRefCntPtr(new DiagnosticIDs()), DiagOpts.get()); // Determine a formatting style from options. format::FormatStyle FormatStyle; Index: clang-move/ClangMove.cpp =================================================================== --- clang-move/ClangMove.cpp +++ clang-move/ClangMove.cpp @@ -25,14 +25,13 @@ namespace { // FIXME: Move to ASTMatchers. -AST_MATCHER(VarDecl, isStaticDataMember) { - return Node.isStaticDataMember(); -} +AST_MATCHER(VarDecl, isStaticDataMember) { return Node.isStaticDataMember(); } AST_MATCHER_P(Decl, hasOutermostEnclosingClass, ast_matchers::internal::Matcher, InnerMatcher) { - const auto* Context = Node.getDeclContext(); - if (!Context) return false; + const auto *Context = Node.getDeclContext(); + if (!Context) + return false; while (const auto *NextContext = Context->getParent()) { if (isa(NextContext) || isa(NextContext)) @@ -46,7 +45,8 @@ AST_MATCHER_P(CXXMethodDecl, ofOutermostEnclosingClass, ast_matchers::internal::Matcher, InnerMatcher) { const CXXRecordDecl *Parent = Node.getParent(); - if (!Parent) return false; + if (!Parent) + return false; while (const auto *NextParent = dyn_cast(Parent->getParent())) { Parent = NextParent; @@ -64,7 +64,7 @@ llvm::SmallString<128> AbsolutePath(Path); if (std::error_code EC = llvm::sys::fs::make_absolute(InitialDirectory, AbsolutePath)) - llvm::errs() << "Warning: could not make absolute file: '" << EC.message() + llvm::errs() << "Warning: could not make absolute file: '" << EC.message() << '\n'; llvm::sys::path::remove_dots(AbsolutePath, /*remove_dot_dot=*/true); llvm::sys::path::native(AbsolutePath); @@ -76,16 +76,17 @@ // // The Path can be a path relative to the build directory, or retrieved from // the SourceManager. -std::string MakeAbsolutePath(const SourceManager& SM, StringRef Path) { +std::string MakeAbsolutePath(const SourceManager &SM, StringRef Path) { llvm::SmallString<128> AbsolutePath(Path); if (std::error_code EC = - SM.getFileManager().getVirtualFileSystem()->makeAbsolute(AbsolutePath)) - llvm::errs() << "Warning: could not make absolute file: '" << EC.message() + SM.getFileManager().getVirtualFileSystem()->makeAbsolute( + AbsolutePath)) + llvm::errs() << "Warning: could not make absolute file: '" << EC.message() << '\n'; // Handle symbolic link path cases. // We are trying to get the real file path of the symlink. const DirectoryEntry *Dir = SM.getFileManager().getDirectory( - llvm::sys::path::parent_path(AbsolutePath.str())); + llvm::sys::path::parent_path(AbsolutePath.str())); if (Dir) { StringRef DirName = SM.getFileManager().getCanonicalName(Dir); SmallVector AbsoluteFilename; @@ -156,7 +157,7 @@ // FIXME: this is a bit hacky to get ReadToEndOfLine work. Lex.setParsingPreprocessorDirective(true); Lex.ReadToEndOfLine(&Line); - SourceLocation EndLoc = D->getLocEnd().getLocWithOffset(Line.size()); + SourceLocation EndLoc = D->getLocEnd().getLocWithOffset(Line.size()); // If we already reach EOF, just return the EOF SourceLocation; // otherwise, move 1 offset ahead to include the trailing newline character // '\n'. @@ -172,14 +173,12 @@ clang::SourceRange Full = D->getSourceRange(); Full.setEnd(getLocForEndOfDecl(D, SM)); // Expand to comments that are associated with the Decl. - if (const auto* Comment = - D->getASTContext().getRawCommentForDeclNoCache(D)) { + if (const auto *Comment = D->getASTContext().getRawCommentForDeclNoCache(D)) { if (SM->isBeforeInTranslationUnit(Full.getEnd(), Comment->getLocEnd())) Full.setEnd(Comment->getLocEnd()); // FIXME: Don't delete a preceding comment, if there are no other entities // it could refer to. - if (SM->isBeforeInTranslationUnit(Comment->getLocStart(), - Full.getBegin())) + if (SM->isBeforeInTranslationUnit(Comment->getLocStart(), Full.getBegin())) Full.setBegin(Comment->getLocStart()); } @@ -228,8 +227,7 @@ clang::tooling::Replacements createInsertedReplacements(const std::vector &Includes, const std::vector &Decls, - llvm::StringRef FileName, - bool IsHeader = false) { + llvm::StringRef FileName, bool IsHeader = false) { std::string NewCode; std::string GuardName(FileName); if (IsHeader) { @@ -325,8 +323,8 @@ auto InOldHeader = isExpansionInFile( MakeAbsolutePath(OriginalRunningDirectory, Spec.OldHeader)); - auto InOldCC = isExpansionInFile( - MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC)); + auto InOldCC = + isExpansionInFile(MakeAbsolutePath(OriginalRunningDirectory, Spec.OldCC)); auto InOldFiles = anyOf(InOldHeader, InOldCC); auto InMovedClass = hasOutermostEnclosingClass(cxxRecordDecl(*InMovedClassNames)); @@ -346,10 +344,10 @@ this); // Match static member variable definition of the moved class. - Finder->addMatcher(varDecl(InMovedClass, InOldCC, isDefinition(), - isStaticDataMember()) - .bind("class_static_var_decl"), - this); + Finder->addMatcher( + varDecl(InMovedClass, InOldCC, isDefinition(), isStaticDataMember()) + .bind("class_static_var_decl"), + this); auto InOldCCNamedNamespace = allOf(hasParent(namespaceDecl(unless(isAnonymous()))), InOldCC); @@ -357,10 +355,9 @@ // in classes, functions and anonymous namespaces are covered in other // matchers. Finder->addMatcher( - namedDecl( - anyOf(usingDecl(InOldCCNamedNamespace), - usingDirectiveDecl(InOldCC, InOldCCNamedNamespace), - typeAliasDecl(InOldCC, InOldCCNamedNamespace))) + namedDecl(anyOf(usingDecl(InOldCCNamedNamespace), + usingDirectiveDecl(InOldCC, InOldCCNamedNamespace), + typeAliasDecl(InOldCC, InOldCCNamedNamespace))) .bind("using_decl"), this); @@ -373,11 +370,10 @@ auto IsOldCCStaticDefinition = allOf(isDefinition(), unless(InMovedClass), InOldCCNamedNamespace, isStaticStorageClass()); - Finder->addMatcher( - namedDecl(anyOf(functionDecl(IsOldCCStaticDefinition), - varDecl(IsOldCCStaticDefinition))) - .bind("static_decls"), - this); + Finder->addMatcher(namedDecl(anyOf(functionDecl(IsOldCCStaticDefinition), + varDecl(IsOldCCStaticDefinition))) + .bind("static_decls"), + this); // Match forward declarations in old header. Finder->addMatcher( @@ -413,8 +409,8 @@ MovedDecls.emplace_back(FWD, &Result.Context->getSourceManager()); } } - } else if (const auto *ANS = Result.Nodes.getNodeAs( - "anonymous_ns")) { + } else if (const auto *ANS = + Result.Nodes.getNodeAs("anonymous_ns")) { MovedDecls.emplace_back(ANS, &Result.Context->getSourceManager()); } else if (const auto *ND = Result.Nodes.getNodeAs("static_decls")) { @@ -425,11 +421,10 @@ } } -void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, - bool IsAngled, +void ClangMoveTool::addIncludes(llvm::StringRef IncludeHeader, bool IsAngled, llvm::StringRef SearchPath, llvm::StringRef FileName, - const SourceManager& SM) { + const SourceManager &SM) { SmallVector HeaderWithSearchPath; llvm::sys::path::append(HeaderWithSearchPath, SearchPath, IncludeHeader); std::string AbsoluteOldHeader = @@ -460,8 +455,8 @@ const auto &SM = *MovedDecl.SM; auto Range = GetFullRange(&SM, MovedDecl.Decl); clang::tooling::Replacement RemoveReplacement( - *MovedDecl.SM, clang::CharSourceRange::getCharRange( - Range.getBegin(), Range.getEnd()), + *MovedDecl.SM, + clang::CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()), ""); std::string FilePath = RemoveReplacement.getFilePath().str(); auto Err = FileToReplacements[FilePath].add(RemoveReplacement); Index: clang-move/tool/ClangMoveMain.cpp =================================================================== --- clang-move/tool/ClangMoveMain.cpp +++ clang-move/tool/ClangMoveMain.cpp @@ -77,8 +77,8 @@ // Add "-fparse-all-comments" compile option to make clang parse all comments, // otherwise, ordinary comments like "//" and "/*" won't get parsed (This is // a bit of hacky). - std::vector ExtraArgs( argv, argv + argc ); - ExtraArgs.insert(ExtraArgs.begin()+1, "-extra-arg=-fparse-all-comments"); + std::vector ExtraArgs(argv, argv + argc); + ExtraArgs.insert(ExtraArgs.begin() + 1, "-extra-arg=-fparse-all-comments"); std::unique_ptr RawExtraArgs( new const char *[ExtraArgs.size()]); for (size_t i = 0; i < ExtraArgs.size(); ++i) @@ -90,7 +90,7 @@ tooling::RefactoringTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList()); move::ClangMoveTool::MoveDefinitionSpec Spec; - Spec.Names = { Names.begin(), Names.end() }; + Spec.Names = {Names.begin(), Names.end()}; Spec.OldHeader = OldHeader; Spec.NewHeader = NewHeader; Spec.OldCC = OldCC; Index: clang-query/Query.cpp =================================================================== --- clang-query/Query.cpp +++ clang-query/Query.cpp @@ -65,7 +65,7 @@ } }; -} // namespace +} // namespace bool MatchQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const { unsigned MatchCount = 0; @@ -100,11 +100,10 @@ if (R.isValid()) { TextDiagnostic TD(OS, AST->getASTContext().getLangOpts(), &AST->getDiagnostics().getDiagnosticOptions()); - TD.emitDiagnostic( - R.getBegin(), DiagnosticsEngine::Note, - "\"" + BI->first + "\" binds here", - CharSourceRange::getTokenRange(R), - None, &AST->getSourceManager()); + TD.emitDiagnostic(R.getBegin(), DiagnosticsEngine::Note, + "\"" + BI->first + "\" binds here", + CharSourceRange::getTokenRange(R), None, + &AST->getSourceManager()); } break; } Index: clang-query/QueryParser.cpp =================================================================== --- clang-query/QueryParser.cpp +++ clang-query/QueryParser.cpp @@ -76,9 +76,7 @@ return *this; } - T Default(const T& Value) const { - return Switch.Default(Value); - } + T Default(const T &Value) const { return Switch.Default(Value); } }; // Lexes a word and stores it in Word. Returns a LexOrCompleteWord object @@ -101,9 +99,9 @@ QueryRef QueryParser::parseSetBool(bool QuerySession::*Var) { StringRef ValStr; unsigned Value = lexOrCompleteWord(ValStr) - .Case("false", 0) - .Case("true", 1) - .Default(~0u); + .Case("false", 0) + .Case("true", 1) + .Default(~0u); if (Value == ~0u) { return new InvalidQuery("expected 'true' or 'false', got '" + ValStr + "'"); } @@ -145,11 +143,7 @@ PQK_Quit }; -enum ParsedQueryVariable { - PQV_Invalid, - PQV_Output, - PQV_BindRoot -}; +enum ParsedQueryVariable { PQV_Invalid, PQV_Output, PQV_BindRoot }; QueryRef makeInvalidQueryFromDiagnostics(const Diagnostics &Diag) { std::string ErrStr; @@ -158,7 +152,7 @@ return new InvalidQuery(OS.str()); } -} // namespace +} // namespace QueryRef QueryParser::completeMatcherExpression() { std::vector Comps = Parser::completeExpression( Index: clang-reorder-fields/ReorderFieldsAction.cpp =================================================================== --- clang-reorder-fields/ReorderFieldsAction.cpp +++ clang-reorder-fields/ReorderFieldsAction.cpp @@ -1,4 +1,5 @@ -//===-- tools/extra/clang-reorder-fields/ReorderFieldsAction.cpp -*- C++ -*-===// +//===-- tools/extra/clang-reorder-fields/ReorderFieldsAction.cpp -*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -129,8 +130,10 @@ /// \brief Reorders initializers in a C++ struct/class constructor. /// -/// A constructor can have initializers for an arbitrary subset of the class's fields. -/// Thus, we need to ensure that we reorder just the initializers that are present. +/// A constructor can have initializers for an arbitrary subset of the class's +/// fields. +/// Thus, we need to ensure that we reorder just the initializers that are +/// present. static void reorderFieldsInConstructor( const CXXConstructorDecl *CtorDecl, ArrayRef NewFieldsOrder, const ASTContext &Context, @@ -182,11 +185,12 @@ const ASTContext &Context, std::map &Replacements) { assert(InitListEx && "Init list expression is null"); - // We care only about InitListExprs which originate from source code. + // We care only about InitListExprs which originate from source code. // Implicit InitListExprs are created by the semantic analyzer. if (!InitListEx->isExplicit()) return true; - // The method InitListExpr::getSyntacticForm may return nullptr indicating that + // The method InitListExpr::getSyntacticForm may return nullptr indicating + // that // the current initializer list also serves as its syntactic form. if (const auto *SyntacticForm = InitListEx->getSyntacticForm()) InitListEx = SyntacticForm; @@ -199,10 +203,9 @@ } for (unsigned i = 0, e = InitListEx->getNumInits(); i < e; ++i) if (i != NewFieldsOrder[i]) - addReplacement( - InitListEx->getInit(i)->getSourceRange(), - InitListEx->getInit(NewFieldsOrder[i])->getSourceRange(), Context, - Replacements); + addReplacement(InitListEx->getInit(i)->getSourceRange(), + InitListEx->getInit(NewFieldsOrder[i])->getSourceRange(), + Context, Replacements); return true; } Index: clang-reorder-fields/tool/ClangReorderFields.cpp =================================================================== --- clang-reorder-fields/tool/ClangReorderFields.cpp +++ clang-reorder-fields/tool/ClangReorderFields.cpp @@ -1,4 +1,5 @@ -//===-- tools/extra/clang-reorder-fields/tool/ClangReorderFields.cpp -*- C++ -*-===// +//===-- tools/extra/clang-reorder-fields/tool/ClangReorderFields.cpp -*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // Index: clang-tidy/ClangTidyDiagnosticConsumer.cpp =================================================================== --- clang-tidy/ClangTidyDiagnosticConsumer.cpp +++ clang-tidy/ClangTidyDiagnosticConsumer.cpp @@ -83,7 +83,7 @@ // applied). if (Err) { llvm::errs() << "Fix conflicts with existing fix! " - << llvm::toString(std::move(Err)) << "\n"; + << llvm::toString(std::move(Err)) << "\n"; assert(false && "Fix conflicts with existing fix!"); } } @@ -124,10 +124,9 @@ ClangTidyError::ClangTidyError(StringRef CheckName, ClangTidyError::Level DiagLevel, - bool IsWarningAsError, - StringRef BuildDirectory) - : CheckName(CheckName), BuildDirectory(BuildDirectory), DiagLevel(DiagLevel), - IsWarningAsError(IsWarningAsError) {} + bool IsWarningAsError, StringRef BuildDirectory) + : CheckName(CheckName), BuildDirectory(BuildDirectory), + DiagLevel(DiagLevel), IsWarningAsError(IsWarningAsError) {} // Returns true if GlobList starts with the negative indicator ('-'), removes it // from the GlobList. @@ -279,7 +278,7 @@ LastErrorPassesLineFilter = false; } -static bool LineIsMarkedWithNOLINT(SourceManager& SM, SourceLocation Loc) { +static bool LineIsMarkedWithNOLINT(SourceManager &SM, SourceLocation Loc) { bool Invalid; const char *CharacterData = SM.getCharacterData(Loc, &Invalid); if (!Invalid) { @@ -312,10 +311,10 @@ if (LastErrorWasIgnored && DiagLevel == DiagnosticsEngine::Note) return; - if (Info.getLocation().isValid() && - DiagLevel != DiagnosticsEngine::Error && + if (Info.getLocation().isValid() && DiagLevel != DiagnosticsEngine::Error && DiagLevel != DiagnosticsEngine::Fatal && - LineIsMarkedWithNOLINTinMacro(Diags->getSourceManager(), Info.getLocation())) { + LineIsMarkedWithNOLINTinMacro(Diags->getSourceManager(), + Info.getLocation())) { ++Context.Stats.ErrorsIgnoredNOLINT; // Ignored a warning, should ignore related notes as well LastErrorWasIgnored = true; Index: clang-tidy/ClangTidyOptions.cpp =================================================================== --- clang-tidy/ClangTidyOptions.cpp +++ clang-tidy/ClangTidyOptions.cpp @@ -215,8 +215,7 @@ const ClangTidyOptions &OverrideOptions, const FileOptionsProvider::ConfigFileHandlers &ConfigHandlers) : DefaultOptionsProvider(GlobalOptions, DefaultOptions), - OverrideOptions(OverrideOptions), ConfigHandlers(ConfigHandlers) { -} + OverrideOptions(OverrideOptions), ConfigHandlers(ConfigHandlers) {} // FIXME: This method has some common logic with clang::format::getStyle(). // Consider pulling out common bits to a findParentFileWithName function or Index: clang-tidy/cert/CERTTidyModule.cpp =================================================================== --- clang-tidy/cert/CERTTidyModule.cpp +++ clang-tidy/cert/CERTTidyModule.cpp @@ -34,8 +34,7 @@ void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { // C++ checkers // DCL - CheckFactories.registerCheck( - "cert-dcl50-cpp"); + CheckFactories.registerCheck("cert-dcl50-cpp"); CheckFactories.registerCheck( "cert-dcl54-cpp"); CheckFactories.registerCheck( @@ -46,37 +45,27 @@ // ERR CheckFactories.registerCheck( "cert-err09-cpp"); - CheckFactories.registerCheck( - "cert-err52-cpp"); - CheckFactories.registerCheck( - "cert-err58-cpp"); - CheckFactories.registerCheck( - "cert-err60-cpp"); + CheckFactories.registerCheck("cert-err52-cpp"); + CheckFactories.registerCheck("cert-err58-cpp"); + CheckFactories.registerCheck("cert-err60-cpp"); CheckFactories.registerCheck( "cert-err61-cpp"); // MSC - CheckFactories.registerCheck( - "cert-msc50-cpp"); + CheckFactories.registerCheck("cert-msc50-cpp"); // C checkers // DCL - CheckFactories.registerCheck( - "cert-dcl03-c"); + CheckFactories.registerCheck("cert-dcl03-c"); // ENV - CheckFactories.registerCheck( - "cert-env33-c"); + CheckFactories.registerCheck("cert-env33-c"); // FLP - CheckFactories.registerCheck( - "cert-flp30-c"); + CheckFactories.registerCheck("cert-flp30-c"); // FIO - CheckFactories.registerCheck( - "cert-fio38-c"); + CheckFactories.registerCheck("cert-fio38-c"); // ERR - CheckFactories.registerCheck( - "cert-err34-c"); + CheckFactories.registerCheck("cert-err34-c"); // MSC - CheckFactories.registerCheck( - "cert-msc30-c"); + CheckFactories.registerCheck("cert-msc30-c"); } ClangTidyOptions getModuleOptions() override { ClangTidyOptions Options; @@ -89,8 +78,8 @@ // Register the MiscTidyModule using this statically initialized variable. static ClangTidyModuleRegistry::Add -X("cert-module", - "Adds lint checks corresponding to CERT secure coding guidelines."); + X("cert-module", + "Adds lint checks corresponding to CERT secure coding guidelines."); // This anchor is used to force the linker to link in the generated object file // and thus register the CERTModule. Index: clang-tidy/cert/LimitedRandomnessCheck.cpp =================================================================== --- clang-tidy/cert/LimitedRandomnessCheck.cpp +++ clang-tidy/cert/LimitedRandomnessCheck.cpp @@ -30,11 +30,9 @@ msg = "; use C++11 random library instead"; const auto *MatchedDecl = Result.Nodes.getNodeAs("randomGenerator"); - diag(MatchedDecl->getLocStart(), - "rand() has limited randomness" + msg); + diag(MatchedDecl->getLocStart(), "rand() has limited randomness" + msg); } } // namespace cert } // namespace tidy } // namespace clang - Index: clang-tidy/cert/StaticObjectExceptionCheck.cpp =================================================================== --- clang-tidy/cert/StaticObjectExceptionCheck.cpp +++ clang-tidy/cert/StaticObjectExceptionCheck.cpp @@ -47,7 +47,7 @@ << VD << (VD->getStorageDuration() == SD_Static ? 0 : 1); SourceLocation FuncLocation = Func->getLocation(); - if(FuncLocation.isValid()) { + if (FuncLocation.isValid()) { diag(FuncLocation, "possibly throwing %select{constructor|function}0 declared here", DiagnosticIDs::Note) Index: clang-tidy/cert/StrToNumCheck.cpp =================================================================== --- clang-tidy/cert/StrToNumCheck.cpp +++ clang-tidy/cert/StrToNumCheck.cpp @@ -8,9 +8,9 @@ //===----------------------------------------------------------------------===// #include "StrToNumCheck.h" -#include "clang/Analysis/Analyses/FormatString.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/Analysis/Analyses/FormatString.h" #include "llvm/ADT/StringSwitch.h" #include Index: clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp =================================================================== --- clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp +++ clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp @@ -22,8 +22,8 @@ #include "ProTypeStaticCastDowncastCheck.h" #include "ProTypeUnionAccessCheck.h" #include "ProTypeVarargCheck.h" -#include "SpecialMemberFunctionsCheck.h" #include "SlicingCheck.h" +#include "SpecialMemberFunctionsCheck.h" namespace clang { namespace tidy { @@ -57,8 +57,7 @@ "cppcoreguidelines-pro-type-vararg"); CheckFactories.registerCheck( "cppcoreguidelines-special-member-functions"); - CheckFactories.registerCheck( - "cppcoreguidelines-slicing"); + CheckFactories.registerCheck("cppcoreguidelines-slicing"); CheckFactories.registerCheck( "cppcoreguidelines-c-copy-assignment-signature"); } Index: clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp =================================================================== --- clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp +++ clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp @@ -47,12 +47,12 @@ // Note: if a struct contains an array member, the compiler-generated // constructor has an arraySubscriptExpr. - Finder->addMatcher(arraySubscriptExpr(hasBase(ignoringImpCasts(hasType( - constantArrayType().bind("type")))), - hasIndex(expr().bind("index")), - unless(hasAncestor(isImplicit()))) - .bind("expr"), - this); + Finder->addMatcher( + arraySubscriptExpr( + hasBase(ignoringImpCasts(hasType(constantArrayType().bind("type")))), + hasIndex(expr().bind("index")), unless(hasAncestor(isImplicit()))) + .bind("expr"), + this); Finder->addMatcher( cxxOperatorCallExpr( @@ -112,8 +112,7 @@ return; if (Index.isSigned() && Index.isNegative()) { - diag(Matched->getExprLoc(), - "std::array<> index %0 is negative") + diag(Matched->getExprLoc(), "std::array<> index %0 is negative") << Index.toString(10); return; } @@ -130,8 +129,9 @@ // Get uint64_t values, because different bitwidths would lead to an assertion // in APInt::uge. if (Index.getZExtValue() >= ArraySize.getZExtValue()) { - diag(Matched->getExprLoc(), "std::array<> index %0 is past the end of the array " - "(which contains %1 elements)") + diag(Matched->getExprLoc(), + "std::array<> index %0 is past the end of the array " + "(which contains %1 elements)") << Index.toString(10) << ArraySize.toString(10, false); } } Index: clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.cpp =================================================================== --- clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.cpp +++ clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.cpp @@ -47,8 +47,8 @@ this); } -void -ProBoundsPointerArithmeticCheck::check(const MatchFinder::MatchResult &Result) { +void ProBoundsPointerArithmeticCheck::check( + const MatchFinder::MatchResult &Result) { const auto *MatchedExpr = Result.Nodes.getNodeAs("expr"); diag(MatchedExpr->getExprLoc(), "do not use pointer arithmetic"); Index: clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp =================================================================== --- clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp +++ clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp @@ -278,8 +278,7 @@ // AST. Finder->addMatcher( cxxRecordDecl( - isDefinition(), unless(isInstantiated()), - hasDefaultConstructor(), + isDefinition(), unless(isInstantiated()), hasDefaultConstructor(), anyOf(has(cxxConstructorDecl(isDefaultConstructor(), isDefaulted(), unless(isImplicit()))), unless(has(cxxConstructorDecl()))), @@ -465,7 +464,7 @@ << toCommaSeparatedString(AllBases, BasesToInit); if (Ctor) - fixInitializerList(Context, Diag, Ctor, BasesToInit); + fixInitializerList(Context, Diag, Ctor, BasesToInit); } void ProTypeMemberInitCheck::checkUninitializedTrivialType( Index: clang-tidy/cppcoreguidelines/ProTypeStaticCastDowncastCheck.cpp =================================================================== --- clang-tidy/cppcoreguidelines/ProTypeStaticCastDowncastCheck.cpp +++ clang-tidy/cppcoreguidelines/ProTypeStaticCastDowncastCheck.cpp @@ -26,7 +26,8 @@ this); } -void ProTypeStaticCastDowncastCheck::check(const MatchFinder::MatchResult &Result) { +void ProTypeStaticCastDowncastCheck::check( + const MatchFinder::MatchResult &Result) { const auto *MatchedCast = Result.Nodes.getNodeAs("cast"); if (MatchedCast->getCastKind() != CK_BaseToDerived) return; Index: clang-tidy/cppcoreguidelines/ProTypeUnionAccessCheck.cpp =================================================================== --- clang-tidy/cppcoreguidelines/ProTypeUnionAccessCheck.cpp +++ clang-tidy/cppcoreguidelines/ProTypeUnionAccessCheck.cpp @@ -21,15 +21,18 @@ if (!getLangOpts().CPlusPlus) return; - Finder->addMatcher(memberExpr(hasObjectExpression(hasType(recordDecl(isUnion())))).bind("expr"), this); + Finder->addMatcher( + memberExpr(hasObjectExpression(hasType(recordDecl(isUnion())))) + .bind("expr"), + this); } void ProTypeUnionAccessCheck::check(const MatchFinder::MatchResult &Result) { const auto *Matched = Result.Nodes.getNodeAs("expr"); - diag(Matched->getMemberLoc(), "do not access members of unions; use (boost::)variant instead"); + diag(Matched->getMemberLoc(), + "do not access members of unions; use (boost::)variant instead"); } } // namespace cppcoreguidelines } // namespace tidy } // namespace clang - Index: clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp =================================================================== --- clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp +++ clang-tidy/cppcoreguidelines/ProTypeVarargCheck.cpp @@ -26,9 +26,7 @@ Finder->addMatcher(vAArgExpr().bind("va_use"), this); Finder->addMatcher( - callExpr(callee(functionDecl(isVariadic()))) - .bind("callvararg"), - this); + callExpr(callee(functionDecl(isVariadic()))).bind("callvararg"), this); } static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) { Index: clang-tidy/google/AvoidCStyleCastsCheck.cpp =================================================================== --- clang-tidy/google/AvoidCStyleCastsCheck.cpp +++ clang-tidy/google/AvoidCStyleCastsCheck.cpp @@ -20,8 +20,8 @@ namespace google { namespace readability { -void -AvoidCStyleCastsCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { +void AvoidCStyleCastsCheck::registerMatchers( + ast_matchers::MatchFinder *Finder) { Finder->addMatcher( cStyleCastExpr( // Filter out (EnumType)IntegerLiteral construct, which is generated @@ -29,7 +29,8 @@ // FIXME: Remove this once this is fixed in the AST. unless(hasParent(substNonTypeTemplateParmExpr())), // Avoid matches in template instantiations. - unless(isInTemplateInstantiation())).bind("cast"), + unless(isInTemplateInstantiation())) + .bind("cast"), this); } @@ -143,7 +144,7 @@ ReplaceWithCast("const_cast"); return; } - // FALLTHROUGH + // FALLTHROUGH case clang::CK_IntegralCast: // Convert integral and no-op casts between builtin types and enums to // static_cast. A cast from enum to integer may be unnecessary, but it's Index: clang-tidy/google/ExplicitMakePairCheck.cpp =================================================================== --- clang-tidy/google/ExplicitMakePairCheck.cpp +++ clang-tidy/google/ExplicitMakePairCheck.cpp @@ -25,8 +25,8 @@ namespace google { namespace build { -void -ExplicitMakePairCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { +void ExplicitMakePairCheck::registerMatchers( + ast_matchers::MatchFinder *Finder) { // Only register the matchers for C++; the functionality currently does not // provide any benefit to other languages, despite being benign. if (!getLangOpts().CPlusPlus) @@ -39,7 +39,8 @@ callee(expr(ignoringParenImpCasts( declRefExpr(hasExplicitTemplateArgs(), to(functionDecl(hasName("::std::make_pair")))) - .bind("declref"))))).bind("call"), + .bind("declref"))))) + .bind("call"), this); } @@ -61,13 +62,13 @@ Arg1->getType() != Call->getArg(1)->getType()) { diag(Call->getLocStart(), "for C++11-compatibility, use pair directly") << FixItHint::CreateReplacement( - SourceRange(DeclRef->getLocStart(), DeclRef->getLAngleLoc()), - "std::pair<"); + SourceRange(DeclRef->getLocStart(), DeclRef->getLAngleLoc()), + "std::pair<"); } else { diag(Call->getLocStart(), "for C++11-compatibility, omit template arguments from make_pair") << FixItHint::CreateRemoval( - SourceRange(DeclRef->getLAngleLoc(), DeclRef->getRAngleLoc())); + SourceRange(DeclRef->getLAngleLoc(), DeclRef->getRAngleLoc())); } } Index: clang-tidy/google/GlobalNamesInHeadersCheck.cpp =================================================================== --- clang-tidy/google/GlobalNamesInHeadersCheck.cpp +++ clang-tidy/google/GlobalNamesInHeadersCheck.cpp @@ -1,4 +1,5 @@ -//===--- GlobalNamesInHeadersCheck.cpp - clang-tidy -----------------*- C++ -*-===// +//===--- GlobalNamesInHeadersCheck.cpp - clang-tidy -----------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -26,8 +27,7 @@ RawStringHeaderFileExtensions( Options.getLocalOrGlobal("HeaderFileExtensions", "h")) { if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions, - HeaderFileExtensions, - ',')) { + HeaderFileExtensions, ',')) { llvm::errs() << "Invalid header file extension: " << RawStringHeaderFileExtensions << "\n"; } @@ -38,12 +38,12 @@ Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions); } -void -GlobalNamesInHeadersCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { - Finder->addMatcher( - decl(anyOf(usingDecl(), usingDirectiveDecl()), - hasDeclContext(translationUnitDecl())).bind("using_decl"), - this); +void GlobalNamesInHeadersCheck::registerMatchers( + ast_matchers::MatchFinder *Finder) { + Finder->addMatcher(decl(anyOf(usingDecl(), usingDirectiveDecl()), + hasDeclContext(translationUnitDecl())) + .bind("using_decl"), + this); } void GlobalNamesInHeadersCheck::check(const MatchFinder::MatchResult &Result) { @@ -61,7 +61,7 @@ return; } - if (const auto* UsingDirective = dyn_cast(D)) { + if (const auto *UsingDirective = dyn_cast(D)) { if (UsingDirective->getNominatedNamespace()->isAnonymousNamespace()) { // Anynoumous namespaces inject a using directive into the AST to import // the names into the containing namespace. Index: clang-tidy/google/GoogleTidyModule.cpp =================================================================== --- clang-tidy/google/GoogleTidyModule.cpp +++ clang-tidy/google/GoogleTidyModule.cpp @@ -21,8 +21,8 @@ #include "GlobalNamesInHeadersCheck.h" #include "IntegerTypesCheck.h" #include "MemsetZeroLengthCheck.h" -#include "OverloadedUnaryAndCheck.h" #include "NonConstReferences.h" +#include "OverloadedUnaryAndCheck.h" #include "StringReferenceMemberCheck.h" #include "TodoCommentCheck.h" #include "UnnamedNamespaceInHeaderCheck.h" Index: clang-tidy/google/IntegerTypesCheck.cpp =================================================================== --- clang-tidy/google/IntegerTypesCheck.cpp +++ clang-tidy/google/IntegerTypesCheck.cpp @@ -40,7 +40,6 @@ namespace google { namespace runtime { - IntegerTypesCheck::IntegerTypesCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), UnsignedTypePrefix(Options.get("UnsignedTypePrefix", "uint")), Index: clang-tidy/google/MemsetZeroLengthCheck.cpp =================================================================== --- clang-tidy/google/MemsetZeroLengthCheck.cpp +++ clang-tidy/google/MemsetZeroLengthCheck.cpp @@ -1,4 +1,5 @@ -//===--- MemsetZeroLengthCheck.cpp - clang-tidy -------------------*- C++ -*-===// +//===--- MemsetZeroLengthCheck.cpp - clang-tidy -------------------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // @@ -20,15 +21,16 @@ namespace google { namespace runtime { -void -MemsetZeroLengthCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { +void MemsetZeroLengthCheck::registerMatchers( + ast_matchers::MatchFinder *Finder) { // Look for memset(x, y, 0) as those is most likely an argument swap. // TODO: Also handle other standard functions that suffer from the same // problem, e.g. memchr. - Finder->addMatcher( - callExpr(callee(functionDecl(hasName("::memset"))), argumentCountIs(3), - unless(isInTemplateInstantiation())).bind("decl"), - this); + Finder->addMatcher(callExpr(callee(functionDecl(hasName("::memset"))), + argumentCountIs(3), + unless(isInTemplateInstantiation())) + .bind("decl"), + this); } /// \brief Get a StringRef representing a SourceRange. Index: clang-tidy/google/NonConstReferences.cpp =================================================================== --- clang-tidy/google/NonConstReferences.cpp +++ clang-tidy/google/NonConstReferences.cpp @@ -27,8 +27,8 @@ utils::options::parseStringList(Options.get("WhiteListTypes", ""))) {} void NonConstReferences::storeOptions(ClangTidyOptions::OptionMap &Opts) { - Options.store(Opts, "WhiteListTypes", - utils::options::serializeStringList(WhiteListTypes)); + Options.store(Opts, "WhiteListTypes", + utils::options::serializeStringList(WhiteListTypes)); } void NonConstReferences::registerMatchers(MatchFinder *Finder) { @@ -86,41 +86,41 @@ if (Function->isOverloadedOperator()) { switch (Function->getOverloadedOperator()) { - case clang::OO_LessLess: - case clang::OO_PlusPlus: - case clang::OO_MinusMinus: - case clang::OO_PlusEqual: - case clang::OO_MinusEqual: - case clang::OO_StarEqual: - case clang::OO_SlashEqual: - case clang::OO_PercentEqual: - case clang::OO_LessLessEqual: - case clang::OO_GreaterGreaterEqual: - case clang::OO_PipeEqual: - case clang::OO_CaretEqual: - case clang::OO_AmpEqual: - // Don't warn on the first parameter of operator<<(Stream&, ...), - // operator++, operator-- and operation+assignment operators. - if (Function->getParamDecl(0) == Parameter) - return; - break; - case clang::OO_GreaterGreater: { - auto isNonConstRef = [](clang::QualType T) { - return T->isReferenceType() && - !T.getNonReferenceType().isConstQualified(); - }; - // Don't warn on parameters of stream extractors: - // Stream& operator>>(Stream&, Value&); - // Both parameters should be non-const references by convention. - if (isNonConstRef(Function->getParamDecl(0)->getType()) && - (Function->getNumParams() < 2 || // E.g. member operator>>. - isNonConstRef(Function->getParamDecl(1)->getType())) && - isNonConstRef(Function->getReturnType())) - return; - break; - } - default: - break; + case clang::OO_LessLess: + case clang::OO_PlusPlus: + case clang::OO_MinusMinus: + case clang::OO_PlusEqual: + case clang::OO_MinusEqual: + case clang::OO_StarEqual: + case clang::OO_SlashEqual: + case clang::OO_PercentEqual: + case clang::OO_LessLessEqual: + case clang::OO_GreaterGreaterEqual: + case clang::OO_PipeEqual: + case clang::OO_CaretEqual: + case clang::OO_AmpEqual: + // Don't warn on the first parameter of operator<<(Stream&, ...), + // operator++, operator-- and operation+assignment operators. + if (Function->getParamDecl(0) == Parameter) + return; + break; + case clang::OO_GreaterGreater: { + auto isNonConstRef = [](clang::QualType T) { + return T->isReferenceType() && + !T.getNonReferenceType().isConstQualified(); + }; + // Don't warn on parameters of stream extractors: + // Stream& operator>>(Stream&, Value&); + // Both parameters should be non-const references by convention. + if (isNonConstRef(Function->getParamDecl(0)->getType()) && + (Function->getNumParams() < 2 || // E.g. member operator>>. + isNonConstRef(Function->getParamDecl(1)->getType())) && + isNonConstRef(Function->getReturnType())) + return; + break; + } + default: + break; } } @@ -133,9 +133,8 @@ return; if (Parameter->getName().empty()) { - diag(Parameter->getLocation(), - "non-const reference parameter at index %0, " - "make it const or use a pointer") + diag(Parameter->getLocation(), "non-const reference parameter at index %0, " + "make it const or use a pointer") << Parameter->getFunctionScopeIndex(); } else { diag(Parameter->getLocation(), Index: clang-tidy/google/OverloadedUnaryAndCheck.cpp =================================================================== --- clang-tidy/google/OverloadedUnaryAndCheck.cpp +++ clang-tidy/google/OverloadedUnaryAndCheck.cpp @@ -19,8 +19,8 @@ namespace google { namespace runtime { -void -OverloadedUnaryAndCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { +void OverloadedUnaryAndCheck::registerMatchers( + ast_matchers::MatchFinder *Finder) { // Only register the matchers for C++; the functionality currently does not // provide any benefit to other languages, despite being benign. if (!getLangOpts().CPlusPlus) @@ -34,10 +34,10 @@ // Also match freestanding unary operator& overloads. Be careful not to match // binary methods. Finder->addMatcher( - functionDecl( - allOf(unless(cxxMethodDecl()), - functionDecl(parameterCountIs(1), - hasOverloadedOperatorName("&")).bind("overload"))), + functionDecl(allOf( + unless(cxxMethodDecl()), + functionDecl(parameterCountIs(1), hasOverloadedOperatorName("&")) + .bind("overload"))), this); } Index: clang-tidy/google/StringReferenceMemberCheck.cpp =================================================================== --- clang-tidy/google/StringReferenceMemberCheck.cpp +++ clang-tidy/google/StringReferenceMemberCheck.cpp @@ -32,13 +32,13 @@ auto ConstString = qualType(isConstQualified(), hasDeclaration(String)); // Ignore members in template instantiations. - Finder->addMatcher(fieldDecl(hasType(references(ConstString)), - unless(isInstantiated())).bind("member"), - this); + Finder->addMatcher( + fieldDecl(hasType(references(ConstString)), unless(isInstantiated())) + .bind("member"), + this); } -void -StringReferenceMemberCheck::check(const MatchFinder::MatchResult &Result) { +void StringReferenceMemberCheck::check(const MatchFinder::MatchResult &Result) { const auto *Member = Result.Nodes.getNodeAs("member"); diag(Member->getLocStart(), "const string& members are dangerous; it is much " "better to use alternatives, such as pointers or " Index: clang-tidy/google/UnnamedNamespaceInHeaderCheck.cpp =================================================================== --- clang-tidy/google/UnnamedNamespaceInHeaderCheck.cpp +++ clang-tidy/google/UnnamedNamespaceInHeaderCheck.cpp @@ -25,8 +25,7 @@ RawStringHeaderFileExtensions( Options.getLocalOrGlobal("HeaderFileExtensions", "h,hh,hpp,hxx")) { if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions, - HeaderFileExtensions, - ',')) { + HeaderFileExtensions, ',')) { llvm::errs() << "Invalid header file extension: " << RawStringHeaderFileExtensions << "\n"; } @@ -46,8 +45,8 @@ this); } -void -UnnamedNamespaceInHeaderCheck::check(const MatchFinder::MatchResult &Result) { +void UnnamedNamespaceInHeaderCheck::check( + const MatchFinder::MatchResult &Result) { const auto *N = Result.Nodes.getNodeAs("anonymousNamespace"); SourceLocation Loc = N->getLocStart(); if (!Loc.isValid()) Index: clang-tidy/google/UsingNamespaceDirectiveCheck.cpp =================================================================== --- clang-tidy/google/UsingNamespaceDirectiveCheck.cpp +++ clang-tidy/google/UsingNamespaceDirectiveCheck.cpp @@ -27,8 +27,8 @@ Finder->addMatcher(usingDirectiveDecl().bind("usingNamespace"), this); } -void -UsingNamespaceDirectiveCheck::check(const MatchFinder::MatchResult &Result) { +void UsingNamespaceDirectiveCheck::check( + const MatchFinder::MatchResult &Result) { const auto *U = Result.Nodes.getNodeAs("usingNamespace"); SourceLocation Loc = U->getLocStart(); if (U->isImplicit() || !Loc.isValid()) Index: clang-tidy/llvm/HeaderGuardCheck.cpp =================================================================== --- clang-tidy/llvm/HeaderGuardCheck.cpp +++ clang-tidy/llvm/HeaderGuardCheck.cpp @@ -14,7 +14,7 @@ namespace llvm { LLVMHeaderGuardCheck::LLVMHeaderGuardCheck(StringRef Name, - ClangTidyContext* Context) + ClangTidyContext *Context) : HeaderGuardCheck(Name, Context), RawStringHeaderFileExtensions( Options.getLocalOrGlobal("HeaderFileExtensions", ",h,hh,hpp,hxx")) { Index: clang-tidy/misc/ArgumentCommentCheck.cpp =================================================================== --- clang-tidy/misc/ArgumentCommentCheck.cpp +++ clang-tidy/misc/ArgumentCommentCheck.cpp @@ -164,8 +164,8 @@ << Matches[2] << II; if (isLikelyTypo(Callee->parameters(), Matches[2], I)) { Diag << FixItHint::CreateReplacement( - Comment.first, - (Matches[1] + II->getName() + Matches[3]).str()); + Comment.first, + (Matches[1] + II->getName() + Matches[3]).str()); } } diag(PVD->getLocation(), "%0 declared here", DiagnosticIDs::Note) Index: clang-tidy/misc/BoolPointerImplicitConversionCheck.cpp =================================================================== --- clang-tidy/misc/BoolPointerImplicitConversionCheck.cpp +++ clang-tidy/misc/BoolPointerImplicitConversionCheck.cpp @@ -25,7 +25,8 @@ hasType(pointerType(pointee(booleanType()))), ignoringParenImpCasts(declRefExpr().bind("expr")))), hasCastKind(CK_PointerToBoolean))))), - unless(isInTemplateInstantiation())).bind("if"), + unless(isInTemplateInstantiation())) + .bind("if"), this); } Index: clang-tidy/misc/DefinitionsInHeadersCheck.cpp =================================================================== --- clang-tidy/misc/DefinitionsInHeadersCheck.cpp +++ clang-tidy/misc/DefinitionsInHeadersCheck.cpp @@ -35,8 +35,7 @@ RawStringHeaderFileExtensions( Options.getLocalOrGlobal("HeaderFileExtensions", ",h,hh,hpp,hxx")) { if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions, - HeaderFileExtensions, - ',')) { + HeaderFileExtensions, ',')) { // FIXME: Find a more suitable way to handle invalid configuration // options. llvm::errs() << "Invalid header file extension: " Index: clang-tidy/misc/ForwardDeclarationNamespaceCheck.cpp =================================================================== --- clang-tidy/misc/ForwardDeclarationNamespaceCheck.cpp +++ clang-tidy/misc/ForwardDeclarationNamespaceCheck.cpp @@ -8,12 +8,12 @@ //===----------------------------------------------------------------------===// #include "ForwardDeclarationNamespaceCheck.h" -#include -#include #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" +#include +#include using namespace clang::ast_matchers; Index: clang-tidy/misc/IncorrectRoundings.cpp =================================================================== --- clang-tidy/misc/IncorrectRoundings.cpp +++ clang-tidy/misc/IncorrectRoundings.cpp @@ -31,7 +31,6 @@ } } // namespace - void IncorrectRoundings::registerMatchers(MatchFinder *MatchFinder) { // Match a floating literal with value 0.5. auto FloatHalf = floatLiteral(floatHalf()); Index: clang-tidy/misc/MacroParenthesesCheck.cpp =================================================================== --- clang-tidy/misc/MacroParenthesesCheck.cpp +++ clang-tidy/misc/MacroParenthesesCheck.cpp @@ -79,7 +79,8 @@ if (Tok == MI->tokens_end()) return false; - // If we see int/short/struct/etc., just assume this is a variable declaration. + // If we see int/short/struct/etc., just assume this is a variable + // declaration. if (isVarDeclKeyword(*Tok)) return true; @@ -88,10 +89,10 @@ return false; // Skip possible types, etc - while ( - Tok != MI->tokens_end() && - Tok->isOneOf(tok::identifier, tok::raw_identifier, tok::coloncolon, - tok::star, tok::amp, tok::ampamp, tok::less, tok::greater)) + while (Tok != MI->tokens_end() && + Tok->isOneOf(tok::identifier, tok::raw_identifier, tok::coloncolon, + tok::star, tok::amp, tok::ampamp, tok::less, + tok::greater)) Tok++; // Return true for possible variable declarations. Index: clang-tidy/misc/MacroRepeatedSideEffectsCheck.cpp =================================================================== --- clang-tidy/misc/MacroRepeatedSideEffectsCheck.cpp +++ clang-tidy/misc/MacroRepeatedSideEffectsCheck.cpp @@ -9,9 +9,9 @@ #include "MacroRepeatedSideEffectsCheck.h" #include "clang/Frontend/CompilerInstance.h" +#include "clang/Lex/MacroArgs.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/Preprocessor.h" -#include "clang/Lex/MacroArgs.h" namespace clang { namespace tidy { Index: clang-tidy/misc/MiscTidyModule.cpp =================================================================== --- clang-tidy/misc/MiscTidyModule.cpp +++ clang-tidy/misc/MiscTidyModule.cpp @@ -12,8 +12,6 @@ #include "../ClangTidyModuleRegistry.h" #include "ArgumentCommentCheck.h" #include "AssertSideEffectCheck.h" -#include "MisplacedConstCheck.h" -#include "UnconventionalAssignOperatorCheck.h" #include "BoolPointerImplicitConversionCheck.h" #include "DanglingHandleCheck.h" #include "DefinitionsInHeadersCheck.h" @@ -24,6 +22,7 @@ #include "InefficientAlgorithmCheck.h" #include "MacroParenthesesCheck.h" #include "MacroRepeatedSideEffectsCheck.h" +#include "MisplacedConstCheck.h" #include "MisplacedWideningCastCheck.h" #include "MoveConstantArgumentCheck.h" #include "MoveConstructorInitCheck.h" @@ -44,6 +43,7 @@ #include "SuspiciousStringCompareCheck.h" #include "SwappedArgumentsCheck.h" #include "ThrowByValueCatchByReferenceCheck.h" +#include "UnconventionalAssignOperatorCheck.h" #include "UndelegatedConstructor.h" #include "UniqueptrResetReleaseCheck.h" #include "UnusedAliasDeclsCheck.h" @@ -63,22 +63,18 @@ CheckFactories.registerCheck("misc-argument-comment"); CheckFactories.registerCheck( "misc-assert-side-effect"); - CheckFactories.registerCheck( - "misc-misplaced-const"); + CheckFactories.registerCheck("misc-misplaced-const"); CheckFactories.registerCheck( "misc-unconventional-assign-operator"); CheckFactories.registerCheck( "misc-bool-pointer-implicit-conversion"); - CheckFactories.registerCheck( - "misc-dangling-handle"); + CheckFactories.registerCheck("misc-dangling-handle"); CheckFactories.registerCheck( "misc-definitions-in-headers"); - CheckFactories.registerCheck( - "misc-fold-init-type"); + CheckFactories.registerCheck("misc-fold-init-type"); CheckFactories.registerCheck( "misc-forward-declaration-namespace"); - CheckFactories.registerCheck( - "misc-inaccurate-erase"); + CheckFactories.registerCheck("misc-inaccurate-erase"); CheckFactories.registerCheck( "misc-incorrect-roundings"); CheckFactories.registerCheck( @@ -108,8 +104,7 @@ CheckFactories.registerCheck("misc-sizeof-container"); CheckFactories.registerCheck( "misc-sizeof-expression"); - CheckFactories.registerCheck( - "misc-static-assert"); + CheckFactories.registerCheck("misc-static-assert"); CheckFactories.registerCheck( "misc-string-constructor"); CheckFactories.registerCheck( @@ -147,7 +142,7 @@ // Register the MiscTidyModule using this statically initialized variable. static ClangTidyModuleRegistry::Add -X("misc-module", "Adds miscellaneous lint checks."); + X("misc-module", "Adds miscellaneous lint checks."); // This anchor is used to force the linker to link in the generated object file // and thus register the MiscModule. Index: clang-tidy/misc/MisplacedWideningCastCheck.cpp =================================================================== --- clang-tidy/misc/MisplacedWideningCastCheck.cpp +++ clang-tidy/misc/MisplacedWideningCastCheck.cpp @@ -8,9 +8,9 @@ //===----------------------------------------------------------------------===// #include "MisplacedWideningCastCheck.h" +#include "../utils/Matchers.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" -#include "../utils/Matchers.h" using namespace clang::ast_matchers; @@ -49,8 +49,7 @@ Finder->addMatcher(callExpr(hasAnyArgument(Cast)), this); Finder->addMatcher(binaryOperator(hasOperatorName("="), hasRHS(Cast)), this); Finder->addMatcher( - binaryOperator(matchers::isComparisonOperator(), - hasEitherOperand(Cast)), + binaryOperator(matchers::isComparisonOperator(), hasEitherOperand(Cast)), this); } Index: clang-tidy/misc/MoveConstantArgumentCheck.cpp =================================================================== --- clang-tidy/misc/MoveConstantArgumentCheck.cpp +++ clang-tidy/misc/MoveConstantArgumentCheck.cpp @@ -83,8 +83,8 @@ "has no effect; remove std::move()" "%select{| or make the variable non-const}3") << IsConstArg << IsVariable << IsTriviallyCopyable - << (IsConstArg && IsVariable && !IsTriviallyCopyable) - << Var << Arg->getType(); + << (IsConstArg && IsVariable && !IsTriviallyCopyable) << Var + << Arg->getType(); ReplaceCallWithArg(CallMove, Diag, SM, getLangOpts()); } else if (ReceivingExpr) { Index: clang-tidy/misc/MoveConstructorInitCheck.cpp =================================================================== --- clang-tidy/misc/MoveConstructorInitCheck.cpp +++ clang-tidy/misc/MoveConstructorInitCheck.cpp @@ -126,7 +126,8 @@ void MoveConstructorInitCheck::handleMoveConstructor( const MatchFinder::MatchResult &Result) { const auto *CopyCtor = Result.Nodes.getNodeAs("ctor"); - const auto *Initializer = Result.Nodes.getNodeAs("move-init"); + const auto *Initializer = + Result.Nodes.getNodeAs("move-init"); // Do not diagnose if the expression used to perform the initialization is a // trivially-copyable type. Index: clang-tidy/misc/MultipleStatementMacroCheck.cpp =================================================================== --- clang-tidy/misc/MultipleStatementMacroCheck.cpp +++ clang-tidy/misc/MultipleStatementMacroCheck.cpp @@ -29,7 +29,7 @@ const Stmt *Parent = Parents[0].get(); if (!Parent) return nullptr; - const Stmt* Prev = nullptr; + const Stmt *Prev = nullptr; for (const Stmt *Child : Parent->children()) { if (Prev == S) return Child; @@ -53,7 +53,7 @@ return Locs; } -} // namespace +} // namespace void MultipleStatementMacroCheck::registerMatchers(MatchFinder *Finder) { const auto Inner = expr(isInMacro(), unless(compoundStmt())).bind("inner"); Index: clang-tidy/misc/NewDeleteOverloadsCheck.cpp =================================================================== --- clang-tidy/misc/NewDeleteOverloadsCheck.cpp +++ clang-tidy/misc/NewDeleteOverloadsCheck.cpp @@ -64,7 +64,8 @@ OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) { switch (FD->getOverloadedOperator()) { - default: break; + default: + break; case OO_New: return OO_Delete; case OO_Delete: @@ -79,7 +80,8 @@ const char *getOperatorName(OverloadedOperatorKind K) { switch (K) { - default: break; + default: + break; case OO_New: return "operator new"; case OO_Delete: @@ -140,13 +142,12 @@ // However, I think it's more reasonable to warn in this case as the user // should really be writing that as a deleted function. Finder->addMatcher( - functionDecl( - unless(anyOf(isImplicit(), isPlacementOverload(), isDeleted(), - cxxMethodDecl(isPrivate()))), - anyOf(hasOverloadedOperatorName("new"), - hasOverloadedOperatorName("new[]"), - hasOverloadedOperatorName("delete"), - hasOverloadedOperatorName("delete[]"))) + functionDecl(unless(anyOf(isImplicit(), isPlacementOverload(), + isDeleted(), cxxMethodDecl(isPrivate()))), + anyOf(hasOverloadedOperatorName("new"), + hasOverloadedOperatorName("new[]"), + hasOverloadedOperatorName("delete"), + hasOverloadedOperatorName("delete[]"))) .bind("func"), this); } Index: clang-tidy/misc/NoexceptMoveConstructorCheck.cpp =================================================================== --- clang-tidy/misc/NoexceptMoveConstructorCheck.cpp +++ clang-tidy/misc/NoexceptMoveConstructorCheck.cpp @@ -43,27 +43,27 @@ } const auto *ProtoType = Decl->getType()->getAs(); - switch(ProtoType->getNoexceptSpec(*Result.Context)) { - case FunctionProtoType::NR_NoNoexcept: - diag(Decl->getLocation(), "move %0s should be marked noexcept") + switch (ProtoType->getNoexceptSpec(*Result.Context)) { + case FunctionProtoType::NR_NoNoexcept: + diag(Decl->getLocation(), "move %0s should be marked noexcept") + << MethodType; + // FIXME: Add a fixit. + break; + case FunctionProtoType::NR_Throw: + // Don't complain about nothrow(false), but complain on nothrow(expr) + // where expr evaluates to false. + if (const Expr *E = ProtoType->getNoexceptExpr()) { + if (isa(E)) + break; + diag(E->getExprLoc(), + "noexcept specifier on the move %0 evaluates to 'false'") << MethodType; - // FIXME: Add a fixit. - break; - case FunctionProtoType::NR_Throw: - // Don't complain about nothrow(false), but complain on nothrow(expr) - // where expr evaluates to false. - if (const Expr *E = ProtoType->getNoexceptExpr()) { - if (isa(E)) - break; - diag(E->getExprLoc(), - "noexcept specifier on the move %0 evaluates to 'false'") - << MethodType; - } - break; - case FunctionProtoType::NR_Nothrow: - case FunctionProtoType::NR_Dependent: - case FunctionProtoType::NR_BadNoexcept: - break; + } + break; + case FunctionProtoType::NR_Nothrow: + case FunctionProtoType::NR_Dependent: + case FunctionProtoType::NR_BadNoexcept: + break; } } } @@ -71,4 +71,3 @@ } // namespace misc } // namespace tidy } // namespace clang - Index: clang-tidy/misc/NonCopyableObjects.cpp =================================================================== --- clang-tidy/misc/NonCopyableObjects.cpp +++ clang-tidy/misc/NonCopyableObjects.cpp @@ -23,22 +23,15 @@ // users can add their own elements to the list. However, it may require some // extra thought since POSIX types and FILE types are usable in different ways. bool isPOSIXTypeName(StringRef ClassName) { - static const char *const TypeNames[] = { - "::pthread_cond_t", - "::pthread_mutex_t", - "pthread_cond_t", - "pthread_mutex_t" - }; + static const char *const TypeNames[] = {"::pthread_cond_t", + "::pthread_mutex_t", "pthread_cond_t", + "pthread_mutex_t"}; return std::binary_search(std::begin(TypeNames), std::end(TypeNames), ClassName); } bool isFILETypeName(StringRef ClassName) { - static const char *const TypeNames[] = { - "::FILE", - "FILE", - "std::FILE" - }; + static const char *const TypeNames[] = {"::FILE", "FILE", "std::FILE"}; return std::binary_search(std::begin(TypeNames), std::end(TypeNames), ClassName); } @@ -96,4 +89,3 @@ } // namespace misc } // namespace tidy } // namespace clang - Index: clang-tidy/misc/SizeofContainerCheck.cpp =================================================================== --- clang-tidy/misc/SizeofContainerCheck.cpp +++ clang-tidy/misc/SizeofContainerCheck.cpp @@ -47,4 +47,3 @@ } // namespace misc } // namespace tidy } // namespace clang - Index: clang-tidy/misc/SizeofExpressionCheck.cpp =================================================================== --- clang-tidy/misc/SizeofExpressionCheck.cpp +++ clang-tidy/misc/SizeofExpressionCheck.cpp @@ -8,9 +8,9 @@ //===----------------------------------------------------------------------===// #include "SizeofExpressionCheck.h" +#include "../utils/Matchers.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" -#include "../utils/Matchers.h" using namespace clang::ast_matchers; Index: clang-tidy/misc/SuspiciousMissingCommaCheck.cpp =================================================================== --- clang-tidy/misc/SuspiciousMissingCommaCheck.cpp +++ clang-tidy/misc/SuspiciousMissingCommaCheck.cpp @@ -19,8 +19,8 @@ namespace { -bool isConcatenatedLiteralsOnPurpose(ASTContext* Ctx, - const StringLiteral* Lit) { +bool isConcatenatedLiteralsOnPurpose(ASTContext *Ctx, + const StringLiteral *Lit) { // String literals surrounded by parentheses are assumed to be on purpose. // i.e.: const char* Array[] = { ("a" "b" "c"), "d", [...] }; auto Parents = Ctx->getParents(*Lit); @@ -36,13 +36,13 @@ // "second literal", // [...] // }; - const SourceManager& SM = Ctx->getSourceManager(); + const SourceManager &SM = Ctx->getSourceManager(); bool IndentedCorrectly = true; SourceLocation FirstToken = Lit->getStrTokenLoc(0); FileID BaseFID = SM.getFileID(FirstToken); unsigned int BaseIndent = SM.getSpellingColumnNumber(FirstToken); unsigned int BaseLine = SM.getSpellingLineNumber(FirstToken); - for (unsigned int TokNum = 1; TokNum < Lit->getNumConcatenated(); ++ TokNum) { + for (unsigned int TokNum = 1; TokNum < Lit->getNumConcatenated(); ++TokNum) { SourceLocation Token = Lit->getStrTokenLoc(TokNum); FileID FID = SM.getFileID(Token); unsigned int Indent = SM.getSpellingColumnNumber(Token); @@ -59,14 +59,14 @@ return false; } -AST_MATCHER_P(StringLiteral, isConcatenatedLiteral, - unsigned, MaxConcatenatedTokens) { +AST_MATCHER_P(StringLiteral, isConcatenatedLiteral, unsigned, + MaxConcatenatedTokens) { return Node.getNumConcatenated() > 1 && Node.getNumConcatenated() < MaxConcatenatedTokens && !isConcatenatedLiteralsOnPurpose(&Finder->getASTContext(), &Node); } -} // namespace +} // namespace SuspiciousMissingCommaCheck::SuspiciousMissingCommaCheck( StringRef Name, ClangTidyContext *Context) @@ -102,25 +102,28 @@ // Skip small arrays as they often generate false-positive. unsigned int Size = InitializerList->getNumInits(); - if (Size < SizeThreshold) return; + if (Size < SizeThreshold) + return; // Count the number of occurence of concatenated string literal. unsigned int Count = 0; for (unsigned int i = 0; i < Size; ++i) { const Expr *Child = InitializerList->getInit(i)->IgnoreImpCasts(); if (const auto *Literal = dyn_cast(Child)) { - if (Literal->getNumConcatenated() > 1) ++Count; + if (Literal->getNumConcatenated() > 1) + ++Count; } } // Warn only when concatenation is not common in this initializer list. // The current threshold is set to less than 1/5 of the string literals. - if (double(Count) / Size > RatioThreshold) return; + if (double(Count) / Size > RatioThreshold) + return; diag(ConcatenatedLiteral->getLocStart(), "suspicious string literal, probably missing a comma"); } -} // namespace misc -} // namespace tidy -} // namespace clang +} // namespace misc +} // namespace tidy +} // namespace clang Index: clang-tidy/misc/SuspiciousStringCompareCheck.cpp =================================================================== --- clang-tidy/misc/SuspiciousStringCompareCheck.cpp +++ clang-tidy/misc/SuspiciousStringCompareCheck.cpp @@ -20,7 +20,6 @@ namespace tidy { namespace misc { - // Semicolon separated list of known string compare-like functions. The list // must ends with a semicolon. static const char KnownStringCompareFunctions[] = "__builtin_memcmp;" @@ -104,13 +103,12 @@ .bind("decl"); const auto DirectStringCompareCallExpr = callExpr(hasDeclaration(FunctionCompareDecl)).bind("call"); - const auto MacroStringCompareCallExpr = - conditionalOperator( - anyOf(hasTrueExpression(ignoringParenImpCasts(DirectStringCompareCallExpr)), - hasFalseExpression(ignoringParenImpCasts(DirectStringCompareCallExpr)))); + const auto MacroStringCompareCallExpr = conditionalOperator(anyOf( + hasTrueExpression(ignoringParenImpCasts(DirectStringCompareCallExpr)), + hasFalseExpression(ignoringParenImpCasts(DirectStringCompareCallExpr)))); // The implicit cast is not present in C. const auto StringCompareCallExpr = ignoringParenImpCasts( - anyOf(DirectStringCompareCallExpr, MacroStringCompareCallExpr)); + anyOf(DirectStringCompareCallExpr, MacroStringCompareCallExpr)); if (WarnOnImplicitComparison) { // Detect suspicious calls to string compare: @@ -203,7 +201,8 @@ << Decl; } - if (const auto* BinOp = Result.Nodes.getNodeAs("suspicious-operator")) { + if (const auto *BinOp = + Result.Nodes.getNodeAs("suspicious-operator")) { diag(Call->getLocStart(), "results of function %0 used by operator '%1'") << Decl << BinOp->getOpcodeStr(); } Index: clang-tidy/misc/ThrowByValueCatchByReferenceCheck.cpp =================================================================== --- clang-tidy/misc/ThrowByValueCatchByReferenceCheck.cpp +++ clang-tidy/misc/ThrowByValueCatchByReferenceCheck.cpp @@ -9,8 +9,8 @@ #include "ThrowByValueCatchByReferenceCheck.h" #include "clang/AST/ASTContext.h" -#include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/AST/OperationKinds.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" using namespace clang::ast_matchers; Index: clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp =================================================================== --- clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp +++ clang-tidy/misc/UnconventionalAssignOperatorCheck.cpp @@ -17,7 +17,8 @@ namespace tidy { namespace misc { -void UnconventionalAssignOperatorCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { +void UnconventionalAssignOperatorCheck::registerMatchers( + ast_matchers::MatchFinder *Finder) { // Only register the matchers for C++; the functionality currently does not // provide any benefit to other languages, despite being benign. if (!getLangOpts().CPlusPlus) @@ -65,7 +66,8 @@ this); } -void UnconventionalAssignOperatorCheck::check(const MatchFinder::MatchResult &Result) { +void UnconventionalAssignOperatorCheck::check( + const MatchFinder::MatchResult &Result) { if (const auto *RetStmt = Result.Nodes.getNodeAs("returnStmt")) { diag(RetStmt->getLocStart(), "operator=() should always return '*this'"); } else { Index: clang-tidy/misc/UndelegatedConstructor.cpp =================================================================== --- clang-tidy/misc/UndelegatedConstructor.cpp +++ clang-tidy/misc/UndelegatedConstructor.cpp @@ -72,7 +72,8 @@ this); } -void UndelegatedConstructorCheck::check(const MatchFinder::MatchResult &Result) { +void UndelegatedConstructorCheck::check( + const MatchFinder::MatchResult &Result) { const auto *E = Result.Nodes.getStmtAs("construct"); diag(E->getLocStart(), "did you intend to call a delegated constructor? " "A temporary object is created here instead"); Index: clang-tidy/misc/UniqueptrResetReleaseCheck.cpp =================================================================== --- clang-tidy/misc/UniqueptrResetReleaseCheck.cpp +++ clang-tidy/misc/UniqueptrResetReleaseCheck.cpp @@ -91,7 +91,7 @@ return false; } -} // namespace +} // namespace void UniqueptrResetReleaseCheck::check(const MatchFinder::MatchResult &Result) { if (!areDeletersCompatible(Result)) @@ -127,9 +127,8 @@ } std::string NewText = LeftText + " = " + RightText; - diag(ResetMember->getExprLoc(), DiagText) - << FixItHint::CreateReplacement( - CharSourceRange::getTokenRange(ResetCall->getSourceRange()), NewText); + diag(ResetMember->getExprLoc(), DiagText) << FixItHint::CreateReplacement( + CharSourceRange::getTokenRange(ResetCall->getSourceRange()), NewText); } } // namespace misc Index: clang-tidy/misc/UnusedParametersCheck.cpp =================================================================== --- clang-tidy/misc/UnusedParametersCheck.cpp +++ clang-tidy/misc/UnusedParametersCheck.cpp @@ -107,8 +107,7 @@ void UnusedParametersCheck::check(const MatchFinder::MatchResult &Result) { const auto *Function = Result.Nodes.getNodeAs("function"); if (!Function->doesThisDeclarationHaveABody() || - !Function->hasWrittenPrototype() || - Function->isTemplateInstantiation()) + !Function->hasWrittenPrototype() || Function->isTemplateInstantiation()) return; if (const auto *Method = dyn_cast(Function)) if (Method->isLambdaStaticInvoker()) Index: clang-tidy/misc/UnusedUsingDeclsCheck.cpp =================================================================== --- clang-tidy/misc/UnusedUsingDeclsCheck.cpp +++ clang-tidy/misc/UnusedUsingDeclsCheck.cpp @@ -42,8 +42,9 @@ anyOf(refersToTemplate(templateName().bind("used")), refersToDeclaration(functionDecl().bind("used"))))))), this); - Finder->addMatcher(loc(templateSpecializationType( - hasAnyTemplateArgument(templateArgument().bind("used")))), this); + Finder->addMatcher(loc(templateSpecializationType(hasAnyTemplateArgument( + templateArgument().bind("used")))), + this); } void UnusedUsingDeclsCheck::check(const MatchFinder::MatchResult &Result) { @@ -126,7 +127,7 @@ } // Check the uninstantiated template function usage. if (const auto *ULE = Result.Nodes.getNodeAs("used")) { - for (const NamedDecl* ND : ULE->decls()) { + for (const NamedDecl *ND : ULE->decls()) { if (const auto *USD = dyn_cast(ND)) removeFromFoundDecls(USD->getTargetDecl()->getCanonicalDecl()); } Index: clang-tidy/misc/UseAfterMoveCheck.cpp =================================================================== --- clang-tidy/misc/UseAfterMoveCheck.cpp +++ clang-tidy/misc/UseAfterMoveCheck.cpp @@ -604,8 +604,7 @@ } } -static void emitDiagnostic(const Expr *MovingCall, - const DeclRefExpr *MoveArg, +static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg, const UseAfterMove &Use, ClangTidyCheck *Check, ASTContext *Context) { SourceLocation UseLoc = Use.DeclRef->getExprLoc(); @@ -631,12 +630,11 @@ return; auto CallMoveMatcher = - callExpr( - callee(functionDecl(hasName("::std::move"))), argumentCountIs(1), - hasArgument(0, declRefExpr().bind("arg")), - anyOf(hasAncestor(lambdaExpr().bind("containing-lambda")), - hasAncestor(functionDecl().bind("containing-func"))), - unless(inDecltypeOrTemplateArg())) + callExpr(callee(functionDecl(hasName("::std::move"))), argumentCountIs(1), + hasArgument(0, declRefExpr().bind("arg")), + anyOf(hasAncestor(lambdaExpr().bind("containing-lambda")), + hasAncestor(functionDecl().bind("containing-func"))), + unless(inDecltypeOrTemplateArg())) .bind("call-move"); Finder->addMatcher( Index: clang-tidy/modernize/AvoidBindCheck.cpp =================================================================== --- clang-tidy/modernize/AvoidBindCheck.cpp +++ clang-tidy/modernize/AvoidBindCheck.cpp @@ -154,7 +154,7 @@ addPlaceholderArgs(Args, Stream); Stream << " { return "; Ref->printPretty(Stream, nullptr, Result.Context->getPrintingPolicy()); - Stream<< "("; + Stream << "("; addFunctionCallArgs(Args, Stream); Stream << "); };"; Index: clang-tidy/modernize/ModernizeTidyModule.cpp =================================================================== --- clang-tidy/modernize/ModernizeTidyModule.cpp +++ clang-tidy/modernize/ModernizeTidyModule.cpp @@ -37,8 +37,7 @@ class ModernizeModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { - CheckFactories.registerCheck( - "modernize-avoid-bind"); + CheckFactories.registerCheck("modernize-avoid-bind"); CheckFactories.registerCheck( "modernize-deprecated-headers"); CheckFactories.registerCheck("modernize-loop-convert"); Index: clang-tidy/modernize/RawStringLiteralCheck.cpp =================================================================== --- clang-tidy/modernize/RawStringLiteralCheck.cpp +++ clang-tidy/modernize/RawStringLiteralCheck.cpp @@ -133,7 +133,7 @@ diag(Literal->getLocStart(), "escaped string literal can be written as a raw string literal") << FixItHint::CreateReplacement( - CharRange, asRawStringLiteral(Literal, DelimiterStem)); + CharRange, asRawStringLiteral(Literal, DelimiterStem)); } } // namespace modernize Index: clang-tidy/modernize/UseAutoCheck.cpp =================================================================== --- clang-tidy/modernize/UseAutoCheck.cpp +++ clang-tidy/modernize/UseAutoCheck.cpp @@ -9,8 +9,8 @@ #include "UseAutoCheck.h" #include "clang/AST/ASTContext.h" -#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" using namespace clang; using namespace clang::ast_matchers; @@ -114,20 +114,19 @@ /// recordDecl(hasStdContainerName()) matches \c vector and \c forward_list /// but not \c my_vec. AST_MATCHER(NamedDecl, hasStdContainerName) { - static const char *const ContainerNames[] = {"array", "deque", - "forward_list", "list", - "vector", + static const char *const ContainerNames[] = { + "array", "deque", + "forward_list", "list", + "vector", - "map", "multimap", - "set", "multiset", + "map", "multimap", + "set", "multiset", - "unordered_map", - "unordered_multimap", - "unordered_set", - "unordered_multiset", + "unordered_map", "unordered_multimap", + "unordered_set", "unordered_multiset", - "queue", "priority_queue", - "stack"}; + "queue", "priority_queue", + "stack"}; for (const char *Name : ContainerNames) { if (hasName(Name).matches(Node, Finder, Builder)) Index: clang-tidy/modernize/UseNullptrCheck.cpp =================================================================== --- clang-tidy/modernize/UseNullptrCheck.cpp +++ clang-tidy/modernize/UseNullptrCheck.cpp @@ -38,8 +38,7 @@ /// can be replaced instead of just the inner-most implicit cast. StatementMatcher makeCastSequenceMatcher() { StatementMatcher ImplicitCastToNull = implicitCastExpr( - anyOf(hasCastKind(CK_NullToPointer), - hasCastKind(CK_NullToMemberPointer)), + anyOf(hasCastKind(CK_NullToPointer), hasCastKind(CK_NullToMemberPointer)), unless(hasSourceExpression(hasType(sugaredNullptrType())))); return castExpr(anyOf(ImplicitCastToNull, Index: clang-tidy/performance/FasterStringFindCheck.cpp =================================================================== --- clang-tidy/performance/FasterStringFindCheck.cpp +++ clang-tidy/performance/FasterStringFindCheck.cpp @@ -30,10 +30,12 @@ } // Now replace the " with '. auto pos = Result.find_first_of('"'); - if (pos == Result.npos) return llvm::None; + if (pos == Result.npos) + return llvm::None; Result[pos] = '\''; pos = Result.find_last_of('"'); - if (pos == Result.npos) return llvm::None; + if (pos == Result.npos) + return llvm::None; Result[pos] = '\''; return Result; } @@ -50,8 +52,7 @@ ClangTidyContext *Context) : ClangTidyCheck(Name, Context), StringLikeClasses(utils::options::parseStringList( - Options.get("StringLikeClasses", "std::basic_string"))) { -} + Options.get("StringLikeClasses", "std::basic_string"))) {} void FasterStringFindCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "StringLikeClasses", Index: clang-tidy/performance/ImplicitCastInLoopCheck.cpp =================================================================== --- clang-tidy/performance/ImplicitCastInLoopCheck.cpp +++ clang-tidy/performance/ImplicitCastInLoopCheck.cpp @@ -29,7 +29,7 @@ bool IsNonTrivialImplicitCast(const Stmt *ST) { if (const auto *ICE = dyn_cast(ST)) { return (ICE->getCastKind() != CK_NoOp) || - IsNonTrivialImplicitCast(ICE->getSubExpr()); + IsNonTrivialImplicitCast(ICE->getSubExpr()); } return false; } Index: clang-tidy/performance/UnnecessaryCopyInitialization.cpp =================================================================== --- clang-tidy/performance/UnnecessaryCopyInitialization.cpp +++ clang-tidy/performance/UnnecessaryCopyInitialization.cpp @@ -27,7 +27,6 @@ } // namespace - using namespace ::clang::ast_matchers; using utils::decl_ref_expr::isOnlyUsedAsConst; @@ -44,9 +43,9 @@ // variable being declared. The assumption is that the const reference being // returned either points to a global static variable or to a member of the // called object. - auto ConstRefReturningMethodCall = cxxMemberCallExpr( - callee(cxxMethodDecl(returns(ConstReference))), - on(declRefExpr(to(varDecl().bind("objectArg"))))); + auto ConstRefReturningMethodCall = + cxxMemberCallExpr(callee(cxxMethodDecl(returns(ConstReference))), + on(declRefExpr(to(varDecl().bind("objectArg"))))); auto ConstRefReturningFunctionCall = callExpr(callee(functionDecl(returns(ConstReference))), unless(callee(cxxMethodDecl()))); @@ -63,14 +62,14 @@ isCopyConstructor())), hasArgument(0, CopyCtorArg)) .bind("ctorCall"))) - .bind("newVarDecl"))).bind("declStmt"))) + .bind("newVarDecl"))) + .bind("declStmt"))) .bind("blockStmt"); }; - Finder->addMatcher( - localVarCopiedFrom(anyOf(ConstRefReturningFunctionCall, - ConstRefReturningMethodCall)), - this); + Finder->addMatcher(localVarCopiedFrom(anyOf(ConstRefReturningFunctionCall, + ConstRefReturningMethodCall)), + this); Finder->addMatcher(localVarCopiedFrom(declRefExpr( to(varDecl(hasLocalStorage()).bind("oldVarDecl")))), Index: clang-tidy/performance/UnnecessaryValueParamCheck.cpp =================================================================== --- clang-tidy/performance/UnnecessaryValueParamCheck.cpp +++ clang-tidy/performance/UnnecessaryValueParamCheck.cpp @@ -127,7 +127,7 @@ FunctionDecl = FunctionDecl->getPreviousDecl()) { const auto &CurrentParam = *FunctionDecl->getParamDecl(Index); Diag << utils::fixit::changeVarDeclToReference(CurrentParam, - *Result.Context); + *Result.Context); // The parameter of each declaration needs to be checked individually as to // whether it is const or not as constness can differ between definition and // declaration. Index: clang-tidy/readability/AvoidConstParamsInDecls.cpp =================================================================== --- clang-tidy/readability/AvoidConstParamsInDecls.cpp +++ clang-tidy/readability/AvoidConstParamsInDecls.cpp @@ -8,10 +8,10 @@ //===----------------------------------------------------------------------===// #include "AvoidConstParamsInDecls.h" -#include "llvm/ADT/Optional.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Lex/Lexer.h" +#include "llvm/ADT/Optional.h" using namespace clang::ast_matchers; Index: clang-tidy/readability/BracesAroundStatementsCheck.cpp =================================================================== --- clang-tidy/readability/BracesAroundStatementsCheck.cpp +++ clang-tidy/readability/BracesAroundStatementsCheck.cpp @@ -117,8 +117,8 @@ // Always add braces by default. ShortStatementLines(Options.get("ShortStatementLines", 0U)) {} -void -BracesAroundStatementsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { +void BracesAroundStatementsCheck::storeOptions( + ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "ShortStatementLines", ShortStatementLines); } @@ -130,8 +130,8 @@ Finder->addMatcher(cxxForRangeStmt().bind("for-range"), this); } -void -BracesAroundStatementsCheck::check(const MatchFinder::MatchResult &Result) { +void BracesAroundStatementsCheck::check( + const MatchFinder::MatchResult &Result) { const SourceManager &SM = *Result.SourceManager; const ASTContext *Context = Result.Context; Index: clang-tidy/readability/IdentifierNamingCheck.cpp =================================================================== --- clang-tidy/readability/IdentifierNamingCheck.cpp +++ clang-tidy/readability/IdentifierNamingCheck.cpp @@ -9,13 +9,13 @@ #include "IdentifierNamingCheck.h" -#include "llvm/ADT/DenseMapInfo.h" -#include "llvm/Support/Debug.h" -#include "llvm/Support/Format.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/Preprocessor.h" +#include "llvm/ADT/DenseMapInfo.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/Format.h" #define DEBUG_TYPE "clang-tidy" @@ -662,7 +662,8 @@ /// Convenience method when the usage to be added is a NamedDecl static void addUsage(IdentifierNamingCheck::NamingCheckFailureMap &Failures, - const NamedDecl *Decl, SourceRange Range, SourceManager *SourceMgr = nullptr) { + const NamedDecl *Decl, SourceRange Range, + SourceManager *SourceMgr = nullptr) { return addUsage(Failures, IdentifierNamingCheck::NamingCheckId( Decl->getLocation(), Decl->getNameAsString()), Range, SourceMgr); @@ -752,7 +753,8 @@ if (const auto *DeclRef = Result.Nodes.getNodeAs("declRef")) { SourceRange Range = DeclRef->getNameInfo().getSourceRange(); - addUsage(NamingCheckFailures, DeclRef->getDecl(), Range, Result.SourceManager); + addUsage(NamingCheckFailures, DeclRef->getDecl(), Range, + Result.SourceManager); return; } Index: clang-tidy/readability/ImplicitBoolCastCheck.cpp =================================================================== --- clang-tidy/readability/ImplicitBoolCastCheck.cpp +++ clang-tidy/readability/ImplicitBoolCastCheck.cpp @@ -307,8 +307,7 @@ AllowConditionalPointerCasts( Options.get("AllowConditionalPointerCasts", false)) {} -void ImplicitBoolCastCheck::storeOptions( - ClangTidyOptions::OptionMap &Opts) { +void ImplicitBoolCastCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "AllowConditionalIntegerCasts", AllowConditionalIntegerCasts); Options.store(Opts, "AllowConditionalPointerCasts", Index: clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp =================================================================== --- clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp +++ clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp @@ -110,7 +110,8 @@ SourceParamName != OtherParamName) { SourceRange OtherParamNameRange = DeclarationNameInfo((*OtherParamIt)->getDeclName(), - (*OtherParamIt)->getLocation()).getSourceRange(); + (*OtherParamIt)->getLocation()) + .getSourceRange(); bool GenerateFixItHint = checkIfFixItHintIsApplicable( ParameterSourceDeclaration, *SourceParamIt, OriginalDeclaration); @@ -202,13 +203,15 @@ } void formatDifferingParamsDiagnostic( - InconsistentDeclarationParameterNameCheck *Check, - SourceLocation Location, StringRef OtherDeclarationDescription, + InconsistentDeclarationParameterNameCheck *Check, SourceLocation Location, + StringRef OtherDeclarationDescription, const DifferingParamsContainer &DifferingParams) { - auto ChooseOtherName = - [](const DifferingParamInfo &ParamInfo) { return ParamInfo.OtherName; }; - auto ChooseSourceName = - [](const DifferingParamInfo &ParamInfo) { return ParamInfo.SourceName; }; + auto ChooseOtherName = [](const DifferingParamInfo &ParamInfo) { + return ParamInfo.OtherName; + }; + auto ChooseSourceName = [](const DifferingParamInfo &ParamInfo) { + return ParamInfo.SourceName; + }; auto ParamDiag = Check->diag(Location, Index: clang-tidy/readability/NamespaceCommentCheck.cpp =================================================================== --- clang-tidy/readability/NamespaceCommentCheck.cpp +++ clang-tidy/readability/NamespaceCommentCheck.cpp @@ -114,7 +114,8 @@ Message = (llvm::Twine( "%0 ends with a comment that refers to a wrong namespace '") + - NamespaceNameInComment + "'").str(); + NamespaceNameInComment + "'") + .str(); } else if (Comment.startswith("//")) { // Assume that this is an unrecognized form of a namespace closing line // comment. Replace it. Index: clang-tidy/readability/RedundantControlFlowCheck.cpp =================================================================== --- clang-tidy/readability/RedundantControlFlowCheck.cpp +++ clang-tidy/readability/RedundantControlFlowCheck.cpp @@ -33,9 +33,10 @@ void RedundantControlFlowCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( - functionDecl(isDefinition(), returns(voidType()), - has(compoundStmt(hasAnySubstatement(returnStmt( - unless(has(expr()))))).bind("return"))), + functionDecl( + isDefinition(), returns(voidType()), + has(compoundStmt(hasAnySubstatement(returnStmt(unless(has(expr()))))) + .bind("return"))), this); auto CompoundContinue = has(compoundStmt(hasAnySubstatement(continueStmt())).bind("continue")); Index: clang-tidy/readability/RedundantDeclarationCheck.cpp =================================================================== --- clang-tidy/readability/RedundantDeclarationCheck.cpp +++ clang-tidy/readability/RedundantDeclarationCheck.cpp @@ -19,7 +19,8 @@ namespace readability { void RedundantDeclarationCheck::registerMatchers(MatchFinder *Finder) { - Finder->addMatcher(namedDecl(anyOf(varDecl(), functionDecl())).bind("Decl"), this); + Finder->addMatcher(namedDecl(anyOf(varDecl(), functionDecl())).bind("Decl"), + this); } void RedundantDeclarationCheck::check(const MatchFinder::MatchResult &Result) { @@ -33,8 +34,8 @@ const SourceManager &SM = *Result.SourceManager; const bool DifferentHeaders = - !SM.isInMainFile(D->getLocation()) && - !SM.isWrittenInSameFile(Prev->getLocation(), D->getLocation()); + !SM.isInMainFile(D->getLocation()) && + !SM.isWrittenInSameFile(Prev->getLocation(), D->getLocation()); bool MultiVar = false; if (const auto *VD = dyn_cast(D)) { @@ -57,8 +58,7 @@ SourceLocation EndLoc = Lexer::getLocForEndOfToken( D->getSourceRange().getEnd(), 0, SM, Result.Context->getLangOpts()); { - auto Diag = diag(D->getLocation(), "redundant %0 declaration") - << D; + auto Diag = diag(D->getLocation(), "redundant %0 declaration") << D; if (!MultiVar && !DifferentHeaders) Diag << FixItHint::CreateRemoval( SourceRange(D->getSourceRange().getBegin(), EndLoc)); Index: clang-tidy/readability/RedundantMemberInitCheck.cpp =================================================================== --- clang-tidy/readability/RedundantMemberInitCheck.cpp +++ clang-tidy/readability/RedundantMemberInitCheck.cpp @@ -8,10 +8,10 @@ //===----------------------------------------------------------------------===// #include "RedundantMemberInitCheck.h" +#include "../utils/Matchers.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Lex/Lexer.h" -#include "../utils/Matchers.h" #include using namespace clang::ast_matchers; Index: clang-tidy/readability/RedundantStringCStrCheck.cpp =================================================================== --- clang-tidy/readability/RedundantStringCStrCheck.cpp +++ clang-tidy/readability/RedundantStringCStrCheck.cpp @@ -77,17 +77,14 @@ return; // Match expressions of type 'string' or 'string*'. - const auto StringDecl = - cxxRecordDecl(hasName("::std::basic_string")); + const auto StringDecl = cxxRecordDecl(hasName("::std::basic_string")); const auto StringExpr = - expr(anyOf(hasType(StringDecl), - hasType(qualType(pointsTo(StringDecl))))); + expr(anyOf(hasType(StringDecl), hasType(qualType(pointsTo(StringDecl))))); // Match string constructor. const auto StringConstructorExpr = expr(anyOf( - cxxConstructExpr( - argumentCountIs(1), - hasDeclaration(cxxMethodDecl(hasName("basic_string")))), + cxxConstructExpr(argumentCountIs(1), + hasDeclaration(cxxMethodDecl(hasName("basic_string")))), cxxConstructExpr( argumentCountIs(2), hasDeclaration(cxxMethodDecl(hasName("basic_string"))), @@ -103,21 +100,18 @@ .bind("call"); // Detect redundant 'c_str()' calls through a string constructor. - Finder->addMatcher( - cxxConstructExpr(StringConstructorExpr, - hasArgument(0, StringCStrCallExpr)), - this); + Finder->addMatcher(cxxConstructExpr(StringConstructorExpr, + hasArgument(0, StringCStrCallExpr)), + this); // Detect: 's == str.c_str()' -> 's == str' Finder->addMatcher( cxxOperatorCallExpr( - anyOf(hasOverloadedOperatorName("<"), - hasOverloadedOperatorName(">"), - hasOverloadedOperatorName(">="), - hasOverloadedOperatorName("<="), - hasOverloadedOperatorName("!="), - hasOverloadedOperatorName("=="), - hasOverloadedOperatorName("+")), + anyOf( + hasOverloadedOperatorName("<"), hasOverloadedOperatorName(">"), + hasOverloadedOperatorName(">="), hasOverloadedOperatorName("<="), + hasOverloadedOperatorName("!="), hasOverloadedOperatorName("=="), + hasOverloadedOperatorName("+")), anyOf(allOf(hasArgument(0, StringExpr), hasArgument(1, StringCStrCallExpr)), allOf(hasArgument(0, StringCStrCallExpr), @@ -126,47 +120,41 @@ // Detect: 'dst += str.c_str()' -> 'dst += str' // Detect: 's = str.c_str()' -> 's = str' - Finder->addMatcher( - cxxOperatorCallExpr( - anyOf(hasOverloadedOperatorName("="), - hasOverloadedOperatorName("+=")), - hasArgument(0, StringExpr), - hasArgument(1, StringCStrCallExpr)), - this); + Finder->addMatcher(cxxOperatorCallExpr(anyOf(hasOverloadedOperatorName("="), + hasOverloadedOperatorName("+=")), + hasArgument(0, StringExpr), + hasArgument(1, StringCStrCallExpr)), + this); // Detect: 'dst.append(str.c_str())' -> 'dst.append(str)' Finder->addMatcher( - cxxMemberCallExpr(on(StringExpr), - callee(decl(cxxMethodDecl( - hasAnyName("append", "assign", "compare")))), - argumentCountIs(1), - hasArgument(0, StringCStrCallExpr)), + cxxMemberCallExpr(on(StringExpr), callee(decl(cxxMethodDecl(hasAnyName( + "append", "assign", "compare")))), + argumentCountIs(1), hasArgument(0, StringCStrCallExpr)), this); // Detect: 'dst.compare(p, n, str.c_str())' -> 'dst.compare(p, n, str)' Finder->addMatcher( cxxMemberCallExpr(on(StringExpr), - callee(decl(cxxMethodDecl(hasName("compare")))), - argumentCountIs(3), - hasArgument(2, StringCStrCallExpr)), + callee(decl(cxxMethodDecl(hasName("compare")))), + argumentCountIs(3), hasArgument(2, StringCStrCallExpr)), this); // Detect: 'dst.find(str.c_str())' -> 'dst.find(str)' Finder->addMatcher( cxxMemberCallExpr(on(StringExpr), - callee(decl(cxxMethodDecl( - hasAnyName("find", "find_first_not_of", "find_first_of", - "find_last_not_of", "find_last_of", "rfind")))), - anyOf(argumentCountIs(1), argumentCountIs(2)), - hasArgument(0, StringCStrCallExpr)), + callee(decl(cxxMethodDecl(hasAnyName( + "find", "find_first_not_of", "find_first_of", + "find_last_not_of", "find_last_of", "rfind")))), + anyOf(argumentCountIs(1), argumentCountIs(2)), + hasArgument(0, StringCStrCallExpr)), this); // Detect: 'dst.insert(pos, str.c_str())' -> 'dst.insert(pos, str)' Finder->addMatcher( cxxMemberCallExpr(on(StringExpr), - callee(decl(cxxMethodDecl(hasName("insert")))), - argumentCountIs(2), - hasArgument(1, StringCStrCallExpr)), + callee(decl(cxxMethodDecl(hasName("insert")))), + argumentCountIs(2), hasArgument(1, StringCStrCallExpr)), this); // Detect redundant 'c_str()' calls through a StringRef constructor. @@ -176,9 +164,8 @@ // wrt. string types and they internally make a StringRef // referring to the argument. Passing a string directly to // them is preferred to passing a char pointer. - hasDeclaration( - cxxMethodDecl(hasAnyName("::llvm::StringRef::StringRef", - "::llvm::Twine::Twine"))), + hasDeclaration(cxxMethodDecl(hasAnyName( + "::llvm::StringRef::StringRef", "::llvm::Twine::Twine"))), argumentCountIs(1), // The only argument must have the form x.c_str() or p->c_str() // where the method is string::c_str(). StringRef also has Index: clang-tidy/readability/RedundantStringInitCheck.cpp =================================================================== --- clang-tidy/readability/RedundantStringInitCheck.cpp +++ clang-tidy/readability/RedundantStringInitCheck.cpp @@ -33,10 +33,9 @@ hasArgument(1, cxxDefaultArgExpr())))); // Match a string constructor expression with an empty string literal. - const auto EmptyStringCtorExpr = - cxxConstructExpr(StringConstructorExpr, - hasArgument(0, ignoringParenImpCasts( - stringLiteral(hasSize(0))))); + const auto EmptyStringCtorExpr = cxxConstructExpr( + StringConstructorExpr, + hasArgument(0, ignoringParenImpCasts(stringLiteral(hasSize(0))))); const auto EmptyStringCtorExprWithTemporaries = cxxConstructExpr(StringConstructorExpr, Index: clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp =================================================================== --- clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp +++ clang-tidy/readability/UniqueptrDeleteReleaseCheck.cpp @@ -67,4 +67,3 @@ } // namespace readability } // namespace tidy } // namespace clang - Index: clang-tidy/tool/ClangTidyMain.cpp =================================================================== --- clang-tidy/tool/ClangTidyMain.cpp +++ clang-tidy/tool/ClangTidyMain.cpp @@ -93,9 +93,7 @@ SystemHeaders("system-headers", cl::desc("Display the errors from system headers."), cl::init(false), cl::cat(ClangTidyCategory)); -static cl::opt - LineFilter("line-filter", - cl::desc(R"( +static cl::opt LineFilter("line-filter", cl::desc(R"( List of files with line ranges to filter the warnings. Can be used together with -header-filter. The format of the list is a @@ -105,7 +103,8 @@ {"name":"file2.h"} ] )"), - cl::init(""), cl::cat(ClangTidyCategory)); + cl::init(""), + cl::cat(ClangTidyCategory)); static cl::opt Fix("fix", cl::desc(R"( Apply suggested fixes. Without -fix-errors @@ -220,7 +219,7 @@ std::vector> Timers; TimeRecord Total; - for (const auto& P : Profile.Records) { + for (const auto &P : Profile.Records) { Timers.emplace_back(P.getValue(), P.getKey()); Total += P.getValue(); } @@ -324,7 +323,7 @@ std::vector EnabledChecks = getCheckNames(EffectiveOptions); if (ExplainConfig) { - //FIXME: Show other ClangTidyOptions' fields, like ExtraArg. + // FIXME: Show other ClangTidyOptions' fields, like ExtraArg. std::vector RawOptions = OptionsProvider->getRawOptions(FilePath); for (const std::string &Check : EnabledChecks) { @@ -377,8 +376,7 @@ std::vector Errors; ClangTidyStats Stats = runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(), - PathList, &Errors, - EnableCheckProfile ? &Profile : nullptr); + PathList, &Errors, EnableCheckProfile ? &Profile : nullptr); bool FoundErrors = std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) { return E.DiagLevel == ClangTidyError::Error; @@ -458,7 +456,7 @@ // This anchor is used to force the linker to link the MPIModule. extern volatile int MPIModuleAnchorSource; static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination = - MPIModuleAnchorSource; + MPIModuleAnchorSource; // This anchor is used to force the linker to link the PerformanceModule. extern volatile int PerformanceModuleAnchorSource; Index: clang-tidy/utils/IncludeInserter.cpp =================================================================== --- clang-tidy/utils/IncludeInserter.cpp +++ clang-tidy/utils/IncludeInserter.cpp @@ -21,9 +21,8 @@ // Implements PPCallbacks::InclusionDerective(). Records the names and source // locations of the inclusions in the main source file being processed. void InclusionDirective(SourceLocation HashLocation, - const Token & IncludeToken, - StringRef FileNameRef, bool IsAngled, - CharSourceRange FileNameRange, + const Token &IncludeToken, StringRef FileNameRef, + bool IsAngled, CharSourceRange FileNameRange, const FileEntry * /*IncludedFile*/, StringRef /*SearchPath*/, StringRef /*RelativePath*/, const Module * /*ImportedModule*/) override { Index: clang-tidy/utils/NamespaceAliaser.cpp =================================================================== --- clang-tidy/utils/NamespaceAliaser.cpp +++ clang-tidy/utils/NamespaceAliaser.cpp @@ -35,11 +35,9 @@ if (!Function || !Function->hasBody()) return None; - if (AddedAliases[Function].count(Namespace.str()) != 0) return None; - // FIXME: Doesn't consider the order of declarations. // If we accidentially pick an alias defined later in the function, // the output won't compile. Index: clang-tidy/utils/TypeTraits.cpp =================================================================== --- clang-tidy/utils/TypeTraits.cpp +++ clang-tidy/utils/TypeTraits.cpp @@ -65,7 +65,8 @@ if (ClassDecl->hasTrivialDefaultConstructor()) return true; - // If all its fields are trivially constructible and have no default initializers. + // If all its fields are trivially constructible and have no default + // initializers. for (const FieldDecl *Field : ClassDecl->fields()) { if (Field->hasInClassInitializer()) return false; @@ -84,8 +85,7 @@ } // Based on QualType::isTrivial. -bool isTriviallyDefaultConstructible(QualType Type, - const ASTContext &Context) { +bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context) { if (Type.isNull()) return false; Index: clang-tidy/utils/UsingInserter.cpp =================================================================== --- clang-tidy/utils/UsingInserter.cpp +++ clang-tidy/utils/UsingInserter.cpp @@ -68,7 +68,8 @@ if (HasConflictingDeclaration || HasConflictingDeclRef) return None; - std::string Declaration = (llvm::Twine("\nusing ") + QualifiedName + ";").str(); + std::string Declaration = + (llvm::Twine("\nusing ") + QualifiedName + ";").str(); AddedUsing.emplace(std::make_pair(Function, QualifiedName.str())); return FixItHint::CreateInsertion(InsertLoc, Declaration); Index: include-fixer/IncludeFixer.cpp =================================================================== --- include-fixer/IncludeFixer.cpp +++ include-fixer/IncludeFixer.cpp @@ -279,7 +279,8 @@ // It's unsafe to do nested search for the identifier with scoped namespace // context, it might treat the identifier as a nested class of the scoped // namespace. - MatchedSymbols = SymbolIndexMgr.search(QueryString, /*IsNestedSearch=*/false); + MatchedSymbols = + SymbolIndexMgr.search(QueryString, /*IsNestedSearch=*/false); if (MatchedSymbols.empty()) MatchedSymbols = SymbolIndexMgr.search(Query); DEBUG(llvm::dbgs() << "Having found " << MatchedSymbols.size() Index: include-fixer/IncludeFixerContext.cpp =================================================================== --- include-fixer/IncludeFixerContext.cpp +++ include-fixer/IncludeFixerContext.cpp @@ -24,8 +24,7 @@ } std::string createQualifiedNameForReplacement( - llvm::StringRef RawSymbolName, - llvm::StringRef SymbolScopedQualifiersName, + llvm::StringRef RawSymbolName, llvm::StringRef SymbolScopedQualifiersName, const find_all_symbols::SymbolInfo &MatchedSymbol) { // No need to add missing qualifiers if SymbolIndentifer has a global scope // operator "::". Index: include-fixer/find-all-symbols/FindAllMacros.cpp =================================================================== --- include-fixer/find-all-symbols/FindAllMacros.cpp +++ include-fixer/find-all-symbols/FindAllMacros.cpp @@ -23,7 +23,8 @@ const MacroDirective *MD) { SourceLocation Loc = SM->getExpansionLoc(MacroNameTok.getLocation()); std::string FilePath = getIncludePath(*SM, Loc, Collector); - if (FilePath.empty()) return; + if (FilePath.empty()) + return; SymbolInfo Symbol(MacroNameTok.getIdentifierInfo()->getName(), SymbolInfo::SymbolKind::Macro, FilePath, Index: include-fixer/find-all-symbols/FindAllSymbols.cpp =================================================================== --- include-fixer/find-all-symbols/FindAllSymbols.cpp +++ include-fixer/find-all-symbols/FindAllSymbols.cpp @@ -40,8 +40,7 @@ llvm::isa(Context)) break; - assert(llvm::isa(Context) && - "Expect Context to be a NamedDecl"); + assert(llvm::isa(Context) && "Expect Context to be a NamedDecl"); if (const auto *NSD = dyn_cast(Context)) { if (!NSD->isInlineNamespace()) Contexts.emplace_back(SymbolInfo::ContextType::Namespace, @@ -95,7 +94,8 @@ } std::string FilePath = getIncludePath(SM, Loc, Collector); - if (FilePath.empty()) return llvm::None; + if (FilePath.empty()) + return llvm::None; return SymbolInfo(ND->getNameAsString(), Type, FilePath, SM.getExpansionLineNumber(Loc), GetContexts(ND)); @@ -198,8 +198,7 @@ // inside toplevel translation unit or a namespace. MatchFinder->addMatcher( enumConstantDecl( - CommonFilter, - unless(isInScopedEnum()), + CommonFilter, unless(isInScopedEnum()), anyOf(hasDeclContext(enumDecl(HasNSOrTUCtxMatcher)), ExternCMatcher)) .bind("decl"), this); @@ -215,8 +214,7 @@ assert(ND && "Matched declaration must be a NamedDecl!"); const SourceManager *SM = Result.SourceManager; - llvm::Optional Symbol = - CreateSymbolInfo(ND, *SM, Collector); + llvm::Optional Symbol = CreateSymbolInfo(ND, *SM, Collector); if (Symbol) Reporter->reportSymbol( SM->getFileEntryForID(SM->getMainFileID())->getName(), *Symbol); Index: include-fixer/find-all-symbols/FindAllSymbolsAction.cpp =================================================================== --- include-fixer/find-all-symbols/FindAllSymbolsAction.cpp +++ include-fixer/find-all-symbols/FindAllSymbolsAction.cpp @@ -1,4 +1,5 @@ -//===-- FindAllSymbolsAction.cpp - find all symbols action --------*- C++ -*-===// +//===-- FindAllSymbolsAction.cpp - find all symbols action --------*- C++ +//-*-===// // // The LLVM Compiler Infrastructure // Index: include-fixer/tool/ClangIncludeFixer.cpp =================================================================== --- include-fixer/tool/ClangIncludeFixer.cpp +++ include-fixer/tool/ClangIncludeFixer.cpp @@ -99,9 +99,9 @@ cl::opt QuerySymbol("query-symbol", - cl::desc("Query a given symbol (e.g. \"a::b::foo\") in\n" - "database directly without parsing the file."), - cl::cat(IncludeFixerCategory)); + cl::desc("Query a given symbol (e.g. \"a::b::foo\") in\n" + "database directly without parsing the file."), + cl::cat(IncludeFixerCategory)); cl::opt MinimizeIncludePaths("minimize-paths", @@ -209,10 +209,10 @@ return SymbolIndexMgr; } -void writeToJson(llvm::raw_ostream &OS, const IncludeFixerContext& Context) { +void writeToJson(llvm::raw_ostream &OS, const IncludeFixerContext &Context) { OS << "{\n" - << " \"FilePath\": \"" - << llvm::yaml::escape(Context.getFilePath()) << "\",\n" + << " \"FilePath\": \"" << llvm::yaml::escape(Context.getFilePath()) + << "\",\n" << " \"QuerySymbolInfos\": [\n"; for (const auto &Info : Context.getQuerySymbolInfos()) { OS << " {\"RawIdentifier\": \"" << Info.RawIdentifier << "\",\n"; @@ -257,7 +257,7 @@ } Code = std::move(CodeOrErr.get()); if (Code->getBufferSize() == 0) - return 0; // Skip empty files. + return 0; // Skip empty files. tool.mapVirtualFile(SourceFilePath, Code->getBuffer()); } @@ -277,7 +277,7 @@ // We only accept one unique header. // Check all elements in HeaderInfos have the same header. bool IsUniqueHeader = std::equal( - HeaderInfos.begin()+1, HeaderInfos.end(), HeaderInfos.begin(), + HeaderInfos.begin() + 1, HeaderInfos.end(), HeaderInfos.begin(), [](const IncludeFixerContext::HeaderInfo &LHS, const IncludeFixerContext::HeaderInfo &RHS) { return LHS.Header == RHS.Header; @@ -431,6 +431,4 @@ } // namespace -int main(int argc, const char **argv) { - return includeFixerMain(argc, argv); -} +int main(int argc, const char **argv) { return includeFixerMain(argc, argv); } Index: modularize/CoverageChecker.cpp =================================================================== --- modularize/CoverageChecker.cpp +++ modularize/CoverageChecker.cpp @@ -51,9 +51,9 @@ // //===----------------------------------------------------------------------===// +#include "CoverageChecker.h" #include "ModularizeUtilities.h" #include "clang/AST/ASTConsumer.h" -#include "CoverageChecker.h" #include "clang/AST/ASTContext.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Basic/SourceManager.h" @@ -115,9 +115,9 @@ protected: std::unique_ptr CreateASTConsumer(CompilerInstance &CI, - StringRef InFile) override { + StringRef InFile) override { return llvm::make_unique(Checker, - CI.getPreprocessor()); + CI.getPreprocessor()); } private: @@ -127,7 +127,7 @@ class CoverageCheckerFrontendActionFactory : public FrontendActionFactory { public: CoverageCheckerFrontendActionFactory(CoverageChecker &Checker) - : Checker(Checker) {} + : Checker(Checker) {} CoverageCheckerAction *create() override { return new CoverageCheckerAction(Checker); @@ -141,21 +141,20 @@ // Constructor. CoverageChecker::CoverageChecker(StringRef ModuleMapPath, - std::vector &IncludePaths, - ArrayRef CommandLine, - clang::ModuleMap *ModuleMap) - : ModuleMapPath(ModuleMapPath), IncludePaths(IncludePaths), - CommandLine(CommandLine), - ModMap(ModuleMap) {} + std::vector &IncludePaths, + ArrayRef CommandLine, + clang::ModuleMap *ModuleMap) + : ModuleMapPath(ModuleMapPath), IncludePaths(IncludePaths), + CommandLine(CommandLine), ModMap(ModuleMap) {} // Create instance of CoverageChecker, to simplify setting up // subordinate objects. CoverageChecker *CoverageChecker::createCoverageChecker( - StringRef ModuleMapPath, std::vector &IncludePaths, - ArrayRef CommandLine, clang::ModuleMap *ModuleMap) { + StringRef ModuleMapPath, std::vector &IncludePaths, + ArrayRef CommandLine, clang::ModuleMap *ModuleMap) { return new CoverageChecker(ModuleMapPath, IncludePaths, CommandLine, - ModuleMap); + ModuleMap); } // Do checks. @@ -194,8 +193,8 @@ // ModuleMapHeadersSet. void CoverageChecker::collectModuleHeaders() { for (ModuleMap::module_iterator I = ModMap->module_begin(), - E = ModMap->module_end(); - I != E; ++I) { + E = ModMap->module_end(); + I != E; ++I) { collectModuleHeaders(*I->second); } } @@ -208,13 +207,12 @@ if (const FileEntry *UmbrellaHeader = Mod.getUmbrellaHeader().Entry) { // Collect umbrella header. - ModuleMapHeadersSet.insert(ModularizeUtilities::getCanonicalPath( - UmbrellaHeader->getName())); + ModuleMapHeadersSet.insert( + ModularizeUtilities::getCanonicalPath(UmbrellaHeader->getName())); // Preprocess umbrella header and collect the headers it references. if (!collectUmbrellaHeaderHeaders(UmbrellaHeader->getName())) return false; - } - else if (const DirectoryEntry *UmbrellaDir = Mod.getUmbrellaDir().Entry) { + } else if (const DirectoryEntry *UmbrellaDir = Mod.getUmbrellaDir().Entry) { // Collect headers in umbrella directory. if (!collectUmbrellaHeaders(UmbrellaDir->getName())) return false; @@ -222,12 +220,12 @@ for (auto &HeaderKind : Mod.Headers) for (auto &Header : HeaderKind) - ModuleMapHeadersSet.insert(ModularizeUtilities::getCanonicalPath( - Header.Entry->getName())); + ModuleMapHeadersSet.insert( + ModularizeUtilities::getCanonicalPath(Header.Entry->getName())); for (Module::submodule_const_iterator MI = Mod.submodule_begin(), - MIEnd = Mod.submodule_end(); - MI != MIEnd; ++MI) + MIEnd = Mod.submodule_end(); + MI != MIEnd; ++MI) collectModuleHeaders(**MI); return true; @@ -245,7 +243,7 @@ std::error_code EC; sys::fs::file_status Status; for (sys::fs::directory_iterator I(Directory.str(), EC), E; I != E; - I.increment(EC)) { + I.increment(EC)) { if (EC) return false; std::string File(I->path()); @@ -267,8 +265,8 @@ } // Collect headers rferenced from an umbrella file. -bool -CoverageChecker::collectUmbrellaHeaderHeaders(StringRef UmbrellaHeaderName) { +bool CoverageChecker::collectUmbrellaHeaderHeaders( + StringRef UmbrellaHeaderName) { SmallString<256> PathBuf(ModuleMapDirectory); @@ -324,13 +322,12 @@ if (IncludePaths.size() == 0) { if (!collectFileSystemHeaders(StringRef(""))) return false; - } - else { + } else { // Otherwise we only look at the sub-trees specified by the // include paths. for (std::vector::const_iterator I = IncludePaths.begin(), - E = IncludePaths.end(); - I != E; ++I) { + E = IncludePaths.end(); + I != E; ++I) { if (!collectFileSystemHeaders(*I)) return false; } @@ -356,9 +353,9 @@ if (Directory.size() == 0) Directory = "."; if (IncludePath.startswith("/") || IncludePath.startswith("\\") || - ((IncludePath.size() >= 2) && (IncludePath[1] == ':'))) { + ((IncludePath.size() >= 2) && (IncludePath[1] == ':'))) { llvm::errs() << "error: Include path \"" << IncludePath - << "\" is not relative to the module map file.\n"; + << "\" is not relative to the module map file.\n"; return false; } @@ -367,10 +364,10 @@ sys::fs::file_status Status; int Count = 0; for (sys::fs::recursive_directory_iterator I(Directory.str(), EC), E; I != E; - I.increment(EC)) { + I.increment(EC)) { if (EC) return false; - //std::string file(I->path()); + // std::string file(I->path()); StringRef file(I->path()); I->status(Status); sys::fs::file_type type = Status.type(); @@ -391,7 +388,7 @@ } if (Count == 0) { llvm::errs() << "warning: No headers found in include path: \"" - << IncludePath << "\"\n"; + << IncludePath << "\"\n"; } return true; } @@ -409,13 +406,13 @@ void CoverageChecker::findUnaccountedForHeaders() { // Walk over file system headers. for (std::vector::const_iterator I = FileSystemHeaders.begin(), - E = FileSystemHeaders.end(); - I != E; ++I) { + E = FileSystemHeaders.end(); + I != E; ++I) { // Look for header in module map. if (ModuleMapHeadersSet.insert(*I).second) { UnaccountedForHeaders.push_back(*I); llvm::errs() << "warning: " << ModuleMapPath - << " does not account for file: " << *I << "\n"; + << " does not account for file: " << *I << "\n"; } } } Index: modularize/Modularize.cpp =================================================================== --- modularize/Modularize.cpp +++ modularize/Modularize.cpp @@ -290,45 +290,42 @@ // Option to specify list of problem files for assistant. // This will cause assistant to exclude these files. static cl::opt ProblemFilesList( - "problem-files-list", cl::init(""), - cl::desc( - "List of files with compilation or modularization problems for" - " assistant mode. This will be excluded.")); + "problem-files-list", cl::init(""), + cl::desc("List of files with compilation or modularization problems for" + " assistant mode. This will be excluded.")); // Option for assistant mode, telling modularize the name of the root module. static cl::opt -RootModule("root-module", cl::init(""), - cl::desc("Specify the name of the root module.")); + RootModule("root-module", cl::init(""), + cl::desc("Specify the name of the root module.")); // Option for limiting the #include-inside-extern-or-namespace-block // check to only those headers explicitly listed in the header list. // This is a work-around for private includes that purposefully get // included inside blocks. -static cl::opt -BlockCheckHeaderListOnly("block-check-header-list-only", cl::init(false), -cl::desc("Only warn if #include directives are inside extern or namespace" - " blocks if the included header is in the header list.")); +static cl::opt BlockCheckHeaderListOnly( + "block-check-header-list-only", cl::init(false), + cl::desc("Only warn if #include directives are inside extern or namespace" + " blocks if the included header is in the header list.")); // Option for include paths for coverage check. static cl::list -IncludePaths("I", cl::desc("Include path for coverage check."), -cl::ZeroOrMore, cl::value_desc("path")); + IncludePaths("I", cl::desc("Include path for coverage check."), + cl::ZeroOrMore, cl::value_desc("path")); // Option for disabling the coverage check. -static cl::opt -NoCoverageCheck("no-coverage-check", cl::init(false), -cl::desc("Don't do the coverage check.")); +static cl::opt NoCoverageCheck("no-coverage-check", cl::init(false), + cl::desc("Don't do the coverage check.")); // Option for just doing the coverage check. -static cl::opt -CoverageCheckOnly("coverage-check-only", cl::init(false), -cl::desc("Only do the coverage check.")); +static cl::opt CoverageCheckOnly("coverage-check-only", cl::init(false), + cl::desc("Only do the coverage check.")); // Option for displaying lists of good, bad, and mixed files. -static cl::opt -DisplayFileLists("display-file-lists", cl::init(false), -cl::desc("Display lists of good files (no compile errors), problem files," - " and a combined list with problem files preceded by a '#'.")); +static cl::opt DisplayFileLists( + "display-file-lists", cl::init(false), + cl::desc("Display lists of good files (no compile errors), problem files," + " and a combined list with problem files preceded by a '#'.")); // Save the program name for error messages. const char *Argv0; @@ -356,28 +353,28 @@ // if no other "-x" option is present. static ArgumentsAdjuster getModularizeArgumentsAdjuster(DependencyMap &Dependencies) { - return [&Dependencies](const CommandLineArguments &Args, - StringRef /*unused*/) { - std::string InputFile = findInputFile(Args); - DependentsVector &FileDependents = Dependencies[InputFile]; - CommandLineArguments NewArgs(Args); - if (int Count = FileDependents.size()) { - for (int Index = 0; Index < Count; ++Index) { - NewArgs.push_back("-include"); - std::string File(std::string("\"") + FileDependents[Index] + - std::string("\"")); - NewArgs.push_back(FileDependents[Index]); - } - } - // Ignore warnings. (Insert after "clang_tool" at beginning.) - NewArgs.insert(NewArgs.begin() + 1, "-w"); - // Since we are compiling .h files, assume C++ unless given a -x option. - if (std::find(NewArgs.begin(), NewArgs.end(), "-x") == NewArgs.end()) { - NewArgs.insert(NewArgs.begin() + 2, "-x"); - NewArgs.insert(NewArgs.begin() + 3, "c++"); - } - return NewArgs; - }; + return + [&Dependencies](const CommandLineArguments &Args, StringRef /*unused*/) { + std::string InputFile = findInputFile(Args); + DependentsVector &FileDependents = Dependencies[InputFile]; + CommandLineArguments NewArgs(Args); + if (int Count = FileDependents.size()) { + for (int Index = 0; Index < Count; ++Index) { + NewArgs.push_back("-include"); + std::string File(std::string("\"") + FileDependents[Index] + + std::string("\"")); + NewArgs.push_back(FileDependents[Index]); + } + } + // Ignore warnings. (Insert after "clang_tool" at beginning.) + NewArgs.insert(NewArgs.begin() + 1, "-w"); + // Since we are compiling .h files, assume C++ unless given a -x option. + if (std::find(NewArgs.begin(), NewArgs.end(), "-x") == NewArgs.end()) { + NewArgs.insert(NewArgs.begin() + 2, "-x"); + NewArgs.insert(NewArgs.begin() + 3, "c++"); + } + return NewArgs; + }; } // FIXME: The Location class seems to be something that we might @@ -485,13 +482,13 @@ typedef std::vector HeaderContents; -class EntityMap : public StringMap > { +class EntityMap : public StringMap> { public: DenseMap HeaderContentMismatches; void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) { // Record this entity in its header. - HeaderEntry HE = { Name, Loc }; + HeaderEntry HE = {Name, Loc}; CurHeaderContents[Loc.File].push_back(HE); // Check whether we've seen this entry before. @@ -502,7 +499,7 @@ } // We have not seen this entry before; record it. - Entry E = { Kind, Loc }; + Entry E = {Kind, Loc}; Entries.push_back(E); } @@ -734,8 +731,7 @@ int &HadErrors; }; -class CompileCheckVisitor - : public RecursiveASTVisitor { +class CompileCheckVisitor : public RecursiveASTVisitor { public: CompileCheckVisitor() {} @@ -755,7 +751,7 @@ return true; } bool TraverseTemplateArguments(const TemplateArgument *Args, - unsigned NumArgs) { + unsigned NumArgs) { return true; } bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; } @@ -765,19 +761,13 @@ } // Check 'extern "*" {}' block for #include directives. - bool VisitLinkageSpecDecl(LinkageSpecDecl *D) { - return true; - } + bool VisitLinkageSpecDecl(LinkageSpecDecl *D) { return true; } // Check 'namespace (name) {}' block for #include directives. - bool VisitNamespaceDecl(const NamespaceDecl *D) { - return true; - } + bool VisitNamespaceDecl(const NamespaceDecl *D) { return true; } // Collect definition entities. - bool VisitNamedDecl(NamedDecl *ND) { - return true; - } + bool VisitNamedDecl(NamedDecl *ND) { return true; } }; class CompileCheckConsumer : public ASTConsumer { @@ -795,7 +785,7 @@ protected: std::unique_ptr - CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override { + CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override { return llvm::make_unique(); } }; @@ -804,9 +794,7 @@ public: CompileCheckFrontendActionFactory() {} - CompileCheckAction *create() override { - return new CompileCheckAction(); - } + CompileCheckAction *create() override { return new CompileCheckAction(); } }; int main(int Argc, const char **Argv) { @@ -833,8 +821,7 @@ std::unique_ptr ModUtil; int HadErrors = 0; - ModUtil.reset( - ModularizeUtilities::createModularizeUtilities( + ModUtil.reset(ModularizeUtilities::createModularizeUtilities( ListFileNames, HeaderPrefix, ProblemFilesList)); // Get header file names and dependencies. @@ -844,8 +831,8 @@ // If we are in assistant mode, output the module map and quit. if (ModuleMapPath.length() != 0) { if (!createModuleMap(ModuleMapPath, ModUtil->HeaderFileNames, - ModUtil->ProblemFileNames, - ModUtil->Dependencies, HeaderPrefix, RootModule)) + ModUtil->ProblemFileNames, ModUtil->Dependencies, + HeaderPrefix, RootModule)) return 1; // Failed. return 0; // Success - Skip checks in assistant mode. } @@ -869,9 +856,8 @@ new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments)); // Create preprocessor tracker, to watch for macro and conditional problems. - std::unique_ptr PPTracker( - PreprocessorTracker::create(ModUtil->HeaderFileNames, - BlockCheckHeaderListOnly)); + std::unique_ptr PPTracker(PreprocessorTracker::create( + ModUtil->HeaderFileNames, BlockCheckHeaderListOnly)); // Coolect entities here. EntityMap Entities; @@ -887,24 +873,23 @@ CompileCheckFileArray.push_back(CompileCheckFile); ClangTool CompileCheckTool(*Compilations, CompileCheckFileArray); CompileCheckTool.appendArgumentsAdjuster( - getModularizeArgumentsAdjuster(ModUtil->Dependencies)); + getModularizeArgumentsAdjuster(ModUtil->Dependencies)); int CompileCheckFileErrors = 0; CompileCheckFrontendActionFactory CompileCheckFactory; CompileCheckFileErrors |= CompileCheckTool.run(&CompileCheckFactory); if (CompileCheckFileErrors != 0) { - ModUtil->addUniqueProblemFile(CompileCheckFile); // Save problem file. + ModUtil->addUniqueProblemFile(CompileCheckFile); // Save problem file. HadErrors |= 1; - } - else + } else ModUtil->addNoCompileErrorsFile(CompileCheckFile); // Save good file. } } // Then we make another pass on the good files to do the rest of the work. - ClangTool Tool(*Compilations, - (DisplayFileLists ? ModUtil->GoodFileNames : ModUtil->HeaderFileNames)); + ClangTool Tool(*Compilations, (DisplayFileLists ? ModUtil->GoodFileNames + : ModUtil->HeaderFileNames)); Tool.appendArgumentsAdjuster( - getModularizeArgumentsAdjuster(ModUtil->Dependencies)); + getModularizeArgumentsAdjuster(ModUtil->Dependencies)); ModularizeFrontendActionFactory Factory(Entities, *PPTracker, HadErrors); HadErrors |= Tool.run(&Factory); @@ -939,7 +924,8 @@ for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end(); DI != DE; ++DI, ++KindIndex) { int ECount = DI->size(); - // If only 1 occurrence of this entity, skip it, we only report duplicates. + // If only 1 occurrence of this entity, skip it, we only report + // duplicates. if (ECount <= 1) continue; LocationArray::iterator FI = DI->begin(); Index: modularize/ModularizeUtilities.cpp =================================================================== --- modularize/ModularizeUtilities.cpp +++ modularize/ModularizeUtilities.cpp @@ -13,17 +13,17 @@ // //===----------------------------------------------------------------------===// +#include "ModularizeUtilities.h" +#include "CoverageChecker.h" #include "clang/Basic/SourceManager.h" #include "clang/Driver/Options.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendActions.h" -#include "CoverageChecker.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" -#include "ModularizeUtilities.h" using namespace clang; using namespace llvm; @@ -44,25 +44,22 @@ ModularizeUtilities::ModularizeUtilities(std::vector &InputPaths, llvm::StringRef Prefix, llvm::StringRef ProblemFilesListPath) - : InputFilePaths(InputPaths), - HeaderPrefix(Prefix), - ProblemFilesPath(ProblemFilesListPath), - HasModuleMap(false), - MissingHeaderCount(0), - // Init clang stuff needed for loading the module map and preprocessing. - LangOpts(new LangOptions()), DiagIDs(new DiagnosticIDs()), - DiagnosticOpts(new DiagnosticOptions()), - DC(llvm::errs(), DiagnosticOpts.get()), - Diagnostics( - new DiagnosticsEngine(DiagIDs, DiagnosticOpts.get(), &DC, false)), - TargetOpts(new ModuleMapTargetOptions()), - Target(TargetInfo::CreateTargetInfo(*Diagnostics, TargetOpts)), - FileMgr(new FileManager(FileSystemOpts)), - SourceMgr(new SourceManager(*Diagnostics, *FileMgr, false)), - HeaderSearchOpts(new HeaderSearchOptions()), - HeaderInfo(new HeaderSearch(HeaderSearchOpts, *SourceMgr, *Diagnostics, - *LangOpts, Target.get())) { -} + : InputFilePaths(InputPaths), HeaderPrefix(Prefix), + ProblemFilesPath(ProblemFilesListPath), HasModuleMap(false), + MissingHeaderCount(0), + // Init clang stuff needed for loading the module map and preprocessing. + LangOpts(new LangOptions()), DiagIDs(new DiagnosticIDs()), + DiagnosticOpts(new DiagnosticOptions()), + DC(llvm::errs(), DiagnosticOpts.get()), + Diagnostics( + new DiagnosticsEngine(DiagIDs, DiagnosticOpts.get(), &DC, false)), + TargetOpts(new ModuleMapTargetOptions()), + Target(TargetInfo::CreateTargetInfo(*Diagnostics, TargetOpts)), + FileMgr(new FileManager(FileSystemOpts)), + SourceMgr(new SourceManager(*Diagnostics, *FileMgr, false)), + HeaderSearchOpts(new HeaderSearchOptions()), + HeaderInfo(new HeaderSearch(HeaderSearchOpts, *SourceMgr, *Diagnostics, + *LangOpts, Target.get())) {} // Create instance of ModularizeUtilities, to simplify setting up // subordinate objects. @@ -84,12 +81,12 @@ // Load the module map. if (std::error_code EC = loadModuleMap(InputPath)) return EC; - } - else { + } else { // Else we assume it's a header list and load it. - if (std::error_code EC = loadSingleHeaderListsAndDependencies(InputPath)) { + if (std::error_code EC = + loadSingleHeaderListsAndDependencies(InputPath)) { errs() << "modularize: error: Unable to get header list '" << InputPath - << "': " << EC.message() << '\n'; + << "': " << EC.message() << '\n'; return EC; } } @@ -98,8 +95,8 @@ if (ProblemFilesPath.size() != 0) { // Load problem files list. if (std::error_code EC = loadProblemHeaderList(ProblemFilesPath)) { - errs() << "modularize: error: Unable to get problem header list '" << ProblemFilesPath - << "': " << EC.message() << '\n'; + errs() << "modularize: error: Unable to get problem header list '" + << ProblemFilesPath << "': " << EC.message() << '\n'; return EC; } } @@ -116,16 +113,17 @@ // Returns 0 if there were no errors or warnings, 1 if there // were warnings, 2 if any other problem, such as a bad // module map path argument was specified. -std::error_code ModularizeUtilities::doCoverageCheck( - std::vector &IncludePaths, - llvm::ArrayRef CommandLine) { +std::error_code +ModularizeUtilities::doCoverageCheck(std::vector &IncludePaths, + llvm::ArrayRef CommandLine) { int ModuleMapCount = ModuleMaps.size(); int ModuleMapIndex; std::error_code EC; for (ModuleMapIndex = 0; ModuleMapIndex < ModuleMapCount; ++ModuleMapIndex) { std::unique_ptr &ModMap = ModuleMaps[ModuleMapIndex]; CoverageChecker *Checker = CoverageChecker::createCoverageChecker( - InputFilePaths[ModuleMapIndex], IncludePaths, CommandLine, ModMap.get()); + InputFilePaths[ModuleMapIndex], IncludePaths, CommandLine, + ModMap.get()); std::error_code LocalEC = Checker->doChecks(); if (LocalEC.value() > 0) EC = LocalEC; @@ -149,7 +147,7 @@ // Read the header list file into a buffer. ErrorOr> listBuffer = - MemoryBuffer::getFile(InputPath); + MemoryBuffer::getFile(InputPath); if (std::error_code EC = listBuffer.getError()) return EC; @@ -159,8 +157,8 @@ // Collect the header file names from the string list. for (SmallVectorImpl::iterator I = Strings.begin(), - E = Strings.end(); - I != E; ++I) { + E = Strings.end(); + I != E; ++I) { StringRef Line = I->trim(); // Ignore comments and empty lines. if (Line.empty() || (Line[0] == '#')) @@ -207,8 +205,8 @@ } // Load problem header list. -std::error_code ModularizeUtilities::loadProblemHeaderList( - llvm::StringRef InputPath) { +std::error_code +ModularizeUtilities::loadProblemHeaderList(llvm::StringRef InputPath) { // By default, use the path component of the list file name. SmallString<256> HeaderDirectory(InputPath); @@ -222,7 +220,7 @@ // Read the header list file into a buffer. ErrorOr> listBuffer = - MemoryBuffer::getFile(InputPath); + MemoryBuffer::getFile(InputPath); if (std::error_code EC = listBuffer.getError()) return EC; @@ -232,8 +230,8 @@ // Collect the header file names from the string list. for (SmallVectorImpl::iterator I = Strings.begin(), - E = Strings.end(); - I != E; ++I) { + E = Strings.end(); + I != E; ++I) { StringRef Line = I->trim(); // Ignore comments and empty lines. if (Line.empty() || (Line[0] == '#')) @@ -259,11 +257,10 @@ } // Load single module map and extract header file list. -std::error_code ModularizeUtilities::loadModuleMap( - llvm::StringRef InputPath) { +std::error_code ModularizeUtilities::loadModuleMap(llvm::StringRef InputPath) { // Get file entry for module.modulemap file. const FileEntry *ModuleMapEntry = - SourceMgr->getFileManager().getFile(InputPath); + SourceMgr->getFileManager().getFile(InputPath); // return error if not found. if (!ModuleMapEntry) { @@ -288,8 +285,8 @@ } std::unique_ptr ModMap; - ModMap.reset(new ModuleMap(*SourceMgr, *Diagnostics, *LangOpts, - Target.get(), *HeaderInfo)); + ModMap.reset(new ModuleMap(*SourceMgr, *Diagnostics, *LangOpts, Target.get(), + *HeaderInfo)); // Parse module.modulemap file into module map. if (ModMap->parseModuleMapFile(ModuleMapEntry, false, Dir)) { @@ -323,8 +320,8 @@ // HeaderFileNames. bool ModularizeUtilities::collectModuleMapHeaders(clang::ModuleMap *ModMap) { for (ModuleMap::module_iterator I = ModMap->module_begin(), - E = ModMap->module_end(); - I != E; ++I) { + E = ModMap->module_end(); + I != E; ++I) { if (!collectModuleHeaders(*I->second)) return false; } @@ -346,8 +343,8 @@ // Recursively do submodules. for (clang::Module::submodule_const_iterator MI = Mod.submodule_begin(), - MIEnd = Mod.submodule_end(); - MI != MIEnd; ++MI) + MIEnd = Mod.submodule_end(); + MI != MIEnd; ++MI) collectModuleHeaders(**MI); if (const FileEntry *UmbrellaHeader = Mod.getUmbrellaHeader().Entry) { @@ -356,8 +353,7 @@ HeaderFileNames.push_back(HeaderPath); // FUTURE: When needed, umbrella header header collection goes here. - } - else if (const DirectoryEntry *UmbrellaDir = Mod.getUmbrellaDir().Entry) { + } else if (const DirectoryEntry *UmbrellaDir = Mod.getUmbrellaDir().Entry) { // If there normal headers, assume these are umbrellas and skip collection. if (Mod.Headers->size() == 0) { // Collect headers in umbrella directory. @@ -377,7 +373,7 @@ DependentsVector NormalDependents; // Collect normal header. const clang::Module::Header &Header( - Mod.Headers[clang::Module::HK_Normal][Index]); + Mod.Headers[clang::Module::HK_Normal][Index]); std::string HeaderPath = getCanonicalPath(Header.Entry->getName()); HeaderFileNames.push_back(HeaderPath); } @@ -388,7 +384,7 @@ std::string MissingFile = Mod.MissingHeaders[Index].FileName; SourceLocation Loc = Mod.MissingHeaders[Index].FileNameLoc; errs() << Loc.printToString(*SourceMgr) - << ": error : Header not found: " << MissingFile << "\n"; + << ": error : Header not found: " << MissingFile << "\n"; } MissingHeaderCount += MissingCountThisModule; @@ -398,14 +394,14 @@ // Collect headers from an umbrella directory. bool ModularizeUtilities::collectUmbrellaHeaders(StringRef UmbrellaDirName, - DependentsVector &Dependents) { + DependentsVector &Dependents) { // Initialize directory name. SmallString<256> Directory(UmbrellaDirName); // Walk the directory. std::error_code EC; llvm::sys::fs::file_status Status; for (llvm::sys::fs::directory_iterator I(Directory.str(), EC), E; I != E; - I.increment(EC)) { + I.increment(EC)) { if (EC) return false; std::string File(I->path()); @@ -432,11 +428,10 @@ static std::string replaceDotDot(StringRef Path) { SmallString<128> Buffer; llvm::sys::path::const_iterator B = llvm::sys::path::begin(Path), - E = llvm::sys::path::end(Path); + E = llvm::sys::path::end(Path); while (B != E) { if (B->compare(".") == 0) { - } - else if (B->compare("..") == 0) + } else if (B->compare("..") == 0) llvm::sys::path::remove_filename(Buffer); else llvm::sys::path::append(Buffer, *B); @@ -494,7 +489,7 @@ void ModularizeUtilities::addUniqueProblemFile(std::string FilePath) { FilePath = getCanonicalPath(FilePath); // Don't add if already present. - for(auto &TestFilePath : ProblemFileNames) { + for (auto &TestFilePath : ProblemFileNames) { if (TestFilePath == FilePath) return; } @@ -534,8 +529,8 @@ // List files with problem files commented out. void ModularizeUtilities::displayCombinedFiles() { - errs() << - "\nThese are the combined files, with problem files preceded by #:\n\n"; + errs() << "\nThese are the combined files, with problem files preceded by " + "#:\n\n"; for (auto &File : HeaderFileNames) { bool Good = true; for (auto &ProblemFile : ProblemFileNames) { Index: modularize/ModuleAssistant.cpp =================================================================== --- modularize/ModuleAssistant.cpp +++ modularize/ModuleAssistant.cpp @@ -64,7 +64,7 @@ // Constructors. Module::Module(llvm::StringRef Name, bool Problem) - : Name(Name), IsProblem(Problem) {} + : Name(Name), IsProblem(Problem) {} Module::Module() : IsProblem(false) {} // Destructor. @@ -138,9 +138,9 @@ // Keep in sync with keywords in module map parser in Lex/ModuleMap.cpp, // such as in ModuleMapParser::consumeToken(). static const char *const ReservedNames[] = { - "config_macros", "export", "module", "conflict", "framework", - "requires", "exclude", "header", "private", "explicit", - "link", "umbrella", "extern", "use", nullptr // Flag end. + "config_macros", "export", "module", "conflict", "framework", + "requires", "exclude", "header", "private", "explicit", + "link", "umbrella", "extern", "use", nullptr // Flag end. }; // Convert module name to a non-keyword. @@ -159,8 +159,7 @@ // Convert module name to a non-keyword. // Prepends a '_' to the name if and only if the name is a keyword. -static std::string -ensureVaidModuleName(llvm::StringRef MightBeInvalidName) { +static std::string ensureVaidModuleName(llvm::StringRef MightBeInvalidName) { std::string SafeName = MightBeInvalidName; std::replace(SafeName.begin(), SafeName.end(), '-', '_'); std::replace(SafeName.begin(), SafeName.end(), '.', '_'); @@ -223,8 +222,8 @@ // Create the internal module tree representation. static Module *loadModuleDescriptions( llvm::StringRef RootModuleName, llvm::ArrayRef HeaderFileNames, - llvm::ArrayRef ProblemFileNames, - DependencyMap &Dependencies, llvm::StringRef HeaderPrefix) { + llvm::ArrayRef ProblemFileNames, DependencyMap &Dependencies, + llvm::StringRef HeaderPrefix) { // Create root module. Module *RootModule = new Module(RootModuleName, false); @@ -249,7 +248,8 @@ } } // Add as a module. - if (!addModuleDescription(RootModule, Header, HeaderPrefix, Dependencies, IsProblemFile)) + if (!addModuleDescription(RootModule, Header, HeaderPrefix, Dependencies, + IsProblemFile)) return nullptr; } @@ -310,9 +310,8 @@ llvm::StringRef RootModuleName) { // Load internal representation of modules. std::unique_ptr RootModule( - loadModuleDescriptions( - RootModuleName, HeaderFileNames, ProblemFileNames, Dependencies, - HeaderPrefix)); + loadModuleDescriptions(RootModuleName, HeaderFileNames, ProblemFileNames, + Dependencies, HeaderPrefix)); if (!RootModule.get()) return false; Index: modularize/PreprocessorTracker.cpp =================================================================== --- modularize/PreprocessorTracker.cpp +++ modularize/PreprocessorTracker.cpp @@ -244,14 +244,14 @@ // //===--------------------------------------------------------------------===// -#include "clang/Lex/LexDiagnostic.h" #include "PreprocessorTracker.h" +#include "ModularizeUtilities.h" +#include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/MacroArgs.h" #include "clang/Lex/PPCallbacks.h" #include "llvm/ADT/SmallSet.h" #include "llvm/Support/StringPool.h" #include "llvm/Support/raw_ostream.h" -#include "ModularizeUtilities.h" namespace Modularize { @@ -429,7 +429,7 @@ const clang::Token *ArgTok = Args->getUnexpArgument(ArgNo); if (Args->ArgNeedsPreexpansion(ArgTok, PP)) ResultArgToks = &(const_cast(Args)) - ->getPreExpArgument(ArgNo, MI, PP)[0]; + ->getPreExpArgument(ArgNo, MI, PP)[0]; else ResultArgToks = ArgTok; // Use non-preexpanded Tokens. // If the arg token didn't expand into anything, ignore it. @@ -459,10 +459,7 @@ namespace { // ConditionValueKind strings. -const char * -ConditionValueKindStrings[] = { - "(not evaluated)", "false", "true" -}; +const char *ConditionValueKindStrings[] = {"(not evaluated)", "false", "true"}; bool operator<(const StringHandle &H1, const StringHandle &H2) { const char *S1 = (H1 ? *H1 : ""); @@ -650,7 +647,9 @@ // for use in telling the user the nested include path to the header. class ConditionalExpansionInstance { public: - ConditionalExpansionInstance(clang::PPCallbacks::ConditionValueKind ConditionValue, InclusionPathHandle H) + ConditionalExpansionInstance( + clang::PPCallbacks::ConditionValueKind ConditionValue, + InclusionPathHandle H) : ConditionValue(ConditionValue) { InclusionPathHandles.push_back(H); } @@ -699,8 +698,8 @@ ConditionalTracker() {} // Find a matching condition expansion instance. - ConditionalExpansionInstance * - findConditionalExpansionInstance(clang::PPCallbacks::ConditionValueKind ConditionValue) { + ConditionalExpansionInstance *findConditionalExpansionInstance( + clang::PPCallbacks::ConditionValueKind ConditionValue) { for (std::vector::iterator I = ConditionalExpansionInstances.begin(), E = ConditionalExpansionInstances.end(); @@ -713,9 +712,9 @@ } // Add a conditional expansion instance. - void - addConditionalExpansionInstance(clang::PPCallbacks::ConditionValueKind ConditionValue, - InclusionPathHandle InclusionPathHandle) { + void addConditionalExpansionInstance( + clang::PPCallbacks::ConditionValueKind ConditionValue, + InclusionPathHandle InclusionPathHandle) { ConditionalExpansionInstances.push_back( ConditionalExpansionInstance(ConditionValue, InclusionPathHandle)); } @@ -786,12 +785,12 @@ // Preprocessor macro expansion item map types. typedef std::map MacroExpansionMap; typedef std::map::iterator -MacroExpansionMapIter; + MacroExpansionMapIter; // Preprocessor conditional expansion item map types. typedef std::map ConditionalExpansionMap; typedef std::map::iterator -ConditionalExpansionMapIter; + ConditionalExpansionMapIter; // Preprocessor tracker for modularize. // @@ -800,14 +799,14 @@ class PreprocessorTrackerImpl : public PreprocessorTracker { public: PreprocessorTrackerImpl(llvm::SmallVector &Headers, - bool DoBlockCheckHeaderListOnly) + bool DoBlockCheckHeaderListOnly) : BlockCheckHeaderListOnly(DoBlockCheckHeaderListOnly), CurrentInclusionPathHandle(InclusionPathHandleInvalid), InNestedHeader(false) { // Use canonical header path representation. for (llvm::ArrayRef::iterator I = Headers.begin(), - E = Headers.end(); - I != E; ++I) { + E = Headers.end(); + I != E; ++I) { HeaderList.push_back(getCanonicalPath(*I)); } } @@ -820,8 +819,8 @@ HeadersInThisCompile.clear(); assert((HeaderStack.size() == 0) && "Header stack should be empty."); pushHeaderHandle(addHeader(rootHeaderFile)); - PP.addPPCallbacks(llvm::make_unique(*this, PP, - rootHeaderFile)); + PP.addPPCallbacks( + llvm::make_unique(*this, PP, rootHeaderFile)); } // Handle exiting a preprocessing session. void handlePreprocessorExit() override { HeaderStack.clear(); } @@ -941,8 +940,8 @@ bool isHeaderListHeader(llvm::StringRef HeaderPath) const { std::string CanonicalPath = getCanonicalPath(HeaderPath); for (llvm::ArrayRef::iterator I = HeaderList.begin(), - E = HeaderList.end(); - I != E; ++I) { + E = HeaderList.end(); + I != E; ++I) { if (*I == CanonicalPath) return true; } @@ -1101,13 +1100,13 @@ } // Add a conditional expansion instance. - void - addConditionalExpansionInstance(clang::Preprocessor &PP, HeaderHandle H, - clang::SourceLocation InstanceLoc, - clang::tok::PPKeywordKind DirectiveKind, - clang::PPCallbacks::ConditionValueKind ConditionValue, - llvm::StringRef ConditionUnexpanded, - InclusionPathHandle InclusionPathHandle) { + void addConditionalExpansionInstance( + clang::Preprocessor &PP, HeaderHandle H, + clang::SourceLocation InstanceLoc, + clang::tok::PPKeywordKind DirectiveKind, + clang::PPCallbacks::ConditionValueKind ConditionValue, + llvm::StringRef ConditionUnexpanded, + InclusionPathHandle InclusionPathHandle) { // Ignore header guards, assuming the header guard is the only conditional. if (InNestedHeader) return; @@ -1291,9 +1290,9 @@ PreprocessorTracker::~PreprocessorTracker() {} // Create instance of PreprocessorTracker. -PreprocessorTracker *PreprocessorTracker::create( - llvm::SmallVector &Headers, - bool DoBlockCheckHeaderListOnly) { +PreprocessorTracker * +PreprocessorTracker::create(llvm::SmallVector &Headers, + bool DoBlockCheckHeaderListOnly) { return new PreprocessorTrackerImpl(Headers, DoBlockCheckHeaderListOnly); } @@ -1366,19 +1365,19 @@ (MI ? "true" : "false"), PPTracker.getCurrentInclusionPathHandle()); } -void PreprocessorCallbacks::If(clang::SourceLocation Loc, - clang::SourceRange ConditionRange, - clang::PPCallbacks::ConditionValueKind ConditionResult) { +void PreprocessorCallbacks::If( + clang::SourceLocation Loc, clang::SourceRange ConditionRange, + clang::PPCallbacks::ConditionValueKind ConditionResult) { std::string Unexpanded(getSourceString(PP, ConditionRange)); PPTracker.addConditionalExpansionInstance( PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_if, ConditionResult, Unexpanded, PPTracker.getCurrentInclusionPathHandle()); } -void PreprocessorCallbacks::Elif(clang::SourceLocation Loc, - clang::SourceRange ConditionRange, - clang::PPCallbacks::ConditionValueKind ConditionResult, - clang::SourceLocation IfLoc) { +void PreprocessorCallbacks::Elif( + clang::SourceLocation Loc, clang::SourceRange ConditionRange, + clang::PPCallbacks::ConditionValueKind ConditionResult, + clang::SourceLocation IfLoc) { std::string Unexpanded(getSourceString(PP, ConditionRange)); PPTracker.addConditionalExpansionInstance( PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_elif, @@ -1389,7 +1388,7 @@ const clang::Token &MacroNameTok, const clang::MacroDefinition &MD) { clang::PPCallbacks::ConditionValueKind IsDefined = - (MD ? clang::PPCallbacks::CVK_True : clang::PPCallbacks::CVK_False ); + (MD ? clang::PPCallbacks::CVK_True : clang::PPCallbacks::CVK_False); PPTracker.addConditionalExpansionInstance( PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_ifdef, IsDefined, PP.getSpelling(MacroNameTok), @@ -1400,7 +1399,7 @@ const clang::Token &MacroNameTok, const clang::MacroDefinition &MD) { clang::PPCallbacks::ConditionValueKind IsNotDefined = - (!MD ? clang::PPCallbacks::CVK_True : clang::PPCallbacks::CVK_False ); + (!MD ? clang::PPCallbacks::CVK_True : clang::PPCallbacks::CVK_False); PPTracker.addConditionalExpansionInstance( PP, PPTracker.getCurrentHeaderHandle(), Loc, clang::tok::pp_ifndef, IsNotDefined, PP.getSpelling(MacroNameTok), Index: pp-trace/PPCallbacksTracker.cpp =================================================================== --- pp-trace/PPCallbacksTracker.cpp +++ pp-trace/PPCallbacksTracker.cpp @@ -55,37 +55,31 @@ // FileChangeReason strings. static const char *const FileChangeReasonStrings[] = { - "EnterFile", "ExitFile", "SystemHeaderPragma", "RenameFile" -}; + "EnterFile", "ExitFile", "SystemHeaderPragma", "RenameFile"}; // CharacteristicKind strings. -static const char *const CharacteristicKindStrings[] = { "C_User", "C_System", - "C_ExternCSystem" }; +static const char *const CharacteristicKindStrings[] = {"C_User", "C_System", + "C_ExternCSystem"}; // MacroDirective::Kind strings. static const char *const MacroDirectiveKindStrings[] = { - "MD_Define","MD_Undefine", "MD_Visibility" -}; + "MD_Define", "MD_Undefine", "MD_Visibility"}; // PragmaIntroducerKind strings. -static const char *const PragmaIntroducerKindStrings[] = { "PIK_HashPragma", - "PIK__Pragma", - "PIK___pragma" }; +static const char *const PragmaIntroducerKindStrings[] = { + "PIK_HashPragma", "PIK__Pragma", "PIK___pragma"}; // PragmaMessageKind strings. static const char *const PragmaMessageKindStrings[] = { - "PMK_Message", "PMK_Warning", "PMK_Error" -}; + "PMK_Message", "PMK_Warning", "PMK_Error"}; // ConditionValueKind strings. static const char *const ConditionValueKindStrings[] = { - "CVK_NotEvaluated", "CVK_False", "CVK_True" -}; + "CVK_NotEvaluated", "CVK_False", "CVK_True"}; // Mapping strings. -static const char *const MappingStrings[] = { "0", "MAP_IGNORE", - "MAP_REMARK", "MAP_WARNING", - "MAP_ERROR", "MAP_FATAL" }; +static const char *const MappingStrings[] = { + "0", "MAP_IGNORE", "MAP_REMARK", "MAP_WARNING", "MAP_ERROR", "MAP_FATAL"}; // PPCallbacksTracker functions. @@ -111,10 +105,9 @@ // Callback invoked whenever a source file is skipped as the result // of header guard optimization. -void -PPCallbacksTracker::FileSkipped(const clang::FileEntry &SkippedFile, - const clang::Token &FilenameTok, - clang::SrcMgr::CharacteristicKind FileType) { +void PPCallbacksTracker::FileSkipped( + const clang::FileEntry &SkippedFile, const clang::Token &FilenameTok, + clang::SrcMgr::CharacteristicKind FileType) { beginCallback("FileSkipped"); appendArgument("ParentFile", &SkippedFile); appendArgument("FilenameTok", FilenameTok); @@ -123,9 +116,8 @@ // Callback invoked whenever an inclusion directive results in a // file-not-found error. -bool -PPCallbacksTracker::FileNotFound(llvm::StringRef FileName, - llvm::SmallVectorImpl &RecoveryPath) { +bool PPCallbacksTracker::FileNotFound( + llvm::StringRef FileName, llvm::SmallVectorImpl &RecoveryPath) { beginCallback("FileNotFound"); appendFilePathArgument("FileName", FileName); return false; @@ -174,9 +166,8 @@ } // Callback invoked when start reading any pragma directive. -void -PPCallbacksTracker::PragmaDirective(clang::SourceLocation Loc, - clang::PragmaIntroducerKind Introducer) { +void PPCallbacksTracker::PragmaDirective( + clang::SourceLocation Loc, clang::PragmaIntroducerKind Introducer) { beginCallback("PragmaDirective"); appendArgument("Loc", Loc); appendArgument("Introducer", Introducer, PragmaIntroducerKindStrings); @@ -300,11 +291,10 @@ // Called by Preprocessor::HandleMacroExpandedIdentifier when a // macro invocation is found. -void -PPCallbacksTracker::MacroExpands(const clang::Token &MacroNameTok, - const clang::MacroDefinition &MacroDefinition, - clang::SourceRange Range, - const clang::MacroArgs *Args) { +void PPCallbacksTracker::MacroExpands( + const clang::Token &MacroNameTok, + const clang::MacroDefinition &MacroDefinition, clang::SourceRange Range, + const clang::MacroArgs *Args) { beginCallback("MacroExpands"); appendArgument("MacroNameTok", MacroNameTok); appendArgument("MacroDefinition", MacroDefinition); @@ -313,9 +303,9 @@ } // Hook called whenever a macro definition is seen. -void -PPCallbacksTracker::MacroDefined(const clang::Token &MacroNameTok, - const clang::MacroDirective *MacroDirective) { +void PPCallbacksTracker::MacroDefined( + const clang::Token &MacroNameTok, + const clang::MacroDirective *MacroDirective) { beginCallback("MacroDefined"); appendArgument("MacroNameTok", MacroNameTok); appendArgument("MacroDirective", MacroDirective); @@ -570,7 +560,8 @@ Any = true; } for (auto *MM : Value.getModuleMacros()) { - if (Any) SS << ", "; + if (Any) + SS << ", "; SS << MM->getOwningModule()->getFullModuleName(); } SS << "]"; Index: pp-trace/PPTrace.cpp =================================================================== --- pp-trace/PPTrace.cpp +++ pp-trace/PPTrace.cpp @@ -110,8 +110,8 @@ PPTraceConsumer(SmallSet &Ignore, std::vector &CallbackCalls, Preprocessor &PP) { // PP takes ownership. - PP.addPPCallbacks(llvm::make_unique(Ignore, - CallbackCalls, PP)); + PP.addPPCallbacks( + llvm::make_unique(Ignore, CallbackCalls, PP)); } }; @@ -183,8 +183,9 @@ // Parse the IgnoreCallbacks list into strings. SmallVector IgnoreCallbacksStrings; - StringRef(IgnoreCallbacks).split(IgnoreCallbacksStrings, ",", - /*MaxSplit=*/ -1, /*KeepEmpty=*/false); + StringRef(IgnoreCallbacks) + .split(IgnoreCallbacksStrings, ",", + /*MaxSplit=*/-1, /*KeepEmpty=*/false); SmallSet Ignore; for (SmallVector::iterator I = IgnoreCallbacksStrings.begin(), E = IgnoreCallbacksStrings.end(); Index: test/clang-apply-replacements/Inputs/format/yes.cpp =================================================================== --- test/clang-apply-replacements/Inputs/format/yes.cpp +++ test/clang-apply-replacements/Inputs/format/yes.cpp @@ -1,6 +1,6 @@ class MyType012345678901234567890123456789 {}; -void g(int, int*, int, int*, int, int*, int); +void g(int, int *, int, int *, int, int *, int); void f() { MyType012345678901234567890123456789 *a = Index: test/clang-rename/ClassAsTemplateArgument.cpp =================================================================== --- test/clang-rename/ClassAsTemplateArgument.cpp +++ test/clang-rename/ClassAsTemplateArgument.cpp @@ -1,4 +1,4 @@ -class Foo /* Test 1 */ {}; // CHECK: class Bar /* Test 1 */ {}; +class Foo /* Test 1 */ {}; // CHECK: class Bar /* Test 1 */ {}; template void func() {} @@ -7,8 +7,8 @@ class Baz {}; int main() { - func(); // CHECK: func(); - Baz /* Test 2 */ obj; // CHECK: Baz /* Test 2 */ obj; + func(); // CHECK: func(); + Baz /* Test 2 */ obj; // CHECK: Baz /* Test 2 */ obj; return 0; } Index: test/clang-rename/ClassFindByName.cpp =================================================================== --- test/clang-rename/ClassFindByName.cpp +++ test/clang-rename/ClassFindByName.cpp @@ -1,4 +1,4 @@ -class Foo { // CHECK: class Bar { +class Foo { // CHECK: class Bar { }; int main() { Index: test/clang-rename/ClassSimpleRenaming.cpp =================================================================== --- test/clang-rename/ClassSimpleRenaming.cpp +++ test/clang-rename/ClassSimpleRenaming.cpp @@ -1,9 +1,9 @@ -class Foo /* Test 1 */ { // CHECK: class Bar /* Test 1 */ { +class Foo /* Test 1 */ { // CHECK: class Bar /* Test 1 */ { public: void foo(int x); }; -void Foo::foo(int x) /* Test 2 */ {} // CHECK: void Bar::foo(int x) /* Test 2 */ {} +void Foo::foo(int x) /* Test 2 */ {} // CHECK: void Bar::foo(int x) /* Test 2 */ {} // Test 1. // RUN: clang-rename -offset=6 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s Index: test/clang-rename/ComplexFunctionOverride.cpp =================================================================== --- test/clang-rename/ComplexFunctionOverride.cpp +++ test/clang-rename/ComplexFunctionOverride.cpp @@ -1,34 +1,34 @@ struct A { - virtual void foo() {} /* Test 1 */ // CHECK: virtual void bar() {} + virtual void foo() {} /* Test 1 */ // CHECK: virtual void bar() {} }; struct B : A { - void foo() override {} /* Test 2 */ // CHECK: void bar() override {} + void foo() override {} /* Test 2 */ // CHECK: void bar() override {} }; struct C : B { - void foo() override {} /* Test 3 */ // CHECK: void bar() override {} + void foo() override {} /* Test 3 */ // CHECK: void bar() override {} }; struct D : B { - void foo() override {} /* Test 4 */ // CHECK: void bar() override {} + void foo() override {} /* Test 4 */ // CHECK: void bar() override {} }; struct E : D { - void foo() override {} /* Test 5 */ // CHECK: void bar() override {} + void foo() override {} /* Test 5 */ // CHECK: void bar() override {} }; int main() { A a; - a.foo(); // CHECK: a.bar(); + a.foo(); // CHECK: a.bar(); B b; - b.foo(); // CHECK: b.bar(); + b.foo(); // CHECK: b.bar(); C c; - c.foo(); // CHECK: c.bar(); + c.foo(); // CHECK: c.bar(); D d; - d.foo(); // CHECK: d.bar(); + d.foo(); // CHECK: d.bar(); E e; - e.foo(); // CHECK: e.bar(); + e.foo(); // CHECK: e.bar(); return 0; } Index: test/clang-rename/ComplicatedClassType.cpp =================================================================== --- test/clang-rename/ComplicatedClassType.cpp +++ test/clang-rename/ComplicatedClassType.cpp @@ -1,20 +1,20 @@ // Forward declaration. -class Foo; /* Test 1 */ // CHECK: class Bar; /* Test 1 */ +class Foo; /* Test 1 */ // CHECK: class Bar; /* Test 1 */ class Baz { virtual int getValue() const = 0; }; -class Foo : public Baz { /* Test 2 */// CHECK: class Bar : public Baz { +class Foo : public Baz { /* Test 2 */ // CHECK: class Bar : public Baz { public: - Foo(int value = 0) : x(value) {} // CHECK: Bar(int value = 0) : x(value) {} + Foo(int value = 0) : x(value) {} // CHECK: Bar(int value = 0) : x(value) {} - Foo &operator++(int) { // CHECK: Bar &operator++(int) { + Foo &operator++(int) { // CHECK: Bar &operator++(int) { x++; return *this; } - bool operator<(Foo const &rhs) { // CHECK: bool operator<(Bar const &rhs) { + bool operator<(Foo const &rhs) { // CHECK: bool operator<(Bar const &rhs) { return this->x < rhs.x; } @@ -31,16 +31,16 @@ Foo Variable = Foo(10); // CHECK: Bar Variable = Bar(10); for (Foo it; it < Variable; it++) { // CHECK: for (Bar it; it < Variable; it++) { } - const Foo *C = new Foo(); // CHECK: const Bar *C = new Bar(); - const_cast(C)->getValue(); // CHECK: const_cast(C)->getValue(); - Foo foo; // CHECK: Bar foo; + const Foo *C = new Foo(); // CHECK: const Bar *C = new Bar(); + const_cast(C)->getValue(); // CHECK: const_cast(C)->getValue(); + Foo foo; // CHECK: Bar foo; const Baz &BazReference = foo; const Baz *BazPointer = &foo; - dynamic_cast(BazReference).getValue(); /* Test 3 */ // CHECK: dynamic_cast(BazReference).getValue(); - dynamic_cast(BazPointer)->getValue(); /* Test 4 */ // CHECK: dynamic_cast(BazPointer)->getValue(); - reinterpret_cast(BazPointer)->getValue(); /* Test 5 */ // CHECK: reinterpret_cast(BazPointer)->getValue(); - static_cast(BazReference).getValue(); /* Test 6 */ // CHECK: static_cast(BazReference).getValue(); - static_cast(BazPointer)->getValue(); /* Test 7 */ // CHECK: static_cast(BazPointer)->getValue(); + dynamic_cast(BazReference).getValue(); /* Test 3 */ // CHECK: dynamic_cast(BazReference).getValue(); + dynamic_cast(BazPointer)->getValue(); /* Test 4 */ // CHECK: dynamic_cast(BazPointer)->getValue(); + reinterpret_cast(BazPointer)->getValue(); /* Test 5 */ // CHECK: reinterpret_cast(BazPointer)->getValue(); + static_cast(BazReference).getValue(); /* Test 6 */ // CHECK: static_cast(BazReference).getValue(); + static_cast(BazPointer)->getValue(); /* Test 7 */ // CHECK: static_cast(BazPointer)->getValue(); return 0; } Index: test/clang-rename/Ctor.cpp =================================================================== --- test/clang-rename/Ctor.cpp +++ test/clang-rename/Ctor.cpp @@ -1,9 +1,9 @@ -class Foo { // CHECK: class Bar { +class Foo { // CHECK: class Bar { public: - Foo(); /* Test 1 */ // CHECK: Bar(); + Foo(); /* Test 1 */ // CHECK: Bar(); }; -Foo::Foo() /* Test 2 */ {} // CHECK: Bar::Bar() /* Test 2 */ {} +Foo::Foo() /* Test 2 */ {} // CHECK: Bar::Bar() /* Test 2 */ {} // Test 1. // RUN: clang-rename -offset=62 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s Index: test/clang-rename/CtorInitializer.cpp =================================================================== --- test/clang-rename/CtorInitializer.cpp +++ test/clang-rename/CtorInitializer.cpp @@ -1,12 +1,12 @@ class Baz {}; class Qux { - Baz Foo; /* Test 1 */ // CHECK: Baz Bar; + Baz Foo; /* Test 1 */ // CHECK: Baz Bar; public: Qux(); }; -Qux::Qux() : Foo() /* Test 2 */ {} // CHECK: Qux::Qux() : Bar() /* Test 2 */ {} +Qux::Qux() : Foo() /* Test 2 */ {} // CHECK: Qux::Qux() : Bar() /* Test 2 */ {} // Test 1. // RUN: clang-rename -offset=33 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s Index: test/clang-rename/DeclRefExpr.cpp =================================================================== --- test/clang-rename/DeclRefExpr.cpp +++ test/clang-rename/DeclRefExpr.cpp @@ -1,15 +1,15 @@ class C { public: - static int Foo; /* Test 1 */ // CHECK: static int Bar; + static int Foo; /* Test 1 */ // CHECK: static int Bar; }; int foo(int x) { return 0; } #define MACRO(a) foo(a) int main() { - C::Foo = 1; /* Test 2 */ // CHECK: C::Bar = 1; - MACRO(C::Foo); // CHECK: MACRO(C::Bar); - int y = C::Foo; /* Test 3 */ // CHECK: int y = C::Bar; + C::Foo = 1; /* Test 2 */ // CHECK: C::Bar = 1; + MACRO(C::Foo); // CHECK: MACRO(C::Bar); + int y = C::Foo; /* Test 3 */ // CHECK: int y = C::Bar; return 0; } Index: test/clang-rename/Field.cpp =================================================================== --- test/clang-rename/Field.cpp +++ test/clang-rename/Field.cpp @@ -4,7 +4,7 @@ Baz(); }; -Baz::Baz() : Foo(0) /* Test 2 */ {} // CHECK: Baz::Baz() : Bar(0) +Baz::Baz() : Foo(0) /* Test 2 */ {} // CHECK: Baz::Baz() : Bar(0) // Test 1. // RUN: clang-rename -offset=18 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s Index: test/clang-rename/FunctionMacro.cpp =================================================================== --- test/clang-rename/FunctionMacro.cpp +++ test/clang-rename/FunctionMacro.cpp @@ -1,14 +1,14 @@ -#define moo foo // CHECK: #define moo macro_function +#define moo foo // CHECK: #define moo macro_function -int foo() /* Test 1 */ { // CHECK: int macro_function() /* Test 1 */ { +int foo() /* Test 1 */ { // CHECK: int macro_function() /* Test 1 */ { return 42; } void boo(int value) {} void qoo() { - foo(); // CHECK: macro_function(); - boo(foo()); // CHECK: boo(macro_function()); + foo(); // CHECK: macro_function(); + boo(foo()); // CHECK: boo(macro_function()); moo(); boo(moo()); } Index: test/clang-rename/FunctionOverride.cpp =================================================================== --- test/clang-rename/FunctionOverride.cpp +++ test/clang-rename/FunctionOverride.cpp @@ -1,6 +1,12 @@ -class A { virtual void foo(); /* Test 1 */ }; // CHECK: class A { virtual void bar(); -class B : public A { void foo(); /* Test 2 */ }; // CHECK: class B : public A { void bar(); -class C : public B { void foo(); /* Test 3 */ }; // CHECK: class C : public B { void bar(); +class A { + virtual void foo(); /* Test 1 */ +}; // CHECK: class A { virtual void bar(); +class B : public A { + void foo(); /* Test 2 */ +}; // CHECK: class B : public A { void bar(); +class C : public B { + void foo(); /* Test 3 */ +}; // CHECK: class C : public B { void bar(); // Test 1. // RUN: clang-rename -offset=23 -new-name=bar %s -- | sed 's,//.*,,' | FileCheck %s Index: test/clang-rename/FunctionWithClassFindByName.cpp =================================================================== --- test/clang-rename/FunctionWithClassFindByName.cpp +++ test/clang-rename/FunctionWithClassFindByName.cpp @@ -1,7 +1,7 @@ void foo() { } -class Foo { // CHECK: class Bar +class Foo { // CHECK: class Bar }; int main() { Index: test/clang-rename/MemberExprMacro.cpp =================================================================== --- test/clang-rename/MemberExprMacro.cpp +++ test/clang-rename/MemberExprMacro.cpp @@ -1,6 +1,6 @@ class Baz { public: - int Foo; /* Test 1 */ // CHECK: int Bar; + int Foo; /* Test 1 */ // CHECK: int Bar; }; int qux(int x) { return 0; } Index: test/clang-rename/Namespace.cpp =================================================================== --- test/clang-rename/Namespace.cpp +++ test/clang-rename/Namespace.cpp @@ -1,9 +1,9 @@ -namespace gcc /* Test 1 */ { // CHECK: namespace clang /* Test 1 */ { - int x; +namespace gcc /* Test 1 */ { // CHECK: namespace clang /* Test 1 */ { +int x; } void boo() { - gcc::x = 42; // CHECK: clang::x = 42; + gcc::x = 42; // CHECK: clang::x = 42; } // Test 1. Index: test/clang-rename/TemplateClassInstantiation.cpp =================================================================== --- test/clang-rename/TemplateClassInstantiation.cpp +++ test/clang-rename/TemplateClassInstantiation.cpp @@ -1,7 +1,7 @@ template -class Foo { /* Test 1 */ // CHECK: class Bar { /* Test 1 */ +class Foo { /* Test 1 */ // CHECK: class Bar { /* Test 1 */ public: - T foo(T arg, T& ref, T* ptr) { + T foo(T arg, T &ref, T *ptr) { T value; int number = 42; value = (T)number; @@ -14,19 +14,19 @@ template void func() { - Foo obj; /* Test 2 */ // CHECK: Bar obj; + Foo obj; /* Test 2 */ // CHECK: Bar obj; obj.member = T(); - Foo::foo(); // CHECK: Bar::foo(); + Foo::foo(); // CHECK: Bar::foo(); } int main() { - Foo i; /* Test 3 */ // CHECK: Bar i; + Foo i; /* Test 3 */ // CHECK: Bar i; i.member = 0; - Foo::foo(0); // CHECK: Bar::foo(0); + Foo::foo(0); // CHECK: Bar::foo(0); - Foo b; // CHECK: Bar b; + Foo b; // CHECK: Bar b; b.member = false; - Foo::foo(false); // CHECK: Bar::foo(false); + Foo::foo(false); // CHECK: Bar::foo(false); return 0; } Index: test/clang-rename/TemplateTypename.cpp =================================================================== --- test/clang-rename/TemplateTypename.cpp +++ test/clang-rename/TemplateTypename.cpp @@ -1,16 +1,16 @@ -template // CHECK: template +template // CHECK: template class Foo { -T foo(T arg, T& ref, T* /* Test 2 */ ptr) { // CHECK: U foo(U arg, U& ref, U* /* Test 2 */ ptr) { - T value; // CHECK: U value; - int number = 42; - value = (T)number; // CHECK: value = (U)number; - value = static_cast(number); // CHECK: value = static_cast(number); - return value; -} + T foo(T arg, T &ref, T * /* Test 2 */ ptr) { // CHECK: U foo(U arg, U& ref, U* /* Test 2 */ ptr) { + T value; // CHECK: U value; + int number = 42; + value = (T)number; // CHECK: value = (U)number; + value = static_cast(number); // CHECK: value = static_cast(number); + return value; + } -static void foo(T value) {} // CHECK: static void foo(U value) {} + static void foo(T value) {} // CHECK: static void foo(U value) {} -T member; // CHECK: U member; + T member; // CHECK: U member; }; // Test 1. Index: test/clang-rename/TemplatedClassFunction.cpp =================================================================== --- test/clang-rename/TemplatedClassFunction.cpp +++ test/clang-rename/TemplatedClassFunction.cpp @@ -1,12 +1,12 @@ template class A { public: - void foo() /* Test 1 */ {} // CHECK: void bar() /* Test 1 */ {} + void foo() /* Test 1 */ {} // CHECK: void bar() /* Test 1 */ {} }; int main(int argc, char **argv) { A a; - a.foo(); /* Test 2 */ // CHECK: a.bar() /* Test 2 */ + a.foo(); /* Test 2 */ // CHECK: a.bar() /* Test 2 */ return 0; } Index: test/clang-rename/UserDefinedConversion.cpp =================================================================== --- test/clang-rename/UserDefinedConversion.cpp +++ test/clang-rename/UserDefinedConversion.cpp @@ -1,19 +1,19 @@ -class Foo { /* Test 1 */ // CHECK: class Bar { +class Foo { /* Test 1 */ // CHECK: class Bar { public: - Foo() {} // CHECK: Bar() {} + Foo() {} // CHECK: Bar() {} }; class Baz { public: - operator Foo() /* Test 2 */ const { // CHECK: operator Bar() /* Test 2 */ const { - Foo foo; // CHECK: Bar foo; + operator Foo() /* Test 2 */ const { // CHECK: operator Bar() /* Test 2 */ const { + Foo foo; // CHECK: Bar foo; return foo; } }; int main() { Baz boo; - Foo foo = static_cast(boo); // CHECK: Bar foo = static_cast(boo); + Foo foo = static_cast(boo); // CHECK: Bar foo = static_cast(boo); return 0; } Index: test/clang-rename/Variable.cpp =================================================================== --- test/clang-rename/Variable.cpp +++ test/clang-rename/Variable.cpp @@ -1,22 +1,22 @@ namespace A { -int Foo; /* Test 1 */ // CHECK: int Bar; +int Foo; /* Test 1 */ // CHECK: int Bar; } -int Foo; // CHECK: int Foo; -int Qux = Foo; // CHECK: int Qux = Foo; -int Baz = A::Foo; /* Test 2 */ // CHECK: Baz = A::Bar; +int Foo; // CHECK: int Foo; +int Qux = Foo; // CHECK: int Qux = Foo; +int Baz = A::Foo; /* Test 2 */ // CHECK: Baz = A::Bar; void fun() { struct { - int Foo; // CHECK: int Foo; + int Foo; // CHECK: int Foo; } b = {100}; - int Foo = 100; // CHECK: int Foo = 100; - Baz = Foo; // CHECK: Baz = Foo; + int Foo = 100; // CHECK: int Foo = 100; + Baz = Foo; // CHECK: Baz = Foo; { - extern int Foo; // CHECK: extern int Foo; - Baz = Foo; // CHECK: Baz = Foo; - Foo = A::Foo /* Test 3 */ + Baz; // CHECK: Foo = A::Bar /* Test 3 */ + Baz; - A::Foo /* Test 4 */ = b.Foo; // CHECK: A::Bar /* Test 4 */ = b.Foo; + extern int Foo; // CHECK: extern int Foo; + Baz = Foo; // CHECK: Baz = Foo; + Foo = A::Foo /* Test 3 */ + Baz; // CHECK: Foo = A::Bar /* Test 3 */ + Baz; + A::Foo /* Test 4 */ = b.Foo; // CHECK: A::Bar /* Test 4 */ = b.Foo; } - Foo = b.Foo; // Foo = b.Foo; + Foo = b.Foo; // Foo = b.Foo; } // Test 1. Index: test/clang-rename/VariableMacro.cpp =================================================================== --- test/clang-rename/VariableMacro.cpp +++ test/clang-rename/VariableMacro.cpp @@ -3,10 +3,10 @@ void foo(int value) {} void macro() { - int Foo; /* Test 1 */ // CHECK: int Bar; - Foo = 42; /* Test 2 */ // CHECK: Bar = 42; + int Foo; /* Test 1 */ // CHECK: int Bar; + Foo = 42; /* Test 2 */ // CHECK: Bar = 42; Baz -= 0; - foo(Foo); /* Test 3 */ // CHECK: foo(Bar); + foo(Foo); /* Test 3 */ // CHECK: foo(Bar); foo(Baz); } Index: test/clang-reorder-fields/AggregatePartialInitialization.cpp =================================================================== --- test/clang-reorder-fields/AggregatePartialInitialization.cpp +++ test/clang-reorder-fields/AggregatePartialInitialization.cpp @@ -3,12 +3,12 @@ // The order of fields should not change. class Foo { public: - int x; // CHECK: {{^ int x;}} - int y; // CHECK-NEXT: {{^ int y;}} - int z; // CHECK-NEXT: {{^ int z;}} + int x; // CHECK: {{^ int x;}} + int y; // CHECK-NEXT: {{^ int y;}} + int z; // CHECK-NEXT: {{^ int z;}} }; int main() { - Foo foo = { 0, 1 }; // CHECK: {{^ Foo foo = { 0, 1 };}} + Foo foo = {0, 1}; // CHECK: {{^ Foo foo = { 0, 1 };}} return 0; } Index: test/clang-reorder-fields/CStructAmbiguousName.cpp =================================================================== --- test/clang-reorder-fields/CStructAmbiguousName.cpp +++ test/clang-reorder-fields/CStructAmbiguousName.cpp @@ -13,6 +13,6 @@ } // end namespace bar int main() { - bar::Foo foo = { 1, 1.7 }; // CHECK: {{^ bar::Foo foo = { 1, 1.7 };}} + bar::Foo foo = {1, 1.7}; // CHECK: {{^ bar::Foo foo = { 1, 1.7 };}} return 0; } Index: test/clang-reorder-fields/CStructFieldsOrder.cpp =================================================================== --- test/clang-reorder-fields/CStructFieldsOrder.cpp +++ test/clang-reorder-fields/CStructFieldsOrder.cpp @@ -2,7 +2,7 @@ namespace bar { struct Foo { - const int* x; // CHECK: {{^ double z;}} + const int *x; // CHECK: {{^ double z;}} int y; // CHECK-NEXT: {{^ int w;}} double z; // CHECK-NEXT: {{^ int y;}} int w; // CHECK-NEXT: {{^ const int\* x}} @@ -11,6 +11,6 @@ int main() { const int x = 13; - bar::Foo foo = { &x, 0, 1.29, 17 }; // CHECK: {{^ bar::Foo foo = { 1.29, 17, 0, &x };}} + bar::Foo foo = {&x, 0, 1.29, 17}; // CHECK: {{^ bar::Foo foo = { 1.29, 17, 0, &x };}} return 0; } Index: test/clang-reorder-fields/ClassDifferentFieldsAccesses.cpp =================================================================== --- test/clang-reorder-fields/ClassDifferentFieldsAccesses.cpp +++ test/clang-reorder-fields/ClassDifferentFieldsAccesses.cpp @@ -3,11 +3,11 @@ // The order of fields should not change. class Foo { public: - int x; // CHECK: {{^ int x;}} + int x; // CHECK: {{^ int x;}} private: - int y; // CHECK: {{^ int y;}} - int z; // CHECK-NEXT: {{^ int z;}} + int y; // CHECK: {{^ int y;}} + int z; // CHECK-NEXT: {{^ int z;}} }; int main() { Index: test/clang-reorder-fields/ClassMixedInitialization.cpp =================================================================== --- test/clang-reorder-fields/ClassMixedInitialization.cpp +++ test/clang-reorder-fields/ClassMixedInitialization.cpp @@ -5,17 +5,16 @@ Foo(); private: - int x; // CHECK: {{^ double e = 2.71;}} - const char *s1; // CHECK-NEXT: {{^ int x;}} - const char *s2; // CHECK-NEXT: {{^ double pi = 3.14;}} - double pi = 3.14; // CHECK-NEXT: {{^ const char \*s2;}} - double e = 2.71; // CHECK-NEXT: {{^ const char \*s1;}} + int x; // CHECK: {{^ double e = 2.71;}} + const char *s1; // CHECK-NEXT: {{^ int x;}} + const char *s2; // CHECK-NEXT: {{^ double pi = 3.14;}} + double pi = 3.14; // CHECK-NEXT: {{^ const char \*s2;}} + double e = 2.71; // CHECK-NEXT: {{^ const char \*s1;}} }; -Foo::Foo(): - x(12), // CHECK: {{^ x\(12\)}}, - s1("abc"), // CHECK-NEXT: {{^ s2\("def"\)}}, - s2("def") // CHECK-NEXT: {{^ s1\("abc"\)}} +Foo::Foo() : x(12), // CHECK: {{^ x\(12\)}}, + s1("abc"), // CHECK-NEXT: {{^ s2\("def"\)}}, + s2("def") // CHECK-NEXT: {{^ s1\("abc"\)}} {} int main() { Index: test/clang-reorder-fields/ClassSimpleCtor.cpp =================================================================== --- test/clang-reorder-fields/ClassSimpleCtor.cpp +++ test/clang-reorder-fields/ClassSimpleCtor.cpp @@ -5,17 +5,16 @@ Foo(); private: - int x; // CHECK: {{^ const char \*s1;}} - const char *s1; // CHECK-NEXT: {{^ int x;}} - const char *s2; // CHECK-NEXT: {{^ double z;}} - double z; // CHECK-NEXT: {{^ const char \*s2;}} + int x; // CHECK: {{^ const char \*s1;}} + const char *s1; // CHECK-NEXT: {{^ int x;}} + const char *s2; // CHECK-NEXT: {{^ double z;}} + double z; // CHECK-NEXT: {{^ const char \*s2;}} }; -Foo::Foo(): - x(12), // CHECK: {{^ s1\("abc"\),}} - s1("abc"), // CHECK-NEXT: {{^ x\(12\),}} - s2("def"), // CHECK-NEXT: {{^ z\(3.14\),}} - z(3.14) // CHECK-NEXT: {{^ s2\("def"\)}} +Foo::Foo() : x(12), // CHECK: {{^ s1\("abc"\),}} + s1("abc"), // CHECK-NEXT: {{^ x\(12\),}} + s2("def"), // CHECK-NEXT: {{^ z\(3.14\),}} + z(3.14) // CHECK-NEXT: {{^ s2\("def"\)}} {} int main() { Index: test/clang-tidy/boost-use-to-string.cpp =================================================================== --- test/clang-tidy/boost-use-to-string.cpp +++ test/clang-tidy/boost-use-to-string.cpp @@ -27,7 +27,7 @@ // CHECK-FIXES: auto xa = std::to_string(5); auto z = boost::lexical_cast(42LL); - // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use std::to_string + // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: use std::to_string // CHECK-FIXES: auto z = std::to_string(42LL); // this should not trigger @@ -49,22 +49,22 @@ bool j; fun(boost::lexical_cast(a)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string // CHECK-FIXES: fun(std::to_string(a)); fun(boost::lexical_cast(b)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string // CHECK-FIXES: fun(std::to_string(b)); fun(boost::lexical_cast(c)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string // CHECK-FIXES: fun(std::to_string(c)); fun(boost::lexical_cast(d)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string // CHECK-FIXES: fun(std::to_string(d)); fun(boost::lexical_cast(e)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string // CHECK-FIXES: fun(std::to_string(e)); fun(boost::lexical_cast(f)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_string // CHECK-FIXES: fun(std::to_string(f)); // No change for floating numbers. @@ -93,19 +93,19 @@ // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring instead of boost::lexical_cast [boost-use-to-string] // CHECK-FIXES: fun(std::to_wstring(a)); fun(boost::lexical_cast(b)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring // CHECK-FIXES: fun(std::to_wstring(b)); fun(boost::lexical_cast(c)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring // CHECK-FIXES: fun(std::to_wstring(c)); fun(boost::lexical_cast(d)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring // CHECK-FIXES: fun(std::to_wstring(d)); fun(boost::lexical_cast(e)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring // CHECK-FIXES: fun(std::to_wstring(e)); fun(boost::lexical_cast(f)); - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use std::to_wstring // CHECK-FIXES: fun(std::to_wstring(f)); // No change for floating numbers @@ -151,8 +151,8 @@ struct Fields { int integer; float floating; - Fields* wierd; - const int &getConstInteger() const {return integer;} + Fields *wierd; + const int &getConstInteger() const { return integer; } }; void testFields() { Index: test/clang-tidy/cert-env33-c.c =================================================================== --- test/clang-tidy/cert-env33-c.c +++ test/clang-tidy/cert-env33-c.c @@ -1,6 +1,7 @@ // RUN: %check_clang_tidy %s cert-env33-c %t -typedef struct FILE {} FILE; +typedef struct FILE { +} FILE; extern int system(const char *); extern FILE *popen(const char *, const char *); Index: test/clang-tidy/cert-err34-c.c =================================================================== --- test/clang-tidy/cert-err34-c.c +++ test/clang-tidy/cert-err34-c.c @@ -1,16 +1,16 @@ // RUN: %check_clang_tidy %s cert-err34-c %t -- -- -std=c11 -typedef __SIZE_TYPE__ size_t; -typedef signed ptrdiff_t; -typedef long long intmax_t; +typedef __SIZE_TYPE__ size_t; +typedef signed ptrdiff_t; +typedef long long intmax_t; typedef unsigned long long uintmax_t; -typedef void * FILE; +typedef void *FILE; extern FILE *stdin; -extern int fscanf(FILE * restrict stream, const char * restrict format, ...); -extern int scanf(const char * restrict format, ...); -extern int sscanf(const char * restrict s, const char * restrict format, ...); +extern int fscanf(FILE *restrict stream, const char *restrict format, ...); +extern int scanf(const char *restrict format, ...); +extern int sscanf(const char *restrict s, const char *restrict format, ...); extern double atof(const char *nptr); extern int atoi(const char *nptr); @@ -99,5 +99,5 @@ char str[32]; scanf("%s", str); // Not a numerical conversion - scanf("%*d"); // Assignment suppressed + scanf("%*d"); // Assignment suppressed } Index: test/clang-tidy/cert-err34-c.cpp =================================================================== --- test/clang-tidy/cert-err34-c.cpp +++ test/clang-tidy/cert-err34-c.cpp @@ -1,11 +1,11 @@ // RUN: %check_clang_tidy %s cert-err34-c %t -- -- -std=c++11 -typedef void * FILE; +typedef void *FILE; extern FILE *stdin; -extern int fscanf(FILE * stream, const char * format, ...); -extern int sscanf(const char * s, const char * format, ...); +extern int fscanf(FILE *stream, const char *format, ...); +extern int sscanf(const char *s, const char *format, ...); extern double atof(const char *nptr); extern int atoi(const char *nptr); @@ -13,9 +13,14 @@ extern long long int atoll(const char *nptr); namespace std { -using ::FILE; using ::stdin; -using ::fscanf; using ::sscanf; -using ::atof; using ::atoi; using ::atol; using ::atoll; +using ::FILE; +using ::stdin; +using ::fscanf; +using ::sscanf; +using ::atof; +using ::atoi; +using ::atol; +using ::atoll; } void f1(const char *in) { Index: test/clang-tidy/cert-flp30-c.c =================================================================== --- test/clang-tidy/cert-flp30-c.c +++ test/clang-tidy/cert-flp30-c.c @@ -3,17 +3,22 @@ float g(void); void func(void) { - for (float x = 0.1f; x <= 1.0f; x += 0.1f) {} + for (float x = 0.1f; x <= 1.0f; x += 0.1f) { + } // CHECK-MESSAGES: :[[@LINE-1]]:37: warning: loop induction expression should not have floating-point type [cert-flp30-c] float f = 1.0f; - for (; f > 0; --f) {} + for (; f > 0; --f) { + } // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: loop induction expression - for (;;g()) {} + for (;; g()) { + } // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: loop induction expression - for (int i = 0; i < 10; i += 1.0f) {} + for (int i = 0; i < 10; i += 1.0f) { + } - for (int i = 0; i < 10; ++i) {} + for (int i = 0; i < 10; ++i) { + } } Index: test/clang-tidy/cert-limited-randomness.cpp =================================================================== --- test/clang-tidy/cert-limited-randomness.cpp +++ test/clang-tidy/cert-limited-randomness.cpp @@ -8,7 +8,7 @@ } namespace nonstd { - int rand(); +int rand(); } void testFunction1() { @@ -25,4 +25,3 @@ int m = rand(); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: rand() has limited randomness; use C++11 random library instead [cert-msc50-cpp] } - Index: test/clang-tidy/cert-oop11-cpp.cpp =================================================================== --- test/clang-tidy/cert-oop11-cpp.cpp +++ test/clang-tidy/cert-oop11-cpp.cpp @@ -1,10 +1,11 @@ // RUN: %check_clang_tidy %s cert-oop11-cpp %t -- -- -std=c++11 struct B { - B(B&&) noexcept = default; + B(B &&) + noexcept = default; B(const B &) = default; - B& operator=(const B&) = default; + B &operator=(const B &) = default; ~B() {} }; Index: test/clang-tidy/cert-static-object-exception.cpp =================================================================== --- test/clang-tidy/cert-static-object-exception.cpp +++ test/clang-tidy/cert-static-object-exception.cpp @@ -1,11 +1,13 @@ // RUN: %check_clang_tidy %s cert-err58-cpp %t -- -- -std=c++11 -target x86_64-pc-linux-gnu struct S { - S() noexcept(false); + S() + noexcept(false); }; struct T { - T() noexcept; + T() + noexcept; }; struct U { @@ -21,11 +23,13 @@ }; struct W { - W(Cleanup c = {}) noexcept(false); + W(Cleanup c = {}) + noexcept(false); }; struct X { - X(S = {}) noexcept; + X(S = {}) + noexcept; }; struct Y { @@ -94,7 +98,6 @@ int *p = new int(); // CHECK-MESSAGES: :[[@LINE-1]]:6: warning: initialization of 'p' with static storage duration may throw an exception that cannot be caught - thread_local S s3; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: initialization of 's3' with thread_local storage duration may throw an exception that cannot be caught thread_local T t3; // ok @@ -106,23 +109,23 @@ // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: initialization of 'w3' with thread_local storage duration may throw an exception that cannot be caught void f(S s1, T t1, U u1, V v1, W w1) { // ok, ok, ok, ok, ok - S s2; // ok - T t2; // ok - U u2; // ok - V v2("v"); // ok - W w2; // ok - - thread_local S s3; // ok - thread_local T t3; // ok - thread_local U u3; // ok + S s2; // ok + T t2; // ok + U u2; // ok + V v2("v"); // ok + W w2; // ok + + thread_local S s3; // ok + thread_local T t3; // ok + thread_local U u3; // ok thread_local V v3("v"); // ok - thread_local W w3; // ok + thread_local W w3; // ok - static S s4; // ok - static T t4; // ok - static U u4; // ok + static S s4; // ok + static T t4; // ok + static U u4; // ok static V v4("v"); // ok - static W w4; // ok + static W w4; // ok } namespace { Index: test/clang-tidy/cert-throw-exception-type.cpp =================================================================== --- test/clang-tidy/cert-throw-exception-type.cpp +++ test/clang-tidy/cert-throw-exception-type.cpp @@ -4,64 +4,74 @@ struct T : S {}; struct U { U() = default; - U(const U&) = default; + U(const U &) = default; }; struct V { V() = default; - V(const V&) noexcept; + V(const V &) + noexcept; }; struct W { W() = default; - W(const W&) noexcept(false); + W(const W &) + noexcept(false); }; struct X { X() = default; - X(const X&) {} + X(const X &) {} }; struct Y { Y() = default; - Y(const Y&) throw(); + Y(const Y &) + throw(); }; struct Z { Z() = default; - Z(const Z&) throw(int); + Z(const Z &) + throw(int); }; void g() noexcept(false); struct A { A() = default; - A(const A&) noexcept(noexcept(g())); + A(const A &) + noexcept(noexcept(g())); }; struct B { B() = default; - B(const B&) = default; - B(const A&) noexcept(false); + B(const B &) = default; + B(const A &) + noexcept(false); }; class C { W M; // W is not no-throw copy constructible public: C() = default; - C(const C&) = default; + C(const C &) = default; }; struct D { D() = default; - D(const D&) noexcept(false); - D(D&) noexcept(true); + D(const D &) + noexcept(false); + D(D &) + noexcept(true); }; struct E { E() = default; - E(E&) noexcept(true); - E(const E&) noexcept(false); + E(E &) + noexcept(true); + E(const E &) + noexcept(false); }; struct Allocates { @@ -83,13 +93,13 @@ }; void f() { - throw 12; // ok + throw 12; // ok throw "test"; // ok - throw S(); // ok - throw T(); // ok - throw U(); // ok - throw V(); // ok - throw W(); // match, noexcept(false) + throw S(); // ok + throw T(); // ok + throw U(); // ok + throw V(); // ok + throw W(); // match, noexcept(false) // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: thrown exception type is not nothrow copy constructible [cert-err60-cpp] throw X(); // match, no noexcept clause, nontrivial // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: thrown exception type is not nothrow copy constructible @@ -112,7 +122,8 @@ namespace PR25574 { struct B { - B(const B&) noexcept; + B(const B &) + noexcept; }; struct D : B { Index: test/clang-tidy/cert-variadic-function-def.cpp =================================================================== --- test/clang-tidy/cert-variadic-function-def.cpp +++ test/clang-tidy/cert-variadic-function-def.cpp @@ -20,5 +20,5 @@ // Function definitions that are extern "C" are good. extern "C" void f4(int, ...) {} // ok extern "C" { - void f5(int, ...) {} // ok +void f5(int, ...) {} // ok } Index: test/clang-tidy/clang-tidy-diff.cpp =================================================================== --- test/clang-tidy/clang-tidy-diff.cpp +++ test/clang-tidy/clang-tidy-diff.cpp @@ -8,11 +8,11 @@ // CHECK-NOT: warning: struct B : public A { void placeholder_for_f() {} -// CHECK-SANITY: [[@LINE-1]]:8: warning: annotate this -// CHECK: [[@LINE-2]]:8: warning: annotate this + // CHECK-SANITY: [[@LINE-1]]:8: warning: annotate this + // CHECK: [[@LINE-2]]:8: warning: annotate this void g() {} -// CHECK-SANITY: [[@LINE-1]]:8: warning: annotate this -// CHECK-NOT: warning: + // CHECK-SANITY: [[@LINE-1]]:8: warning: annotate this + // CHECK-NOT: warning: }; // CHECK-SANITY-NOT: Suppressed // CHECK: Suppressed 1 warnings (1 due to line filter). Index: test/clang-tidy/clean-up-code.cpp =================================================================== --- test/clang-tidy/clean-up-code.cpp +++ test/clang-tidy/clean-up-code.cpp @@ -1,5 +1,7 @@ // RUN: %check_clang_tidy %s misc-unused-using-decls %t -namespace a { class A {}; } +namespace a { +class A {}; +} namespace b { using a::A; } Index: test/clang-tidy/cppcoreguidelines-interfaces-global-init.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-interfaces-global-init.cpp +++ test/clang-tidy/cppcoreguidelines-interfaces-global-init.cpp @@ -53,7 +53,6 @@ int ExternGlobal2 = 123; static int GlobalScopeGoodInit1 = ExternGlobal2; - // Defined global variables are fine: static int GlobalScope = makesInt(); static int GlobalScopeGoodInit2 = takesInt(GlobalScope); @@ -81,4 +80,3 @@ }; const int B2::I; const int B2::J; - Index: test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp +++ test/clang-tidy/cppcoreguidelines-pro-bounds-array-to-pointer-decay.cpp @@ -43,5 +43,5 @@ void f2(void *const *); void bug25362() { void *a[2]; - f2(static_cast(a)); // OK, explicit cast + f2(static_cast(a)); // OK, explicit cast } Index: test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index-c++03.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index-c++03.cpp +++ test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index-c++03.cpp @@ -2,7 +2,8 @@ // Note: this test expects no diagnostics, but FileCheck cannot handle that, // hence the use of | count 0. -template struct B { +template +struct B { int get() { // The next line used to crash the check (in C++03 mode only). return x[index]; Index: test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index-gslheader.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index-gslheader.cpp +++ test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index-gslheader.cpp @@ -4,20 +4,19 @@ typedef __SIZE_TYPE__ size_t; namespace std { - template - struct array { - T& operator[](size_t n); - T& at(size_t n); - }; +template +struct array { + T &operator[](size_t n); + T &at(size_t n); +}; } - namespace gsl { - template - T& at( T(&a)[N], size_t index ); +template +T &at(T (&a)[N], size_t index); - template - T& at( std::array &a, size_t index ); +template +T &at(std::array &a, size_t index); } constexpr int const_index(int base) { @@ -25,15 +24,15 @@ } void f(std::array a, int pos) { - a [ pos / 2 /*comment*/] = 1; + a[pos / 2 /*comment*/] = 1; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not use array subscript when the index is not an integer constant expression; use gsl::at() instead [cppcoreguidelines-pro-bounds-constant-array-index] // CHECK-FIXES: gsl::at(a, pos / 2 /*comment*/) = 1; int j = a[pos - 1]; // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: do not use array subscript when the index is not an integer constant expression; use gsl::at() instead // CHECK-FIXES: int j = gsl::at(a, pos - 1); - a.at(pos-1) = 2; // OK, at() instead of [] - gsl::at(a, pos-1) = 2; // OK, gsl::at() instead of [] + a.at(pos - 1) = 2; // OK, at() instead of [] + gsl::at(a, pos - 1) = 2; // OK, gsl::at() instead of [] a[-1] = 3; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index -1 is negative [cppcoreguidelines-pro-bounds-constant-array-index] @@ -43,9 +42,9 @@ a[const_index(7)] = 3; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past the end of the array (which contains 10 elements) - a[0] = 3; // OK, constant index and inside bounds - a[1] = 3; // OK, constant index and inside bounds - a[9] = 3; // OK, constant index and inside bounds + a[0] = 3; // OK, constant index and inside bounds + a[1] = 3; // OK, constant index and inside bounds + a[9] = 3; // OK, constant index and inside bounds a[const_index(6)] = 3; // OK, constant index and inside bounds } @@ -58,18 +57,18 @@ gsl::at(a, i) = i; // OK, gsl::at() instead of [] } - a[-1] = 3; // flagged by clang-diagnostic-array-bounds - a[10] = 4; // flagged by clang-diagnostic-array-bounds + a[-1] = 3; // flagged by clang-diagnostic-array-bounds + a[10] = 4; // flagged by clang-diagnostic-array-bounds a[const_index(7)] = 3; // flagged by clang-diagnostic-array-bounds - a[0] = 3; // OK, constant index and inside bounds - a[1] = 3; // OK, constant index and inside bounds - a[9] = 3; // OK, constant index and inside bounds + a[0] = 3; // OK, constant index and inside bounds + a[1] = 3; // OK, constant index and inside bounds + a[9] = 3; // OK, constant index and inside bounds a[const_index(6)] = 3; // OK, constant index and inside bounds } struct S { - int& operator[](int i); + int &operator[](int i); }; void customOperator() { Index: test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index.cpp +++ test/clang-tidy/cppcoreguidelines-pro-bounds-constant-array-index.cpp @@ -3,20 +3,19 @@ typedef __SIZE_TYPE__ size_t; namespace std { - template - struct array { - T& operator[](size_t n); - T& at(size_t n); - }; +template +struct array { + T &operator[](size_t n); + T &at(size_t n); +}; } - namespace gsl { - template - T& at( T(&a)[N], size_t index ); +template +T &at(T (&a)[N], size_t index); - template - T& at( std::array &a, size_t index ); +template +T &at(std::array &a, size_t index); } constexpr int const_index(int base) { @@ -24,13 +23,13 @@ } void f(std::array a, int pos) { - a [ pos / 2 /*comment*/] = 1; + a[pos / 2 /*comment*/] = 1; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not use array subscript when the index is not an integer constant expression; use gsl::at() instead [cppcoreguidelines-pro-bounds-constant-array-index] int j = a[pos - 1]; // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: do not use array subscript when the index is not an integer constant expression; use gsl::at() instead - a.at(pos-1) = 2; // OK, at() instead of [] - gsl::at(a, pos-1) = 2; // OK, gsl::at() instead of [] + a.at(pos - 1) = 2; // OK, at() instead of [] + gsl::at(a, pos - 1) = 2; // OK, gsl::at() instead of [] a[-1] = 3; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index -1 is negative [cppcoreguidelines-pro-bounds-constant-array-index] @@ -40,9 +39,9 @@ a[const_index(7)] = 3; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: std::array<> index 10 is past the end of the array (which contains 10 elements) - a[0] = 3; // OK, constant index and inside bounds - a[1] = 3; // OK, constant index and inside bounds - a[9] = 3; // OK, constant index and inside bounds + a[0] = 3; // OK, constant index and inside bounds + a[1] = 3; // OK, constant index and inside bounds + a[9] = 3; // OK, constant index and inside bounds a[const_index(6)] = 3; // OK, constant index and inside bounds } @@ -55,18 +54,18 @@ gsl::at(a, i) = i; // OK, gsl::at() instead of [] } - a[-1] = 3; // flagged by clang-diagnostic-array-bounds - a[10] = 4; // flagged by clang-diagnostic-array-bounds + a[-1] = 3; // flagged by clang-diagnostic-array-bounds + a[10] = 4; // flagged by clang-diagnostic-array-bounds a[const_index(7)] = 3; // flagged by clang-diagnostic-array-bounds - a[0] = 3; // OK, constant index and inside bounds - a[1] = 3; // OK, constant index and inside bounds - a[9] = 3; // OK, constant index and inside bounds + a[0] = 3; // OK, constant index and inside bounds + a[1] = 3; // OK, constant index and inside bounds + a[9] = 3; // OK, constant index and inside bounds a[const_index(6)] = 3; // OK, constant index and inside bounds } struct S { - int& operator[](int i); + int &operator[](int i); }; void customOperator() { Index: test/clang-tidy/cppcoreguidelines-pro-bounds-pointer-arithmetic.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-bounds-pointer-arithmetic.cpp +++ test/clang-tidy/cppcoreguidelines-pro-bounds-pointer-arithmetic.cpp @@ -85,5 +85,6 @@ auto diff = p - q; // OK, result is arithmetic - for(int ii : a) ; // OK, pointer arithmetic generated by compiler + for (int ii : a) + ; // OK, pointer arithmetic generated by compiler } Index: test/clang-tidy/cppcoreguidelines-pro-type-cstyle-cast.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-type-cstyle-cast.cpp +++ test/clang-tidy/cppcoreguidelines-pro-type-cstyle-cast.cpp @@ -3,23 +3,23 @@ void reinterpretcast() { int i = 0; void *j; - j = (int*)j; + j = (int *)j; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use C-style cast to convert between unrelated types [cppcoreguidelines-pro-type-cstyle-cast] } void constcast() { - int* i; - const int* j; - i = (int*)j; + int *i; + const int *j; + i = (int *)j; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use C-style cast to cast away constness - j = (const int*)i; // OK, const added - (void)j; // OK, not a const_cast + j = (const int *)i; // OK, const added + (void)j; // OK, not a const_cast } void const_and_reinterpret() { - int* i; - const void* j; - i = (int*)j; + int *i; + const void *j; + i = (int *)j; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: do not use C-style cast to convert between unrelated types } @@ -48,88 +48,86 @@ void pointers() { - auto P0 = (Derived*)new Base(); + auto P0 = (Derived *)new Base(); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not use C-style cast to downcast from a base to a derived class - const Base* B0; - auto PC0 = (const Derived*)(B0); + const Base *B0; + auto PC0 = (const Derived *)(B0); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use C-style cast to downcast from a base to a derived class - auto P1 = (Base*)new Derived(); // OK, upcast to a public base - auto P2 = (Base*)new MultiDerived(); // OK, upcast to a public base - auto P3 = (Base2*)new MultiDerived(); // OK, upcast to a public base + auto P1 = (Base *)new Derived(); // OK, upcast to a public base + auto P2 = (Base *)new MultiDerived(); // OK, upcast to a public base + auto P3 = (Base2 *)new MultiDerived(); // OK, upcast to a public base } void pointers_polymorphic() { - auto PP0 = (PolymorphicDerived*)new PolymorphicBase(); + auto PP0 = (PolymorphicDerived *)new PolymorphicBase(); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use C-style cast to downcast from a base to a derived class; use dynamic_cast instead // CHECK-FIXES: auto PP0 = dynamic_cast(new PolymorphicBase()); - const PolymorphicBase* B0; - auto PPC0 = (const PolymorphicDerived*)B0; + const PolymorphicBase *B0; + auto PPC0 = (const PolymorphicDerived *)B0; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: do not use C-style cast to downcast from a base to a derived class; use dynamic_cast instead // CHECK-FIXES: auto PPC0 = dynamic_cast(B0); - - auto B1 = (PolymorphicBase*)new PolymorphicDerived(); // OK, upcast to a public base - auto B2 = (PolymorphicBase*)new PolymorphicMultiDerived(); // OK, upcast to a public base - auto B3 = (Base*)new PolymorphicMultiDerived(); // OK, upcast to a public base + auto B1 = (PolymorphicBase *)new PolymorphicDerived(); // OK, upcast to a public base + auto B2 = (PolymorphicBase *)new PolymorphicMultiDerived(); // OK, upcast to a public base + auto B3 = (Base *)new PolymorphicMultiDerived(); // OK, upcast to a public base } void arrays() { Base ArrayOfBase[10]; - auto A0 = (Derived*)ArrayOfBase; + auto A0 = (Derived *)ArrayOfBase; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not use C-style cast to downcast from a base to a derived class } void arrays_polymorphic() { PolymorphicBase ArrayOfPolymorphicBase[10]; - auto AP0 = (PolymorphicDerived*)ArrayOfPolymorphicBase; + auto AP0 = (PolymorphicDerived *)ArrayOfPolymorphicBase; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use C-style cast to downcast from a base to a derived class; use dynamic_cast instead // CHECK-FIXES: auto AP0 = dynamic_cast(ArrayOfPolymorphicBase); } void references() { Base B0; - auto R0 = (Derived&)B0; + auto R0 = (Derived &)B0; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not use C-style cast to downcast from a base to a derived class - Base& RefToBase = B0; - auto R1 = (Derived&)RefToBase; + Base &RefToBase = B0; + auto R1 = (Derived &)RefToBase; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not use C-style cast to downcast from a base to a derived class - const Base& ConstRefToBase = B0; - auto RC1 = (const Derived&)ConstRefToBase; + const Base &ConstRefToBase = B0; + auto RC1 = (const Derived &)ConstRefToBase; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use C-style cast to downcast from a base to a derived class - Derived RD1; - auto R2 = (Base&)RD1; // OK, upcast to a public base + auto R2 = (Base &)RD1; // OK, upcast to a public base } void references_polymorphic() { PolymorphicBase B0; - auto RP0 = (PolymorphicDerived&)B0; + auto RP0 = (PolymorphicDerived &)B0; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use C-style cast to downcast from a base to a derived class; use dynamic_cast instead // CHECK-FIXES: auto RP0 = dynamic_cast(B0); - PolymorphicBase& RefToPolymorphicBase = B0; - auto RP1 = (PolymorphicDerived&)RefToPolymorphicBase; + PolymorphicBase &RefToPolymorphicBase = B0; + auto RP1 = (PolymorphicDerived &)RefToPolymorphicBase; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use C-style cast to downcast from a base to a derived class; use dynamic_cast instead // CHECK-FIXES: auto RP1 = dynamic_cast(RefToPolymorphicBase); - const PolymorphicBase& ConstRefToPolymorphicBase = B0; - auto RPC2 = (const PolymorphicDerived&)(ConstRefToPolymorphicBase); + const PolymorphicBase &ConstRefToPolymorphicBase = B0; + auto RPC2 = (const PolymorphicDerived &)(ConstRefToPolymorphicBase); // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: do not use C-style cast to downcast from a base to a derived class; use dynamic_cast instead // CHECK-FIXES: auto RPC2 = dynamic_cast(ConstRefToPolymorphicBase); PolymorphicDerived d1; - auto RP2 = (PolymorphicBase&)d1; // OK, upcast to a public base + auto RP2 = (PolymorphicBase &)d1; // OK, upcast to a public base } -template +template void templ() { - auto B0 = (B*)new D(); + auto B0 = (B *)new D(); } void templ_bad_call() { Index: test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp +++ test/clang-tidy/cppcoreguidelines-pro-type-member-init.cpp @@ -91,8 +91,10 @@ }; struct A {}; -template class AA; -template class NegativeTemplateConstructor { +template +class AA; +template +class NegativeTemplateConstructor { NegativeTemplateConstructor(const AA &, A) {} bool Bool{false}; // CHECK-FIXES: bool Bool{false}; @@ -356,8 +358,7 @@ // results in the check seeing a null RecordDecl when examining the base class // initializer list. template -class PositiveSelfInitialization : NegativeAggregateType -{ +class PositiveSelfInitialization : NegativeAggregateType { PositiveSelfInitialization() : PositiveSelfInitialization() {} // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these bases: NegativeAggregateType // CHECK-FIXES: PositiveSelfInitialization() : NegativeAggregateType(), PositiveSelfInitialization() {} @@ -373,8 +374,7 @@ // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructor does not initialize these fields: A }; -void Bug30487() -{ +void Bug30487() { NegativeInClassInitializedDefaulted s; } @@ -451,9 +451,11 @@ char e[]; }; -template class NoCrash { +template +class NoCrash { class B : public NoCrash { - template B(U u) {} + template + B(U u) {} }; }; Index: test/clang-tidy/cppcoreguidelines-pro-type-static-cast-downcast.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-type-static-cast-downcast.cpp +++ test/clang-tidy/cppcoreguidelines-pro-type-static-cast-downcast.cpp @@ -25,88 +25,86 @@ void pointers() { - auto P0 = static_cast(new Base()); + auto P0 = static_cast(new Base()); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not use static_cast to downcast from a base to a derived class [cppcoreguidelines-pro-type-static-cast-downcast] - const Base* B0; - auto PC0 = static_cast(B0); + const Base *B0; + auto PC0 = static_cast(B0); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use static_cast to downcast from a base to a derived class [cppcoreguidelines-pro-type-static-cast-downcast] - auto P1 = static_cast(new Derived()); // OK, upcast to a public base - auto P2 = static_cast(new MultiDerived()); // OK, upcast to a public base - auto P3 = static_cast(new MultiDerived()); // OK, upcast to a public base + auto P1 = static_cast(new Derived()); // OK, upcast to a public base + auto P2 = static_cast(new MultiDerived()); // OK, upcast to a public base + auto P3 = static_cast(new MultiDerived()); // OK, upcast to a public base } void pointers_polymorphic() { - auto PP0 = static_cast(new PolymorphicBase()); + auto PP0 = static_cast(new PolymorphicBase()); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use static_cast to downcast from a base to a derived class; use dynamic_cast instead [cppcoreguidelines-pro-type-static-cast-downcast] // CHECK-FIXES: auto PP0 = dynamic_cast(new PolymorphicBase()); - const PolymorphicBase* B0; - auto PPC0 = static_cast(B0); + const PolymorphicBase *B0; + auto PPC0 = static_cast(B0); // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: do not use static_cast to downcast from a base to a derived class; use dynamic_cast instead [cppcoreguidelines-pro-type-static-cast-downcast] // CHECK-FIXES: auto PPC0 = dynamic_cast(B0); - - auto B1 = static_cast(new PolymorphicDerived()); // OK, upcast to a public base - auto B2 = static_cast(new PolymorphicMultiDerived()); // OK, upcast to a public base - auto B3 = static_cast(new PolymorphicMultiDerived()); // OK, upcast to a public base + auto B1 = static_cast(new PolymorphicDerived()); // OK, upcast to a public base + auto B2 = static_cast(new PolymorphicMultiDerived()); // OK, upcast to a public base + auto B3 = static_cast(new PolymorphicMultiDerived()); // OK, upcast to a public base } void arrays() { Base ArrayOfBase[10]; - auto A0 = static_cast(ArrayOfBase); + auto A0 = static_cast(ArrayOfBase); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not use static_cast to downcast from a base to a derived class [cppcoreguidelines-pro-type-static-cast-downcast] } void arrays_polymorphic() { PolymorphicBase ArrayOfPolymorphicBase[10]; - auto AP0 = static_cast(ArrayOfPolymorphicBase); + auto AP0 = static_cast(ArrayOfPolymorphicBase); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use static_cast to downcast from a base to a derived class; use dynamic_cast instead // CHECK-FIXES: auto AP0 = dynamic_cast(ArrayOfPolymorphicBase); } void references() { Base B0; - auto R0 = static_cast(B0); + auto R0 = static_cast(B0); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not use static_cast to downcast from a base to a derived class [cppcoreguidelines-pro-type-static-cast-downcast] - Base& RefToBase = B0; - auto R1 = static_cast(RefToBase); + Base &RefToBase = B0; + auto R1 = static_cast(RefToBase); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: do not use static_cast to downcast from a base to a derived class [cppcoreguidelines-pro-type-static-cast-downcast] - const Base& ConstRefToBase = B0; - auto RC1 = static_cast(ConstRefToBase); + const Base &ConstRefToBase = B0; + auto RC1 = static_cast(ConstRefToBase); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use static_cast to downcast from a base to a derived class [cppcoreguidelines-pro-type-static-cast-downcast] - Derived RD1; - auto R2 = static_cast(RD1); // OK, upcast to a public base + auto R2 = static_cast(RD1); // OK, upcast to a public base } void references_polymorphic() { PolymorphicBase B0; - auto RP0 = static_cast(B0); + auto RP0 = static_cast(B0); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use static_cast to downcast from a base to a derived class; use dynamic_cast instead // CHECK-FIXES: auto RP0 = dynamic_cast(B0); - PolymorphicBase& RefToPolymorphicBase = B0; - auto RP1 = static_cast(RefToPolymorphicBase); + PolymorphicBase &RefToPolymorphicBase = B0; + auto RP1 = static_cast(RefToPolymorphicBase); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: do not use static_cast to downcast from a base to a derived class; use dynamic_cast instead [cppcoreguidelines-pro-type-static-cast-downcast] // CHECK-FIXES: auto RP1 = dynamic_cast(RefToPolymorphicBase); - const PolymorphicBase& ConstRefToPolymorphicBase = B0; - auto RPC2 = static_cast(ConstRefToPolymorphicBase); + const PolymorphicBase &ConstRefToPolymorphicBase = B0; + auto RPC2 = static_cast(ConstRefToPolymorphicBase); // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: do not use static_cast to downcast from a base to a derived class; use dynamic_cast instead [cppcoreguidelines-pro-type-static-cast-downcast] // CHECK-FIXES: auto RPC2 = dynamic_cast(ConstRefToPolymorphicBase); PolymorphicDerived d1; - auto RP2 = static_cast(d1); // OK, upcast to a public base + auto RP2 = static_cast(d1); // OK, upcast to a public base } -template +template void templ() { - auto B0 = static_cast(new D()); + auto B0 = static_cast(new D()); } void templ_bad_call() { Index: test/clang-tidy/cppcoreguidelines-pro-type-union-access.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-type-union-access.cpp +++ test/clang-tidy/cppcoreguidelines-pro-type-union-access.cpp @@ -15,14 +15,12 @@ } u; } s; - void f(char); void f2(U); -void f3(U&); -void f4(U*); +void f3(U &); +void f4(U *); -void check() -{ +void check() { u.union_member1 = true; // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: do not access members of unions; use (boost::)variant instead [cppcoreguidelines-pro-type-union-access] auto b = u.union_member2; @@ -35,7 +33,7 @@ s.non_union_member = 2; // OK U u2 = u; // OK - f2(u); // OK - f3(u); // OK - f4(&u); // OK + f2(u); // OK + f3(u); // OK + f4(&u); // OK } Index: test/clang-tidy/cppcoreguidelines-pro-type-vararg.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-pro-type-vararg.cpp +++ test/clang-tidy/cppcoreguidelines-pro-type-vararg.cpp @@ -5,10 +5,10 @@ struct C { void g_vararg(...); - void g(const char*); + void g(const char *); } c; -template +template void cpp_vararg(P... p); void check() { @@ -17,27 +17,27 @@ c.g_vararg("foo"); // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: do not call c-style vararg functions - f(3); // OK - c.g("foo"); // OK + f(3); // OK + c.g("foo"); // OK cpp_vararg(1, 7, 9); // OK } // ... as a parameter is allowed (e.g. for SFINAE) template -void CallFooIfAvailableImpl(T& t, ...) { +void CallFooIfAvailableImpl(T &t, ...) { // nothing } template -void CallFooIfAvailableImpl(T& t, decltype(t.foo())*) { +void CallFooIfAvailableImpl(T &t, decltype(t.foo()) *) { t.foo(); } template -void CallFooIfAvailable(T& t) { +void CallFooIfAvailable(T &t) { CallFooIfAvailableImpl(t, 0); // OK to call variadic function when the argument is a literal 0 } #include -void my_printf(const char* format, ...) { +void my_printf(const char *format, ...) { va_list ap; va_start(ap, format); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not call c-style vararg functions @@ -48,4 +48,4 @@ va_end(ap); // Don't warn, va_end is anyway useless without va_start } -int my_vprintf(const char* format, va_list arg ); // OK to declare function taking va_list +int my_vprintf(const char *format, va_list arg); // OK to declare function taking va_list Index: test/clang-tidy/cppcoreguidelines-special-member-functions-cxx-03.cpp =================================================================== --- test/clang-tidy/cppcoreguidelines-special-member-functions-cxx-03.cpp +++ test/clang-tidy/cppcoreguidelines-special-member-functions-cxx-03.cpp @@ -23,4 +23,3 @@ DefinesEverything &operator=(const DefinesEverything &); ~DefinesEverything(); }; - Index: test/clang-tidy/deduplication.cpp =================================================================== --- test/clang-tidy/deduplication.cpp +++ test/clang-tidy/deduplication.cpp @@ -1,6 +1,6 @@ // RUN: %check_clang_tidy %s google-explicit-constructor %t -template +template struct A { A(T); }; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: single-argument constructors must be marked explicit Index: test/clang-tidy/diagnostic.cpp =================================================================== --- test/clang-tidy/diagnostic.cpp +++ test/clang-tidy/diagnostic.cpp @@ -13,7 +13,9 @@ // CHECK2: :[[@LINE+2]]:11: warning: single-argument constructors must be marked explicit // CHECK3: :[[@LINE+1]]:11: warning: single-argument constructors must be marked explicit -class A { A(int) {} }; +class A { + A(int) {} +}; #define MACRO_FROM_COMMAND_LINE // CHECK4: :[[@LINE-1]]:9: warning: 'MACRO_FROM_COMMAND_LINE' macro redefined Index: test/clang-tidy/file-filter.cpp =================================================================== --- test/clang-tidy/file-filter.cpp +++ test/clang-tidy/file-filter.cpp @@ -24,7 +24,9 @@ // CHECK3-NOT: warning: // CHECK4: system-header.h:1:12: warning: single-argument constructors -class A { A(int); }; +class A { + A(int); +}; // CHECK: :[[@LINE-1]]:11: warning: single-argument constructors // CHECK2: :[[@LINE-2]]:11: warning: single-argument constructors // CHECK3: :[[@LINE-3]]:11: warning: single-argument constructors Index: test/clang-tidy/fix-errors.cpp =================================================================== --- test/clang-tidy/fix-errors.cpp +++ test/clang-tidy/fix-errors.cpp @@ -7,7 +7,9 @@ // RUN: FileCheck -input-file=%t.cpp -check-prefix=CHECK-FIX2 %s // RUN: FileCheck -input-file=%t.msg -check-prefix=CHECK-MESSAGES2 %s -class A { A(int i); } +class A { + A(int i); +} // CHECK-FIX: class A { A(int i); }{{$}} // CHECK-MESSAGES: Fixes have NOT been applied. // CHECK-FIX2: class A { explicit A(int i); }; Index: test/clang-tidy/fix.cpp =================================================================== --- test/clang-tidy/fix.cpp +++ test/clang-tidy/fix.cpp @@ -11,7 +11,9 @@ // CHECK-MESSAGES: note: FIX-IT applied suggested code changes // CHECK-YAML: ReplacementText: ' // namespace i' -class A { A(int i); }; +class A { + A(int i); +}; // CHECK: class A { explicit A(int i); }; // CHECK-MESSAGES: note: FIX-IT applied suggested code changes // CHECK-MESSAGES: clang-tidy applied 2 of 2 suggested fixes. Index: test/clang-tidy/google-build-explicit-make-pair.cpp =================================================================== --- test/clang-tidy/google-build-explicit-make-pair.cpp +++ test/clang-tidy/google-build-explicit-make-pair.cpp @@ -16,8 +16,8 @@ void templ(T a, T b) { std::make_pair(a, b); std::make_pair(1, 2); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: for C++11-compatibility, omit template arguments from make_pair -// CHECK-FIXES: std::make_pair(1, 2) + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: for C++11-compatibility, omit template arguments from make_pair + // CHECK-FIXES: std::make_pair(1, 2) } template @@ -25,25 +25,25 @@ void test(int i) { std::make_pair(i, i); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: for C++11-compatibility, omit template arguments from make_pair -// CHECK-FIXES: std::make_pair(i, i) + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: for C++11-compatibility, omit template arguments from make_pair + // CHECK-FIXES: std::make_pair(i, i) std::make_pair(i, i); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: for C++11-compatibility, use pair directly -// CHECK-FIXES: std::pair(i, i) + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: for C++11-compatibility, use pair directly + // CHECK-FIXES: std::pair(i, i) std::make_pair(i, i); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: for C++11-compatibility, use pair directly // CHECK-FIXES: std::pair(i, i) #define M std::make_pair(i, i); -M -// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: for C++11-compatibility, use pair directly -// Can't fix in macros. -// CHECK-FIXES: #define M std::make_pair(i, i); -// CHECK-FIXES-NEXT: M + M + // CHECK-MESSAGES: :[[@LINE-1]]:1: warning: for C++11-compatibility, use pair directly + // Can't fix in macros. + // CHECK-FIXES: #define M std::make_pair(i, i); + // CHECK-FIXES-NEXT: M - templ(i, i); + templ(i, i); templ(1U, 2U); std::make_pair(i, 1); // no-warning Index: test/clang-tidy/google-explicit-constructor.cpp =================================================================== --- test/clang-tidy/google-explicit-constructor.cpp +++ test/clang-tidy/google-explicit-constructor.cpp @@ -1,35 +1,33 @@ // RUN: %check_clang_tidy %s google-explicit-constructor %t namespace std { - typedef decltype(sizeof(int)) size_t; +typedef decltype(sizeof(int)) size_t; - // libc++'s implementation - template - class initializer_list - { - const _E* __begin_; - size_t __size_; +// libc++'s implementation +template +class initializer_list { + const _E *__begin_; + size_t __size_; - initializer_list(const _E* __b, size_t __s) + initializer_list(const _E *__b, size_t __s) : __begin_(__b), - __size_(__s) - {} + __size_(__s) {} - public: - typedef _E value_type; - typedef const _E& reference; - typedef const _E& const_reference; - typedef size_t size_type; +public: + typedef _E value_type; + typedef const _E &reference; + typedef const _E &const_reference; + typedef size_t size_type; - typedef const _E* iterator; - typedef const _E* const_iterator; + typedef const _E *iterator; + typedef const _E *const_iterator; - initializer_list() : __begin_(nullptr), __size_(0) {} + initializer_list() : __begin_(nullptr), __size_(0) {} - size_t size() const {return __size_;} - const _E* begin() const {return __begin_;} - const _E* end() const {return __begin_ + __size_;} - }; + size_t size() const { return __size_; } + const _E *begin() const { return __begin_; } + const _E *end() const { return __begin_ + __size_; } +}; } struct A { @@ -39,7 +37,7 @@ explicit A(void *x) {} explicit A(void *x, void *y) {} - explicit A(const A& a) {} + explicit A(const A &a) {} // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: copy constructor should not be declared explicit [google-explicit-constructor] // CHECK-FIXES: {{^ }}A(const A& a) {} @@ -52,7 +50,7 @@ // CHECK-FIXES: {{^ }}explicit A(double x2, double y = 3.14) {} template - A(T&&... args); + A(T &&... args); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: constructors that are callable with a single argument // CHECK-FIXES: {{^ }}explicit A(T&&... args); }; @@ -97,8 +95,8 @@ template struct C3 { C3(initializer_list list1) {} - C3(const std::initializer_list &list2) {} - C3(::std::initializer_list &&list3) {} + C3(const std::initializer_list &list2) {} + C3(::std::initializer_list &&list3) {} template C3(initializer_list list3) {} Index: test/clang-tidy/google-overloaded-unary-and.cpp =================================================================== --- test/clang-tidy/google-overloaded-unary-and.cpp +++ test/clang-tidy/google-overloaded-unary-and.cpp @@ -2,13 +2,13 @@ struct Foo { void *operator&(); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not overload unary operator&, it is dangerous. [google-runtime-operator] + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not overload unary operator&, it is dangerous. [google-runtime-operator] }; template struct TFoo { T *operator&(); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not overload unary operator& + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: do not overload unary operator& }; TFoo tfoo; Index: test/clang-tidy/google-readability-casting.c =================================================================== --- test/clang-tidy/google-readability-casting.c +++ test/clang-tidy/google-readability-casting.c @@ -13,10 +13,10 @@ #else void f(const char *cpc) { - const char *cpc2 = (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; + char *pc = (char *)cpc; } #endif Index: test/clang-tidy/google-readability-casting.cpp =================================================================== --- test/clang-tidy/google-readability-casting.cpp +++ test/clang-tidy/google-readability-casting.cpp @@ -7,57 +7,57 @@ struct Y : public X {}; void f(int a, double b, const char *cpc, const void *cpv, X *pX) { - const char *cpc2 = (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; typedef const char *Typedef1; typedef const char *Typedef2; Typedef1 t1; - (Typedef2)t1; + (Typedef2) t1; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: possibly redundant cast between typedefs of the same type [google-readability-casting] // CHECK-FIXES: {{^}} (Typedef2)t1; - (const char*)t1; + (const char *)t1; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: possibly redundant cast {{.*}} // CHECK-FIXES: {{^}} (const char*)t1; - (Typedef1)cpc; + (Typedef1) cpc; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: possibly redundant cast {{.*}} // CHECK-FIXES: {{^}} (Typedef1)cpc; - (Typedef1)t1; + (Typedef1) t1; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: redundant cast to the same type // CHECK-FIXES: {{^}} t1; - char *pc = (char*)cpc; + char *pc = (char *)cpc; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: C-style casts are discouraged; use const_cast [google-readability-casting] // CHECK-FIXES: char *pc = const_cast(cpc); - char *pc2 = (char*)(cpc + 33); + char *pc2 = (char *)(cpc + 33); // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: {{.*}}; use const_cast {{.*}} // CHECK-FIXES: char *pc2 = const_cast(cpc + 33); const char &crc = *cpc; - char &rc = (char&)crc; + char &rc = (char &)crc; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: {{.*}}; use const_cast {{.*}} // CHECK-FIXES: char &rc = const_cast(crc); - char &rc2 = (char&)*cpc; + char &rc2 = (char &)*cpc; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: {{.*}}; use const_cast {{.*}} // CHECK-FIXES: char &rc2 = const_cast(*cpc); - char ** const* const* ppcpcpc; - char ****ppppc = (char****)ppcpcpc; + char **const *const *ppcpcpc; + char ****ppppc = (char ****)ppcpcpc; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: {{.*}}; use const_cast {{.*}} // CHECK-FIXES: char ****ppppc = const_cast(ppcpcpc); - char ***pppc = (char***)*(ppcpcpc); + char ***pppc = (char ***)*(ppcpcpc); // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: {{.*}}; use const_cast {{.*}} // CHECK-FIXES: char ***pppc = const_cast(*(ppcpcpc)); - char ***pppc2 = (char***)(*ppcpcpc); + char ***pppc2 = (char ***)(*ppcpcpc); // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: {{.*}}; use const_cast {{.*}} // CHECK-FIXES: char ***pppc2 = const_cast(*ppcpcpc); - char *pc5 = (char*)(const char*)(cpv); + char *pc5 = (char *)(const char *)(cpv); // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: {{.*}}; use const_cast {{.*}} // CHECK-MESSAGES: :[[@LINE-2]]:22: warning: {{.*}}; use reinterpret_cast {{.*}} // CHECK-FIXES: char *pc5 = const_cast(reinterpret_cast(cpv)); @@ -66,16 +66,16 @@ // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: {{.*}}; use static_cast {{.*}} // CHECK-FIXES: int b1 = static_cast(b); - Y *pB = (Y*)pX; + Y *pB = (Y *)pX; // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: {{.*}}; use static_cast/const_cast/reinterpret_cast {{.*}} - Y &rB = (Y&)*pX; + Y &rB = (Y &)*pX; // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: {{.*}}; use static_cast/const_cast/reinterpret_cast {{.*}} - const char *pc3 = (const char*)cpv; + const char *pc3 = (const char *)cpv; // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: {{.*}}; use reinterpret_cast {{.*}} // CHECK-FIXES: const char *pc3 = reinterpret_cast(cpv); - char *pc4 = (char*)cpv; + char *pc4 = (char *)cpv; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: {{.*}}; use static_cast/const_cast/reinterpret_cast {{.*}} // CHECK-FIXES: char *pc4 = (char*)cpv; @@ -127,10 +127,10 @@ extern "C" { void extern_c_code(const char *cpc) { - const char *cpc2 = (const char*)cpc; + const char *cpc2 = (const char *)cpc; // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: redundant cast to the same type // CHECK-FIXES: const char *cpc2 = cpc; - char *pc = (char*)cpc; + char *pc = (char *)cpc; } } Index: test/clang-tidy/google-readability-namespace-comments.cpp =================================================================== --- test/clang-tidy/google-readability-namespace-comments.cpp +++ test/clang-tidy/google-readability-namespace-comments.cpp @@ -3,38 +3,23 @@ namespace n1 { namespace n2 { - void f(); // So that the namespace isn't empty. - // CHECK-MESSAGES: :[[@LINE+4]]:2: warning: namespace 'n2' not terminated with a closing comment [google-readability-namespace-comments] // CHECK-MESSAGES: :[[@LINE-7]]:11: note: namespace 'n2' starts here // CHECK-MESSAGES: :[[@LINE+2]]:3: warning: namespace 'n1' not terminated with // CHECK-MESSAGES: :[[@LINE-10]]:11: note: namespace 'n1' starts here -}} +} +} // CHECK-FIXES: } // namespace n2 // CHECK-FIXES: } // namespace n1 - namespace short1 { namespace short2 { // Namespaces covering 10 lines or fewer are exempt from this rule. - - - - - } } namespace n3 { - - - - - - - - }; // namespace n3 Index: test/clang-tidy/google-runtime-int-std.cpp =================================================================== --- test/clang-tidy/google-runtime-int-std.cpp +++ test/clang-tidy/google-runtime-int-std.cpp @@ -20,31 +20,31 @@ } short bar(const short, unsigned short) { -// CHECK-MESSAGES: [[@LINE-1]]:1: warning: consider replacing 'short' with 'std::int16_t' -// CHECK-MESSAGES: [[@LINE-2]]:17: warning: consider replacing 'short' with 'std::int16_t' -// CHECK-MESSAGES: [[@LINE-3]]:24: warning: consider replacing 'unsigned short' with 'std::uint16_t' + // CHECK-MESSAGES: [[@LINE-1]]:1: warning: consider replacing 'short' with 'std::int16_t' + // CHECK-MESSAGES: [[@LINE-2]]:17: warning: consider replacing 'short' with 'std::int16_t' + // CHECK-MESSAGES: [[@LINE-3]]:24: warning: consider replacing 'unsigned short' with 'std::uint16_t' long double foo = 42; uint64 qux = 42; unsigned short port; const unsigned short bar = 0; -// CHECK-MESSAGES: [[@LINE-1]]:9: warning: consider replacing 'unsigned short' with 'std::uint16_t' + // CHECK-MESSAGES: [[@LINE-1]]:9: warning: consider replacing 'unsigned short' with 'std::uint16_t' long long *baar; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'std::int64_t' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'std::int64_t' const unsigned short &bara = bar; -// CHECK-MESSAGES: [[@LINE-1]]:9: warning: consider replacing 'unsigned short' with 'std::uint16_t' + // CHECK-MESSAGES: [[@LINE-1]]:9: warning: consider replacing 'unsigned short' with 'std::uint16_t' long const long moo = 1; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'std::int64_t' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'std::int64_t' long volatile long wat = 42; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'std::int64_t' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'std::int64_t' unsigned long y; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long' with 'std::uint{{..}}_t' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long' with 'std::uint{{..}}_t' unsigned long long **const *tmp; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long long' with 'std::uint64_t' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long long' with 'std::uint64_t' unsigned long long **const *&z = tmp; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long long' with 'std::uint64_t' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long long' with 'std::uint64_t' unsigned short porthole; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned short' with 'std::uint16_t' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned short' with 'std::uint16_t' uint64 cast = (short)42; // CHECK-MESSAGES: [[@LINE-1]]:18: warning: consider replacing 'short' with 'std::int16_t' @@ -53,5 +53,5 @@ l x; tmpl(); -// CHECK-MESSAGES: [[@LINE-1]]:8: warning: consider replacing 'short' with 'std::int16_t' + // CHECK-MESSAGES: [[@LINE-1]]:8: warning: consider replacing 'short' with 'std::int16_t' } Index: test/clang-tidy/google-runtime-int.cpp =================================================================== --- test/clang-tidy/google-runtime-int.cpp +++ test/clang-tidy/google-runtime-int.cpp @@ -15,31 +15,31 @@ } short bar(const short, unsigned short) { -// CHECK-MESSAGES: [[@LINE-1]]:1: warning: consider replacing 'short' with 'int16' -// CHECK-MESSAGES: [[@LINE-2]]:17: warning: consider replacing 'short' with 'int16' -// CHECK-MESSAGES: [[@LINE-3]]:24: warning: consider replacing 'unsigned short' with 'uint16' + // CHECK-MESSAGES: [[@LINE-1]]:1: warning: consider replacing 'short' with 'int16' + // CHECK-MESSAGES: [[@LINE-2]]:17: warning: consider replacing 'short' with 'int16' + // CHECK-MESSAGES: [[@LINE-3]]:24: warning: consider replacing 'unsigned short' with 'uint16' long double foo = 42; uint64 qux = 42; unsigned short port; const unsigned short bar = 0; -// CHECK-MESSAGES: [[@LINE-1]]:9: warning: consider replacing 'unsigned short' with 'uint16' + // CHECK-MESSAGES: [[@LINE-1]]:9: warning: consider replacing 'unsigned short' with 'uint16' long long *baar; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'int64' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'int64' const unsigned short &bara = bar; -// CHECK-MESSAGES: [[@LINE-1]]:9: warning: consider replacing 'unsigned short' with 'uint16' + // CHECK-MESSAGES: [[@LINE-1]]:9: warning: consider replacing 'unsigned short' with 'uint16' long const long moo = 1; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'int64' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'int64' long volatile long wat = 42; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'int64' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'long long' with 'int64' unsigned long y; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long' with 'uint{{..}}' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long' with 'uint{{..}}' unsigned long long **const *tmp; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long long' with 'uint64' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long long' with 'uint64' unsigned long long **const *&z = tmp; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long long' with 'uint64' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned long long' with 'uint64' unsigned short porthole; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned short' with 'uint16' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'unsigned short' with 'uint16' uint64 cast = (short)42; // CHECK-MESSAGES: [[@LINE-1]]:18: warning: consider replacing 'short' with 'int16' @@ -48,7 +48,7 @@ l x; tmpl(); -// CHECK-MESSAGES: [[@LINE-1]]:8: warning: consider replacing 'short' with 'int16' + // CHECK-MESSAGES: [[@LINE-1]]:8: warning: consider replacing 'short' with 'int16' return 0; } @@ -56,7 +56,7 @@ void qux() { short port; -// CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'short' with 'int16' + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: consider replacing 'short' with 'int16' } // FIXME: This shouldn't warn, as UD-literal operators require one of a handful @@ -65,8 +65,12 @@ constexpr some_value operator"" _some_literal(unsigned long long int i); // CHECK-MESSAGES: [[@LINE-1]]:47: warning: consider replacing 'unsigned long long' -struct A { A& operator=(const A&); }; -class B { A a[0]; }; +struct A { + A &operator=(const A &); +}; +class B { + A a[0]; +}; void fff() { B a, b; Index: test/clang-tidy/google-runtime-member-string-references.cpp =================================================================== --- test/clang-tidy/google-runtime-member-string-references.cpp +++ test/clang-tidy/google-runtime-member-string-references.cpp @@ -1,18 +1,17 @@ // RUN: %check_clang_tidy %s google-runtime-member-string-references %t namespace std { -template - class basic_string {}; +template +class basic_string {}; typedef basic_string string; } class string {}; - struct A { const std::string &s; -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: const string& members are dangerous; it is much better to use alternatives, such as pointers or simple constants [google-runtime-member-string-references] + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: const string& members are dangerous; it is much better to use alternatives, such as pointers or simple constants [google-runtime-member-string-references] }; struct B { @@ -28,14 +27,14 @@ D(); const T &s; const std::string &s2; -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: const string& members are dangerous + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: const string& members are dangerous }; D d; struct AA { const string &s; -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: const string& members are dangerous + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: const string& members are dangerous }; struct BB { Index: test/clang-tidy/google-runtime-memset-zero-length.cpp =================================================================== --- test/clang-tidy/google-runtime-memset-zero-length.cpp +++ test/clang-tidy/google-runtime-memset-zero-length.cpp @@ -3,7 +3,7 @@ void *memset(void *, int, __SIZE_TYPE__); namespace std { - using ::memset; +using ::memset; } template @@ -11,11 +11,11 @@ memset(0, sizeof(int), i); memset(0, sizeof(T), sizeof(T)); memset(0, sizeof(T), 0); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument -// CHECK-FIXES: memset(0, 0, sizeof(T)); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument + // CHECK-FIXES: memset(0, 0, sizeof(T)); memset(0, sizeof(int), 0); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument -// CHECK-FIXES: memset(0, 0, sizeof(int)); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument + // CHECK-FIXES: memset(0, 0, sizeof(int)); } void foo(void *a, int xsize, int ysize) { @@ -24,25 +24,26 @@ // CHECK-FIXES: memset(a, 0, sizeof(int)); #define M memset(a, sizeof(int), 0); M -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument -// CHECK-FIXES: #define M memset(a, sizeof(int), 0); - ::memset(a, xsize * - ysize, 0); -// CHECK-MESSAGES: :[[@LINE-2]]:3: warning: memset of size zero, potentially swapped argument -// CHECK-FIXES: ::memset(a, 0, xsize * -// CHECK-FIXES-NEXT: ysize); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument + // CHECK-FIXES: #define M memset(a, sizeof(int), 0); + ::memset(a, xsize * + ysize, + 0); + // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: memset of size zero, potentially swapped argument + // CHECK-FIXES: ::memset(a, 0, xsize * + // CHECK-FIXES-NEXT: ysize); std::memset(a, sizeof(int), 0x00); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument -// CHECK-FIXES: std::memset(a, 0x00, sizeof(int)); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument + // CHECK-FIXES: std::memset(a, 0x00, sizeof(int)); const int v = 0; memset(a, sizeof(int), v); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument -// CHECK-FIXES: memset(a, v, sizeof(int)); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument + // CHECK-FIXES: memset(a, v, sizeof(int)); memset(a, sizeof(int), v + v); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument -// CHECK-FIXES: memset(a, v + v, sizeof(int)); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: memset of size zero, potentially swapped argument + // CHECK-FIXES: memset(a, v + v, sizeof(int)); memset(a, sizeof(int), v + 1); Index: test/clang-tidy/google-runtime-references.cpp =================================================================== --- test/clang-tidy/google-runtime-references.cpp +++ test/clang-tidy/google-runtime-references.cpp @@ -18,14 +18,14 @@ }; // Don't warn on rvalue-references. struct A2 { - A2(A2&&) = default; - void f(A2&&) {} + A2(A2 &&) = default; + void f(A2 &&) {} }; // Don't warn on iostream parameters. namespace xxx { -class istream { }; -class ostringstream { }; +class istream {}; +class ostringstream {}; } void g1(xxx::istream &istr); void g1(xxx::ostringstream &istr); @@ -47,15 +47,15 @@ // CHECK-MESSAGES: [[@LINE-3]]:30: warning: non-const reference parameter at index 2, {{.*}} class B { - B(B& a) {} -// CHECK-MESSAGES: [[@LINE-1]]:8: warning: non-const reference {{.*}} + B(B &a) {} + // CHECK-MESSAGES: [[@LINE-1]]:8: warning: non-const reference {{.*}} virtual void f(int &a) {} -// CHECK-MESSAGES: [[@LINE-1]]:23: warning: non-const reference {{.*}} + // CHECK-MESSAGES: [[@LINE-1]]:23: warning: non-const reference {{.*}} void g(int &b); -// CHECK-MESSAGES: [[@LINE-1]]:15: warning: non-const reference {{.*}} + // CHECK-MESSAGES: [[@LINE-1]]:15: warning: non-const reference {{.*}} // Don't warn on the parameter of stream extractors defined as members. - B& operator>>(int& val) { return *this; } + B &operator>>(int &val) { return *this; } }; // Only warn on the first declaration of each function to reduce duplicate @@ -63,43 +63,43 @@ void B::g(int &b) {} // Don't warn on the first parameter of stream inserters. -A& operator<<(A& s, int&) { return s; } +A &operator<<(A &s, int &) { return s; } // CHECK-MESSAGES: [[@LINE-1]]:25: warning: non-const reference parameter at index 1, {{.*}} // Don't warn on either parameter of stream extractors. Both need to be // non-const references by convention. -A& operator>>(A& input, int& val) { return input; } +A &operator>>(A &input, int &val) { return input; } // Don't warn on lambdas. -auto lambda = [] (int&) {}; +auto lambda = [](int &) {}; // Don't warn on typedefs, as we'll warn on the function itself. typedef int (*fp)(int &); // Don't warn on function references. typedef void F(); -void g5(const F& func) {} -void g6(F& func) {} +void g5(const F &func) {} +void g6(F &func) {} -template -void g7(const T& t) {} +template +void g7(const T &t) {} -template +template void g8(T t) {} void f5() { g5(f5); g6(f5); g7(f5); - g7(f5); + g7(f5); g8(f5); - g8(f5); + g8(f5); } // Don't warn on dependent types. -template -void g9(T& t) {} -template +template +void g9(T &t) {} +template void g10(T t) {} void f6() { @@ -107,9 +107,9 @@ float f; g9(i); g9(i); - g9(i); - g10(i); - g10(f); + g9(i); + g10(i); + g10(f); } // Warn only on the overridden methods from the base class, as the child class @@ -120,27 +120,27 @@ }; // Don't warn on operator<< with streams-like interface. -A& operator<<(A& s, int) { return s; } +A &operator<<(A &s, int) { return s; } // Don't warn on swap(). -void swap(C& c1, C& c2) {} +void swap(C &c1, C &c2) {} // Don't warn on standalone operator++, operator--, operator+=, operator-=, // operator*=, etc. that all need non-const references to be functional. -A& operator++(A& a) { return a; } -A operator++(A& a, int) { return a; } -A& operator--(A& a) { return a; } -A operator--(A& a, int) { return a; } -A& operator+=(A& a, const A& b) { return a; } -A& operator-=(A& a, const A& b) { return a; } -A& operator*=(A& a, const A& b) { return a; } -A& operator/=(A& a, const A& b) { return a; } -A& operator%=(A& a, const A& b) { return a; } -A& operator<<=(A& a, const A& b) { return a; } -A& operator>>=(A& a, const A& b) { return a; } -A& operator|=(A& a, const A& b) { return a; } -A& operator^=(A& a, const A& b) { return a; } -A& operator&=(A& a, const A& b) { return a; } +A &operator++(A &a) { return a; } +A operator++(A &a, int) { return a; } +A &operator--(A &a) { return a; } +A operator--(A &a, int) { return a; } +A &operator+=(A &a, const A &b) { return a; } +A &operator-=(A &a, const A &b) { return a; } +A &operator*=(A &a, const A &b) { return a; } +A &operator/=(A &a, const A &b) { return a; } +A &operator%=(A &a, const A &b) { return a; } +A &operator<<=(A &a, const A &b) { return a; } +A &operator>>=(A &a, const A &b) { return a; } +A &operator|=(A &a, const A &b) { return a; } +A &operator^=(A &a, const A &b) { return a; } +A &operator&=(A &a, const A &b) { return a; } namespace whitelist { class A {}; Index: test/clang-tidy/line-filter.cpp =================================================================== --- test/clang-tidy/line-filter.cpp +++ test/clang-tidy/line-filter.cpp @@ -15,11 +15,17 @@ #include "header3.h" // CHECK-NOT: header3.h:{{.*}} warning -class A { A(int); }; +class A { + A(int); +}; // CHECK: :[[@LINE-1]]:11: warning: single-argument constructors {{.*}} -class B { B(int); }; +class B { + B(int); +}; // CHECK-NOT: :[[@LINE-1]]:{{.*}} warning -class C { C(int); }; +class C { + C(int); +}; // CHECK: :[[@LINE-1]]:11: warning: single-argument constructors {{.*}} // CHECK-NOT: warning: Index: test/clang-tidy/llvm-include-order.cpp =================================================================== --- test/clang-tidy/llvm-include-order.cpp +++ test/clang-tidy/llvm-include-order.cpp @@ -1,14 +1,14 @@ // RUN: %check_clang_tidy %s llvm-include-order %t -- -- -isystem %S/Inputs/Headers // CHECK-MESSAGES: [[@LINE+2]]:1: warning: #includes are not sorted properly -#include "j.h" -#include "gtest/foo.h" #include "i.h" -#include -#include "llvm/a.h" -#include "clang/b.h" +#include "j.h" #include "clang-c/c.h" // hi +#include "clang/b.h" #include "llvm-c/d.h" // -c +#include "llvm/a.h" +#include "gtest/foo.h" +#include // CHECK-FIXES: #include "j.h" // CHECK-FIXES-NEXT: #include "i.h" @@ -30,8 +30,8 @@ // CHECK-FIXES-NEXT: #endif // CHECK-MESSAGES: [[@LINE+1]]:1: warning: #includes are not sorted properly -#include "b.h" #include "a.h" +#include "b.h" // CHECK-FIXES: #include "a.h" // CHECK-FIXES-NEXT: #include "b.h" Index: test/clang-tidy/llvm-twine-local.cpp =================================================================== --- test/clang-tidy/llvm-twine-local.cpp +++ test/clang-tidy/llvm-twine-local.cpp @@ -20,13 +20,13 @@ int main() { const Twine t = Twine("a") + "b" + Twine(42); -// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: twine variables are prone to use-after-free bugs -// CHECK-MESSAGES: note: FIX-IT applied suggested code changes -// CHECK-FIXES: std::string t = (Twine("a") + "b" + Twine(42)).str(); + // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: twine variables are prone to use-after-free bugs + // CHECK-MESSAGES: note: FIX-IT applied suggested code changes + // CHECK-FIXES: std::string t = (Twine("a") + "b" + Twine(42)).str(); foo(Twine("a") + "b"); Twine Prefix = false ? "__INT_FAST" : "__UINT_FAST"; -// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: twine variables are prone to use-after-free bugs -// CHECK-MESSAGES: note: FIX-IT applied suggested code changes -// CHECK-FIXES: const char * Prefix = false ? "__INT_FAST" : "__UINT_FAST"; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: twine variables are prone to use-after-free bugs + // CHECK-MESSAGES: note: FIX-IT applied suggested code changes + // CHECK-FIXES: const char * Prefix = false ? "__INT_FAST" : "__UINT_FAST"; } Index: test/clang-tidy/macros.cpp =================================================================== --- test/clang-tidy/macros.cpp +++ test/clang-tidy/macros.cpp @@ -1,6 +1,9 @@ // RUN: clang-tidy -checks='-*,google-explicit-constructor' %s -- | FileCheck %s -#define Q(name) class name { name(int i); } +#define Q(name) \ + class name { \ + name(int i); \ + } Q(A); // CHECK: :[[@LINE-1]]:3: warning: single-argument constructors must be marked explicit Index: test/clang-tidy/misc-argument-comment-strict.cpp =================================================================== --- test/clang-tidy/misc-argument-comment-strict.cpp +++ test/clang-tidy/misc-argument-comment-strict.cpp @@ -5,15 +5,15 @@ void g(int x_); void ignores_underscores() { f(/*With_Underscores=*/0); -// CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument name 'With_Underscores' in comment does not match parameter name '_with_underscores_' -// CHECK-FIXES: f(/*_with_underscores_=*/0); + // CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument name 'With_Underscores' in comment does not match parameter name '_with_underscores_' + // CHECK-FIXES: f(/*_with_underscores_=*/0); f(/*with_underscores=*/1); -// CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument name 'with_underscores' in comment does not match parameter name '_with_underscores_' -// CHECK-FIXES: f(/*_with_underscores_=*/1); + // CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument name 'with_underscores' in comment does not match parameter name '_with_underscores_' + // CHECK-FIXES: f(/*_with_underscores_=*/1); f(/*_With_Underscores_=*/2); -// CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument name '_With_Underscores_' in comment does not match parameter name '_with_underscores_' -// CHECK-FIXES: f(/*_with_underscores_=*/2); + // CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument name '_With_Underscores_' in comment does not match parameter name '_with_underscores_' + // CHECK-FIXES: f(/*_with_underscores_=*/2); g(/*X=*/3); -// CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument name 'X' in comment does not match parameter name 'x_' -// CHECK-FIXES: g(/*x_=*/3); + // CHECK-MESSAGES: [[@LINE-1]]:5: warning: argument name 'X' in comment does not match parameter name 'x_' + // CHECK-FIXES: g(/*x_=*/3); } Index: test/clang-tidy/misc-argument-comment.cpp =================================================================== --- test/clang-tidy/misc-argument-comment.cpp +++ test/clang-tidy/misc-argument-comment.cpp @@ -28,11 +28,11 @@ (void)NewPermanentCallback(&ffff, /*xxxx=*/11, /*yyyy=*/22); } -template -void variadic(Args&&... args); +template +void variadic(Args &&... args); -template -void variadic2(int zzz, Args&&... args); +template +void variadic2(int zzz, Args &&... args); void templates() { variadic(/*xxx=*/0, /*yyy=*/1); Index: test/clang-tidy/misc-assert-side-effect.cpp =================================================================== --- test/clang-tidy/misc-assert-side-effect.cpp +++ test/clang-tidy/misc-assert-side-effect.cpp @@ -6,27 +6,26 @@ #ifdef NDEBUG #define assert(x) 1 #else -#define assert(x) \ - if (!(x)) \ +#define assert(x) \ + if (!(x)) \ (void)abort() #endif void print(...); -#define assert2(e) (__builtin_expect(!(e), 0) ? \ - print (#e, __FILE__, __LINE__) : (void)0) +#define assert2(e) (__builtin_expect(!(e), 0) ? print(#e, __FILE__, __LINE__) : (void)0) #ifdef NDEBUG #define my_assert(x) 1 #else -#define my_assert(x) \ +#define my_assert(x) \ ((void)((x) ? 1 : abort())) #endif #ifdef NDEBUG #define not_my_assert(x) 1 #else -#define not_my_assert(x) \ - if (!(x)) \ +#define not_my_assert(x) \ + if (!(x)) \ (void)abort() #endif @@ -35,11 +34,8 @@ #define wrap2(x) wrap1(x) #define convoluted_assert(x) wrap2(x) -#define msvc_assert(expression) (void)( \ - (!!(expression)) || \ - (abort(), 0) \ - ) - +#define msvc_assert(expression) (void)((!!(expression)) || \ + (abort(), 0)) //===----------------------------------------------------------------------===// Index: test/clang-tidy/misc-bool-pointer-implicit-conversion.cpp =================================================================== --- test/clang-tidy/misc-bool-pointer-implicit-conversion.cpp +++ test/clang-tidy/misc-bool-pointer-implicit-conversion.cpp @@ -1,11 +1,10 @@ // RUN: %check_clang_tidy %s misc-bool-pointer-implicit-conversion %t bool *SomeFunction(); -void SomeOtherFunction(bool*); +void SomeOtherFunction(bool *); bool F(); void G(bool); - template void t(T b) { if (b) { @@ -15,13 +14,13 @@ void foo() { bool *b = SomeFunction(); if (b) { -// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: dubious check of 'bool *' against 'nullptr' -// CHECK-FIXES: if (*b) { + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: dubious check of 'bool *' against 'nullptr' + // CHECK-FIXES: if (*b) { } if (F() && b) { -// CHECK-MESSAGES: :[[@LINE-1]]:14: warning: dubious check of 'bool *' against 'nullptr' -// CHECK-FIXES: if (F() && *b) { + // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: dubious check of 'bool *' against 'nullptr' + // CHECK-FIXES: if (F() && *b) { } // TODO: warn here. @@ -72,11 +71,13 @@ struct { bool *b; - } d = { SomeFunction() }; + } d = {SomeFunction()}; if (d.b) (void)*d.b; // no-warning -#define CHECK(b) if (b) {} +#define CHECK(b) \ + if (b) { \ + } CHECK(c) } Index: test/clang-tidy/misc-dangling-handle.cpp =================================================================== --- test/clang-tidy/misc-dangling-handle.cpp +++ test/clang-tidy/misc-dangling-handle.cpp @@ -8,18 +8,18 @@ template class vector { - public: - using const_iterator = const T*; - using iterator = T*; +public: + using const_iterator = const T *; + using iterator = T *; using size_type = int; - void assign(size_type count, const T& value); - iterator insert(const_iterator pos, const T& value); - iterator insert(const_iterator pos, T&& value); - iterator insert(const_iterator pos, size_type count, const T& value); - void push_back(const T&); - void push_back(T&&); - void resize(size_type count, const T& value); + void assign(size_type count, const T &value); + iterator insert(const_iterator pos, const T &value); + iterator insert(const_iterator pos, T &&value); + iterator insert(const_iterator pos, size_type count, const T &value); + void push_back(const T &); + void push_back(T &&); + void resize(size_type count, const T &value); }; template @@ -27,53 +27,53 @@ template class set { - public: - using const_iterator = const T*; - using iterator = T*; - - std::pair insert(const T& value); - std::pair insert(T&& value); - iterator insert(const_iterator hint, const T& value); - iterator insert(const_iterator hint, T&& value); +public: + using const_iterator = const T *; + using iterator = T *; + + std::pair insert(const T &value); + std::pair insert(T &&value); + iterator insert(const_iterator hint, const T &value); + iterator insert(const_iterator hint, T &&value); }; template class map { - public: +public: using value_type = pair; - value_type& operator[](const Key& key); - value_type& operator[](Key&& key); + value_type &operator[](const Key &key); + value_type &operator[](Key &&key); }; class basic_string { - public: +public: basic_string(); - basic_string(const char*); + basic_string(const char *); ~basic_string(); }; typedef basic_string string; class basic_string_view { - public: - basic_string_view(const char*); - basic_string_view(const basic_string&); +public: + basic_string_view(const char *); + basic_string_view(const basic_string &); }; typedef basic_string_view string_view; -} // namespace std +} // namespace std namespace llvm { class StringRef { - public: +public: StringRef(); - StringRef(const char*); - StringRef(const std::string&); + StringRef(const char *); + StringRef(const std::string &); }; -} // namespace llvm +} // namespace llvm std::string ReturnsAString(); @@ -87,7 +87,7 @@ view1 = std::string(); // CHECK-MESSAGES: [[@LINE-1]]:3: warning: std::basic_string_view outlives - const std::string& str_ref = ""; + const std::string &str_ref = ""; std::string_view view3 = true ? "A" : str_ref; // CHECK-MESSAGES: [[@LINE-1]]:20: warning: std::basic_string_view outlives view3 = true ? "A" : str_ref; @@ -106,33 +106,33 @@ std::string_view ReturnStatements(int i, std::string value_arg, const std::string &ref_arg) { const char array[] = "A"; - const char* ptr = "A"; + const char *ptr = "A"; std::string s; static std::string ss; switch (i) { - // Bad cases - case 0: - return array; // refers to local - // CHECK-MESSAGES: [[@LINE-1]]:7: warning: std::basic_string_view outliv - case 1: - return s; // refers to local - // CHECK-MESSAGES: [[@LINE-1]]:7: warning: std::basic_string_view outliv - case 2: - return std::string(); // refers to temporary - // CHECK-MESSAGES: [[@LINE-1]]:7: warning: std::basic_string_view outliv - case 3: - return value_arg; // refers to by-value arg - // CHECK-MESSAGES: [[@LINE-1]]:7: warning: std::basic_string_view outliv - - // Ok cases - case 100: - return ss; // refers to static - case 101: - return static_array; // refers to static - case 102: - return ptr; // pointer is ok - case 103: - return ref_arg; // refers to by-ref arg + // Bad cases + case 0: + return array; // refers to local + // CHECK-MESSAGES: [[@LINE-1]]:7: warning: std::basic_string_view outliv + case 1: + return s; // refers to local + // CHECK-MESSAGES: [[@LINE-1]]:7: warning: std::basic_string_view outliv + case 2: + return std::string(); // refers to temporary + // CHECK-MESSAGES: [[@LINE-1]]:7: warning: std::basic_string_view outliv + case 3: + return value_arg; // refers to by-value arg + // CHECK-MESSAGES: [[@LINE-1]]:7: warning: std::basic_string_view outliv + + // Ok cases + case 100: + return ss; // refers to static + case 101: + return static_array; // refers to static + case 102: + return ptr; // pointer is ok + case 103: + return ref_arg; // refers to by-ref arg } struct S { @@ -144,11 +144,11 @@ // This should not warn. The string is bound by reference. return s; }; - (void)[=]() -> std::string_view { + (void)[=]()->std::string_view { // This should not warn. The reference is valid as long as the lambda. return s; }; - (void)[=]() -> std::string_view { + (void)[=]()->std::string_view { // FIXME: This one should warn. We are returning a reference to a local // lambda variable. std::string local; Index: test/clang-tidy/misc-forward-declaration-namespace.cpp =================================================================== --- test/clang-tidy/misc-forward-declaration-namespace.cpp +++ test/clang-tidy/misc-forward-declaration-namespace.cpp @@ -1,4 +1,4 @@ -// RUN: %check_clang_tidy %s misc-forward-declaration-namespace %t +// RUN: %check_clang_tidy %s misc-forward-declaration-namespace %t namespace { // This is a declaration in a wrong namespace. @@ -93,21 +93,20 @@ // CHECK-MESSAGES: note: a declaration of 'OUTSIDER_1' is found here } - namespace na { -template +template class T_C; } namespace nb { // FIXME: this is an error, but we don't consider template class declaration // now. -template +template class T_C; } namespace na { -template +template class T_C { int x; }; @@ -151,7 +150,6 @@ int f(nd::ne::D &d); - // This should be ignored by the check. template class Observer { Index: test/clang-tidy/misc-inaccurate-erase.cpp =================================================================== --- test/clang-tidy/misc-inaccurate-erase.cpp +++ test/clang-tidy/misc-inaccurate-erase.cpp @@ -1,12 +1,14 @@ // RUN: %check_clang_tidy %s misc-inaccurate-erase %t namespace std { -template struct vec_iterator { +template +struct vec_iterator { T *ptr; vec_iterator operator++(int); }; -template struct vector { +template +struct vector { typedef vec_iterator iterator; iterator begin(); @@ -22,9 +24,11 @@ template FwIt remove_if(FwIt begin, FwIt end, Func f); -template FwIt unique(FwIt begin, FwIt end); +template +FwIt unique(FwIt begin, FwIt end); -template struct unique_ptr {}; +template +struct unique_ptr {}; } // namespace std struct custom_iter {}; @@ -34,7 +38,8 @@ custom_iter end(); }; -template void g() { +template +void g() { T t; t.erase(std::remove(t.begin(), t.end(), 10)); // CHECK-FIXES: {{^ }}t.erase(std::remove(t.begin(), t.end(), 10));{{$}} Index: test/clang-tidy/misc-inefficient-algorithm.cpp =================================================================== --- test/clang-tidy/misc-inefficient-algorithm.cpp +++ test/clang-tidy/misc-inefficient-algorithm.cpp @@ -1,17 +1,20 @@ // RUN: %check_clang_tidy %s misc-inefficient-algorithm %t namespace std { -template struct less { +template +struct less { bool operator()(const T &lhs, const T &rhs) { return lhs < rhs; } }; -template struct greater { +template +struct greater { bool operator()(const T &lhs, const T &rhs) { return lhs > rhs; } }; struct iterator_type {}; -template > struct set { +template > +struct set { typedef iterator_type iterator; iterator find(const K &k); unsigned count(const K &k); @@ -24,7 +27,8 @@ struct other_iterator_type {}; -template > struct map { +template > +struct map { typedef other_iterator_type iterator; iterator find(const K &k); unsigned count(const K &k); @@ -35,24 +39,34 @@ iterator end() const; }; -template struct multimap : map {}; -template struct unordered_set : set {}; -template struct unordered_map : map {}; -template struct unordered_multiset : set {}; -template struct unordered_multimap : map {}; +template +struct multimap : map {}; +template +struct unordered_set : set {}; +template +struct unordered_map : map {}; +template +struct unordered_multiset : set {}; +template +struct unordered_multimap : map {}; -template > struct multiset : set {}; +template > +struct multiset : set {}; -template FwIt find(FwIt, FwIt, const K &); +template +FwIt find(FwIt, FwIt, const K &); template FwIt find(FwIt, FwIt, const K &, Cmp); -template FwIt find_if(FwIt, FwIt, Pred); +template +FwIt find_if(FwIt, FwIt, Pred); -template FwIt count(FwIt, FwIt, const K &); +template +FwIt count(FwIt, FwIt, const K &); -template FwIt lower_bound(FwIt, FwIt, const K &); +template +FwIt lower_bound(FwIt, FwIt, const K &); template FwIt lower_bound(FwIt, FwIt, const K &, Ord); @@ -61,7 +75,8 @@ #define FIND_IN_SET(x) find(x.begin(), x.end(), 10) // CHECK-FIXES: #define FIND_IN_SET(x) find(x.begin(), x.end(), 10) -template void f(const T &t) { +template +void f(const T &t) { std::set s; find(s.begin(), s.end(), 46); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: this STL algorithm call should be @@ -77,11 +92,11 @@ // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: this STL algorithm call should be replaced with a container method [misc-inefficient-algorithm] // CHECK-FIXES: {{^ }}auto it = s.find(43);{{$}} auto c = count(s.begin(), s.end(), 43); - // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: this STL algorithm call should be - // CHECK-FIXES: {{^ }}auto c = s.count(43);{{$}} +// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: this STL algorithm call should be +// CHECK-FIXES: {{^ }}auto c = s.count(43);{{$}} #define SECOND(x, y, z) y - SECOND(q,std::count(s.begin(), s.end(), 22),w); + SECOND(q, std::count(s.begin(), s.end(), 22), w); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: this STL algorithm call should be // CHECK-FIXES: {{^ }}SECOND(q,s.count(22),w);{{$}} Index: test/clang-tidy/misc-macro-parentheses-cmdline.cpp =================================================================== --- test/clang-tidy/misc-macro-parentheses-cmdline.cpp +++ test/clang-tidy/misc-macro-parentheses-cmdline.cpp @@ -5,6 +5,6 @@ // Fixes could not be applied and should not be reported. int foo() { return VAL; } -#define V 0+0 +#define V 0 + 0 int bar() { return V; } // CHECK-FIXES: #define V (0+0) Index: test/clang-tidy/misc-macro-parentheses.cpp =================================================================== --- test/clang-tidy/misc-macro-parentheses.cpp +++ test/clang-tidy/misc-macro-parentheses.cpp @@ -1,49 +1,61 @@ // RUN: %check_clang_tidy %s misc-macro-parentheses %t -#define BAD1 -1 +#define BAD1 -1 // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: macro replacement list should be enclosed in parentheses [misc-macro-parentheses] -#define BAD2 1+2 +#define BAD2 1 + 2 // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: macro replacement list should be enclosed in parentheses [misc-macro-parentheses] -#define BAD3(A) (A+1) +#define BAD3(A) (A + 1) // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: macro argument should be enclosed in parentheses [misc-macro-parentheses] -#define BAD4(x) ((unsigned char)(x & 0xff)) +#define BAD4(x) ((unsigned char)(x & 0xff)) // CHECK-MESSAGES: :[[@LINE-1]]:44: warning: macro argument should be enclosed in parentheses [misc-macro-parentheses] -#define BAD5(X) A*B=(C*)X+2 +#define BAD5(X) A *B = (C *)X + 2 // CHECK-MESSAGES: :[[@LINE-1]]:35: warning: macro argument should be enclosed in parentheses [misc-macro-parentheses] -#define GOOD1 1 -#define GOOD2 (1+2) -#define GOOD3(A) #A -#define GOOD4(A,B) A ## B -#define GOOD5(T) ((T*)0) -#define GOOD6(B) "A" B "C" -#define GOOD7(b) A b -#define GOOD8(a) a B -#define GOOD9(type) (type(123)) -#define GOOD10(car, ...) car -#define GOOD11 a[b+c] -#define GOOD12(x) a[x] -#define GOOD13(x) a.x -#define GOOD14(x) a->x -#define GOOD15(x) ({ int a = x; a+4; }) -#define GOOD16(x) a_ ## x, b_ ## x = c_ ## x - 1, -#define GOOD17 case 123: x=4+5; break; -#define GOOD18(x) ;x; -#define GOOD19 ;-2; -#define GOOD20 void* -#define GOOD21(a) case Fred::a: -#define GOOD22(a) if (verbose) return a; -#define GOOD23(type) (type::Field) -#define GOOD24(t) std::set s -#define GOOD25(t) std::set s -#define GOOD26(x) (a->*x) -#define GOOD27(x) (a.*x) -#define GOOD28(x) namespace x {int b;} -#define GOOD29(...) std::cout << __VA_ARGS__; -#define GOOD30(args...) std::cout << args; -#define GOOD31(X) A*X=2 -#define GOOD32(X) std::vector +#define GOOD1 1 +#define GOOD2 (1 + 2) +#define GOOD3(A) #A +#define GOOD4(A, B) A##B +#define GOOD5(T) ((T *)0) +#define GOOD6(B) "A" B "C" +#define GOOD7(b) A b +#define GOOD8(a) a B +#define GOOD9(type) (type(123)) +#define GOOD10(car, ...) car +#define GOOD11 a[b + c] +#define GOOD12(x) a[x] +#define GOOD13(x) a.x +#define GOOD14(x) a->x +#define GOOD15(x) ({ int a = x; a+4; }) +#define GOOD16(x) a_##x, b_##x = c_##x - 1, +#define GOOD17 \ + case 123: \ + x = 4 + 5; \ + break; +#define GOOD18(x) \ + ; \ + x; +#define GOOD19 \ + ; \ + -2; +#define GOOD20 void * +#define GOOD21(a) case Fred::a: +#define GOOD22(a) \ + if (verbose) \ + return a; +#define GOOD23(type) (type::Field) +#define GOOD24(t) std::set s +#define GOOD25(t) std::set s +#define GOOD26(x) (a->*x) +#define GOOD27(x) (a.*x) +#define GOOD28(x) \ + namespace x { \ + int b; \ + } +#define GOOD29(...) std::cout << __VA_ARGS__; +#define GOOD30(args...) std::cout << args; +#define GOOD31(X) A *X = 2 +#define GOOD32(X) std::vector // These are allowed for now.. -#define MAYBE1 *12.34 -#define MAYBE2 <<3 +#define MAYBE1 *12.34 +#define MAYBE2 << 3 Index: test/clang-tidy/misc-macro-repeated-side-effects.c =================================================================== --- test/clang-tidy/misc-macro-repeated-side-effects.c +++ test/clang-tidy/misc-macro-repeated-side-effects.c @@ -1,6 +1,6 @@ // RUN: %check_clang_tidy %s misc-macro-repeated-side-effects %t -#define badA(x,y) ((x)+((x)+(y))+(y)) +#define badA(x, y) ((x) + ((x) + (y)) + (y)) void bad(int ret, int a, int b) { ret = badA(a++, b); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: side effects in the 1st macro argument 'x' are repeated in macro expansion [misc-macro-repeated-side-effects] @@ -20,9 +20,8 @@ // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: side effects in the 2nd macro argument 'y' } - -#define MIN(A,B) ((A) < (B) ? (A) : (B)) // single ?: -#define LIMIT(X,A,B) ((X) < (A) ? (A) : ((X) > (B) ? (B) : (X))) // two ?: +#define MIN(A, B) ((A) < (B) ? (A) : (B)) // single ?: +#define LIMIT(X, A, B) ((X) < (A) ? (A) : ((X) > (B) ? (B) : (X))) // two ?: void question(int x) { MIN(x++, 12); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: side effects in the 1st macro argument 'A' @@ -38,7 +37,8 @@ // False positive: Repeated side effects is intentional. // It is hard to know when it's done by intention so right now we warn. -#define UNROLL(A) {A A} +#define UNROLL(A) \ + { A A } void fp1(int i) { UNROLL({ i++; }); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: side effects in the 1st macro argument 'A' @@ -46,15 +46,14 @@ // Do not produce a false positive on a strchr() macro. Explanation; Currently the '?' // triggers the test to bail out, because it cannot evaluate __builtin_constant_p(c). -# define strchrs(s, c) \ - (__extension__ (__builtin_constant_p (c) && !__builtin_constant_p (s) \ - && (c) == '\0' \ - ? (char *) __rawmemchr (s, c) \ - : __builtin_strchr (s, c))) -char* __rawmemchr(char* a, char b) { +#define strchrs(s, c) \ + (__extension__(__builtin_constant_p(c) && !__builtin_constant_p(s) && (c) == '\0' \ + ? (char *)__rawmemchr(s, c) \ + : __builtin_strchr(s, c))) +char *__rawmemchr(char *a, char b) { return a; } -void pass(char* pstr, char ch) { +void pass(char *pstr, char ch) { strchrs(pstr, ch++); // No error. } @@ -74,11 +73,11 @@ } // Passing macro argument as argument to __builtin_constant_p and macros. -#define builtinbad(x) (__builtin_constant_p(x) + (x) + (x)) -#define builtingood1(x) (__builtin_constant_p(x) + (x)) -#define builtingood2(x) ((__builtin_constant_p(x) && (x)) || (x)) -#define macrobad(x) (builtingood1(x) + (x) + (x)) -#define macrogood(x) (builtingood1(x) + (x)) +#define builtinbad(x) (__builtin_constant_p(x) + (x) + (x)) +#define builtingood1(x) (__builtin_constant_p(x) + (x)) +#define builtingood2(x) ((__builtin_constant_p(x) && (x)) || (x)) +#define macrobad(x) (builtingood1(x) + (x) + (x)) +#define macrogood(x) (builtingood1(x) + (x)) void builtins(int ret, int a) { ret += builtinbad(a++); // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: side effects in the 1st macro argument 'x' @@ -93,9 +92,13 @@ } // Bail out for conditionals. -#define condB(x,y) if(x) {x=y;} else {x=y + 1;} -void conditionals(int a, int b) -{ +#define condB(x, y) \ + if (x) { \ + x = y; \ + } else { \ + x = y + 1; \ + } +void conditionals(int a, int b) { condB(a, b++); } Index: test/clang-tidy/misc-misplaced-widening-cast.cpp =================================================================== --- test/clang-tidy/misc-misplaced-widening-cast.cpp +++ test/clang-tidy/misc-misplaced-widening-cast.cpp @@ -76,7 +76,8 @@ l = (long)(((*p) << 8) + *(p + 1)); } -template struct DontWarn2 { +template +struct DontWarn2 { void assign(T a, T b) { long l; l = (long)(a * b); @@ -85,15 +86,15 @@ DontWarn2 DW2; // Cast is not suspicious when casting macro. -#define A (X<<2) +#define A (X << 2) long macro1(int X) { return (long)A; } // Don't warn about cast in macro. -#define B(X,Y) (long)(X*Y) +#define B(X, Y) (long)(X * Y) long macro2(int x, int y) { - return B(x,y); + return B(x, y); } void floatingpoint(float a, float b) { Index: test/clang-tidy/misc-move-const-arg.cpp =================================================================== --- test/clang-tidy/misc-move-const-arg.cpp +++ test/clang-tidy/misc-move-const-arg.cpp @@ -1,13 +1,17 @@ // RUN: %check_clang_tidy %s misc-move-const-arg %t namespace std { -template struct remove_reference; +template +struct remove_reference; -template struct remove_reference { typedef _Tp type; }; +template +struct remove_reference { typedef _Tp type; }; -template struct remove_reference<_Tp &> { typedef _Tp type; }; +template +struct remove_reference<_Tp &> { typedef _Tp type; }; -template struct remove_reference<_Tp &&> { typedef _Tp type; }; +template +struct remove_reference<_Tp &&> { typedef _Tp type; }; template constexpr typename std::remove_reference<_Tp>::type &&move(_Tp &&__t); @@ -47,7 +51,8 @@ // CHECK-FIXES: return x5; } -template T f6(const T x6) { return std::move(x6); } +template +T f6(const T x6) { return std::move(x6); } void f7() { int a = f6(10); } @@ -62,7 +67,8 @@ #define M2(x) std::move(x) int f9() { return M2(1); } -template T f10(const int x10) { +template +T f10(const int x10) { return std::move(x10); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: std::move of the const variable 'x10' of the trivially-copyable type 'const int' has no effect; remove std::move() [misc-move-const-arg] // CHECK-FIXES: return x10; @@ -73,7 +79,7 @@ } class NoMoveSemantics { - public: +public: NoMoveSemantics(); NoMoveSemantics(const NoMoveSemantics &); @@ -113,7 +119,7 @@ } class MoveSemantics { - public: +public: MoveSemantics(); MoveSemantics(MoveSemantics &&); Index: test/clang-tidy/misc-move-constructor-init.cpp =================================================================== --- test/clang-tidy/misc-move-constructor-init.cpp +++ test/clang-tidy/misc-move-constructor-init.cpp @@ -4,23 +4,26 @@ // CHECK-FIXES: #include -template struct remove_reference {typedef T type;}; -template struct remove_reference {typedef T type;}; -template struct remove_reference {typedef T type;}; +template +struct remove_reference { typedef T type; }; +template +struct remove_reference { typedef T type; }; +template +struct remove_reference { typedef T type; }; template -typename remove_reference::type&& move(T&& arg) { - return static_cast::type&&>(arg); +typename remove_reference::type &&move(T &&arg) { + return static_cast::type &&>(arg); } struct C { C() = default; - C(const C&) = default; + C(const C &) = default; }; struct B { B() {} - B(const B&) {} + B(const B &) {} B(B &&) {} }; @@ -47,13 +50,13 @@ struct G { G() = default; - G(const G&) = default; - G(G&&) = delete; + G(const G &) = default; + G(G &&) = delete; }; struct H : G { H() = default; - H(const H&) = default; + H(const H &) = default; H(H &&RHS) : G(RHS) {} // ok }; Index: test/clang-tidy/misc-move-forwarding-reference.cpp =================================================================== --- test/clang-tidy/misc-move-forwarding-reference.cpp +++ test/clang-tidy/misc-move-forwarding-reference.cpp @@ -1,13 +1,17 @@ // RUN: %check_clang_tidy %s misc-move-forwarding-reference %t -- -- -std=c++14 -fno-delayed-template-parsing namespace std { -template struct remove_reference; +template +struct remove_reference; -template struct remove_reference { typedef _Tp type; }; +template +struct remove_reference { typedef _Tp type; }; -template struct remove_reference<_Tp &> { typedef _Tp type; }; +template +struct remove_reference<_Tp &> { typedef _Tp type; }; -template struct remove_reference<_Tp &&> { typedef _Tp type; }; +template +struct remove_reference<_Tp &&> { typedef _Tp type; }; template constexpr typename std::remove_reference<_Tp>::type &&move(_Tp &&__t); @@ -15,14 +19,16 @@ } // namespace std // Standard case. -template void f1(U &&SomeU) { +template +void f1(U &&SomeU) { T SomeT(std::move(SomeU)); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: forwarding reference passed to // CHECK-FIXES: T SomeT(std::forward(SomeU)); } // Ignore parentheses around the argument to std::move(). -template void f2(U &&SomeU) { +template +void f2(U &&SomeU) { T SomeT(std::move((SomeU))); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: forwarding reference passed to // CHECK-FIXES: T SomeT(std::forward((SomeU))); @@ -30,7 +36,8 @@ // Handle the case correctly where std::move() is being used through a using // declaration. -template void f3(U &&SomeU) { +template +void f3(U &&SomeU) { using std::move; T SomeT(move(SomeU)); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: forwarding reference passed to @@ -39,7 +46,8 @@ // Handle the case correctly where a global specifier is prepended to // std::move(). -template void f4(U &&SomeU) { +template +void f4(U &&SomeU) { T SomeT(::std::move(SomeU)); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: forwarding reference passed to // CHECK-FIXES: T SomeT(::std::forward(SomeU)); @@ -47,38 +55,43 @@ // Create a correct fix if there are spaces around the scope resolution // operator. -template void f5(U &&SomeU) { +template +void f5(U &&SomeU) { { - T SomeT(:: std :: move(SomeU)); + T SomeT(::std::move(SomeU)); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: forwarding reference passed to // CHECK-FIXES: T SomeT(::std::forward(SomeU)); } { - T SomeT(std :: move(SomeU)); + T SomeT(std::move(SomeU)); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: forwarding reference passed to // CHECK-FIXES: T SomeT(std::forward(SomeU)); } } // Ignore const rvalue reference parameters. -template void f6(const U &&SomeU) { +template +void f6(const U &&SomeU) { T SomeT(std::move(SomeU)); } // Ignore the case where the argument to std::move() is a lambda parameter (and // thus not actually a parameter of the function template). -template void f7() { +template +void f7() { [](U &&SomeU) { T SomeT(std::move(SomeU)); }; } // Ignore the case where the argument is a lvalue reference. -template void f8(U &SomeU) { +template +void f8(U &SomeU) { T SomeT(std::move(SomeU)); } // Ignore the case where the template parameter is a class template parameter // (i.e. no template argument deduction is taking place). -template class SomeClass { +template +class SomeClass { void f(U &&SomeU) { T SomeT(std::move(SomeU)); } }; @@ -86,7 +99,8 @@ // reference but the template argument is explicitly set to be an rvalue // reference. class A {}; -template void foo(T); +template +void foo(T); void f8() { A a; foo(std::move(a)); @@ -95,7 +109,8 @@ // A warning is output, but no fix is suggested, if a macro is used to rename // std::move. #define MOVE(x) std::move((x)) -template void f9(U &&SomeU) { +template +void f9(U &&SomeU) { T SomeT(MOVE(SomeU)); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: forwarding reference passed to } @@ -103,7 +118,8 @@ // Same result if the argument is passed outside of the macro. #undef MOVE #define MOVE std::move -template void f10(U &&SomeU) { +template +void f10(U &&SomeU) { T SomeT(MOVE(SomeU)); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: forwarding reference passed to } @@ -111,15 +127,17 @@ // Same result if the macro does not include the "std" namespace. #undef MOVE #define MOVE move -template void f11(U &&SomeU) { +template +void f11(U &&SomeU) { T SomeT(std::MOVE(SomeU)); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: forwarding reference passed to } // Handle the case correctly where the forwarding reference is a parameter of a // generic lambda. -template void f12() { - [] (auto&& x) { T SomeT(std::move(x)); }; +template +void f12() { + [](auto &&x) { T SomeT(std::move(x)); }; // CHECK-MESSAGES: :[[@LINE-1]]:27: warning: forwarding reference passed to // CHECK-FIXES: [] (auto&& x) { T SomeT(std::forward(x)); } } Index: test/clang-tidy/misc-multiple-statement-macro.cpp =================================================================== --- test/clang-tidy/misc-multiple-statement-macro.cpp +++ test/clang-tidy/misc-multiple-statement-macro.cpp @@ -25,12 +25,12 @@ F(); \ F() -#define GOOD_NESTED(x) \ - if (x) \ - GOOD_MACRO3(x); \ +#define GOOD_NESTED(x) \ + if (x) \ + GOOD_MACRO3(x); \ F(); -#define IF(x) if(x) +#define IF(x) if (x) void positives() { if (1) @@ -51,7 +51,8 @@ // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: multiple statement macro used MACRO_ARG_MACRO(F(); int); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: multiple statement macro used - IF(1) BAD_MACRO(1); + IF(1) + BAD_MACRO(1); // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: multiple statement macro used } @@ -81,5 +82,6 @@ MACRO_ARG_MACRO(GOOD_MACRO); ALL_IN_MACRO(1); - IF(1) GOOD_MACRO(1); + IF(1) + GOOD_MACRO(1); } Index: test/clang-tidy/misc-new-delete-overloads.cpp =================================================================== --- test/clang-tidy/misc-new-delete-overloads.cpp +++ test/clang-tidy/misc-new-delete-overloads.cpp @@ -49,13 +49,13 @@ struct C { void *operator new(size_t, A) noexcept; // ok, placement new private: - void operator delete(void *) noexcept; + void operator delete(void *)noexcept; }; // It is also okay to have a class with a delete free store operator. struct D { void *operator new(size_t, A) noexcept; // ok, placement new - void operator delete(void *) noexcept = delete; + void operator delete(void *)noexcept = delete; }; struct E : U { @@ -68,7 +68,7 @@ }; class G { - void operator delete(void *) noexcept; + void operator delete(void *)noexcept; }; struct H : G { @@ -76,6 +76,7 @@ void *operator new(size_t) noexcept; // base class operator is inaccessible }; -template struct Derived : Base { +template +struct Derived : Base { void operator delete(void *); }; Index: test/clang-tidy/misc-noexcept-move-constructor.cpp =================================================================== --- test/clang-tidy/misc-noexcept-move-constructor.cpp +++ test/clang-tidy/misc-noexcept-move-constructor.cpp @@ -9,7 +9,8 @@ struct B { static constexpr bool kFalse = false; - B(B &&) noexcept(kFalse); + B(B &&) + noexcept(kFalse); // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: noexcept specifier on the move constructor evaluates to 'false' [misc-noexcept-move-constructor] }; @@ -21,10 +22,11 @@ } class OK1 { - public: +public: OK1(); OK1(const OK1 &); - OK1(OK1&&) noexcept; + OK1(OK1 &&) + noexcept; OK1 &operator=(OK1 &&) noexcept; void f(); void g() noexcept; @@ -34,11 +36,13 @@ static constexpr bool kTrue = true; public: - OK2(OK2 &&) noexcept(true) {} + OK2(OK2 &&) + noexcept(true) {} OK2 &operator=(OK2 &&) noexcept(kTrue) { return *this; } }; struct OK3 { - OK3(OK3 &&) noexcept(false) {} + OK3(OK3 &&) + noexcept(false) {} OK3 &operator=(OK3 &&) = delete; }; Index: test/clang-tidy/misc-non-copyable-objects.c =================================================================== --- test/clang-tidy/misc-non-copyable-objects.c +++ test/clang-tidy/misc-non-copyable-objects.c @@ -1,7 +1,9 @@ // RUN: %check_clang_tidy %s misc-non-copyable-objects %t -typedef struct FILE {} FILE; -typedef struct pthread_cond_t {} pthread_cond_t; +typedef struct FILE { +} FILE; +typedef struct pthread_cond_t { +} pthread_cond_t; typedef int pthread_mutex_t; // CHECK-MESSAGES: :[[@LINE+1]]:13: warning: 'f' declared as type 'FILE', which is unsafe to copy; did you mean 'FILE *'? [misc-non-copyable-objects] @@ -32,12 +34,12 @@ g(*f); pthread_mutex_t m; // ok - h(m); // ok + h(m); // ok pthread_cond_t c; // ok - i(c); // ok + i(c); // ok pthread_mutex_t *m1 = &m; // ok // CHECK-MESSAGES: :[[@LINE+1]]:5: warning: expression has opaque data structure type 'pthread_mutex_t'; type should only be used as a pointer and not dereferenced h(*m1); } \ No newline at end of file Index: test/clang-tidy/misc-non-copyable-objects.cpp =================================================================== --- test/clang-tidy/misc-non-copyable-objects.cpp +++ test/clang-tidy/misc-non-copyable-objects.cpp @@ -1,7 +1,8 @@ // RUN: %check_clang_tidy %s misc-non-copyable-objects %t namespace std { -typedef struct FILE {} FILE; +typedef struct FILE { +} FILE; } using namespace std; Index: test/clang-tidy/misc-redundant-expression.cpp =================================================================== --- test/clang-tidy/misc-redundant-expression.cpp +++ test/clang-tidy/misc-redundant-expression.cpp @@ -16,89 +16,128 @@ extern int bat(int x, int y); int Test(int X, int Y) { - if (X - X) return 1; + if (X - X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent [misc-redundant-expression] - if (X / X) return 1; + if (X / X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X % X) return 1; + if (X % X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X & X) return 1; + if (X & X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X | X) return 1; + if (X | X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X ^ X) return 1; + if (X ^ X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X < X) return 1; + if (X < X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X <= X) return 1; + if (X <= X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X > X) return 1; + if (X > X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X >= X) return 1; + if (X >= X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X && X) return 1; + if (X && X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X || X) return 1; + if (X || X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X != (((X)))) return 1; + if (X != (((X)))) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: both side of operator are equivalent - if (X + 1 == X + 1) return 1; + if (X + 1 == X + 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent - if (X + 1 != X + 1) return 1; + if (X + 1 != X + 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent - if (X + 1 <= X + 1) return 1; + if (X + 1 <= X + 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent - if (X + 1 >= X + 1) return 1; + if (X + 1 >= X + 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent - if ((X != 1 || Y != 1) && (X != 1 || Y != 1)) return 1; + if ((X != 1 || Y != 1) && (X != 1 || Y != 1)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:26: warning: both side of operator are equivalent - if (P.a[X - P.x] != P.a[X - P.x]) return 1; + if (P.a[X - P.x] != P.a[X - P.x]) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: both side of operator are equivalent - if ((int)X < (int)X) return 1; + if ((int)X < (int)X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: both side of operator are equivalent - if ( + "dummy" == + "dummy") return 1; + if (+"dummy" == +"dummy") + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: both side of operator are equivalent - if (L"abc" == L"abc") return 1; + if (L"abc" == L"abc") + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: both side of operator are equivalent - if (foo(0) - 2 < foo(0) - 2) return 1; + if (foo(0) - 2 < foo(0) - 2) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: both side of operator are equivalent - if (foo(bar(0)) < (foo(bar((0))))) return 1; + if (foo(bar(0)) < (foo(bar((0))))) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: both side of operator are equivalent - if (P1.x < P2.x && P1.x < P2.x) return 1; + if (P1.x < P2.x && P1.x < P2.x) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: both side of operator are equivalent - if (P2.a[P1.x + 2] < P2.x && P2.a[(P1.x) + (2)] < (P2.x)) return 1; + if (P2.a[P1.x + 2] < P2.x && P2.a[(P1.x) + (2)] < (P2.x)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:29: warning: both side of operator are equivalent return 0; } int Valid(int X, int Y) { - if (X != Y) return 1; - if (X == Y + 0) return 1; - if (P.x == P.y) return 1; - if (P.a[P.x] < P.a[P.y]) return 1; - if (P.a[0] < P.a[1]) return 1; - - if (P.a[0] < P.a[0ULL]) return 1; - if (0 < 0ULL) return 1; - if ((int)0 < (int)0ULL) return 1; - - if (++X != ++X) return 1; - if (P.a[X]++ != P.a[X]++) return 1; - if (P.a[X++] != P.a[X++]) return 1; - - if ("abc" == "ABC") return 1; - if (foo(bar(0)) < (foo(bat(0, 1)))) return 1; + if (X != Y) + return 1; + if (X == Y + 0) + return 1; + if (P.x == P.y) + return 1; + if (P.a[P.x] < P.a[P.y]) + return 1; + if (P.a[0] < P.a[1]) + return 1; + + if (P.a[0] < P.a[0ULL]) + return 1; + if (0 < 0ULL) + return 1; + if ((int)0 < (int)0ULL) + return 1; + + if (++X != ++X) + return 1; + if (P.a[X]++ != P.a[X]++) + return 1; + if (P.a[X++] != P.a[X++]) + return 1; + + if ("abc" == "ABC") + return 1; + if (foo(bar(0)) < (foo(bat(0, 1)))) + return 1; return 0; } @@ -114,46 +153,50 @@ struct MyStruct { int x; } Q; -bool operator==(const MyStruct& lhs, const MyStruct& rhs) { return lhs.x == rhs.x; } -bool TestOperator(const MyStruct& S) { - if (S == Q) return false; +bool operator==(const MyStruct &lhs, const MyStruct &rhs) { return lhs.x == rhs.x; } +bool TestOperator(const MyStruct &S) { + if (S == Q) + return false; return S == S; // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: both side of overloaded operator are equivalent } #define LT(x, y) (void)((x) < (y)) -#define COND(x, y, z) ((x)?(y):(z)) +#define COND(x, y, z) ((x) ? (y) : (z)) #define EQUALS(x, y) (x) == (y) int TestMacro(int X, int Y) { LT(0, 0); LT(1, 0); LT(X, X); - LT(X+1, X + 1); + LT(X + 1, X + 1); COND(X < Y, X, X); EQUALS(Q, Q); } -int TestFalsePositive(int* A, int X, float F) { +int TestFalsePositive(int *A, int X, float F) { // Produced by bison. X = A[(2) - (2)]; X = A['a' - 'a']; // Testing NaN. - if (F != F && F == F) return 1; + if (F != F && F == F) + return 1; return 0; } int TestBannedMacros() { #define EAGAIN 3 #define NOT_EAGAIN 3 - if (EAGAIN == 0 | EAGAIN == 0) return 0; - if (NOT_EAGAIN == 0 | NOT_EAGAIN == 0) return 0; + if (EAGAIN == 0 | EAGAIN == 0) + return 0; + if (NOT_EAGAIN == 0 | NOT_EAGAIN == 0) + return 0; // CHECK-MESSAGES: :[[@LINE-1]]:23: warning: both side of operator are equivalent } struct MyClass { -static const int Value = 42; + static const int Value = 42; }; template void TemplateCheck() { @@ -164,322 +207,467 @@ void TestTemplate() { TemplateCheck(); } int TestArithmetic(int X, int Y) { - if (X + 1 == X) return 1; + if (X + 1 == X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always false - if (X + 1 != X) return 1; + if (X + 1 != X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X - 1 == X) return 1; + if (X - 1 == X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always false - if (X - 1 != X) return 1; + if (X - 1 != X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X + 1LL == X) return 1; + if (X + 1LL == X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always false - if (X + 1ULL == X) return 1; + if (X + 1ULL == X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: logical expression is always false - if (X == X + 1) return 1; + if (X == X + 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: logical expression is always false - if (X != X + 1) return 1; + if (X != X + 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: logical expression is always true - if (X == X - 1) return 1; + if (X == X - 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: logical expression is always false - if (X != X - 1) return 1; + if (X != X - 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: logical expression is always true - if (X != X - 1U) return 1; + if (X != X - 1U) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: logical expression is always true - if (X != X - 1LL) return 1; + if (X != X - 1LL) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: logical expression is always true - if ((X+X) != (X+X) - 1) return 1; + if ((X + X) != (X + X) - 1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X + 1 == X + 2) return 1; + if (X + 1 == X + 2) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always false - if (X + 1 != X + 2) return 1; + if (X + 1 != X + 2) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X - 1 == X - 2) return 1; + if (X - 1 == X - 2) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always false - if (X - 1 != X - 2) return 1; + if (X - 1 != X - 2) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X + 1 == X - -1) return 1; + if (X + 1 == X - -1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X + 1 != X - -1) return 1; + if (X + 1 != X - -1) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always false - if (X + 1 == X - -2) return 1; + if (X + 1 == X - -2) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always false - if (X + 1 != X - -2) return 1; + if (X + 1 != X - -2) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X + 1 == X - (~0)) return 1; + if (X + 1 == X - (~0)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X + 1 == X - (~0U)) return 1; + if (X + 1 == X - (~0U)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if (X + 1 == X - (~0ULL)) return 1; + if (X + 1 == X - (~0ULL)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true // Should not match. - if (X + 0.5 == X) return 1; - if (X + 1 == Y) return 1; - if (X + 1 == Y + 1) return 1; - if (X + 1 == Y + 2) return 1; + if (X + 0.5 == X) + return 1; + if (X + 1 == Y) + return 1; + if (X + 1 == Y + 1) + return 1; + if (X + 1 == Y + 2) + return 1; return 0; } int TestBitwise(int X) { - if ((X & 0xFF) == 0xF00) return 1; + if ((X & 0xFF) == 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always false - if ((X & 0xFF) != 0xF00) return 1; + if ((X & 0xFF) != 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always true - if ((X | 0xFF) == 0xF00) return 1; + if ((X | 0xFF) == 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always false - if ((X | 0xFF) != 0xF00) return 1; + if ((X | 0xFF) != 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always true - if ((X | 0xFFULL) != 0xF00) return 1; + if ((X | 0xFFULL) != 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: logical expression is always true - if ((X | 0xFF) != 0xF00ULL) return 1; + if ((X | 0xFF) != 0xF00ULL) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always true - if ((0xFF & X) == 0xF00) return 1; + if ((0xFF & X) == 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always false - if ((0xFF & X) != 0xF00) return 1; + if ((0xFF & X) != 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always true - if ((0xFF & X) == 0xF00) return 1; + if ((0xFF & X) == 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always false - if ((0xFF & X) != 0xF00) return 1; + if ((0xFF & X) != 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always true - if ((0xFFLL & X) == 0xF00) return 1; + if ((0xFFLL & X) == 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: logical expression is always false - if ((0xFF & X) == 0xF00ULL) return 1; + if ((0xFF & X) == 0xF00ULL) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always false return 0; } int TestRelational(int X, int Y) { - if (X == 10 && X != 10) return 1; + if (X == 10 && X != 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always false - if (X == 10 && (X != 10)) return 1; + if (X == 10 && (X != 10)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always false - if (X == 10 && !(X == 10)) return 1; + if (X == 10 && !(X == 10)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always false - if (!(X != 10) && !(X == 10)) return 1; + if (!(X != 10) && !(X == 10)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always false - if (X == 10ULL && X != 10ULL) return 1; + if (X == 10ULL && X != 10ULL) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always false - if (!(X != 10U) && !(X == 10)) return 1; + if (!(X != 10U) && !(X == 10)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: logical expression is always false - if (!(X != 10LL) && !(X == 10)) return 1; + if (!(X != 10LL) && !(X == 10)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: logical expression is always false - if (!(X != 10ULL) && !(X == 10)) return 1; + if (!(X != 10ULL) && !(X == 10)) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: logical expression is always false - if (X == 0 && X) return 1; + if (X == 0 && X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: logical expression is always false - if (X != 0 && !X) return 1; + if (X != 0 && !X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: logical expression is always false - if (X && !X) return 1; + if (X && !X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: logical expression is always false - if (X && !!X) return 1; + if (X && !!X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: equivalent expression on both side of logical operator - if (X != 0 && X) return 1; + if (X != 0 && X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: equivalent expression on both side of logical operator - if (X != 0 && !!X) return 1; + if (X != 0 && !!X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: equivalent expression on both side of logical operator - if (X == 0 && !X) return 1; + if (X == 0 && !X) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: equivalent expression on both side of logical operator - if (X == 10 && X > 10) return 1; + if (X == 10 && X > 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always false - if (X == 10 && X < 10) return 1; + if (X == 10 && X < 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always false - if (X < 10 && X > 10) return 1; + if (X < 10 && X > 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: logical expression is always false - if (X <= 10 && X > 10) return 1; + if (X <= 10 && X > 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always false - if (X < 10 && X >= 10) return 1; + if (X < 10 && X >= 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: logical expression is always false - if (X < 10 && X == 10) return 1; + if (X < 10 && X == 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: logical expression is always false - if (X > 5 && X <= 5) return 1; + if (X > 5 && X <= 5) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always false - if (X > -5 && X <= -5) return 1; + if (X > -5 && X <= -5) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: logical expression is always false - if (X < 10 || X >= 10) return 1; + if (X < 10 || X >= 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: logical expression is always true - if (X <= 10 || X > 10) return 1; + if (X <= 10 || X > 10) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always true - if (X <= 10 || X >= 11) return 1; + if (X <= 10 || X >= 11) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: logical expression is always true - if (X < 7 && X < 6) return 1; + if (X < 7 && X < 6) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X < 7 && X < 7) return 1; + if (X < 7 && X < 7) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent - if (X < 7 && X < 8) return 1; + if (X < 7 && X < 8) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: expression is redundant - if (X < 7 && X <= 5) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X < 7 && X <= 6) return 1; + if (X < 7 && X <= 5) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant + if (X < 7 && X <= 6) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: equivalent expression on both side of logical operator - if (X < 7 && X <= 7) return 1; + if (X < 7 && X <= 7) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: expression is redundant - if (X < 7 && X <= 8) return 1; + if (X < 7 && X <= 8) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: expression is redundant - if (X <= 7 && X < 6) return 1; + if (X <= 7 && X < 6) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X <= 7 && X < 7) return 1; + if (X <= 7 && X < 7) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X <= 7 && X < 8) return 1; + if (X <= 7 && X < 8) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: equivalent expression on both side of logical operator - if (X <= 7 && X <= 5) return 1; + if (X <= 7 && X <= 5) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X <= 7 && X <= 6) return 1; + if (X <= 7 && X <= 6) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X <= 7 && X <= 7) return 1; + if (X <= 7 && X <= 7) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: both side of operator are equivalent - if (X <= 7 && X <= 8) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: expression is redundant - - if (X == 11 && X > 10) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: expression is redundant - if (X == 11 && X < 12) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: expression is redundant - if (X > 10 && X == 11) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X < 12 && X == 11) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - - if (X != 11 && X == 42) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X != 11 && X > 11) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X != 11 && X < 11) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X != 11 && X < 8) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - if (X != 11 && X > 14) return 1; - // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant - - if (X < 7 || X < 6) return 1; + if (X <= 7 && X <= 8) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: expression is redundant + + if (X == 11 && X > 10) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: expression is redundant + if (X == 11 && X < 12) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:20: warning: expression is redundant + if (X > 10 && X == 11) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant + if (X < 12 && X == 11) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant + + if (X != 11 && X == 42) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant + if (X != 11 && X > 11) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant + if (X != 11 && X < 11) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant + if (X != 11 && X < 8) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant + if (X != 11 && X > 14) + return 1; + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant + + if (X < 7 || X < 6) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: expression is redundant - if (X < 7 || X < 7) return 1; + if (X < 7 || X < 7) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: both side of operator are equivalent - if (X < 7 || X < 8) return 1; + if (X < 7 || X < 8) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: expression is redundant // Should not match. - if (X == 10 && Y == 10) return 1; - if (X != 10 && X != 12) return 1; - if (X == 10 || X == 12) return 1; - if (X < 10 || X > 12) return 1; - if (X > 10 && X < 12) return 1; - if (X < 10 || X >= 12) return 1; - if (X > 10 && X <= 12) return 1; - if (X <= 10 || X > 12) return 1; - if (X >= 10 && X < 12) return 1; - if (X <= 10 || X >= 12) return 1; - if (X >= 10 && X <= 12) return 1; - if (X >= 10 && X <= 11) return 1; - if (X >= 10 && X < 11) return 1; - if (X > 10 && X <= 11) return 1; - if (X > 10 && X != 11) return 1; - if (X >= 10 && X <= 10) return 1; - if (X <= 10 && X >= 10) return 1; - if (!X && !Y) return 1; - if (!X && Y) return 1; - if (!X && Y == 0) return 1; - if (X == 10 && Y != 10) return 1; - if (X < 0 || X > 0) return 1; + if (X == 10 && Y == 10) + return 1; + if (X != 10 && X != 12) + return 1; + if (X == 10 || X == 12) + return 1; + if (X < 10 || X > 12) + return 1; + if (X > 10 && X < 12) + return 1; + if (X < 10 || X >= 12) + return 1; + if (X > 10 && X <= 12) + return 1; + if (X <= 10 || X > 12) + return 1; + if (X >= 10 && X < 12) + return 1; + if (X <= 10 || X >= 12) + return 1; + if (X >= 10 && X <= 12) + return 1; + if (X >= 10 && X <= 11) + return 1; + if (X >= 10 && X < 11) + return 1; + if (X > 10 && X <= 11) + return 1; + if (X > 10 && X != 11) + return 1; + if (X >= 10 && X <= 10) + return 1; + if (X <= 10 && X >= 10) + return 1; + if (!X && !Y) + return 1; + if (!X && Y) + return 1; + if (!X && Y == 0) + return 1; + if (X == 10 && Y != 10) + return 1; + if (X < 0 || X > 0) + return 1; return 0; } int TestValidExpression(int X) { - if (X - 1 == 1 - X) return 1; - if (2 * X == X) return 1; - if ((X << 1) == X) return 1; + if (X - 1 == 1 - X) + return 1; + if (2 * X == X) + return 1; + if ((X << 1) == X) + return 1; return 0; } -enum Color { Red, Yellow, Green }; +enum Color { Red, + Yellow, + Green }; int TestRelatiopnalWithEnum(enum Color C) { - if (C == Red && C == Yellow) return 1; + if (C == Red && C == Yellow) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: logical expression is always false - if (C == Red && C != Red) return 1; + if (C == Red && C != Red) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: logical expression is always false // Should not match. - if (C == Red || C == Yellow) return 1; - if (C != Red && C != Yellow) return 1; + if (C == Red || C == Yellow) + return 1; + if (C != Red && C != Yellow) + return 1; return 0; } -template +template int TestRelationalTemplated(int X) { // This test causes a corner case with |isIntegerConstantExpr| where the type // is dependant. There is an assert failing when evaluating // sizeof(). - if (sizeof(T) == 4 || sizeof(T) == 8) return 1; + if (sizeof(T) == 4 || sizeof(T) == 8) + return 1; - if (X + 0 == -X) return 1; - if (X + 0 < X) return 1; + if (X + 0 == -X) + return 1; + if (X + 0 < X) + return 1; return 0; } int TestWithSignedUnsigned(int X) { - if (X + 1 == X + 1ULL) return 1; + if (X + 1 == X + 1ULL) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: logical expression is always true - if ((X & 0xFFU) == 0xF00) return 1; + if ((X & 0xFFU) == 0xF00) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: logical expression is always false - if ((X & 0xFF) == 0xF00U) return 1; + if ((X & 0xFF) == 0xF00U) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: logical expression is always false - if ((X & 0xFFU) == 0xF00U) return 1; + if ((X & 0xFFU) == 0xF00U) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: logical expression is always false return 0; } int TestWithLong(int X, I64 Y) { - if (X + 0ULL == -X) return 1; - if (Y + 0 == -Y) return 1; - if (Y <= 10 && X >= 10LL) return 1; - if (Y <= 10 && X >= 10ULL) return 1; - if (X <= 10 || X > 12LL) return 1; - if (X <= 10 || X > 12ULL) return 1; - if (Y <= 10 || Y > 12) return 1; + if (X + 0ULL == -X) + return 1; + if (Y + 0 == -Y) + return 1; + if (Y <= 10 && X >= 10LL) + return 1; + if (Y <= 10 && X >= 10ULL) + return 1; + if (X <= 10 || X > 12LL) + return 1; + if (X <= 10 || X > 12ULL) + return 1; + if (Y <= 10 || Y > 12) + return 1; return 0; } int TestWithMinMaxInt(int X) { - if (X <= X + 0xFFFFFFFFU) return 1; - if (X <= X + 0x7FFFFFFF) return 1; - if (X <= X + 0x80000000) return 1; - if (X <= 0xFFFFFFFFU && X > 0) return 1; - if (X <= 0xFFFFFFFFU && X > 0U) return 1; - - if (X + 0x80000000 == X - 0x80000000) return 1; + if (X <= X + 0xFFFFFFFFU) + return 1; + if (X <= X + 0x7FFFFFFF) + return 1; + if (X <= X + 0x80000000) + return 1; + if (X <= 0xFFFFFFFFU && X > 0) + return 1; + if (X <= 0xFFFFFFFFU && X > 0U) + return 1; + + if (X + 0x80000000 == X - 0x80000000) + return 1; // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: logical expression is always true - if (X > 0x7FFFFFFF || X < ((-0x7FFFFFFF)-1)) return 1; - if (X <= 0x7FFFFFFF && X >= ((-0x7FFFFFFF)-1)) return 1; - + if (X > 0x7FFFFFFF || X < ((-0x7FFFFFFF) - 1)) + return 1; + if (X <= 0x7FFFFFFF && X >= ((-0x7FFFFFFF) - 1)) + return 1; + return 0; } Index: test/clang-tidy/misc-sizeof-container.cpp =================================================================== --- test/clang-tidy/misc-sizeof-container.cpp +++ test/clang-tidy/misc-sizeof-container.cpp @@ -38,7 +38,6 @@ struct fake_container2 { size_t size(); // non-const }; - } using std::size_t; @@ -53,7 +52,7 @@ std::size_t size() const; }; -template +template void g(T t) { (void)sizeof(t); } @@ -64,15 +63,15 @@ std::vector v; int a = 42 + sizeof(s1); -// CHECK-MESSAGES: :[[@LINE-1]]:16: warning: sizeof() doesn't return the size of the container; did you mean .size()? [misc-sizeof-container] + // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: sizeof() doesn't return the size of the container; did you mean .size()? [misc-sizeof-container] a = 123 * sizeof(s2); -// CHECK-MESSAGES: :[[@LINE-1]]:13: warning: sizeof() doesn't return the size + // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: sizeof() doesn't return the size a = 45 + sizeof(s2 + "asdf"); -// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: sizeof() doesn't return the size + // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: sizeof() doesn't return the size a = sizeof(v); -// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: sizeof() doesn't return the size + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: sizeof() doesn't return the size a = sizeof(std::vector{}); -// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: sizeof() doesn't return the size + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: sizeof() doesn't return the size a = sizeof(a); a = sizeof(int); @@ -93,7 +92,6 @@ a = sizeof(std_bitset); a = sizeof(std_array); - std::string arr[3]; a = ARRAYSIZE(arr); a = ARRAYSIZE2(arr); Index: test/clang-tidy/misc-sizeof-expression.cpp =================================================================== --- test/clang-tidy/misc-sizeof-expression.cpp +++ test/clang-tidy/misc-sizeof-expression.cpp @@ -12,9 +12,11 @@ extern short B[10]; #pragma pack(1) -struct S { char a, b, c; }; +struct S { + char a, b, c; +}; -int Test1(const char* ptr) { +int Test1(const char *ptr) { int sum = 0; sum += sizeof(LEN); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(K)' @@ -32,7 +34,7 @@ // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(sizeof(...))' sum += sizeof(LEN + -sizeof(X)); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(sizeof(...))' - sum += sizeof(LEN + - + -sizeof(X)); + sum += sizeof(LEN + -+-sizeof(X)); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(sizeof(...))' sum += sizeof(char) / sizeof(char); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T)/sizeof(T)' @@ -48,11 +50,11 @@ // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)' sum += sizeof(ptr) / sizeof(ptr[0]); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)' - sum += sizeof(ptr) / sizeof(char*); + sum += sizeof(ptr) / sizeof(char *); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)' - sum += sizeof(ptr) / sizeof(void*); + sum += sizeof(ptr) / sizeof(void *); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)' - sum += sizeof(ptr) / sizeof(const void volatile*); + sum += sizeof(ptr) / sizeof(const void volatile *); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(P*)/sizeof(Q*)' sum += sizeof(ptr) / sizeof(char); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T*)/sizeof(T)' @@ -66,10 +68,12 @@ // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious 'sizeof' by 'sizeof' multiplication sum += (2 * sizeof(char)) * sizeof(int); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious 'sizeof' by 'sizeof' multiplication - if (sizeof(A) < 0x100000) sum += 42; - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: suspicious comparison of 'sizeof(expr)' to a constant - if (sizeof(A) <= 0xFFFFFFFEU) sum += 42; - // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: suspicious comparison of 'sizeof(expr)' to a constant + if (sizeof(A) < 0x100000) + sum += 42; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: suspicious comparison of 'sizeof(expr)' to a constant + if (sizeof(A) <= 0xFFFFFFFEU) + sum += 42; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: suspicious comparison of 'sizeof(expr)' to a constant return sum; } @@ -78,16 +82,16 @@ int CE0 = sizeof sizeof(char); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: suspicious usage of 'sizeof(sizeof(...))' -int CE1 = sizeof +sizeof(char); +int CE1 = sizeof + sizeof(char); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: suspicious usage of 'sizeof(sizeof(...))' -int CE2 = sizeof sizeof(const char*); +int CE2 = sizeof sizeof(const char *); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: suspicious usage of 'sizeof(sizeof(...))' -int CE3 = sizeof sizeof(const volatile char* const*); +int CE3 = sizeof sizeof(const volatile char *const *); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: suspicious usage of 'sizeof(sizeof(...))' int CE4 = sizeof sizeof(MyConstChar); // CHECK-MESSAGES: :[[@LINE-1]]:11: warning: suspicious usage of 'sizeof(sizeof(...))' -int Test2(MyConstChar* A) { +int Test2(MyConstChar *A) { int sum = 0; sum += sizeof(MyConstChar) / sizeof(char); // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of sizeof pointer 'sizeof(T)/sizeof(T)' @@ -99,15 +103,21 @@ } template -int Foo() { int A[T]; return sizeof(T); } +int Foo() { + int A[T]; + return sizeof(T); +} // CHECK-MESSAGES: :[[@LINE-1]]:30: warning: suspicious usage of 'sizeof(K)' template -int Bar() { T A[5]; return sizeof(A[0]) / sizeof(T); } +int Bar() { + T A[5]; + return sizeof(A[0]) / sizeof(T); +} // CHECK-MESSAGES: :[[@LINE-1]]:28: warning: suspicious usage of sizeof pointer 'sizeof(T)/sizeof(T)' int Test3() { return Foo<42>() + Bar(); } -static const char* kABC = "abc"; -static const wchar_t* kDEF = L"def"; +static const char *kABC = "abc"; +static const wchar_t *kDEF = L"def"; int Test4(const char A[10]) { int sum = 0; sum += sizeof(kABC); @@ -122,43 +132,43 @@ struct MyStruct { Array10 arr; - Array10* ptr; + Array10 *ptr; }; typedef const MyStruct TMyStruct; static TMyStruct kGlocalMyStruct = {}; - static TMyStruct volatile * kGlocalMyStructPtr = &kGlocalMyStruct; + static TMyStruct volatile *kGlocalMyStructPtr = &kGlocalMyStruct; MyStruct S; Array10 A10; int sum = 0; sum += sizeof(&S.arr); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(&kGlocalMyStruct.arr); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(&kGlocalMyStructPtr->arr); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(S.arr + 0); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate - sum += sizeof(+ S.arr); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate - sum += sizeof((int*)S.arr); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + sum += sizeof(+S.arr); + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + sum += sizeof((int *)S.arr); + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(S.ptr); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(kGlocalMyStruct.ptr); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(kGlocalMyStructPtr->ptr); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(&kGlocalMyStruct); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(&S); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate sum += sizeof(&A10); - // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: suspicious usage of 'sizeof(A*)'; pointer to aggregate return sum; } @@ -166,15 +176,15 @@ int ValidExpressions() { int A[] = {1, 2, 3, 4}; static const char str[] = "hello"; - static const char* ptr[] { "aaa", "bbb", "ccc" }; + static const char *ptr[]{"aaa", "bbb", "ccc"}; int sum = 0; if (sizeof(A) < 10) sum += sizeof(A); sum += sizeof(int); sum += sizeof(A[sizeof(A) / sizeof(int)]); sum += sizeof(&A[sizeof(A) / sizeof(int)]); - sum += sizeof(sizeof(0)); // Special case: sizeof size_t. - sum += sizeof(void*); + sum += sizeof(sizeof(0)); // Special case: sizeof size_t. + sum += sizeof(void *); sum += sizeof(void const *); sum += sizeof(void const *) / 4; sum += sizeof(str); Index: test/clang-tidy/misc-static-assert.c =================================================================== --- test/clang-tidy/misc-static-assert.c +++ test/clang-tidy/misc-static-assert.c @@ -5,21 +5,21 @@ #ifdef NDEBUG #define assert(x) 1 #else -#define assert(x) \ - if (!(x)) \ +#define assert(x) \ + if (!(x)) \ abort() #endif void f(void) { int x = 1; assert(x == 0); - // CHECK-FIXES: {{^ }}assert(x == 0); +// CHECK-FIXES: {{^ }}assert(x == 0); - #define static_assert(x, msg) _Static_assert(x, msg) +#define static_assert(x, msg) _Static_assert(x, msg) assert(11 == 5 + 6); - // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be - // CHECK-FIXES: {{^ }}static_assert(11 == 5 + 6, ""); - #undef static_assert +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be +// CHECK-FIXES: {{^ }}static_assert(11 == 5 + 6, ""); +#undef static_assert assert(10 == 5 + 5); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be Index: test/clang-tidy/misc-static-assert.cpp =================================================================== --- test/clang-tidy/misc-static-assert.cpp +++ test/clang-tidy/misc-static-assert.cpp @@ -4,8 +4,8 @@ #ifdef NDEBUG #define assert(x) 1 #else -#define assert(x) \ - if (!(x)) \ +#define assert(x) \ + if (!(x)) \ abort() #endif @@ -34,7 +34,8 @@ constexpr bool method() { return true; } }; -template void doSomething(T t) { +template +void doSomething(T t) { assert(myfunc(1, 2)); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be replaced by static_assert() [misc-static-assert] // CHECK-FIXES: {{^ }}static_assert(myfunc(1, 2), ""); @@ -80,9 +81,9 @@ // CHECK-FIXES: {{^ }}assert(0 && "Don't report me!"); assert(false && "Don't report me!"); - // CHECK-FIXES: {{^ }}assert(false && "Don't report me!"); +// CHECK-FIXES: {{^ }}assert(false && "Don't report me!"); -#define NULL ((void*)0) +#define NULL ((void *)0) assert(NULL && "Don't report me!"); // CHECK-FIXES: {{^ }}assert(NULL && "Don't report me!"); @@ -93,18 +94,18 @@ // CHECK-FIXES: {{^ }}assert("Don't report me!" == NULL); assert(0 == "Don't report me!"); - // CHECK-FIXES: {{^ }}assert(0 == "Don't report me!"); +// CHECK-FIXES: {{^ }}assert(0 == "Don't report me!"); #define NULL ((unsigned int)0) assert(NULL && "Report me!"); - // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be - // CHECK-FIXES: {{^ }}static_assert(NULL , "Report me!"); +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be +// CHECK-FIXES: {{^ }}static_assert(NULL , "Report me!"); #define NULL __null assert(__null == "Don't report me!"); // CHECK-FIXES: {{^ }}assert(__null == "Don't report me!"); assert(NULL == "Don't report me!"); - // CHECK-FIXES: {{^ }}assert(NULL == "Don't report me!"); +// CHECK-FIXES: {{^ }}assert(NULL == "Don't report me!"); #undef NULL assert(ZERO_MACRO && "Report me!"); @@ -120,20 +121,20 @@ assert(false); #undef false - assert(10==5 && "Report me!"); + assert(10 == 5 && "Report me!"); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be // CHECK-FIXES: {{^ }}static_assert(10==5 , "Report me!"); assert(strlen("12345") == 5); - // CHECK-FIXES: {{^ }}assert(strlen("12345") == 5); +// CHECK-FIXES: {{^ }}assert(strlen("12345") == 5); -#define assert(e) (__builtin_expect(!(e), 0) ? print (#e, __FILE__, __LINE__) : (void)0) +#define assert(e) (__builtin_expect(!(e), 0) ? print(#e, __FILE__, __LINE__) : (void)0) assert(false); // CHECK-FIXES: {{^ }}assert(false); assert(10 == 5 + 5); - // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be - // CHECK-FIXES: {{^ }}static_assert(10 == 5 + 5, ""); +// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: found assert() that could be +// CHECK-FIXES: {{^ }}static_assert(10 == 5 + 5, ""); #undef assert return 0; Index: test/clang-tidy/misc-string-constructor.cpp =================================================================== --- test/clang-tidy/misc-string-constructor.cpp +++ test/clang-tidy/misc-string-constructor.cpp @@ -5,34 +5,34 @@ class allocator {}; template class char_traits {}; -template , typename A = std::allocator > +template , typename A = std::allocator> struct basic_string { basic_string(); - basic_string(const C*, unsigned int size); + basic_string(const C *, unsigned int size); basic_string(unsigned int size, C c); }; typedef basic_string string; typedef basic_string wstring; } -const char* kText = ""; +const char *kText = ""; const char kText2[] = ""; extern const char kText3[]; void Test() { std::string str('x', 4); // CHECK-MESSAGES: [[@LINE-1]]:15: warning: string constructor parameters are probably swapped; expecting string(count, character) [misc-string-constructor] - // CHECK-FIXES: std::string str(4, 'x'); + // CHECK-FIXES: std::string str(4, 'x'); std::wstring wstr(L'x', 4); // CHECK-MESSAGES: [[@LINE-1]]:16: warning: string constructor parameters are probably swapped - // CHECK-FIXES: std::wstring wstr(4, L'x'); + // CHECK-FIXES: std::wstring wstr(4, L'x'); std::string s0(0, 'x'); // CHECK-MESSAGES: [[@LINE-1]]:15: warning: constructor creating an empty string std::string s1(-4, 'x'); // CHECK-MESSAGES: [[@LINE-1]]:15: warning: negative value used as length parameter std::string s2(0x1000000, 'x'); // CHECK-MESSAGES: [[@LINE-1]]:15: warning: suspicious large length parameter - + std::string q0("test", 0); // CHECK-MESSAGES: [[@LINE-1]]:15: warning: constructor creating an empty string std::string q1(kText, -4); @@ -43,7 +43,7 @@ // CHECK-MESSAGES: [[@LINE-1]]:15: warning: length is bigger then string literal size std::string q4(kText2, 200); // CHECK-MESSAGES: [[@LINE-1]]:15: warning: length is bigger then string literal size - std::string q5(kText3, 0x1000000); + std::string q5(kText3, 0x1000000); // CHECK-MESSAGES: [[@LINE-1]]:15: warning: suspicious large length parameter } Index: test/clang-tidy/misc-string-integer-assignment.cpp =================================================================== --- test/clang-tidy/misc-string-integer-assignment.cpp +++ test/clang-tidy/misc-string-integer-assignment.cpp @@ -1,12 +1,12 @@ // RUN: %check_clang_tidy %s misc-string-integer-assignment %t namespace std { -template +template struct basic_string { - basic_string& operator=(T); - basic_string& operator=(basic_string); - basic_string& operator+=(T); - basic_string& operator+=(basic_string); + basic_string &operator=(T); + basic_string &operator=(basic_string); + basic_string &operator+=(T); + basic_string &operator+=(basic_string); }; typedef basic_string string; @@ -21,33 +21,32 @@ int x = 5; s = 6; -// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: an integer is interpreted as a character code when assigning {{.*}} [misc-string-integer-assignment] -// CHECK-FIXES: {{^}} s = '6';{{$}} + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: an integer is interpreted as a character code when assigning {{.*}} [misc-string-integer-assignment] + // CHECK-FIXES: {{^}} s = '6';{{$}} s = 66; -// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: an integer is interpreted as a chara -// CHECK-FIXES: {{^}} s = "66";{{$}} + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: an integer is interpreted as a chara + // CHECK-FIXES: {{^}} s = "66";{{$}} s = x; -// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: an integer is interpreted as a chara -// CHECK-FIXES: {{^}} s = std::to_string(x);{{$}} + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: an integer is interpreted as a chara + // CHECK-FIXES: {{^}} s = std::to_string(x);{{$}} s = 'c'; s = static_cast(6); -// += + // += ws += 6; -// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: an integer is interpreted as a chara -// CHECK-FIXES: {{^}} ws += L'6';{{$}} + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: an integer is interpreted as a chara + // CHECK-FIXES: {{^}} ws += L'6';{{$}} ws += 66; -// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: an integer is interpreted as a chara -// CHECK-FIXES: {{^}} ws += L"66";{{$}} + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: an integer is interpreted as a chara + // CHECK-FIXES: {{^}} ws += L"66";{{$}} ws += x; -// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: an integer is interpreted as a chara -// CHECK-FIXES: {{^}} ws += std::to_wstring(x);{{$}} + // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: an integer is interpreted as a chara + // CHECK-FIXES: {{^}} ws += std::to_wstring(x);{{$}} ws += L'c'; ws += (wchar_t)6; std::basic_string as; as = 6; -// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: an integer is interpreted as a chara -// CHECK-FIXES: {{^}} as = 6;{{$}} - + // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: an integer is interpreted as a chara + // CHECK-FIXES: {{^}} as = 6;{{$}} } Index: test/clang-tidy/misc-string-literal-with-embedded-nul.cpp =================================================================== --- test/clang-tidy/misc-string-literal-with-embedded-nul.cpp +++ test/clang-tidy/misc-string-literal-with-embedded-nul.cpp @@ -11,17 +11,16 @@ basic_string(); basic_string(const C *p, const A &a = A()); - _Type& operator+=(const C* s); - _Type& operator=(const C* s); + _Type &operator+=(const C *s); + _Type &operator=(const C *s); }; typedef basic_string, std::allocator> string; typedef basic_string, std::allocator> wstring; } -bool operator==(const std::string&, const char*); -bool operator==(const char*, const std::string&); - +bool operator==(const std::string &, const char *); +bool operator==(const char *, const std::string &); const char Valid[] = "This is valid \x12."; const char Strange[] = "This is strange \0x12 and must be fixed"; @@ -48,7 +47,10 @@ const char J[] = "\0\0\0\0\0\0"; const char K[] = ""; -const char L[] = "\0x12" "\0x12" "\0x12" "\0x12"; +const char L[] = "\0x12" + "\0x12" + "\0x12" + "\0x12"; // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: suspicious embedded NUL character void TestA() { @@ -67,9 +69,11 @@ str = "abc\0def"; // CHECK-MESSAGES: :[[@LINE-1]]:9: warning: truncated string literal - if (str == "abc\0def") return; + if (str == "abc\0def") + return; // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: truncated string literal - if ("abc\0def" == str) return; + if ("abc\0def" == str) + return; // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: truncated string literal } Index: test/clang-tidy/misc-suspicious-missing-comma.cpp =================================================================== --- test/clang-tidy/misc-suspicious-missing-comma.cpp +++ test/clang-tidy/misc-suspicious-missing-comma.cpp @@ -1,82 +1,91 @@ // RUN: %check_clang_tidy %s misc-suspicious-missing-comma %t -const char* Cartoons[] = { - "Bugs Bunny", - "Homer Simpson", - "Mickey Mouse", - "Bart Simpson", - "Charlie Brown" // There is a missing comma here. - "Fred Flintstone", - "Popeye", +const char *Cartoons[] = { + "Bugs Bunny", + "Homer Simpson", + "Mickey Mouse", + "Bart Simpson", + "Charlie Brown" // There is a missing comma here. + "Fred Flintstone", + "Popeye", }; // CHECK-MESSAGES: :[[@LINE-4]]:3: warning: suspicious string literal, probably missing a comma [misc-suspicious-missing-comma] -const wchar_t* Colors[] = { - L"Red", L"Yellow", L"Blue", L"Green", L"Purple", L"Rose", L"White", L"Black" -}; +const wchar_t *Colors[] = { + L"Red", L"Yellow", L"Blue", L"Green", L"Purple", L"Rose", L"White", L"Black"}; // The following array should not trigger any warnings. There is more than 5 // elements, but they are all concatenated string literals. -const char* HttpCommands[] = { - "GET / HTTP/1.0\r\n" - "\r\n", +const char *HttpCommands[] = { + "GET / HTTP/1.0\r\n" + "\r\n", - "GET /index.html HTTP/1.0\r\n" - "\r\n", + "GET /index.html HTTP/1.0\r\n" + "\r\n", - "GET /favicon.ico HTTP/1.0\r\n" - "header: dummy" - "\r\n", + "GET /favicon.ico HTTP/1.0\r\n" + "header: dummy" + "\r\n", - "GET /index.html-en HTTP/1.0\r\n" - "\r\n", + "GET /index.html-en HTTP/1.0\r\n" + "\r\n", - "GET /index.html-fr HTTP/1.0\r\n" - "\r\n", + "GET /index.html-fr HTTP/1.0\r\n" + "\r\n", - "GET /index.html-es HTTP/1.0\r\n" - "\r\n", + "GET /index.html-es HTTP/1.0\r\n" + "\r\n", }; // This array is too small to trigger a warning. -const char* SmallArray[] = { - "a" "b", "c" -}; +const char *SmallArray[] = { + "a" + "b", + "c"}; // Parentheses should be enough to avoid warnings. -const char* ParentheseArray[] = { - ("a" "b"), "c", - ("d" - "e" - "f"), - "g", "h", "i", "j", "k", "l" -}; +const char *ParentheseArray[] = { + ("a" + "b"), + "c", + ("d" + "e" + "f"), + "g", "h", "i", "j", "k", "l"}; // Indentation should be enough to avoid warnings. -const char* CorrectlyIndentedArray[] = { - "This is a long message " - "which is spanning over multiple lines." - "And this should be fine.", - "a", "b", "c", "d", "e", "f", - "g", "h", "i", "j", "k", "l" -}; +const char *CorrectlyIndentedArray[] = { + "This is a long message " + "which is spanning over multiple lines." + "And this should be fine.", + "a", "b", "c", "d", "e", "f", + "g", "h", "i", "j", "k", "l"}; -const char* IncorrectlyIndentedArray[] = { - "This is a long message " - "which is spanning over multiple lines." - "And this should be fine.", - "a", "b", "c", "d", "e", "f", - "g", "h", "i", "j", "k", "l" -}; +const char *IncorrectlyIndentedArray[] = { + "This is a long message " + "which is spanning over multiple lines." + "And this should be fine.", + "a", "b", "c", "d", "e", "f", + "g", "h", "i", "j", "k", "l"}; // CHECK-MESSAGES: :[[@LINE-6]]:3: warning: suspicious string literal, probably missing a comma [misc-suspicious-missing-comma] -const char* TooManyConcatenatedTokensArray[] = { - "Dummy line", - "Dummy line", - "a" "b" "c" "d" "e" "f", - "g" "h" "i" "j" "k" "l", - "Dummy line", - "Dummy line", - "Dummy line", - "Dummy line", +const char *TooManyConcatenatedTokensArray[] = { + "Dummy line", + "Dummy line", + "a" + "b" + "c" + "d" + "e" + "f", + "g" + "h" + "i" + "j" + "k" + "l", + "Dummy line", + "Dummy line", + "Dummy line", + "Dummy line", }; Index: test/clang-tidy/misc-suspicious-semicolon-fail.cpp =================================================================== --- test/clang-tidy/misc-suspicious-semicolon-fail.cpp +++ test/clang-tidy/misc-suspicious-semicolon-fail.cpp @@ -6,7 +6,8 @@ bool g(); void f() { - if (g()); + if (g()) + ; // CHECK-NOT: [misc-suspicious-semicolon] int a } Index: test/clang-tidy/misc-suspicious-semicolon.cpp =================================================================== --- test/clang-tidy/misc-suspicious-semicolon.cpp +++ test/clang-tidy/misc-suspicious-semicolon.cpp @@ -4,74 +4,71 @@ void nop(); -void correct1() -{ - if(x < 5) nop(); +void correct1() { + if (x < 5) + nop(); } -void correct2() -{ - if(x == 5) - nop(); +void correct2() { + if (x == 5) + nop(); } -void correct3() -{ - if(x > 5) - { - nop(); - } +void correct3() { + if (x > 5) { + nop(); + } } -void fail1() -{ - if(x > 5); nop(); +void fail1() { + if (x > 5) + ; + nop(); // CHECK-MESSAGES: :[[@LINE-1]]:12: warning: potentially unintended semicolon [misc-suspicious-semicolon] // CHECK-FIXES: if(x > 5) nop(); } -void fail2() -{ - if(x == 5); - nop(); +void fail2() { + if (x == 5) + ; + nop(); // CHECK-MESSAGES: :[[@LINE-2]]:12: warning: potentially unintended semicolon [misc-suspicious-semicolon] // CHECK-FIXES: if(x == 5){{$}} } -void fail3() -{ - if(x < 5); - { - nop(); - } +void fail3() { + if (x < 5) + ; + { + nop(); + } // CHECK-MESSAGES: :[[@LINE-4]]:11: warning: potentially unintended semicolon // CHECK-FIXES: if(x < 5){{$}} } -void correct4() -{ - while(x % 5 == 1); +void correct4() { + while (x % 5 == 1) + ; nop(); } -void correct5() -{ - for(int i = 0; i < x; ++i) - ; +void correct5() { + for (int i = 0; i < x; ++i) + ; } -void fail4() -{ - for(int i = 0; i < x; ++i); - nop(); +void fail4() { + for (int i = 0; i < x; ++i) + ; + nop(); // CHECK-MESSAGES: :[[@LINE-2]]:28: warning: potentially unintended semicolon // CHECK-FIXES: for(int i = 0; i < x; ++i){{$}} } -void fail5() -{ - if(x % 5 == 1); - nop(); +void fail5() { + if (x % 5 == 1) + ; + nop(); // CHECK-MESSAGES: :[[@LINE-2]]:16: warning: potentially unintended semicolon // CHECK-FIXES: if(x % 5 == 1){{$}} } @@ -79,8 +76,9 @@ void fail6() { int a = 0; if (a != 0) { - } else if (a != 1); - a = 2; + } else if (a != 1) + ; + a = 2; // CHECK-MESSAGES: :[[@LINE-2]]:21: warning: potentially unintended semicolon // CHECK-FIXES: } else if (a != 1){{$}} } @@ -91,13 +89,13 @@ // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: potentially unintended semicolon } -void correct6() -{ - do; while(false); +void correct6() { + do + ; + while (false); } -int correct7() -{ +int correct7() { int t_num = 0; char c = 'b'; char *s = "a"; Index: test/clang-tidy/misc-suspicious-string-compare.c =================================================================== --- test/clang-tidy/misc-suspicious-string-compare.c +++ test/clang-tidy/misc-suspicious-string-compare.c @@ -43,37 +43,44 @@ } void test_structure_patterns() { - if (strcmp(A, "a")) {} + if (strcmp(A, "a")) { + } // CHECK-MESSAGES: [[@LINE-1]]:7: warning: function 'strcmp' is called without explicitly comparing result // CHECK-FIXES: if (strcmp(A, "a") != 0) {} - while (strcmp(A, "a")) {} + while (strcmp(A, "a")) { + } // CHECK-MESSAGES: [[@LINE-1]]:10: warning: function 'strcmp' is called without explicitly comparing result // CHECK-FIXES: while (strcmp(A, "a") != 0) {} - for (;strcmp(A, "a");) {} + for (; strcmp(A, "a");) { + } // CHECK-MESSAGES: [[@LINE-1]]:9: warning: function 'strcmp' is called without explicitly comparing result // CHECK-FIXES: for (;strcmp(A, "a") != 0;) {} } int test_valid_patterns() { // The following cases are valid. - if (strcmp(A, "a") < 0) return 0; - if (strcmp(A, "a") == 0) return 0; - if (strcmp(A, "a") <= 0) return 0; - if (strcmp(A, "a") == strcmp(A, "b")) return 0; + if (strcmp(A, "a") < 0) + return 0; + if (strcmp(A, "a") == 0) + return 0; + if (strcmp(A, "a") <= 0) + return 0; + if (strcmp(A, "a") == strcmp(A, "b")) + return 0; return 1; } -int wrapper(const char* a, const char* b) { +int wrapper(const char *a, const char *b) { return strcmp(a, b); } -int assignment_wrapper(const char* a, const char* b) { +int assignment_wrapper(const char *a, const char *b) { int cmp = strcmp(a, b); return cmp; } -int condexpr_wrapper(const char* a, const char* b) { +int condexpr_wrapper(const char *a, const char *b) { return (a < b) ? strcmp(a, b) : strcmp(b, a); } Index: test/clang-tidy/misc-suspicious-string-compare.cpp =================================================================== --- test/clang-tidy/misc-suspicious-string-compare.cpp +++ test/clang-tidy/misc-suspicious-string-compare.cpp @@ -7,7 +7,7 @@ typedef __SIZE_TYPE__ size; struct locale_t { - void* dummy; + void *dummy; } locale; static const char A[] = "abc"; @@ -30,7 +30,7 @@ int stricmp(const char *, const char *); int strcmpi(const char *, const char *); int strnicmp(const char *, const char *, size); -int _stricmp(const char *, const char * ); +int _stricmp(const char *, const char *); int _strnicmp(const char *, const char *, size); int _stricmp_l(const char *, const char *, locale_t); int _strnicmp_l(const char *, const char *, size, locale_t); @@ -300,23 +300,20 @@ return 1; } -int strcmp_wrapper1(const char* a, const char* b) { +int strcmp_wrapper1(const char *a, const char *b) { return strcmp(a, b); } -int strcmp_wrapper2(const char* a, const char* b) { +int strcmp_wrapper2(const char *a, const char *b) { return (a && b) ? strcmp(a, b) : 0; } -#define macro_strncmp(s1, s2, n) \ - (__extension__ (__builtin_constant_p (n) \ - && ((__builtin_constant_p (s1) \ - && strlen (s1) < ((size) (n))) \ - || (__builtin_constant_p (s2) \ - && strlen (s2) < ((size) (n)))) \ - ? strcmp (s1, s2) : strncmp (s1, s2, n))) +#define macro_strncmp(s1, s2, n) \ + (__extension__(__builtin_constant_p(n) && ((__builtin_constant_p(s1) && strlen(s1) < ((size)(n))) || (__builtin_constant_p(s2) && strlen(s2) < ((size)(n)))) \ + ? strcmp(s1, s2) \ + : strncmp(s1, s2, n))) -int strncmp_macro(const char* a, const char* b) { +int strncmp_macro(const char *a, const char *b) { if (macro_strncmp(a, b, 4)) return 0; // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strcmp' is called without explicitly comparing result Index: test/clang-tidy/misc-swapped-arguments.cpp =================================================================== --- test/clang-tidy/misc-swapped-arguments.cpp +++ test/clang-tidy/misc-swapped-arguments.cpp @@ -8,8 +8,8 @@ void G(T a, U b) { F(a, b); // no-warning F(2.0, 4); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: argument with implicit conversion from 'int' to 'double' followed by argument converted from 'double' to 'int', potentially swapped arguments. -// CHECK-FIXES: F(4, 2.0) + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: argument with implicit conversion from 'int' to 'double' followed by argument converted from 'double' to 'int', potentially swapped arguments. + // CHECK-FIXES: F(4, 2.0) } void foo() { @@ -27,9 +27,9 @@ #define N F(b, SomeFunction()) N; -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: argument with implicit conversion from 'int' to 'double' followed by argument converted from 'double' to 'int', potentially swapped arguments. -// In macro, don't emit fixits. -// CHECK-FIXES: #define N F(b, SomeFunction()) + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: argument with implicit conversion from 'int' to 'double' followed by argument converted from 'double' to 'int', potentially swapped arguments. + // In macro, don't emit fixits. + // CHECK-FIXES: #define N F(b, SomeFunction()) G(b, 3); G(3, 1.0); @@ -48,6 +48,6 @@ #define PARAMS 1.0, 3 #define CALL(P) F(P) CALL(PARAMS); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: argument with implicit conversion from 'int' to 'double' followed by argument converted from 'double' to 'int', potentially swapped arguments. -// In macro, don't emit fixits. + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: argument with implicit conversion from 'int' to 'double' followed by argument converted from 'double' to 'int', potentially swapped arguments. + // In macro, don't emit fixits. } Index: test/clang-tidy/misc-throw-by-value-catch-by-reference.cpp =================================================================== --- test/clang-tidy/misc-throw-by-value-catch-by-reference.cpp +++ test/clang-tidy/misc-throw-by-value-catch-by-reference.cpp @@ -1,6 +1,5 @@ // RUN: %check_clang_tidy %s misc-throw-by-value-catch-by-reference %t -- -- -std=c++11 -fcxx-exceptions - class logic_error { public: logic_error(const char *message) {} @@ -11,11 +10,15 @@ int lastException; -template struct remove_reference { typedef T type; }; -template struct remove_reference { typedef T type; }; -template struct remove_reference { typedef T type; }; +template +struct remove_reference { typedef T type; }; +template +struct remove_reference { typedef T type; }; +template +struct remove_reference { typedef T type; }; -template typename remove_reference::type &&move(T &&arg) { +template +typename remove_reference::type &&move(T &&arg) { return static_cast::type &&>(arg); } Index: test/clang-tidy/misc-unconventional-assign-operator.cpp =================================================================== --- test/clang-tidy/misc-unconventional-assign-operator.cpp +++ test/clang-tidy/misc-unconventional-assign-operator.cpp @@ -11,52 +11,51 @@ typename remove_reference::type &&move(T &&t); } - struct Good { - Good& operator=(const Good&); - Good& operator=(Good&&); + Good &operator=(const Good &); + Good &operator=(Good &&); // Assign from other types is fine too. - Good& operator=(int); + Good &operator=(int); }; struct AlsoGood { // By value is also fine. - AlsoGood& operator=(AlsoGood); + AlsoGood &operator=(AlsoGood); }; struct BadReturnType { - void operator=(const BadReturnType&); + void operator=(const BadReturnType &); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should return 'BadReturnType&' [misc-unconventional-assign-operator] - const BadReturnType& operator=(BadReturnType&&); + const BadReturnType &operator=(BadReturnType &&); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should return 'Bad void operator=(int); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should return 'Bad }; struct BadReturnType2 { - BadReturnType2&& operator=(const BadReturnType2&); + BadReturnType2 &&operator=(const BadReturnType2 &); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should return 'Bad - int operator=(BadReturnType2&&); + int operator=(BadReturnType2 &&); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should return 'Bad }; struct BadArgument { - BadArgument& operator=(BadArgument&); + BadArgument &operator=(BadArgument &); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should take 'BadArgument const&', 'BadArgument&&' or 'BadArgument' - BadArgument& operator=(const BadArgument&&); + BadArgument &operator=(const BadArgument &&); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should take 'BadAr }; struct BadModifier { - BadModifier& operator=(const BadModifier&) const; + BadModifier &operator=(const BadModifier &) const; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should not be marked 'const' }; struct Deleted { // We don't check the return value of deleted operators. - void operator=(const Deleted&) = delete; - void operator=(Deleted&&) = delete; + void operator=(const Deleted &) = delete; + void operator=(Deleted &&) = delete; }; class Private { @@ -66,7 +65,7 @@ }; struct Virtual { - virtual Virtual& operator=(const Virtual &); + virtual Virtual &operator=(const Virtual &); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should not be marked 'virtual' }; @@ -74,15 +73,15 @@ int n; public: - BadReturnStatement& operator=(BadReturnStatement&& rhs) { + BadReturnStatement &operator=(BadReturnStatement &&rhs) { n = std::move(rhs.n); return rhs; -// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: operator=() should always return '*this' + // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: operator=() should always return '*this' } // Do not check if return type is different from '&BadReturnStatement' int operator=(int i) { - // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should return 'Bad + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: operator=() should return 'Bad n = i; return n; } Index: test/clang-tidy/misc-undelegated-constructor.cpp =================================================================== --- test/clang-tidy/misc-undelegated-constructor.cpp +++ test/clang-tidy/misc-undelegated-constructor.cpp @@ -9,18 +9,18 @@ Ctor(int, int); Ctor(Ctor *i) { Ctor(); -// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? A temporary object is created here instead [misc-undelegated-constructor] + // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? A temporary object is created here instead [misc-undelegated-constructor] Ctor(0); -// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? + // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? Ctor(1, 2); -// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? + // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? foo(); } }; Ctor::Ctor() { Ctor(1); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: did you intend to call a delegated constructor? + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: did you intend to call a delegated constructor? } Ctor::Ctor(int i) : Ctor(i, 1) {} // properly delegated. @@ -31,11 +31,11 @@ Dtor(int, int); Dtor(Ctor *i) { Dtor(); -// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? + // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? Dtor(0); -// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? + // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? Dtor(1, 2); -// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? + // CHECK-MESSAGES: :[[@LINE-1]]:5: warning: did you intend to call a delegated constructor? } ~Dtor(); }; @@ -43,7 +43,7 @@ struct Base {}; struct Derived : public Base { Derived() { Base(); } -// CHECK-MESSAGES: :[[@LINE-1]]:15: warning: did you intend to call a delegated constructor? + // CHECK-MESSAGES: :[[@LINE-1]]:15: warning: did you intend to call a delegated constructor? }; template Index: test/clang-tidy/misc-unused-parameters.c =================================================================== --- test/clang-tidy/misc-unused-parameters.c +++ test/clang-tidy/misc-unused-parameters.c @@ -13,5 +13,6 @@ // Unchanged cases // =============== -void h(i, c, d) int i; char *c, *d; {} // Don't mess with K&R style - +void h(i, c, d) int i; +char *c, *d; +{} // Don't mess with K&R style Index: test/clang-tidy/misc-unused-parameters.cpp =================================================================== --- test/clang-tidy/misc-unused-parameters.cpp +++ test/clang-tidy/misc-unused-parameters.cpp @@ -26,7 +26,7 @@ void h(int i) { (void)i; } // Don't remove used parameters bool useLambda(int (*fn)(int)); -static bool static_var = useLambda([] (int a) { return a; }); +static bool static_var = useLambda([](int a) { return a; }); // Remove parameters of local functions // ==================================== @@ -44,7 +44,10 @@ // CHECK-MESSAGES: :[[@LINE-1]]:33: warning // CHECK-FIXES: {{^}}static void staticFunctionC(int j) -static void staticFunctionD(int i, int j, int k) { (void)i; (void)k; } +static void staticFunctionD(int i, int j, int k) { + (void)i; + (void)k; +} // CHECK-MESSAGES: :[[@LINE-1]]:40: warning // CHECK-FIXES: {{^}}static void staticFunctionD(int i, int k) @@ -52,16 +55,15 @@ // CHECK-MESSAGES: :[[@LINE-1]]:33: warning // CHECK-FIXES: {{^}}static void staticFunctionE() - static void someCallSites() { staticFunctionA(1); -// CHECK-FIXES: staticFunctionA(); + // CHECK-FIXES: staticFunctionA(); staticFunctionB(1, 2); -// CHECK-FIXES: staticFunctionB(1); + // CHECK-FIXES: staticFunctionB(1); staticFunctionC(1, 2); -// CHECK-FIXES: staticFunctionC(2); + // CHECK-FIXES: staticFunctionC(2); staticFunctionD(1, 2, 3); -// CHECK-FIXES: staticFunctionD(1, 3); + // CHECK-FIXES: staticFunctionD(1, 3); staticFunctionE(); } @@ -74,40 +76,40 @@ // Regression test for long variable names and expressions // ======================================================= static int variableWithLongName1(int LongName1, int LongName2) { -// CHECK-MESSAGES: :[[@LINE-1]]:53: warning: parameter 'LongName2' is unused -// CHECK-FIXES: {{^}}static int variableWithLongName1(int LongName1) { + // CHECK-MESSAGES: :[[@LINE-1]]:53: warning: parameter 'LongName2' is unused + // CHECK-FIXES: {{^}}static int variableWithLongName1(int LongName1) { return LongName1; } static int variableWithLongName2(int LongName1, int LongName2) { -// CHECK-MESSAGES: :[[@LINE-1]]:38: warning: parameter 'LongName1' is unused -// CHECK-FIXES: {{^}}static int variableWithLongName2(int LongName2) { + // CHECK-MESSAGES: :[[@LINE-1]]:38: warning: parameter 'LongName1' is unused + // CHECK-FIXES: {{^}}static int variableWithLongName2(int LongName2) { return LongName2; } static void someLongNameCallSites() { int LongName1 = 7, LongName2 = 17; variableWithLongName1(LongName1, LongName2); -// CHECK-FIXES: variableWithLongName1(LongName1); + // CHECK-FIXES: variableWithLongName1(LongName1); variableWithLongName2(LongName1, LongName2); -// CHECK-FIXES: variableWithLongName2(LongName2); + // CHECK-FIXES: variableWithLongName2(LongName2); } class SomeClass { static void f(int i) {} -// CHECK-MESSAGES: :[[@LINE-1]]:21: warning -// CHECK-FIXES: static void f(int /*i*/) {} + // CHECK-MESSAGES: :[[@LINE-1]]:21: warning + // CHECK-FIXES: static void f(int /*i*/) {} }; namespace { class C { public: void f(int i); -// CHECK-FIXES: void f(); + // CHECK-FIXES: void f(); void g(int i) {} -// CHECK-MESSAGES: :[[@LINE-1]]:14: warning -// CHECK-FIXES: void g() {} + // CHECK-MESSAGES: :[[@LINE-1]]:14: warning + // CHECK-FIXES: void g() {} void h(int i) {} -// CHECK-MESSAGES: :[[@LINE-1]]:14: warning -// CHECK-FIXES: void h(int /*i*/) {} + // CHECK-MESSAGES: :[[@LINE-1]]:14: warning + // CHECK-FIXES: void h(int /*i*/) {} }; void C::f(int i) {} @@ -120,9 +122,9 @@ void someMoreCallSites() { C c; c.f(1); -// CHECK-FIXES: c.f(); + // CHECK-FIXES: c.f(); c.g(1); -// CHECK-FIXES: c.g(); + // CHECK-FIXES: c.g(); useFunction(&C::h); } @@ -133,26 +135,33 @@ class Derived : public Base { void f(int i) override {} -// CHECK-MESSAGES: :[[@LINE-1]]:14: warning -// CHECK-FIXES: void f(int /*i*/) override {} + // CHECK-MESSAGES: :[[@LINE-1]]:14: warning + // CHECK-FIXES: void f(int /*i*/) override {} }; } // end namespace -template void someFunctionTemplate(T b, T e) { (void)b; (void)e; } +template +void someFunctionTemplate(T b, T e) { + (void)b; + (void)e; +} -template void someFunctionTemplateOneUnusedParam(T b, T e) { (void)e; } +template +void someFunctionTemplateOneUnusedParam(T b, T e) { (void)e; } // CHECK-MESSAGES: :[[@LINE-1]]:65: warning // CHECK-FIXES: {{^}}template void someFunctionTemplateOneUnusedParam(T /*b*/, T e) { (void)e; } -template void someFunctionTemplateAllUnusedParams(T b, T e) {} +template +void someFunctionTemplateAllUnusedParams(T b, T e) {} // CHECK-MESSAGES: :[[@LINE-1]]:66: warning // CHECK-MESSAGES: :[[@LINE-2]]:71: warning // CHECK-FIXES: {{^}}template void someFunctionTemplateAllUnusedParams(T /*b*/, T /*e*/) {} static void dontGetConfusedByParametersInFunctionTypes() { void (*F)(int i); } -template class Function {}; +template +class Function {}; static Function dontGetConfusedByFunctionReturnTypes() { return Function(); } Index: test/clang-tidy/misc-unused-raii.cpp =================================================================== --- test/clang-tidy/misc-unused-raii.cpp +++ test/clang-tidy/misc-unused-raii.cpp @@ -38,21 +38,21 @@ void test() { Foo(42); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? -// CHECK-FIXES: Foo give_me_a_name(42); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? + // CHECK-FIXES: Foo give_me_a_name(42); Foo(23, 42); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? -// CHECK-FIXES: Foo give_me_a_name(23, 42); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? + // CHECK-FIXES: Foo give_me_a_name(23, 42); Foo(); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? -// CHECK-FIXES: Foo give_me_a_name; + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? + // CHECK-FIXES: Foo give_me_a_name; TFoo(23); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? -// CHECK-FIXES: TFoo give_me_a_name(23); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? + // CHECK-FIXES: TFoo give_me_a_name(23); FooBar(); -// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? -// CHECK-FIXES: FooBar give_me_a_name; + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object? + // CHECK-FIXES: FooBar give_me_a_name; Bar(); f(); Index: test/clang-tidy/misc-unused-using-decls.cpp =================================================================== --- test/clang-tidy/misc-unused-using-decls.cpp +++ test/clang-tidy/misc-unused-using-decls.cpp @@ -1,38 +1,53 @@ // RUN: %check_clang_tidy %s misc-unused-using-decls %t -- -- -fno-delayed-template-parsing -isystem %S/Inputs/ - // ----- Definitions ----- -template class vector {}; +template +class vector {}; namespace n { class A; class B; class C; class D; -class D { public: static int i; }; -template class E {}; -template class F {}; -class G { public: static void func() {} }; -class H { public: static int i; }; +class D { +public: + static int i; +}; +template +class E {}; +template +class F {}; +class G { +public: + static void func() {} +}; +class H { +public: + static int i; +}; class I { - public: +public: static int ii; }; -template class J {}; +template +class J {}; class G; class H; -template class K {}; +template +class K {}; template