Hi klimek,

Based on a discussion on cfe-dev, simplify (and make more explicit, in places) 
the ownership semantics of FrontendActions and FrontendActionFactories using 
value semantics and std::unique_ptr in places.

http://reviews.llvm.org/D4313

Files:
  include/clang/Tooling/Refactoring.h
  include/clang/Tooling/Tooling.h
  lib/Tooling/Refactoring.cpp
  lib/Tooling/Tooling.cpp
  tools/clang-check/ClangCheck.cpp
  unittests/AST/ASTContextParentMapTest.cpp
  unittests/AST/DeclPrinterTest.cpp
  unittests/AST/DeclTest.cpp
  unittests/AST/EvaluateAsRValueTest.cpp
  unittests/AST/MatchVerifier.h
  unittests/AST/NamedDeclPrinterTest.cpp
  unittests/AST/StmtPrinterTest.cpp
  unittests/ASTMatchers/ASTMatchersTest.cpp
  unittests/ASTMatchers/ASTMatchersTest.h
  unittests/Sema/ExternalSemaSourceTest.cpp
  unittests/Tooling/CommentHandlerTest.cpp
  unittests/Tooling/RefactoringCallbacksTest.cpp
  unittests/Tooling/RefactoringTest.cpp
  unittests/Tooling/TestVisitor.h
  unittests/Tooling/ToolingTest.cpp
Index: include/clang/Tooling/Refactoring.h
===================================================================
--- include/clang/Tooling/Refactoring.h
+++ include/clang/Tooling/Refactoring.h
@@ -212,7 +212,7 @@
   /// the results to disk.
   ///
   /// \returns 0 upon success. Non-zero upon failure.
-  int runAndSave(FrontendActionFactory *ActionFactory);
+  int runAndSave(const FrontendActionFactory &ActionFactory);
 
   /// \brief Apply all stored replacements to the given Rewriter.
   ///
Index: include/clang/Tooling/Tooling.h
===================================================================
--- include/clang/Tooling/Tooling.h
+++ include/clang/Tooling/Tooling.h
@@ -39,6 +39,7 @@
 #include "clang/Tooling/CompilationDatabase.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/Twine.h"
+#include "llvm/ADT/STLExtras.h"
 #include <memory>
 #include <string>
 #include <vector>
@@ -66,7 +67,7 @@
   /// \brief Perform an action for an invocation.
   virtual bool runInvocation(clang::CompilerInvocation *Invocation,
                              FileManager *Files,
-                             DiagnosticConsumer *DiagConsumer) = 0;
+                             DiagnosticConsumer *DiagConsumer) const = 0;
 };
 
 /// \brief Interface to generate clang::FrontendActions.
@@ -81,27 +82,16 @@
 
   /// \brief Invokes the compiler with a FrontendAction created by create().
   bool runInvocation(clang::CompilerInvocation *Invocation, FileManager *Files,
-                     DiagnosticConsumer *DiagConsumer) override;
+                     DiagnosticConsumer *DiagConsumer) const override;
 
   /// \brief Returns a new clang::FrontendAction.
   ///
   /// The caller takes ownership of the returned action.
-  virtual clang::FrontendAction *create() = 0;
+  virtual std::unique_ptr<clang::FrontendAction> create() const = 0;
 };
 
-/// \brief Returns a new FrontendActionFactory for a given type.
-///
-/// T must derive from clang::FrontendAction.
-///
-/// Example:
-/// FrontendActionFactory *Factory =
-///   newFrontendActionFactory<clang::SyntaxOnlyAction>();
-template <typename T>
-std::unique_ptr<FrontendActionFactory> newFrontendActionFactory();
-
 /// \brief Callbacks called before and after each source file processed by a
-/// FrontendAction created by the FrontedActionFactory returned by \c
-/// newFrontendActionFactory.
+/// FrontendAction created by the FrontedActionFactoryAdapter.
 class SourceFileCallbacks {
 public:
   virtual ~SourceFileCallbacks() {}
@@ -117,30 +107,15 @@
   virtual void handleEndSource() {}
 };
 
-/// \brief Returns a new FrontendActionFactory for any type that provides an
-/// implementation of newASTConsumer().
-///
-/// FactoryT must implement: ASTConsumer *newASTConsumer().
-///
-/// Example:
-/// struct ProvidesASTConsumers {
-///   clang::ASTConsumer *newASTConsumer();
-/// } Factory;
-/// std::unique_ptr<FrontendActionFactory> FactoryAdapter(
-///   newFrontendActionFactory(&Factory));
-template <typename FactoryT>
-inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(
-    FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks = nullptr);
-
 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag.
 ///
 /// \param ToolAction The action to run over the code.
 /// \param Code C++ code.
 /// \param FileName The file name which 'Code' will be mapped as.
 ///
 /// \return - True if 'ToolAction' was successfully executed.
-bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
-                   const Twine &FileName = "input.cc");
+bool runToolOnCode(std::unique_ptr<clang::FrontendAction> ToolAction,
+                   const Twine &Code, const Twine &FileName = "input.cc");
 
 /// \brief Runs (and deletes) the tool on 'Code' with the -fsyntax-only flag and
 ///        with additional other flags.
@@ -151,7 +126,8 @@
 /// \param FileName The file name which 'Code' will be mapped as.
 ///
 /// \return - True if 'ToolAction' was successfully executed.
-bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
+bool runToolOnCodeWithArgs(std::unique_ptr<clang::FrontendAction> ToolAction,
+                           const Twine &Code,
                            const std::vector<std::string> &Args,
                            const Twine &FileName = "input.cc");
 
@@ -188,16 +164,16 @@
   /// \param FAction The action to be executed. Class takes ownership.
   /// \param Files The FileManager used for the execution. Class does not take
   /// ownership.
-  ToolInvocation(std::vector<std::string> CommandLine, FrontendAction *FAction,
-                 FileManager *Files);
+   ToolInvocation(std::vector<std::string> CommandLine,
+                  std::unique_ptr<FrontendAction> FAction, FileManager *Files);
 
   /// \brief Create a tool invocation.
   ///
   /// \param CommandLine The command line arguments to clang.
   /// \param Action The action to be executed.
   /// \param Files The FileManager used for the execution.
-  ToolInvocation(std::vector<std::string> CommandLine, ToolAction *Action,
-                 FileManager *Files);
+   ToolInvocation(std::vector<std::string> CommandLine,
+                  const ToolAction *Action, FileManager *Files);
 
   ~ToolInvocation();
 
@@ -220,10 +196,10 @@
 
   bool runInvocation(const char *BinaryName,
                      clang::driver::Compilation *Compilation,
-                     clang::CompilerInvocation *Invocation);
+                     clang::CompilerInvocation *Invocation) const;
 
   std::vector<std::string> CommandLine;
-  ToolAction *Action;
+  const ToolAction *Action;
   bool OwnsAction;
   FileManager *Files;
   // Maps <file name> -> <file content>.
@@ -280,7 +256,7 @@
   /// Runs an action over all files specified in the command line.
   ///
   /// \param Action Tool action.
-  int run(ToolAction *Action);
+  int run(const ToolAction &Action);
 
   /// \brief Create an AST for each file specified in the command line and
   /// append them to ASTs.
@@ -304,67 +280,73 @@
   DiagnosticConsumer *DiagConsumer;
 };
 
+namespace internal {
 template <typename T>
-std::unique_ptr<FrontendActionFactory> newFrontendActionFactory() {
-  class SimpleFrontendActionFactory : public FrontendActionFactory {
-  public:
-    clang::FrontendAction *create() override { return new T; }
-  };
-
-  return std::unique_ptr<FrontendActionFactory>(
-      new SimpleFrontendActionFactory);
-}
+struct SimpleFrontendActionFactory : FrontendActionFactory {
+  std::unique_ptr<clang::FrontendAction> create() const override {
+    return llvm::make_unique<T>();
+  }
+};
 
 template <typename FactoryT>
-inline std::unique_ptr<FrontendActionFactory> newFrontendActionFactory(
-    FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks) {
-  class FrontendActionFactoryAdapter : public FrontendActionFactory {
-  public:
-    explicit FrontendActionFactoryAdapter(FactoryT *ConsumerFactory,
-                                          SourceFileCallbacks *Callbacks)
+class FrontendActionFactoryAdapter : public FrontendActionFactory {
+public:
+  explicit FrontendActionFactoryAdapter(
+      FactoryT *ConsumerFactory, SourceFileCallbacks *Callbacks = nullptr)
       : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {}
 
-    clang::FrontendAction *create() override {
-      return new ConsumerFactoryAdaptor(ConsumerFactory, Callbacks);
-    }
+  std::unique_ptr<clang::FrontendAction> create() const override {
+    return llvm::make_unique<ConsumerFactoryAdaptor>(ConsumerFactory,
+                                                     Callbacks);
+  }
 
-  private:
-    class ConsumerFactoryAdaptor : public clang::ASTFrontendAction {
-    public:
-      ConsumerFactoryAdaptor(FactoryT *ConsumerFactory,
-                             SourceFileCallbacks *Callbacks)
+private:
+  class ConsumerFactoryAdaptor : public clang::ASTFrontendAction {
+  public:
+    ConsumerFactoryAdaptor(FactoryT *ConsumerFactory,
+                           SourceFileCallbacks *Callbacks)
         : ConsumerFactory(ConsumerFactory), Callbacks(Callbacks) {}
 
-      clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &,
-                                            StringRef) override {
-        return ConsumerFactory->newASTConsumer();
-      }
-
-    protected:
-      bool BeginSourceFileAction(CompilerInstance &CI,
-                                 StringRef Filename) override {
-        if (!clang::ASTFrontendAction::BeginSourceFileAction(CI, Filename))
-          return false;
-        if (Callbacks)
-          return Callbacks->handleBeginSource(CI, Filename);
-        return true;
-      }
-      void EndSourceFileAction() override {
-        if (Callbacks)
-          Callbacks->handleEndSource();
-        clang::ASTFrontendAction::EndSourceFileAction();
-      }
-
-    private:
-      FactoryT *ConsumerFactory;
-      SourceFileCallbacks *Callbacks;
-    };
+    clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &,
+                                          StringRef) override {
+      return ConsumerFactory->newASTConsumer();
+    }
+
+  protected:
+    bool BeginSourceFileAction(CompilerInstance &CI,
+                               StringRef Filename) override {
+      if (!clang::ASTFrontendAction::BeginSourceFileAction(CI, Filename))
+        return false;
+      if (Callbacks != NULL)
+        return Callbacks->handleBeginSource(CI, Filename);
+      return true;
+    }
+    void EndSourceFileAction() override {
+      if (Callbacks != NULL)
+        Callbacks->handleEndSource();
+      clang::ASTFrontendAction::EndSourceFileAction();
+    }
+
+  private:
     FactoryT *ConsumerFactory;
     SourceFileCallbacks *Callbacks;
   };
+  FactoryT *ConsumerFactory;
+  SourceFileCallbacks *Callbacks;
+};
+}
 
