Home | History | Annotate | Download | only in arcmt-test
      1 //===-- arcmt-test.cpp - ARC Migration Tool testbed -----------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "clang/ARCMigrate/ARCMT.h"
     11 #include "clang/Frontend/ASTUnit.h"
     12 #include "clang/Frontend/TextDiagnosticPrinter.h"
     13 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
     14 #include "clang/Frontend/Utils.h"
     15 #include "clang/Lex/Preprocessor.h"
     16 #include "llvm/Support/MemoryBuffer.h"
     17 #include "llvm/Support/FileSystem.h"
     18 #include "llvm/Support/Signals.h"
     19 #include "llvm/Support/system_error.h"
     20 
     21 using namespace clang;
     22 using namespace arcmt;
     23 
     24 static llvm::cl::opt<bool>
     25 CheckOnly("check-only",
     26       llvm::cl::desc("Just check for issues that need to be handled manually"));
     27 
     28 //static llvm::cl::opt<bool>
     29 //TestResultForARC("test-result",
     30 //llvm::cl::desc("Test the result of transformations by parsing it in ARC mode"));
     31 
     32 static llvm::cl::opt<bool>
     33 OutputTransformations("output-transformations",
     34                       llvm::cl::desc("Print the source transformations"));
     35 
     36 static llvm::cl::opt<bool>
     37 VerifyDiags("verify",llvm::cl::desc("Verify emitted diagnostics and warnings"));
     38 
     39 static llvm::cl::opt<bool>
     40 VerboseOpt("v", llvm::cl::desc("Enable verbose output"));
     41 
     42 static llvm::cl::opt<bool>
     43 VerifyTransformedFiles("verify-transformed-files",
     44 llvm::cl::desc("Read pairs of file mappings (typically the output of "
     45                "c-arcmt-test) and compare their contents with the filenames "
     46                "provided in command-line"));
     47 
     48 static llvm::cl::opt<std::string>
     49 RemappingsFile("remappings-file",
     50                llvm::cl::desc("Pairs of file mappings (typically the output of "
     51                "c-arcmt-test)"));
     52 
     53 static llvm::cl::list<std::string>
     54 ResultFiles(llvm::cl::Positional, llvm::cl::desc("<filename>..."));
     55 
     56 static llvm::cl::extrahelp extraHelp(
     57   "\nusage with compiler args: arcmt-test [options] --args [compiler flags]\n");
     58 
     59 // This function isn't referenced outside its translation unit, but it
     60 // can't use the "static" keyword because its address is used for
     61 // GetMainExecutable (since some platforms don't support taking the
     62 // address of main, and some platforms can't implement GetMainExecutable
     63 // without being given the address of a function in the main executable).
     64 llvm::sys::Path GetExecutablePath(const char *Argv0) {
     65   // This just needs to be some symbol in the binary; C++ doesn't
     66   // allow taking the address of ::main however.
     67   void *MainAddr = (void*) (intptr_t) GetExecutablePath;
     68   return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
     69 }
     70 
     71 static void printSourceLocation(SourceLocation loc, ASTContext &Ctx,
     72                                 raw_ostream &OS);
     73 static void printSourceRange(CharSourceRange range, ASTContext &Ctx,
     74                              raw_ostream &OS);
     75 
     76 namespace {
     77 
     78 class PrintTransforms : public MigrationProcess::RewriteListener {
     79   ASTContext *Ctx;
     80   raw_ostream &OS;
     81 
     82 public:
     83   PrintTransforms(raw_ostream &OS)
     84     : Ctx(0), OS(OS) { }
     85 
     86   virtual void start(ASTContext &ctx) { Ctx = &ctx; }
     87   virtual void finish() { Ctx = 0; }
     88 
     89   virtual void insert(SourceLocation loc, StringRef text) {
     90     assert(Ctx);
     91     OS << "Insert: ";
     92     printSourceLocation(loc, *Ctx, OS);
     93     OS << " \"" << text << "\"\n";
     94   }
     95 
     96   virtual void remove(CharSourceRange range) {
     97     assert(Ctx);
     98     OS << "Remove: ";
     99     printSourceRange(range, *Ctx, OS);
    100     OS << '\n';
    101   }
    102 };
    103 
    104 } // anonymous namespace
    105 
    106 static bool checkForMigration(StringRef resourcesPath,
    107                               ArrayRef<const char *> Args) {
    108   DiagnosticConsumer *DiagClient =
    109     new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
    110   llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    111   llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
    112       new DiagnosticsEngine(DiagID, DiagClient));
    113   // Chain in -verify checker, if requested.
    114   VerifyDiagnosticConsumer *verifyDiag = 0;
    115   if (VerifyDiags) {
    116     verifyDiag = new VerifyDiagnosticConsumer(*Diags);
    117     Diags->setClient(verifyDiag);
    118   }
    119 
    120   CompilerInvocation CI;
    121   CompilerInvocation::CreateFromArgs(CI, Args.begin(), Args.end(), *Diags);
    122 
    123   if (CI.getFrontendOpts().Inputs.empty()) {
    124     llvm::errs() << "error: no input files\n";
    125     return true;
    126   }
    127 
    128   if (!CI.getLangOpts().ObjC1)
    129     return false;
    130 
    131   arcmt::checkForManualIssues(CI,
    132                               CI.getFrontendOpts().Inputs[0].second,
    133                               CI.getFrontendOpts().Inputs[0].first,
    134                               Diags->getClient());
    135   return Diags->getClient()->getNumErrors() > 0;
    136 }
    137 
    138 static void printResult(FileRemapper &remapper, raw_ostream &OS) {
    139   CompilerInvocation CI;
    140   remapper.applyMappings(CI);
    141   PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
    142   // The changed files will be in memory buffers, print them.
    143   for (unsigned i = 0, e = PPOpts.RemappedFileBuffers.size(); i != e; ++i) {
    144     const llvm::MemoryBuffer *mem = PPOpts.RemappedFileBuffers[i].second;
    145     OS << mem->getBuffer();
    146   }
    147 }
    148 
    149 static bool performTransformations(StringRef resourcesPath,
    150                                    ArrayRef<const char *> Args) {
    151   // Check first.
    152   if (checkForMigration(resourcesPath, Args))
    153     return true;
    154 
    155   DiagnosticConsumer *DiagClient =
    156     new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
    157   llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
    158   llvm::IntrusiveRefCntPtr<DiagnosticsEngine> TopDiags(
    159       new DiagnosticsEngine(DiagID, DiagClient));
    160 
    161   CompilerInvocation origCI;
    162   CompilerInvocation::CreateFromArgs(origCI, Args.begin(), Args.end(),
    163                                      *TopDiags);
    164 
    165   if (origCI.getFrontendOpts().Inputs.empty()) {
    166     llvm::errs() << "error: no input files\n";
    167     return true;
    168   }
    169 
    170   if (!origCI.getLangOpts().ObjC1)
    171     return false;
    172 
    173   MigrationProcess migration(origCI, DiagClient);
    174 
    175   std::vector<TransformFn> transforms = arcmt::getAllTransformations();
    176   assert(!transforms.empty());
    177 
    178   llvm::OwningPtr<PrintTransforms> transformPrinter;
    179   if (OutputTransformations)
    180     transformPrinter.reset(new PrintTransforms(llvm::outs()));
    181 
    182   for (unsigned i=0, e = transforms.size(); i != e; ++i) {
    183     bool err = migration.applyTransform(transforms[i], transformPrinter.get());
    184     if (err) return true;
    185 
    186     if (VerboseOpt) {
    187       if (i == e-1)
    188         llvm::errs() << "\n##### FINAL RESULT #####\n";
    189       else
    190         llvm::errs() << "\n##### OUTPUT AFTER "<< i+1 <<". TRANSFORMATION #####\n";
    191       printResult(migration.getRemapper(), llvm::errs());
    192       llvm::errs() << "\n##########################\n\n";
    193     }
    194   }
    195 
    196   if (!OutputTransformations)
    197     printResult(migration.getRemapper(), llvm::outs());
    198 
    199   // FIXME: TestResultForARC
    200 
    201   return false;
    202 }
    203 
    204 static bool filesCompareEqual(StringRef fname1, StringRef fname2) {
    205   using namespace llvm;
    206 
    207   OwningPtr<MemoryBuffer> file1;
    208   MemoryBuffer::getFile(fname1, file1);
    209   if (!file1)
    210     return false;
    211 
    212   OwningPtr<MemoryBuffer> file2;
    213   MemoryBuffer::getFile(fname2, file2);
    214   if (!file2)
    215     return false;
    216 
    217   return file1->getBuffer() == file2->getBuffer();
    218 }
    219 
    220 static bool verifyTransformedFiles(ArrayRef<std::string> resultFiles) {
    221   using namespace llvm;
    222 
    223   assert(!resultFiles.empty());
    224 
    225   std::map<StringRef, StringRef> resultMap;
    226 
    227   for (ArrayRef<std::string>::iterator
    228          I = resultFiles.begin(), E = resultFiles.end(); I != E; ++I) {
    229     StringRef fname(*I);
    230     if (!fname.endswith(".result")) {
    231       errs() << "error: filename '" << fname
    232                    << "' does not have '.result' extension\n";
    233       return true;
    234     }
    235     resultMap[sys::path::stem(fname)] = fname;
    236   }
    237 
    238   OwningPtr<MemoryBuffer> inputBuf;
    239   if (RemappingsFile.empty())
    240     MemoryBuffer::getSTDIN(inputBuf);
    241   else
    242     MemoryBuffer::getFile(RemappingsFile, inputBuf);
    243   if (!inputBuf) {
    244     errs() << "error: could not read remappings input\n";
    245     return true;
    246   }
    247 
    248   SmallVector<StringRef, 8> strs;
    249   inputBuf->getBuffer().split(strs, "\n", /*MaxSplit=*/-1, /*KeepEmpty=*/false);
    250 
    251   if (strs.empty()) {
    252     errs() << "error: no files to verify from stdin\n";
    253     return true;
    254   }
    255   if (strs.size() % 2 != 0) {
    256     errs() << "error: files to verify are not original/result pairs\n";
    257     return true;
    258   }
    259 
    260   for (unsigned i = 0, e = strs.size(); i != e; i += 2) {
    261     StringRef inputOrigFname = strs[i];
    262     StringRef inputResultFname = strs[i+1];
    263 
    264     std::map<StringRef, StringRef>::iterator It;
    265     It = resultMap.find(sys::path::filename(inputOrigFname));
    266     if (It == resultMap.end()) {
    267       errs() << "error: '" << inputOrigFname << "' is not in the list of "
    268              << "transformed files to verify\n";
    269       return true;
    270     }
    271 
    272     bool exists = false;
    273     sys::fs::exists(It->second, exists);
    274     if (!exists) {
    275       errs() << "error: '" << It->second << "' does not exist\n";
    276       return true;
    277     }
    278     sys::fs::exists(inputResultFname, exists);
    279     if (!exists) {
    280       errs() << "error: '" << inputResultFname << "' does not exist\n";
    281       return true;
    282     }
    283 
    284     if (!filesCompareEqual(It->second, inputResultFname)) {
    285       errs() << "error: '" << It->second << "' is different than "
    286              << "'" << inputResultFname << "'\n";
    287       return true;
    288     }
    289 
    290     resultMap.erase(It);
    291   }
    292 
    293   if (!resultMap.empty()) {
    294     for (std::map<StringRef, StringRef>::iterator
    295            I = resultMap.begin(), E = resultMap.end(); I != E; ++I)
    296       errs() << "error: '" << I->second << "' was not verified!\n";
    297     return true;
    298   }
    299 
    300   return false;
    301 }
    302 
    303 //===----------------------------------------------------------------------===//
    304 // Misc. functions.
    305 //===----------------------------------------------------------------------===//
    306 
    307 static void printSourceLocation(SourceLocation loc, ASTContext &Ctx,
    308                                 raw_ostream &OS) {
    309   SourceManager &SM = Ctx.getSourceManager();
    310   PresumedLoc PL = SM.getPresumedLoc(loc);
    311 
    312   OS << llvm::sys::path::filename(PL.getFilename());
    313   OS << ":" << PL.getLine() << ":"
    314             << PL.getColumn();
    315 }
    316 
    317 static void printSourceRange(CharSourceRange range, ASTContext &Ctx,
    318                              raw_ostream &OS) {
    319   SourceManager &SM = Ctx.getSourceManager();
    320   const LangOptions &langOpts = Ctx.getLangOptions();
    321 
    322   PresumedLoc PL = SM.getPresumedLoc(range.getBegin());
    323 
    324   OS << llvm::sys::path::filename(PL.getFilename());
    325   OS << " [" << PL.getLine() << ":"
    326              << PL.getColumn();
    327   OS << " - ";
    328 
    329   SourceLocation end = range.getEnd();
    330   PL = SM.getPresumedLoc(end);
    331 
    332   unsigned endCol = PL.getColumn() - 1;
    333   if (!range.isTokenRange())
    334     endCol += Lexer::MeasureTokenLength(end, SM, langOpts);
    335   OS << PL.getLine() << ":" << endCol << "]";
    336 }
    337 
    338 //===----------------------------------------------------------------------===//
    339 // Command line processing.
    340 //===----------------------------------------------------------------------===//
    341 
    342 int main(int argc, const char **argv) {
    343   void *MainAddr = (void*) (intptr_t) GetExecutablePath;
    344   llvm::sys::PrintStackTraceOnErrorSignal();
    345 
    346   std::string
    347     resourcesPath = CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
    348 
    349   int optargc = 0;
    350   for (; optargc != argc; ++optargc) {
    351     if (StringRef(argv[optargc]) == "--args")
    352       break;
    353   }
    354   llvm::cl::ParseCommandLineOptions(optargc, const_cast<char **>(argv), "arcmt-test");
    355 
    356   if (VerifyTransformedFiles) {
    357     if (ResultFiles.empty()) {
    358       llvm::cl::PrintHelpMessage();
    359       return 1;
    360     }
    361     return verifyTransformedFiles(ResultFiles);
    362   }
    363 
    364   if (optargc == argc) {
    365     llvm::cl::PrintHelpMessage();
    366     return 1;
    367   }
    368 
    369   ArrayRef<const char*> Args(argv+optargc+1, argc-optargc-1);
    370 
    371   if (CheckOnly)
    372     return checkForMigration(resourcesPath, Args);
    373 
    374   return performTransformations(resourcesPath, Args);
    375 }
    376