- Immediately abort when conversion operators found in initializer

Hi klimek,

http://llvm-reviews.chandlerc.com/D392

CHANGE SINCE LAST DIFF
  http://llvm-reviews.chandlerc.com/D392?vs=954&id=958#toc

Files:
  cpp11-migrate/CMakeLists.txt
  cpp11-migrate/Makefile
  cpp11-migrate/Transforms.cpp
  cpp11-migrate/UseAuto/UseAuto.cpp
  cpp11-migrate/UseAuto/UseAuto.h
  cpp11-migrate/UseAuto/UseAutoActions.cpp
  cpp11-migrate/UseAuto/UseAutoActions.h
  cpp11-migrate/UseAuto/UseAutoMatchers.cpp
  cpp11-migrate/UseAuto/UseAutoMatchers.h
  test/cpp11-migrate/UseAuto/iterator.cpp
Index: cpp11-migrate/CMakeLists.txt
===================================================================
--- cpp11-migrate/CMakeLists.txt
+++ cpp11-migrate/CMakeLists.txt
@@ -15,6 +15,9 @@
 file(GLOB_RECURSE UseNullptrSources "UseNullptr/*.cpp")
 list(APPEND Cpp11MigrateSources ${UseNullptrSources})
 
+file(GLOB_RECURSE UseAutoSources "UseAuto/*.cpp")
+list(APPEND Cpp11MigrateSources ${UseAutoSources})
+
 add_clang_executable(cpp11-migrate
   ${Cpp11MigrateSources}
   )