-  return std::unique_ptr<FrontendActionFactory>(
-      new FrontendActionFactoryAdapter(ConsumerFactory, Callbacks));
+template <typename T>
+internal::SimpleFrontendActionFactory<T> newFrontendActionFactory() {
+  return internal::SimpleFrontendActionFactory<T>();
+}
+
+template <typename FactoryT>
+internal::FrontendActionFactoryAdapter<FactoryT>
+newFrontendActionFactory(FactoryT *ConsumerFactory,
+                         SourceFileCallbacks *Callbacks = 0) {
+  return internal::FrontendActionFactoryAdapter<FactoryT>(ConsumerFactory,
+                                                          Callbacks);
 }
 
 /// \brief Returns the absolute path of \c File, by prepending it with
Index: lib/Tooling/Refactoring.cpp
===================================================================
--- lib/Tooling/Refactoring.cpp
+++ lib/Tooling/Refactoring.cpp
@@ -277,7 +277,7 @@
 
 Replacements &RefactoringTool::getReplacements() { return Replace; }
 
-int RefactoringTool::runAndSave(FrontendActionFactory *ActionFactory) {
+int RefactoringTool::runAndSave(const FrontendActionFactory &ActionFactory) {
   if (int Result = run(ActionFactory)) {
     return Result;
   }
Index: lib/Tooling/Tooling.cpp
===================================================================
--- lib/Tooling/Tooling.cpp
+++ lib/Tooling/Tooling.cpp
@@ -104,10 +104,10 @@
   return Invocation;
 }
 
-bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
-                   const Twine &FileName) {
-  return runToolOnCodeWithArgs(
-      ToolAction, Code, std::vector<std::string>(), FileName);
+bool runToolOnCode(std::unique_ptr<clang::FrontendAction> ToolAction,
+                   const Twine &Code, const Twine &FileName) {
+  return runToolOnCodeWithArgs(std::move(ToolAction), Code,
+                               std::vector<std::string>(), FileName);
 }
 
 static std::vector<std::string>
@@ -121,15 +121,16 @@
   return Args;
 }
 
-bool runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
+bool runToolOnCodeWithArgs(std::unique_ptr<clang::FrontendAction> ToolAction,
+                           const Twine &Code,
                            const std::vector<std::string> &Args,
                            const Twine &FileName) {
   SmallString<16> FileNameStorage;
   StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
   llvm::IntrusiveRefCntPtr<FileManager> Files(
       new FileManager(FileSystemOptions()));
-  ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef), ToolAction,
-                            Files.getPtr());
+  ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef),
+                            std::move(ToolAction), Files.getPtr());
 
   SmallString<1024> CodeStorage;
   Invocation.mapVirtualFile(FileNameRef,
@@ -155,28 +156,32 @@
 namespace {
 
 class SingleFrontendActionFactory : public FrontendActionFactory {
-  FrontendAction *Action;
+  mutable std::unique_ptr<FrontendAction> Action;
 
 public:
-  SingleFrontendActionFactory(FrontendAction *Action) : Action(Action) {}
+  SingleFrontendActionFactory(std::unique_ptr<FrontendAction> Action)
+      : Action(std::move(Action)) {}
 
-  FrontendAction *create() override { return Action; }
+  std::unique_ptr<FrontendAction> create() const override {
+    return std::move(Action);
+  }
 };
 
 }
 
 ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine,
-                               ToolAction *Action, FileManager *Files)
+                               const ToolAction *Action, FileManager *Files)
     : CommandLine(std::move(CommandLine)),
       Action(Action),
       OwnsAction(false),
       Files(Files),
       DiagConsumer(nullptr) {}
 
 ToolInvocation::ToolInvocation(std::vector<std::string> CommandLine,
-                               FrontendAction *FAction, FileManager *Files)
+                               std::unique_ptr<FrontendAction> FAction,
+                               FileManager *Files)
     : CommandLine(std::move(CommandLine)),
-      Action(new SingleFrontendActionFactory(FAction)),
+      Action(new SingleFrontendActionFactory(std::move(FAction))),
       OwnsAction(true),
       Files(Files),
       DiagConsumer(nullptr) {}
@@ -229,10 +234,10 @@
   return runInvocation(BinaryName, Compilation.get(), Invocation.release());
 }
 
