17330f729Sjoerg //===-- arcmt-test.cpp - ARC Migration Tool testbed -----------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg
97330f729Sjoerg #include "clang/ARCMigrate/ARCMT.h"
107330f729Sjoerg #include "clang/AST/ASTContext.h"
117330f729Sjoerg #include "clang/Frontend/PCHContainerOperations.h"
127330f729Sjoerg #include "clang/Frontend/TextDiagnosticPrinter.h"
137330f729Sjoerg #include "clang/Frontend/Utils.h"
147330f729Sjoerg #include "clang/Frontend/VerifyDiagnosticConsumer.h"
157330f729Sjoerg #include "clang/Lex/Preprocessor.h"
167330f729Sjoerg #include "clang/Lex/PreprocessorOptions.h"
177330f729Sjoerg #include "llvm/Support/FileSystem.h"
187330f729Sjoerg #include "llvm/Support/MemoryBuffer.h"
197330f729Sjoerg #include "llvm/Support/Path.h"
207330f729Sjoerg #include "llvm/Support/Signals.h"
217330f729Sjoerg #include <system_error>
227330f729Sjoerg
237330f729Sjoerg using namespace clang;
247330f729Sjoerg using namespace arcmt;
257330f729Sjoerg
267330f729Sjoerg static llvm::cl::opt<bool>
277330f729Sjoerg CheckOnly("check-only",
287330f729Sjoerg llvm::cl::desc("Just check for issues that need to be handled manually"));
297330f729Sjoerg
307330f729Sjoerg //static llvm::cl::opt<bool>
317330f729Sjoerg //TestResultForARC("test-result",
327330f729Sjoerg //llvm::cl::desc("Test the result of transformations by parsing it in ARC mode"));
337330f729Sjoerg
347330f729Sjoerg static llvm::cl::opt<bool>
357330f729Sjoerg OutputTransformations("output-transformations",
367330f729Sjoerg llvm::cl::desc("Print the source transformations"));
377330f729Sjoerg
387330f729Sjoerg static llvm::cl::opt<bool>
397330f729Sjoerg VerifyDiags("verify",llvm::cl::desc("Verify emitted diagnostics and warnings"));
407330f729Sjoerg
417330f729Sjoerg static llvm::cl::opt<bool>
427330f729Sjoerg VerboseOpt("v", llvm::cl::desc("Enable verbose output"));
437330f729Sjoerg
447330f729Sjoerg static llvm::cl::opt<bool>
457330f729Sjoerg VerifyTransformedFiles("verify-transformed-files",
467330f729Sjoerg llvm::cl::desc("Read pairs of file mappings (typically the output of "
477330f729Sjoerg "c-arcmt-test) and compare their contents with the filenames "
487330f729Sjoerg "provided in command-line"));
497330f729Sjoerg
507330f729Sjoerg static llvm::cl::opt<std::string>
517330f729Sjoerg RemappingsFile("remappings-file",
527330f729Sjoerg llvm::cl::desc("Pairs of file mappings (typically the output of "
537330f729Sjoerg "c-arcmt-test)"));
547330f729Sjoerg
557330f729Sjoerg static llvm::cl::list<std::string>
567330f729Sjoerg ResultFiles(llvm::cl::Positional, llvm::cl::desc("<filename>..."));
577330f729Sjoerg
587330f729Sjoerg static llvm::cl::extrahelp extraHelp(
597330f729Sjoerg "\nusage with compiler args: arcmt-test [options] --args [compiler flags]\n");
607330f729Sjoerg
617330f729Sjoerg // This function isn't referenced outside its translation unit, but it
627330f729Sjoerg // can't use the "static" keyword because its address is used for
637330f729Sjoerg // GetMainExecutable (since some platforms don't support taking the
647330f729Sjoerg // address of main, and some platforms can't implement GetMainExecutable
657330f729Sjoerg // without being given the address of a function in the main executable).
GetExecutablePath(const char * Argv0)667330f729Sjoerg std::string GetExecutablePath(const char *Argv0) {
677330f729Sjoerg // This just needs to be some symbol in the binary; C++ doesn't
687330f729Sjoerg // allow taking the address of ::main however.
697330f729Sjoerg void *MainAddr = (void*) (intptr_t) GetExecutablePath;
707330f729Sjoerg return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
717330f729Sjoerg }
727330f729Sjoerg
737330f729Sjoerg static void printSourceLocation(SourceLocation loc, ASTContext &Ctx,
747330f729Sjoerg raw_ostream &OS);
757330f729Sjoerg static void printSourceRange(CharSourceRange range, ASTContext &Ctx,
767330f729Sjoerg raw_ostream &OS);
777330f729Sjoerg
787330f729Sjoerg namespace {
797330f729Sjoerg
807330f729Sjoerg class PrintTransforms : public MigrationProcess::RewriteListener {
817330f729Sjoerg ASTContext *Ctx;
827330f729Sjoerg raw_ostream &OS;
837330f729Sjoerg
847330f729Sjoerg public:
PrintTransforms(raw_ostream & OS)857330f729Sjoerg PrintTransforms(raw_ostream &OS)
867330f729Sjoerg : Ctx(nullptr), OS(OS) {}
877330f729Sjoerg
start(ASTContext & ctx)887330f729Sjoerg void start(ASTContext &ctx) override { Ctx = &ctx; }
finish()897330f729Sjoerg void finish() override { Ctx = nullptr; }
907330f729Sjoerg
insert(SourceLocation loc,StringRef text)917330f729Sjoerg void insert(SourceLocation loc, StringRef text) override {
927330f729Sjoerg assert(Ctx);
937330f729Sjoerg OS << "Insert: ";
947330f729Sjoerg printSourceLocation(loc, *Ctx, OS);
957330f729Sjoerg OS << " \"" << text << "\"\n";
967330f729Sjoerg }
977330f729Sjoerg
remove(CharSourceRange range)987330f729Sjoerg void remove(CharSourceRange range) override {
997330f729Sjoerg assert(Ctx);
1007330f729Sjoerg OS << "Remove: ";
1017330f729Sjoerg printSourceRange(range, *Ctx, OS);
1027330f729Sjoerg OS << '\n';
1037330f729Sjoerg }
1047330f729Sjoerg };
1057330f729Sjoerg
1067330f729Sjoerg } // anonymous namespace
1077330f729Sjoerg
checkForMigration(StringRef resourcesPath,ArrayRef<const char * > Args)1087330f729Sjoerg static bool checkForMigration(StringRef resourcesPath,
1097330f729Sjoerg ArrayRef<const char *> Args) {
1107330f729Sjoerg IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1117330f729Sjoerg DiagnosticConsumer *DiagClient =
1127330f729Sjoerg new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
1137330f729Sjoerg IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
1147330f729Sjoerg IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
1157330f729Sjoerg new DiagnosticsEngine(DiagID, &*DiagOpts, DiagClient));
1167330f729Sjoerg // Chain in -verify checker, if requested.
1177330f729Sjoerg VerifyDiagnosticConsumer *verifyDiag = nullptr;
1187330f729Sjoerg if (VerifyDiags) {
1197330f729Sjoerg verifyDiag = new VerifyDiagnosticConsumer(*Diags);
1207330f729Sjoerg Diags->setClient(verifyDiag);
1217330f729Sjoerg }
1227330f729Sjoerg
1237330f729Sjoerg CompilerInvocation CI;
1247330f729Sjoerg if (!CompilerInvocation::CreateFromArgs(CI, Args, *Diags))
1257330f729Sjoerg return true;
1267330f729Sjoerg
1277330f729Sjoerg if (CI.getFrontendOpts().Inputs.empty()) {
1287330f729Sjoerg llvm::errs() << "error: no input files\n";
1297330f729Sjoerg return true;
1307330f729Sjoerg }
1317330f729Sjoerg
1327330f729Sjoerg if (!CI.getLangOpts()->ObjC)
1337330f729Sjoerg return false;
1347330f729Sjoerg
1357330f729Sjoerg arcmt::checkForManualIssues(CI, CI.getFrontendOpts().Inputs[0],
1367330f729Sjoerg std::make_shared<PCHContainerOperations>(),
1377330f729Sjoerg Diags->getClient());
1387330f729Sjoerg return Diags->getClient()->getNumErrors() > 0;
1397330f729Sjoerg }
1407330f729Sjoerg
printResult(FileRemapper & remapper,raw_ostream & OS)1417330f729Sjoerg static void printResult(FileRemapper &remapper, raw_ostream &OS) {
142*e038c9c4Sjoerg remapper.forEachMapping([](StringRef, StringRef) {},
143*e038c9c4Sjoerg [&](StringRef, const llvm::MemoryBufferRef &Buffer) {
144*e038c9c4Sjoerg OS << Buffer.getBuffer();
145*e038c9c4Sjoerg });
1467330f729Sjoerg }
1477330f729Sjoerg
performTransformations(StringRef resourcesPath,ArrayRef<const char * > Args)1487330f729Sjoerg static bool performTransformations(StringRef resourcesPath,
1497330f729Sjoerg ArrayRef<const char *> Args) {
1507330f729Sjoerg // Check first.
1517330f729Sjoerg if (checkForMigration(resourcesPath, Args))
1527330f729Sjoerg return true;
1537330f729Sjoerg
1547330f729Sjoerg IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1557330f729Sjoerg DiagnosticConsumer *DiagClient =
1567330f729Sjoerg new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
1577330f729Sjoerg IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
1587330f729Sjoerg IntrusiveRefCntPtr<DiagnosticsEngine> TopDiags(
1597330f729Sjoerg new DiagnosticsEngine(DiagID, &*DiagOpts, &*DiagClient));
1607330f729Sjoerg
1617330f729Sjoerg CompilerInvocation origCI;
1627330f729Sjoerg if (!CompilerInvocation::CreateFromArgs(origCI, Args, *TopDiags))
1637330f729Sjoerg return true;
1647330f729Sjoerg
1657330f729Sjoerg if (origCI.getFrontendOpts().Inputs.empty()) {
1667330f729Sjoerg llvm::errs() << "error: no input files\n";
1677330f729Sjoerg return true;
1687330f729Sjoerg }
1697330f729Sjoerg
1707330f729Sjoerg if (!origCI.getLangOpts()->ObjC)
1717330f729Sjoerg return false;
1727330f729Sjoerg
1737330f729Sjoerg MigrationProcess migration(origCI, std::make_shared<PCHContainerOperations>(),
1747330f729Sjoerg DiagClient);
1757330f729Sjoerg
1767330f729Sjoerg std::vector<TransformFn>
1777330f729Sjoerg transforms = arcmt::getAllTransformations(origCI.getLangOpts()->getGC(),
1787330f729Sjoerg origCI.getMigratorOpts().NoFinalizeRemoval);
1797330f729Sjoerg assert(!transforms.empty());
1807330f729Sjoerg
1817330f729Sjoerg std::unique_ptr<PrintTransforms> transformPrinter;
1827330f729Sjoerg if (OutputTransformations)
1837330f729Sjoerg transformPrinter.reset(new PrintTransforms(llvm::outs()));
1847330f729Sjoerg
1857330f729Sjoerg for (unsigned i=0, e = transforms.size(); i != e; ++i) {
1867330f729Sjoerg bool err = migration.applyTransform(transforms[i], transformPrinter.get());
1877330f729Sjoerg if (err) return true;
1887330f729Sjoerg
1897330f729Sjoerg if (VerboseOpt) {
1907330f729Sjoerg if (i == e-1)
1917330f729Sjoerg llvm::errs() << "\n##### FINAL RESULT #####\n";
1927330f729Sjoerg else
1937330f729Sjoerg llvm::errs() << "\n##### OUTPUT AFTER "<< i+1 <<". TRANSFORMATION #####\n";
1947330f729Sjoerg printResult(migration.getRemapper(), llvm::errs());
1957330f729Sjoerg llvm::errs() << "\n##########################\n\n";
1967330f729Sjoerg }
1977330f729Sjoerg }
1987330f729Sjoerg
1997330f729Sjoerg if (!OutputTransformations)
2007330f729Sjoerg printResult(migration.getRemapper(), llvm::outs());
2017330f729Sjoerg
2027330f729Sjoerg // FIXME: TestResultForARC
2037330f729Sjoerg
2047330f729Sjoerg return false;
2057330f729Sjoerg }
2067330f729Sjoerg
filesCompareEqual(StringRef fname1,StringRef fname2)2077330f729Sjoerg static bool filesCompareEqual(StringRef fname1, StringRef fname2) {
2087330f729Sjoerg using namespace llvm;
2097330f729Sjoerg
210*e038c9c4Sjoerg ErrorOr<std::unique_ptr<MemoryBuffer>> file1 =
211*e038c9c4Sjoerg MemoryBuffer::getFile(fname1, /*IsText=*/true);
2127330f729Sjoerg if (!file1)
2137330f729Sjoerg return false;
2147330f729Sjoerg
215*e038c9c4Sjoerg ErrorOr<std::unique_ptr<MemoryBuffer>> file2 =
216*e038c9c4Sjoerg MemoryBuffer::getFile(fname2, /*IsText=*/true);
2177330f729Sjoerg if (!file2)
2187330f729Sjoerg return false;
2197330f729Sjoerg
2207330f729Sjoerg return file1.get()->getBuffer() == file2.get()->getBuffer();
2217330f729Sjoerg }
2227330f729Sjoerg
verifyTransformedFiles(ArrayRef<std::string> resultFiles)2237330f729Sjoerg static bool verifyTransformedFiles(ArrayRef<std::string> resultFiles) {
2247330f729Sjoerg using namespace llvm;
2257330f729Sjoerg
2267330f729Sjoerg assert(!resultFiles.empty());
2277330f729Sjoerg
2287330f729Sjoerg std::map<StringRef, StringRef> resultMap;
2297330f729Sjoerg
2307330f729Sjoerg for (ArrayRef<std::string>::iterator
2317330f729Sjoerg I = resultFiles.begin(), E = resultFiles.end(); I != E; ++I) {
2327330f729Sjoerg StringRef fname(*I);
2337330f729Sjoerg if (!fname.endswith(".result")) {
2347330f729Sjoerg errs() << "error: filename '" << fname
2357330f729Sjoerg << "' does not have '.result' extension\n";
2367330f729Sjoerg return true;
2377330f729Sjoerg }
2387330f729Sjoerg resultMap[sys::path::stem(fname)] = fname;
2397330f729Sjoerg }
2407330f729Sjoerg
2417330f729Sjoerg ErrorOr<std::unique_ptr<MemoryBuffer>> inputBuf = std::error_code();
2427330f729Sjoerg if (RemappingsFile.empty())
2437330f729Sjoerg inputBuf = MemoryBuffer::getSTDIN();
2447330f729Sjoerg else
245*e038c9c4Sjoerg inputBuf = MemoryBuffer::getFile(RemappingsFile, /*IsText=*/true);
2467330f729Sjoerg if (!inputBuf) {
2477330f729Sjoerg errs() << "error: could not read remappings input\n";
2487330f729Sjoerg return true;
2497330f729Sjoerg }
2507330f729Sjoerg
2517330f729Sjoerg SmallVector<StringRef, 8> strs;
2527330f729Sjoerg inputBuf.get()->getBuffer().split(strs, "\n", /*MaxSplit=*/-1,
2537330f729Sjoerg /*KeepEmpty=*/false);
2547330f729Sjoerg
2557330f729Sjoerg if (strs.empty()) {
2567330f729Sjoerg errs() << "error: no files to verify from stdin\n";
2577330f729Sjoerg return true;
2587330f729Sjoerg }
2597330f729Sjoerg if (strs.size() % 2 != 0) {
2607330f729Sjoerg errs() << "error: files to verify are not original/result pairs\n";
2617330f729Sjoerg return true;
2627330f729Sjoerg }
2637330f729Sjoerg
2647330f729Sjoerg for (unsigned i = 0, e = strs.size(); i != e; i += 2) {
2657330f729Sjoerg StringRef inputOrigFname = strs[i];
2667330f729Sjoerg StringRef inputResultFname = strs[i+1];
2677330f729Sjoerg
2687330f729Sjoerg std::map<StringRef, StringRef>::iterator It;
2697330f729Sjoerg It = resultMap.find(sys::path::filename(inputOrigFname));
2707330f729Sjoerg if (It == resultMap.end()) {
2717330f729Sjoerg errs() << "error: '" << inputOrigFname << "' is not in the list of "
2727330f729Sjoerg << "transformed files to verify\n";
2737330f729Sjoerg return true;
2747330f729Sjoerg }
2757330f729Sjoerg
2767330f729Sjoerg if (!sys::fs::exists(It->second)) {
2777330f729Sjoerg errs() << "error: '" << It->second << "' does not exist\n";
2787330f729Sjoerg return true;
2797330f729Sjoerg }
2807330f729Sjoerg if (!sys::fs::exists(inputResultFname)) {
2817330f729Sjoerg errs() << "error: '" << inputResultFname << "' does not exist\n";
2827330f729Sjoerg return true;
2837330f729Sjoerg }
2847330f729Sjoerg
2857330f729Sjoerg if (!filesCompareEqual(It->second, inputResultFname)) {
2867330f729Sjoerg errs() << "error: '" << It->second << "' is different than "
2877330f729Sjoerg << "'" << inputResultFname << "'\n";
2887330f729Sjoerg return true;
2897330f729Sjoerg }
2907330f729Sjoerg
2917330f729Sjoerg resultMap.erase(It);
2927330f729Sjoerg }
2937330f729Sjoerg
2947330f729Sjoerg if (!resultMap.empty()) {
2957330f729Sjoerg for (std::map<StringRef, StringRef>::iterator
2967330f729Sjoerg I = resultMap.begin(), E = resultMap.end(); I != E; ++I)
2977330f729Sjoerg errs() << "error: '" << I->second << "' was not verified!\n";
2987330f729Sjoerg return true;
2997330f729Sjoerg }
3007330f729Sjoerg
3017330f729Sjoerg return false;
3027330f729Sjoerg }
3037330f729Sjoerg
3047330f729Sjoerg //===----------------------------------------------------------------------===//
3057330f729Sjoerg // Misc. functions.
3067330f729Sjoerg //===----------------------------------------------------------------------===//
3077330f729Sjoerg
printSourceLocation(SourceLocation loc,ASTContext & Ctx,raw_ostream & OS)3087330f729Sjoerg static void printSourceLocation(SourceLocation loc, ASTContext &Ctx,
3097330f729Sjoerg raw_ostream &OS) {
3107330f729Sjoerg SourceManager &SM = Ctx.getSourceManager();
3117330f729Sjoerg PresumedLoc PL = SM.getPresumedLoc(loc);
3127330f729Sjoerg
3137330f729Sjoerg OS << llvm::sys::path::filename(PL.getFilename());
3147330f729Sjoerg OS << ":" << PL.getLine() << ":"
3157330f729Sjoerg << PL.getColumn();
3167330f729Sjoerg }
3177330f729Sjoerg
printSourceRange(CharSourceRange range,ASTContext & Ctx,raw_ostream & OS)3187330f729Sjoerg static void printSourceRange(CharSourceRange range, ASTContext &Ctx,
3197330f729Sjoerg raw_ostream &OS) {
3207330f729Sjoerg SourceManager &SM = Ctx.getSourceManager();
3217330f729Sjoerg const LangOptions &langOpts = Ctx.getLangOpts();
3227330f729Sjoerg
3237330f729Sjoerg PresumedLoc PL = SM.getPresumedLoc(range.getBegin());
3247330f729Sjoerg
3257330f729Sjoerg OS << llvm::sys::path::filename(PL.getFilename());
3267330f729Sjoerg OS << " [" << PL.getLine() << ":"
3277330f729Sjoerg << PL.getColumn();
3287330f729Sjoerg OS << " - ";
3297330f729Sjoerg
3307330f729Sjoerg SourceLocation end = range.getEnd();
3317330f729Sjoerg PL = SM.getPresumedLoc(end);
3327330f729Sjoerg
3337330f729Sjoerg unsigned endCol = PL.getColumn() - 1;
3347330f729Sjoerg if (!range.isTokenRange())
3357330f729Sjoerg endCol += Lexer::MeasureTokenLength(end, SM, langOpts);
3367330f729Sjoerg OS << PL.getLine() << ":" << endCol << "]";
3377330f729Sjoerg }
3387330f729Sjoerg
3397330f729Sjoerg //===----------------------------------------------------------------------===//
3407330f729Sjoerg // Command line processing.
3417330f729Sjoerg //===----------------------------------------------------------------------===//
3427330f729Sjoerg
main(int argc,const char ** argv)3437330f729Sjoerg int main(int argc, const char **argv) {
3447330f729Sjoerg void *MainAddr = (void*) (intptr_t) GetExecutablePath;
3457330f729Sjoerg llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
3467330f729Sjoerg
3477330f729Sjoerg std::string
3487330f729Sjoerg resourcesPath = CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
3497330f729Sjoerg
3507330f729Sjoerg int optargc = 0;
3517330f729Sjoerg for (; optargc != argc; ++optargc) {
3527330f729Sjoerg if (StringRef(argv[optargc]) == "--args")
3537330f729Sjoerg break;
3547330f729Sjoerg }
3557330f729Sjoerg llvm::cl::ParseCommandLineOptions(optargc, argv, "arcmt-test");
3567330f729Sjoerg
3577330f729Sjoerg if (VerifyTransformedFiles) {
3587330f729Sjoerg if (ResultFiles.empty()) {
3597330f729Sjoerg llvm::cl::PrintHelpMessage();
3607330f729Sjoerg return 1;
3617330f729Sjoerg }
3627330f729Sjoerg return verifyTransformedFiles(ResultFiles);
3637330f729Sjoerg }
3647330f729Sjoerg
3657330f729Sjoerg if (optargc == argc) {
3667330f729Sjoerg llvm::cl::PrintHelpMessage();
3677330f729Sjoerg return 1;
3687330f729Sjoerg }
3697330f729Sjoerg
3707330f729Sjoerg ArrayRef<const char*> Args(argv+optargc+1, argc-optargc-1);
3717330f729Sjoerg
3727330f729Sjoerg if (CheckOnly)
3737330f729Sjoerg return checkForMigration(resourcesPath, Args);
3747330f729Sjoerg
3757330f729Sjoerg return performTransformations(resourcesPath, Args);
3767330f729Sjoerg }
377