Index: cpp11-migrate/Makefile
===================================================================
--- cpp11-migrate/Makefile
+++ cpp11-migrate/Makefile
@@ -26,6 +26,8 @@
 BUILT_SOURCES = $(ObjDir)/LoopConvert/.objdir
 SOURCES += $(addprefix UseNullptr/,$(notdir $(wildcard $(PROJ_SRC_DIR)/UseNullptr/*.cpp)))
 BUILT_SOURCES += $(ObjDir)/UseNullptr/.objdir
+SOURCES += $(addprefix UseNullptr/,$(notdir $(wildcard $(PROJ_SRC_DIR)/UseAuto/*.cpp)))
+BUILT_SOURCES += $(ObjDir)/UseAuto/.objdir
 
 LINK_COMPONENTS := $(TARGETS_TO_BUILD) asmparser bitreader support mc
 USEDLIBS = clangTooling.a clangFrontend.a clangSerialization.a clangDriver.a \
Index: cpp11-migrate/Transforms.cpp
===================================================================
--- cpp11-migrate/Transforms.cpp
+++ cpp11-migrate/Transforms.cpp
@@ -15,6 +15,7 @@
 #include "Transforms.h"
 #include "LoopConvert/LoopConvert.h"
 #include "UseNullptr/UseNullptr.h"
+#include "UseAuto/UseAuto.h"
 
 namespace cl = llvm::cl;
 
@@ -47,6 +48,12 @@
         cl::desc("Make use of nullptr keyword where possible")),
       &ConstructTransform<UseNullptrTransform>));
 
+  Options.push_back(
+    OptionVec::value_type(
+      new cl::opt<bool>("use-auto",
+        cl::desc("Use of 'auto' type specifier")),
+      &ConstructTransform<UseAutoTransform>));
+
   // Add more transform options here.
 }
 
Index: cpp11-migrate/UseAuto/UseAuto.cpp
===================================================================
--- /dev/null
+++ cpp11-migrate/UseAuto/UseAuto.cpp
@@ -0,0 +1,58 @@
+//===-- UseAuto/UseAuto.cpp - Use auto type specifier -----------*- C++ -*-===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file provides the implementation of the UseAutoTransform class.
+///
+//===----------------------------------------------------------------------===//
+
+#include "UseAuto.h"
+#include "UseAutoActions.h"
+#include "UseAutoMatchers.h"
+
+using clang::ast_matchers::MatchFinder;
+using namespace clang;
+using namespace clang::tooling;
+
+int UseAutoTransform::apply(const FileContentsByPath &InputStates,
+                            RiskLevel MaxRisk,
+                            const clang::tooling::CompilationDatabase &Database,
+                            const std::vector<std::string> &SourcePaths,
+                            FileContentsByPath &ResultStates) {
+  RefactoringTool UseAutoTool(Database, SourcePaths);
+
+  for (FileContentsByPath::const_iterator I = InputStates.begin(),
+                                          E = InputStates.end();
+       I != E; ++I)
+    UseAutoTool.mapVirtualFile(I->first, I->second);
+
+  unsigned AcceptedChanges = 0;
+
+  MatchFinder Finder;
+  UseAutoFixer Fixer(UseAutoTool.getReplacements(), AcceptedChanges, MaxRisk);
+
+  Finder.addMatcher(makeIteratorMatcher(), &Fixer);
+
+  if (int Result = UseAutoTool.run(newFrontendActionFactory(&Finder))) {
+    llvm::errs() << "Error encountered during translation.\n";
+    return Result;
+  }
+
+  RewriterContainer Rewrite(UseAutoTool.getFiles(), InputStates);
+
+  // FIXME: Do something if some replacements didn't get applied?
+  UseAutoTool.applyAllReplacements(Rewrite.getRewriter());
+
+  collectResults(Rewrite.getRewriter(), ResultStates);
+
+  if (AcceptedChanges > 0)
+    setChangesMade();
+
+  return 0;
+}
Index: cpp11-migrate/UseAuto/UseAuto.h
===================================================================
--- /dev/null
+++ cpp11-migrate/UseAuto/UseAuto.h
@@ -0,0 +1,49 @@
+//===-- UseAuto/UseAuto.h - Use auto type specifier -------------*- C++ -*-===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file provides the definition of the UseAutoTransform class
+/// which is the main interface to the use-auto transform that replaces
+/// type specifiers with the special C++11 'auto' type specifier in certain
+/// situations.
+///
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_H
+#define LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_H
+
+#include "Transform.h"
+#include "llvm/Support/Compiler.h"
+
+/// \brief Subclass of Transform that transforms type specifiers into the
+/// special C++11 'auto' type specifier in certain situations.
+///
+/// In addition to being used as the type specifier for variable declarations
+/// auto can be used in these ways (C++11 [dcl.spec.auto] p2):
+/// * With functions with trailing return type
+///   - Not covered by this transform
+/// * In the condition of a selection statement but only if the type is
+/// convertible to bool.
+/// * Declaring a static data member with a brace-or-equal initializer.
+/// * In an iteration statement.
+/// * With operator new
+///   * This transform applies auto only to the variable declaration not to the
+///   new expression as described in C++11 [expr.new] p2.
+/// * A for-range-declaration
+class UseAutoTransform : public Transform {
+public:
+  /// \see Transform::run().
+  virtual int apply(const FileContentsByPath &InputStates,
+                    RiskLevel MaxRiskLEvel,
+                    const clang::tooling::CompilationDatabase &Database,
+                    const std::vector<std::string> &SourcePaths,
+                    FileContentsByPath &ResultStates) LLVM_OVERRIDE;
+};
+
+#endif // LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_H
+
Index: cpp11-migrate/UseAuto/UseAutoActions.cpp
===================================================================
--- /dev/null
+++ cpp11-migrate/UseAuto/UseAutoActions.cpp
@@ -0,0 +1,63 @@
+//===-- UseAuto/UseAutoActions.cpp - Matcher callback impl ----------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+///  \file
+///  \brief This file contains the implementation of the UseAutoFixer class.
+///
+//===----------------------------------------------------------------------===//
+#include "UseAutoActions.h"
+#include "UseAutoMatchers.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tooling;
+using namespace clang;
+
+void UseAutoFixer::run(const MatchFinder::MatchResult &Result) {
+  const VarDecl *D = Result.Nodes.getNodeAs<VarDecl>(DeclNodeId);
+
+  assert(D && "Bad Callback. No node provided");
+
+  SourceManager &SM = *Result.SourceManager;
+  if (!SM.isFromMainFile(D->getLocStart()))
+    return;
+
+  const CXXConstructExpr *Construct = cast<CXXConstructExpr>(D->getInit());
+  assert(Construct->getNumArgs() == 1u &&
+         "Expected constructor with single argument");
+
+  // Drill down to the as-written initializer.
+  const Expr *E = Construct->arg_begin()->IgnoreParenImpCasts();
+
+  while (true) {
+    const Expr *E2 = E->IgnoreParenImpCasts();
+    if (E2 != E) {
+      E = E2;
+      continue;
+    }
+
+    E2 = E->IgnoreConversionOperator();
+    if (E2 != E) {
+      // We hit a conversion operator. Since they may do non-trivial work,
+      // making use of auto would result in this operator no-longer being
+      // called.
+      return;
+    }
+
+    // Nothing changed. We're down as far as we can go.
+    break;
+  }
+
+  // Compare canonical types so typedefs don't mess the comparison up.
+  if (D->getType().getCanonicalType() == E->getType().getCanonicalType()) {
+    TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
+    CharSourceRange Range(TL.getSourceRange(), true);
+    Replace.insert(tooling::Replacement(SM, Range, "auto"));
+    ++AcceptedChanges;
+  }
+}
Index: cpp11-migrate/UseAuto/UseAutoActions.h
===================================================================
--- /dev/null
+++ cpp11-migrate/UseAuto/UseAutoActions.h
@@ -0,0 +1,38 @@
+//===-- UseAuto/Actions.h - Matcher callback ---------------------*- C++ -*-==//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+///  \file
+///  \brief This file contains the declaration of the UseAutoFixer class which
+///  is used as an ASTMatcher callback.
+///
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_ACTIONS_H
+#define LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_ACTIONS_H
+
+#include "Transform.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Tooling/Refactoring.h"
+
+/// \brief The callback to be used for use-auto AST matchers.
+class UseAutoFixer : public clang::ast_matchers::MatchFinder::MatchCallback {
+public:
+  UseAutoFixer(clang::tooling::Replacements &Replace, unsigned &AcceptedChanges,
+               RiskLevel)
+      : Replace(Replace), AcceptedChanges(AcceptedChanges) {
+  }
+
+  /// \brief Entry point to the callback called when matches are made.
+  virtual void run(const clang::ast_matchers::MatchFinder::MatchResult &Result);
+
+private:
+  clang::tooling::Replacements &Replace;
+  unsigned &AcceptedChanges;
+};
+
+#endif // LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_ACTIONS_H
Index: cpp11-migrate/UseAuto/UseAutoMatchers.cpp
===================================================================
--- /dev/null
+++ cpp11-migrate/UseAuto/UseAutoMatchers.cpp
@@ -0,0 +1,77 @@
+//===-- UseAutoMatchers.cpp - Matchers for use-auto transform -------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+///  \file
+///  \brief This file contains the implementation for matcher-generating
+///  functions and custom AST_MATCHERs.
+///
+//===----------------------------------------------------------------------===//
+#include "UseAutoMatchers.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/Basic/SourceManager.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace clang::ast_matchers;
+using namespace clang;
+
+const char *DeclNodeId = "decl";
+
+namespace clang {
+namespace ast_matchers {
+
+/// \brief Matches variable declarations that have explicit initializers that
+/// are not initializer lists.
+///
+/// Given
+/// \code
+///   iterator I = C.begin(); // A
+///   MyType A(42);           // B
+///   MyType A{2};            // C
+///   MyType B;               // D
+/// \endcode
+/// varDecl(hasWrittenNonListInitializer()) matches \c A and \c B but not \c C
+/// or \c D.
+AST_MATCHER(VarDecl, hasWrittenNonListInitializer) {
+  const Expr *Init = Node.getAnyInitializer();
+  if (!Init)
+    return false;
+
+  // The following test is taken from DeclPrinter::VisitVarDecl() to find if an
+  // initializer is implicit or not.
+  bool ImplicitInit = false;
+  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
+    if (Construct->isListInitialization())
+      return false;
+    ImplicitInit = Construct->getNumArgs() == 0 ||
+                   Construct->getArg(0)->isDefaultArgument();
+  } else
+    if (Node.getInitStyle() == VarDecl::ListInit)
+      return false;
+
+  return !ImplicitInit;
+}
+
+} // namespace ast_matchers
+} // namespace clang
+
+DeclarationMatcher makeIteratorMatcher() {
+  // FIXME: Instead of looking for traits, should test for existence of
+  // std::iterator_traits<T> which will catch pointers used as iterators as
+  // well.
+  return varDecl(allOf(hasWrittenNonListInitializer(),
+                       hasType(recordDecl(anyOf(
+                           isDerivedFrom("std::iterator"),
+                           allOf(has(namedDecl(hasName("value_type"))),
+                                 has(namedDecl(hasName("difference_type"))),
+                                 has(namedDecl(hasName("iterator_category"))),
+                                 has(namedDecl(hasName("reference"))),
+                                 has(namedDecl(hasName("pointer"))))))),
+                       // Skip type-specifiers that are already 'auto'.
+                       unless(hasType(autoType())))).bind(DeclNodeId);
+}
Index: cpp11-migrate/UseAuto/UseAutoMatchers.h
===================================================================
--- /dev/null
+++ cpp11-migrate/UseAuto/UseAutoMatchers.h
@@ -0,0 +1,26 @@
+//===-- UseAutoMatchers.h - Matchers for use-auto transform ----*- C++ -*--===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+///  \file
+///  \brief This file contains the declarations for matcher-generating functions
+///  and names for bound nodes found by AST matchers.
+///
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_MATCHERS_H
+#define LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_MATCHERS_H
+
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+extern const char *DeclNodeId;
+
+/// \brief Create a matcher that matches declarations where the type is a
+/// subclass of std::iterator or has standard iterator traits.
+clang::ast_matchers::DeclarationMatcher makeIteratorMatcher();
+
+#endif // LLVM_TOOLS_CLANG_TOOLS_EXTRA_CPP11_MIGRATE_USE_AUTO_MATCHERS_H
Index: test/cpp11-migrate/UseAuto/iterator.cpp
===================================================================
--- /dev/null
+++ test/cpp11-migrate/UseAuto/iterator.cpp
@@ -0,0 +1,120 @@
+// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
+// RUN: cpp11-migrate -use-auto %t.cpp -- --std=c++11
+// RUN: FileCheck -input-file=%t.cpp %s
+#include <vector>
+#include <array>
+
+class MyIterator : public std::iterator<std::forward_iterator_tag, int> {
+public:
+  MyIterator(int i = 9) : i(i) {}
+  MyIterator(std::vector<int>::iterator I) : I(I) {}
+
+  operator std::vector<int>::iterator()
+  {
+    return I;
+  }
+
+private:
+  std::vector<int>::iterator I;
+  int i;
+};
+
+MyIterator begin()
+{
+  return MyIterator();
+}
+
+class DummyIterator {
+public:
+  typedef void value_type;
+  typedef void difference_type;
+  typedef void iterator_category;
+  typedef void reference;
+  typedef void pointer;
+};
+DummyIterator makeDummy() {
+  return DummyIterator();
+}
+
+typedef std::vector<int>::iterator int_iterator;
+
+int main(int argc, char **argv) {
+  std::vector<int> vec;
+  // CHECK: std::vector<int> vec;
+
+  // MyIterator inherits from std::iterator so it should be transformed.
+  MyIterator myI = begin();
+  // CHECK: auto myI = begin();
+
+  // The constructor taking one arg with a default value will be used here.
+  // Ensure auto is not used.
+  MyIterator myI2;
+  // CHECK: MyIterator myI2;
+
+  // DummyIterator provides the iterator type traits so it should be
+  // transformed.
+  DummyIterator dummyI = makeDummy();
+  // CHECK: auto dummyI = makeDummy();
+
+  // Default constructor used so auto should not be.
+  DummyIterator dummy2;
+  // CHECK: DummyIterator dummy2;
+
+  // Simple variable declaration.
+  std::vector<int>::iterator I = vec.begin();
+  // CHECK: auto I = vec.begin();
+
+  // declarator-id is not the same type as initializer expression. No transform
+  // should happen.
+  std::vector<int>::iterator I2 = myI;
+  // CHECK: std::vector<int>::iterator I2 = myI;
+
+  // Make sure we test on canonical types.
+  int_iterator I3 = I;
+  // CHECK: auto I3 = I;
+
+  // Weird cases with pointers and references to iterators not covered.
+  int_iterator *IPtr = &I;
+  // CHECK: int_iterator *IPtr = &I;
+
+  int_iterator &IRef = I;
+  // CHECK: int_iterator &IRef = I;
+
+  // 'auto' will deduce to std::initializer_list in this case so no
+  // replacement.
+
+  std::vector<int>::iterator I4{vec.begin()};
+  // CHECK: std::vector<int>::iterator I4{vec.begin()};
+
+  std::vector<int>::iterator I5 = {vec.begin()};
+  // CHECK: std::vector<int>::iterator I5 = {vec.begin()};
+
+  std::vector<int>::iterator I6(vec.begin());
+  // CHECK: auto I6(vec.begin());
+
+  std::vector<int>::reverse_iterator R = vec.rbegin();
+  // CHECK: auto R = vec.rbegin();
+
+  // Iteration statement.
+  for (std::vector<int>::iterator I = vec.begin(); I != vec.end(); ++I) {
+    // CHECK: for (auto I = vec.begin(); I != vec.end(); ++I) {
+    ++(*I);
+  }
+
+  // Range-based for.
+  std::array<std::vector<int>::iterator, 5> iter_arr;
+  for (std::vector<int>::iterator I: iter_arr) {
+    // CHECK: for (auto I: iter_arr) {
+    I = vec.begin();
+  }
+
+  // Test with init-declarator-list.
+  for (int_iterator I = vec.begin(),
+       E = vec.end(); I != E; ++I) {
+  // CHECK:      for (auto I = vec.begin(),
+  // CHECK-NEXT:      E = vec.end(); I != E; ++I) {
+    ++(*I);
+  }
+
+  return 0;
+}
_______________________________________________
cfe-commits mailing list
[email protected]
http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits

Reply via email to