-bool ToolInvocation::runInvocation(
-    const char *BinaryName,
-    clang::driver::Compilation *Compilation,
-    clang::CompilerInvocation *Invocation) {
+bool
+ToolInvocation::runInvocation(const char *BinaryName,
+                              clang::driver::Compilation *Compilation,
+                              clang::CompilerInvocation *Invocation) const {
   // Show the invocation, with -v.
   if (Invocation->getHeaderSearchOpts().Verbose) {
     llvm::errs() << "clang Invocation:\n";
@@ -243,9 +248,10 @@
   return Action->runInvocation(Invocation, Files, DiagConsumer);
 }
 
-bool FrontendActionFactory::runInvocation(CompilerInvocation *Invocation,
-                                          FileManager *Files,
-                                          DiagnosticConsumer *DiagConsumer) {
+bool
+FrontendActionFactory::runInvocation(CompilerInvocation *Invocation,
+                                     FileManager *Files,
+                                     DiagnosticConsumer *DiagConsumer) const {
   // Create a compiler instance to handle the actual work.
   clang::CompilerInstance Compiler;
   Compiler.setInvocation(Invocation);
@@ -318,7 +324,7 @@
   ArgsAdjusters.clear();
 }
 
-int ClangTool::run(ToolAction *Action) {
+int ClangTool::run(const ToolAction &Action) {
   // Exists solely for the purpose of lookup of the resource path.
   // This just needs to be some symbol in the binary.
   static int StaticSymbol;
@@ -352,7 +358,7 @@
     DEBUG({
       llvm::dbgs() << "Processing: " << Command.first << ".\n";
     });
-    ToolInvocation Invocation(std::move(CommandLine), Action, Files.getPtr());
+    ToolInvocation Invocation(std::move(CommandLine), &Action, Files.getPtr());
     Invocation.setDiagnosticConsumer(DiagConsumer);
     for (const auto &MappedFile : MappedFileContents) {
       Invocation.mapVirtualFile(MappedFile.first, MappedFile.second);
@@ -375,7 +381,7 @@
   ASTBuilderAction(std::vector<std::unique_ptr<ASTUnit>> &ASTs) : ASTs(ASTs) {}
 
   bool runInvocation(CompilerInvocation *Invocation, FileManager *Files,
-                     DiagnosticConsumer *DiagConsumer) override {
+                     DiagnosticConsumer *DiagConsumer) const override {
     // FIXME: This should use the provided FileManager.
     std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromCompilerInvocation(
         Invocation, CompilerInstance::createDiagnostics(
@@ -393,7 +399,7 @@
 
 int ClangTool::buildASTs(std::vector<std::unique_ptr<ASTUnit>> &ASTs) {
   ASTBuilderAction Action(ASTs);
-  return run(&Action);
+  return run(Action);
 }
 
 std::unique_ptr<ASTUnit> buildASTFromCode(const Twine &Code,
Index: tools/clang-check/ClangCheck.cpp
===================================================================
--- tools/clang-check/ClangCheck.cpp
+++ tools/clang-check/ClangCheck.cpp
@@ -215,15 +215,10 @@
         Analyze ? "--analyze" : "-fsyntax-only", InsertAdjuster::BEGIN));
 
   clang_check::ClangCheckActionFactory CheckFactory;
-  std::unique_ptr<FrontendActionFactory> FrontendFactory;
-
   // Choose the correct factory based on the selected mode.
   if (Analyze)
-    FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
-  else if (Fixit)
-    FrontendFactory = newFrontendActionFactory<FixItAction>();
-  else
-    FrontendFactory = newFrontendActionFactory(&CheckFactory);
-
-  return Tool.run(FrontendFactory.get());
+    return Tool.run(newFrontendActionFactory<clang::ento::AnalysisAction>());
+  if (Fixit)
+    return Tool.run(newFrontendActionFactory<FixItAction>());
+  return Tool.run(newFrontendActionFactory(&CheckFactory));
 }
Index: unittests/AST/ASTContextParentMapTest.cpp
===================================================================
--- unittests/AST/ASTContextParentMapTest.cpp
+++ unittests/AST/ASTContextParentMapTest.cpp
@@ -21,7 +21,6 @@
 namespace clang {
 namespace ast_matchers {
 
-using clang::tooling::newFrontendActionFactory;
 using clang::tooling::runToolOnCodeWithArgs;
 using clang::tooling::FrontendActionFactory;
 
Index: unittests/AST/DeclPrinterTest.cpp
===================================================================
--- unittests/AST/DeclPrinterTest.cpp
+++ unittests/AST/DeclPrinterTest.cpp
@@ -74,10 +74,9 @@
   PrintMatch Printer;
   MatchFinder Finder;
   Finder.addMatcher(NodeMatch, &Printer);
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Finder));
+  auto Factory = newFrontendActionFactory(&Finder);
 
-  if (!runToolOnCodeWithArgs(Factory->create(), Code, Args, FileName))
+  if (!runToolOnCodeWithArgs(Factory.create(), Code, Args, FileName))
     return testing::AssertionFailure()
       << "Parsing error in \"" << Code.str() << "\"";
 
Index: unittests/AST/DeclTest.cpp
===================================================================
--- unittests/AST/DeclTest.cpp
+++ unittests/AST/DeclTest.cpp
@@ -20,16 +20,15 @@
 
 TEST(Decl, CleansUpAPValues) {
   MatchFinder Finder;
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Finder));
+  auto Factory = newFrontendActionFactory(&Finder);
 
   // This is a regression test for a memory leak in APValues for structs that
   // allocate memory. This test only fails if run under valgrind with full leak
   // checking enabled.
   std::vector<std::string> Args(1, "-std=c++11");
   Args.push_back("-fno-ms-extensions");
   ASSERT_TRUE(runToolOnCodeWithArgs(
-      Factory->create(),
+      Factory.create(),
       "struct X { int a; }; constexpr X x = { 42 };"
       "union Y { constexpr Y(int a) : a(a) {} int a; }; constexpr Y y = { 42 };"
       "constexpr int z[2] = { 42, 43 };"
@@ -53,7 +52,6 @@
   // FIXME: Once this test starts breaking we can test APValue::needsCleanup
   // for ComplexInt.
   ASSERT_FALSE(runToolOnCodeWithArgs(
-      Factory->create(),
-      "constexpr _Complex __uint128_t c = 0xffffffffffffffff;",
-      Args));
+      Factory.create(),
+      "constexpr _Complex __uint128_t c = 0xffffffffffffffff;", Args));
 }
Index: unittests/AST/EvaluateAsRValueTest.cpp
===================================================================
--- unittests/AST/EvaluateAsRValueTest.cpp
+++ unittests/AST/EvaluateAsRValueTest.cpp
@@ -91,22 +91,22 @@
     std::vector<std::string> Args(1, Mode);
     Args.push_back("-fno-delayed-template-parsing");
     ASSERT_TRUE(runToolOnCodeWithArgs(
-      new EvaluateConstantInitializersAction(),
-      "template <typename T>"
-      "struct vector {"
-      "  explicit vector(int size);"
-      "};"
-      "template <typename R>"
-      "struct S {"
-      "  vector<R> intervals() const {"
-      "    vector<R> Dependent(2);"
-      "    return Dependent;"
-      "  }"
-      "};"
-      "void doSomething() {"
-      "  int Constant = 2 + 2;"
-      "  (void) Constant;"
-      "}",
-      Args));
+        llvm::make_unique<EvaluateConstantInitializersAction>(),
+        "template <typename T>"
+        "struct vector {"
+        "  explicit vector(int size);"
+        "};"
+        "template <typename R>"
+        "struct S {"
+        "  vector<R> intervals() const {"
+        "    vector<R> Dependent(2);"
+        "    return Dependent;"
+        "  }"
+        "};"
+        "void doSomething() {"
+        "  int Constant = 2 + 2;"
+        "  (void) Constant;"
+        "}",
+        Args));
   }
 }
Index: unittests/AST/MatchVerifier.h
===================================================================
--- unittests/AST/MatchVerifier.h
+++ unittests/AST/MatchVerifier.h
@@ -79,8 +79,7 @@
     std::vector<std::string>& Args, Language L) {
   MatchFinder Finder;
   Finder.addMatcher(AMatcher.bind(""), this);
-  std::unique_ptr<tooling::FrontendActionFactory> Factory(
-      tooling::newFrontendActionFactory(&Finder));
+  auto Factory = tooling::newFrontendActionFactory(&Finder);
 
   StringRef FileName;
   switch (L) {
@@ -106,7 +105,7 @@
 
   // Default to failure in case callback is never called
   setFailure("Could not find match");
-  if (!tooling::runToolOnCodeWithArgs(Factory->create(), Code, Args, FileName))
+  if (!tooling::runToolOnCodeWithArgs(Factory.create(), Code, Args, FileName))
     return testing::AssertionFailure() << "Parsing error";
   if (!Verified)
     return testing::AssertionFailure() << VerifyResult;
Index: unittests/AST/NamedDeclPrinterTest.cpp
===================================================================
--- unittests/AST/NamedDeclPrinterTest.cpp
+++ unittests/AST/NamedDeclPrinterTest.cpp
@@ -68,10 +68,9 @@
   PrintMatch Printer(SuppressUnwrittenScope);
   MatchFinder Finder;
   Finder.addMatcher(NodeMatch, &Printer);
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Finder));
+  auto Factory = newFrontendActionFactory(&Finder);
 
-  if (!runToolOnCodeWithArgs(Factory->create(), Code, Args, FileName))
+  if (!runToolOnCodeWithArgs(Factory.create(), Code, Args, FileName))
     return testing::AssertionFailure()
         << "Parsing error in \"" << Code.str() << "\"";
 
Index: unittests/AST/StmtPrinterTest.cpp
===================================================================
--- unittests/AST/StmtPrinterTest.cpp
+++ unittests/AST/StmtPrinterTest.cpp
@@ -73,10 +73,9 @@
   PrintMatch Printer;
   MatchFinder Finder;
   Finder.addMatcher(NodeMatch, &Printer);
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Finder));
+  auto Factory = newFrontendActionFactory(&Finder);
 
-  if (!runToolOnCodeWithArgs(Factory->create(), Code, Args))
+  if (!runToolOnCodeWithArgs(Factory.create(), Code, Args))
     return testing::AssertionFailure()
       << "Parsing error in \"" << Code.str() << "\"";
 
Index: unittests/ASTMatchers/ASTMatchersTest.cpp
===================================================================
--- unittests/ASTMatchers/ASTMatchersTest.cpp
+++ unittests/ASTMatchers/ASTMatchersTest.cpp
@@ -4237,9 +4237,8 @@
   MatchFinder Finder;
   VerifyStartOfTranslationUnit VerifyCallback;
   Finder.addMatcher(decl(), &VerifyCallback);
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Finder));
-  ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
+  auto Factory = newFrontendActionFactory(&Finder);
+  ASSERT_TRUE(tooling::runToolOnCode(Factory.create(), "int x;"));
   EXPECT_TRUE(VerifyCallback.Called);
 
   VerifyCallback.Called = false;
@@ -4265,9 +4264,8 @@
   MatchFinder Finder;
   VerifyEndOfTranslationUnit VerifyCallback;
   Finder.addMatcher(decl(), &VerifyCallback);
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Finder));
-  ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), "int x;"));
+  auto Factory = newFrontendActionFactory(&Finder);
+  ASSERT_TRUE(tooling::runToolOnCode(Factory.create(), "int x;"));
   EXPECT_TRUE(VerifyCallback.Called);
 
   VerifyCallback.Called = false;
Index: unittests/ASTMatchers/ASTMatchersTest.h
===================================================================
--- unittests/ASTMatchers/ASTMatchersTest.h
+++ unittests/ASTMatchers/ASTMatchersTest.h
@@ -69,11 +69,10 @@
   VerifyMatch VerifyDynamicFound(nullptr, &DynamicFound);
   if (!Finder.addDynamicMatcher(AMatcher, &VerifyDynamicFound))
     return testing::AssertionFailure() << "Could not add dynamic matcher";
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Finder));
+  auto Factory = newFrontendActionFactory(&Finder);
   // Some tests use typeof, which is a gnu extension.
   std::vector<std::string> Args(1, CompileArg);
-  if (!runToolOnCodeWithArgs(Factory->create(), Code, Args)) {
+  if (!runToolOnCodeWithArgs(Factory.create(), Code, Args)) {
     return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
   }
   if (Found != DynamicFound) {
@@ -113,11 +112,10 @@
   MatchFinder Finder;
   VerifyMatch VerifyVerifiedResult(FindResultVerifier, &VerifiedResult);
   Finder.addMatcher(AMatcher, &VerifyVerifiedResult);
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Finder));
+  auto Factory = newFrontendActionFactory(&Finder);
   // Some tests use typeof, which is a gnu extension.
   std::vector<std::string> Args(1, "-std=gnu++98");
-  if (!runToolOnCodeWithArgs(Factory->create(), Code, Args)) {
+  if (!runToolOnCodeWithArgs(Factory.create(), Code, Args)) {
     return testing::AssertionFailure() << "Parsing error in \"" << Code << "\"";
   }
   if (!VerifiedResult && ExpectResult) {
Index: unittests/Sema/ExternalSemaSourceTest.cpp
===================================================================
--- unittests/Sema/ExternalSemaSourceTest.cpp
+++ unittests/Sema/ExternalSemaSourceTest.cpp
@@ -178,37 +178,34 @@
 
 // Make sure that the NamespaceDiagnosticWatcher is not miscounting.
 TEST(ExternalSemaSource, SanityCheck) {
-  std::unique_ptr<ExternalSemaSourceInstaller> Installer(
-      new ExternalSemaSourceInstaller);
+  auto Installer = llvm::make_unique<ExternalSemaSourceInstaller>();
   NamespaceDiagnosticWatcher Watcher("AAB", "BBB");
   Installer->PushWatcher(&Watcher);
   std::vector<std::string> Args(1, "-std=c++11");
   ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
-      Installer.release(), "namespace AAA { } using namespace AAB;", Args));
+      std::move(Installer), "namespace AAA { } using namespace AAB;", Args));
   ASSERT_EQ(0, Watcher.SeenCount);
 }
 
 // Check that when we add a NamespaceTypeProvider, we use that suggestion
 // instead of the usual suggestion we would use above.
 TEST(ExternalSemaSource, ExternalTypoCorrectionPrioritized) {
-  std::unique_ptr<ExternalSemaSourceInstaller> Installer(
-      new ExternalSemaSourceInstaller);
+  auto Installer = llvm::make_unique<ExternalSemaSourceInstaller>();
   NamespaceTypoProvider Provider("AAB", "BBB");
   NamespaceDiagnosticWatcher Watcher("AAB", "BBB");
   Installer->PushSource(&Provider);
   Installer->PushWatcher(&Watcher);
   std::vector<std::string> Args(1, "-std=c++11");
   ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
-      Installer.release(), "namespace AAA { } using namespace AAB;", Args));
+      std::move(Installer), "namespace AAA { } using namespace AAB;", Args));
   ASSERT_LE(0, Provider.CallCount);
   ASSERT_EQ(1, Watcher.SeenCount);
 }
 
 // Check that we use the first successful TypoCorrection returned from an
 // ExternalSemaSource.
 TEST(ExternalSemaSource, ExternalTypoCorrectionOrdering) {
-  std::unique_ptr<ExternalSemaSourceInstaller> Installer(
-      new ExternalSemaSourceInstaller);
+  auto Installer = llvm::make_unique<ExternalSemaSourceInstaller>();
   NamespaceTypoProvider First("XXX", "BBB");
   NamespaceTypoProvider Second("AAB", "CCC");
   NamespaceTypoProvider Third("AAB", "DDD");
@@ -219,7 +216,7 @@
   Installer->PushWatcher(&Watcher);
   std::vector<std::string> Args(1, "-std=c++11");
   ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
-      Installer.release(), "namespace AAA { } using namespace AAB;", Args));
+      std::move(Installer), "namespace AAA { } using namespace AAB;", Args));
   ASSERT_LE(1, First.CallCount);
   ASSERT_LE(1, Second.CallCount);
   ASSERT_EQ(0, Third.CallCount);
@@ -229,34 +226,32 @@
 // We should only try MaybeDiagnoseMissingCompleteType if we can't otherwise
 // solve the problem.
 TEST(ExternalSemaSource, TryOtherTacticsBeforeDiagnosing) {
-  std::unique_ptr<ExternalSemaSourceInstaller> Installer(
-      new ExternalSemaSourceInstaller);
+  auto Installer = llvm::make_unique<ExternalSemaSourceInstaller>();
   CompleteTypeDiagnoser Diagnoser(false);
   Installer->PushSource(&Diagnoser);
   std::vector<std::string> Args(1, "-std=c++11");
   // This code hits the class template specialization/class member of a class
   // template specialization checks in Sema::RequireCompleteTypeImpl.
   ASSERT_TRUE(clang::tooling::runToolOnCodeWithArgs(
-      Installer.release(),
+      std::move(Installer),
       "template <typename T> struct S { class C { }; }; S<char>::C SCInst;",
       Args));
   ASSERT_EQ(0, Diagnoser.CallCount);
 }
 
 // The first ExternalSemaSource where MaybeDiagnoseMissingCompleteType returns
 // true should be the last one called.
 TEST(ExternalSemaSource, FirstDiagnoserTaken) {
-  std::unique_ptr<ExternalSemaSourceInstaller> Installer(
-      new ExternalSemaSourceInstaller);
+  auto Installer = llvm::make_unique<ExternalSemaSourceInstaller>();
   CompleteTypeDiagnoser First(false);
   CompleteTypeDiagnoser Second(true);
   CompleteTypeDiagnoser Third(true);
   Installer->PushSource(&First);
   Installer->PushSource(&Second);
   Installer->PushSource(&Third);
   std::vector<std::string> Args(1, "-std=c++11");
   ASSERT_FALSE(clang::tooling::runToolOnCodeWithArgs(
-      Installer.release(), "class Incomplete; Incomplete IncompleteInstance;",
+      std::move(Installer), "class Incomplete; Incomplete IncompleteInstance;",
       Args));
   ASSERT_EQ(1, First.CallCount);
   ASSERT_EQ(1, Second.CallCount);
Index: unittests/Tooling/CommentHandlerTest.cpp
===================================================================
--- unittests/Tooling/CommentHandlerTest.cpp
+++ unittests/Tooling/CommentHandlerTest.cpp
@@ -56,8 +56,8 @@
   CommentVerifier GetVerifier();
 
 protected:
-  virtual ASTFrontendAction* CreateTestAction() {
-    return new CommentHandlerAction(this);
+  virtual std::unique_ptr<ASTFrontendAction> CreateTestAction() {
+    return llvm::make_unique<CommentHandlerAction>(this);
   }
 
 private:
Index: unittests/Tooling/RefactoringCallbacksTest.cpp
===================================================================
--- unittests/Tooling/RefactoringCallbacksTest.cpp
+++ unittests/Tooling/RefactoringCallbacksTest.cpp
@@ -25,9 +25,8 @@
                      RefactoringCallback &Callback) {
   MatchFinder Finder;
   Finder.addMatcher(AMatcher, &Callback);
-  std::unique_ptr<tooling::FrontendActionFactory> Factory(
-      tooling::newFrontendActionFactory(&Finder));
-  ASSERT_TRUE(tooling::runToolOnCode(Factory->create(), Code))
+  auto Factory = tooling::newFrontendActionFactory(&Finder);
+  ASSERT_TRUE(tooling::runToolOnCode(Factory.create(), Code))
       << "Parsing error in \"" << Code << "\"";
   RewriterTestContext Context;
   FileID ID = Context.createInMemoryFile("input.cc", Code);
Index: unittests/Tooling/RefactoringTest.cpp
===================================================================
--- unittests/Tooling/RefactoringTest.cpp
+++ unittests/Tooling/RefactoringTest.cpp
@@ -276,7 +276,7 @@
 class TestVisitor : public clang::RecursiveASTVisitor<T> {
 public:
   bool runOver(StringRef Code) {
-    return runToolOnCode(new TestAction(this), Code);
+    return runToolOnCode(llvm::make_unique<TestAction>(this), Code);
   }
 
 protected:
Index: unittests/Tooling/TestVisitor.h
===================================================================
--- unittests/Tooling/TestVisitor.h
+++ unittests/Tooling/TestVisitor.h
@@ -74,8 +74,8 @@
   }
 
 protected:
-  virtual ASTFrontendAction* CreateTestAction() {
-    return new TestAction(this);
+  virtual std::unique_ptr<ASTFrontendAction> CreateTestAction() {
+    return llvm::make_unique<TestAction>(this);
   }
 
   class FindConsumer : public ASTConsumer {
Index: unittests/Tooling/ToolingTest.cpp
===================================================================
--- unittests/Tooling/ToolingTest.cpp
+++ unittests/Tooling/ToolingTest.cpp
@@ -59,8 +59,10 @@
 
 TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) {
   bool FoundTopLevelDecl = false;
-  EXPECT_TRUE(runToolOnCode(
-      new TestAction(new FindTopLevelDeclConsumer(&FoundTopLevelDecl)), ""));
+  EXPECT_TRUE(
+      runToolOnCode(llvm::make_unique<TestAction>(
+                        new FindTopLevelDeclConsumer(&FoundTopLevelDecl)),
+                    ""));
   EXPECT_FALSE(FoundTopLevelDecl);
 }
 
@@ -97,13 +99,15 @@
 
 TEST(runToolOnCode, FindsClassDecl) {
   bool FoundClassDeclX = false;
-  EXPECT_TRUE(runToolOnCode(new TestAction(
-      new FindClassDeclXConsumer(&FoundClassDeclX)), "class X;"));
+  EXPECT_TRUE(runToolOnCode(llvm::make_unique<TestAction>(
+                                new FindClassDeclXConsumer(&FoundClassDeclX)),
+                            "class X;"));
   EXPECT_TRUE(FoundClassDeclX);
 
   FoundClassDeclX = false;
-  EXPECT_TRUE(runToolOnCode(new TestAction(
-      new FindClassDeclXConsumer(&FoundClassDeclX)), "class Y;"));
+  EXPECT_TRUE(runToolOnCode(llvm::make_unique<TestAction>(
+                                new FindClassDeclXConsumer(&FoundClassDeclX)),
+                            "class Y;"));
   EXPECT_FALSE(FoundClassDeclX);
 }
 
@@ -118,9 +122,8 @@
 }
 
 TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory<SyntaxOnlyAction>());
-  std::unique_ptr<FrontendAction> Action(Factory->create());
+  auto Factory = newFrontendActionFactory<SyntaxOnlyAction>();
+  std::unique_ptr<FrontendAction> Action = Factory.create();
   EXPECT_TRUE(Action.get() != nullptr);
 }
 
@@ -132,9 +135,8 @@
 
 TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
   IndependentFrontendActionCreator Creator;
-  std::unique_ptr<FrontendActionFactory> Factory(
-      newFrontendActionFactory(&Creator));
-  std::unique_ptr<FrontendAction> Action(Factory->create());
+  auto Factory = newFrontendActionFactory(&Creator);
+  std::unique_ptr<FrontendAction> Action = Factory.create();
   EXPECT_TRUE(Action.get() != nullptr);
 }
 
@@ -146,8 +148,8 @@
   Args.push_back("-Idef");
   Args.push_back("-fsyntax-only");
   Args.push_back("test.cpp");
-  clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
-                                            Files.getPtr());
+  clang::tooling::ToolInvocation Invocation(
+      Args, llvm::make_unique<SyntaxOnlyAction>(), Files.getPtr());
   Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
   Invocation.mapVirtualFile("def/abc", "\n");
   EXPECT_TRUE(Invocation.run());
@@ -165,8 +167,8 @@
   Args.push_back("-Idef");
   Args.push_back("-fsyntax-only");
   Args.push_back("test.cpp");
-  clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
-                                            Files.getPtr());
+  clang::tooling::ToolInvocation Invocation(
+      Args, llvm::make_unique<SyntaxOnlyAction>(), Files.getPtr());
   Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
   Invocation.mapVirtualFile("def/abc", "\n");
   // Add a module.map file in the include directory of our header, so we trigger
@@ -206,9 +208,8 @@
   Tool.mapVirtualFile("/a.cc", "void a() {}");
   Tool.mapVirtualFile("/b.cc", "void b() {}");
 
-  std::unique_ptr<FrontendActionFactory> Action(
-      newFrontendActionFactory(&EndCallback, &EndCallback));
-  Tool.run(Action.get());
+  auto Action = newFrontendActionFactory(&EndCallback, &EndCallback);
+  Tool.run(Action);
 
   EXPECT_TRUE(EndCallback.Matched);
   EXPECT_EQ(2u, EndCallback.BeginCalled);
@@ -233,9 +234,9 @@
 };
 
 TEST(runToolOnCode, TestSkipFunctionBody) {
-  EXPECT_TRUE(runToolOnCode(new SkipBodyAction,
+  EXPECT_TRUE(runToolOnCode(llvm::make_unique<SkipBodyAction>(),
                             "int skipMe() { an_error_here }"));
-  EXPECT_FALSE(runToolOnCode(new SkipBodyAction,
+  EXPECT_FALSE(runToolOnCode(llvm::make_unique<SkipBodyAction>(),
                              "int skipMeNot() { an_error_here }"));
 }
 
@@ -249,7 +250,8 @@
   Args.push_back(DepFilePath.str());
   Args.push_back("-MF");
   Args.push_back(DepFilePath.str());
-  EXPECT_TRUE(runToolOnCodeWithArgs(new SkipBodyAction, "", Args));
+  EXPECT_TRUE(
+      runToolOnCodeWithArgs(llvm::make_unique<SkipBodyAction>(), "", Args));
   EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str()));
   EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
 }
@@ -279,21 +281,20 @@
   ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
   Tool.mapVirtualFile("/a.cc", "void a() {}");
 
-  std::unique_ptr<FrontendActionFactory> Action(
-      newFrontendActionFactory<SyntaxOnlyAction>());
+  auto Action = newFrontendActionFactory<SyntaxOnlyAction>();
 
   bool Found = false;
   bool Ran = false;
   Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran));
-  Tool.run(Action.get());
+  Tool.run(Action);
   EXPECT_TRUE(Ran);
   EXPECT_TRUE(Found);
 
   Ran = Found = false;
   Tool.clearArgumentsAdjusters();
   Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran));
   Tool.appendArgumentsAdjuster(new ClangSyntaxOnlyAdjuster());
-  Tool.run(Action.get());
+  Tool.run(Action);
   EXPECT_TRUE(Ran);
   EXPECT_FALSE(Found);
 }
@@ -330,9 +331,8 @@
   Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
   TestDiagnosticConsumer Consumer;
   Tool.setDiagnosticConsumer(&Consumer);
-  std::unique_ptr<FrontendActionFactory> Action(
-      newFrontendActionFactory<SyntaxOnlyAction>());
-  Tool.run(Action.get());
+  auto Action = newFrontendActionFactory<SyntaxOnlyAction>();
+  Tool.run(Action);
   EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
 }
 
_______________________________________________
cfe-commits mailing list
[email protected]
http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits

Reply via email to