diff options
author | Ted Kremenek <kremenek@apple.com> | 2012-03-06 20:06:33 +0000 |
---|---|---|
committer | Ted Kremenek <kremenek@apple.com> | 2012-03-06 20:06:33 +0000 |
commit | 30660a898545416f0fea2d717f16f75640001e38 (patch) | |
tree | a8408d8c12d992b4110fca1bfe78f337b48f5d11 /lib | |
parent | 2a253960f0312c9759965a1defb9326d6b2764a4 (diff) |
Add new code migrator support for migrating existing Objective-C code to use
the new Objective-C NSArray/NSDictionary/NSNumber literal syntax.
This introduces a new library, libEdit, which provides a new way to support
migration of code that improves on the original ARC migrator. We now believe
that most of its functionality can be refactored into the existing libraries,
and thus this new library may shortly disappear.
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@152141 91177308-0d34-0410-b5e6-96231b3b80d8
Diffstat (limited to 'lib')
-rw-r--r-- | lib/ARCMigrate/ARCMT.cpp | 46 | ||||
-rw-r--r-- | lib/ARCMigrate/CMakeLists.txt | 1 | ||||
-rw-r--r-- | lib/ARCMigrate/FileRemapper.cpp | 26 | ||||
-rw-r--r-- | lib/ARCMigrate/ObjCMT.cpp | 226 | ||||
-rw-r--r-- | lib/ARCMigrate/TransRetainReleaseDealloc.cpp | 94 | ||||
-rw-r--r-- | lib/Basic/DiagnosticIDs.cpp | 13 | ||||
-rw-r--r-- | lib/CMakeLists.txt | 1 | ||||
-rw-r--r-- | lib/Driver/Action.cpp | 7 | ||||
-rw-r--r-- | lib/Driver/Driver.cpp | 3 | ||||
-rw-r--r-- | lib/Driver/ToolChain.cpp | 2 | ||||
-rw-r--r-- | lib/Driver/ToolChains.cpp | 2 | ||||
-rw-r--r-- | lib/Driver/Tools.cpp | 25 | ||||
-rw-r--r-- | lib/Driver/WindowsToolChain.cpp | 1 | ||||
-rw-r--r-- | lib/Edit/CMakeLists.txt | 7 | ||||
-rw-r--r-- | lib/Edit/Commit.cpp | 345 | ||||
-rw-r--r-- | lib/Edit/EditedSource.cpp | 329 | ||||
-rw-r--r-- | lib/Edit/Makefile | 14 | ||||
-rw-r--r-- | lib/Edit/RewriteObjCFoundationAPI.cpp | 589 | ||||
-rw-r--r-- | lib/Frontend/CompilerInvocation.cpp | 31 | ||||
-rw-r--r-- | lib/Frontend/DiagnosticRenderer.cpp | 57 | ||||
-rw-r--r-- | lib/FrontendTool/ExecuteCompilerInvocation.cpp | 9 | ||||
-rwxr-xr-x | lib/Makefile | 2 | ||||
-rw-r--r-- | lib/Rewrite/FixItRewriter.cpp | 69 |
23 files changed, 1834 insertions, 65 deletions
diff --git a/lib/ARCMigrate/ARCMT.cpp b/lib/ARCMigrate/ARCMT.cpp index 61753074e8..07f22c4f36 100644 --- a/lib/ARCMigrate/ARCMT.cpp +++ b/lib/ARCMigrate/ARCMT.cpp @@ -398,13 +398,51 @@ bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > & if (err) return true; - CompilerInvocation CI; - remapper.applyMappings(CI); - remap = CI.getPreprocessorOpts().RemappedFiles; + PreprocessorOptions PPOpts; + remapper.applyMappings(PPOpts); + remap = PPOpts.RemappedFiles; return false; } +bool arcmt::getFileRemappingsFromFileList( + std::vector<std::pair<std::string,std::string> > &remap, + ArrayRef<StringRef> remapFiles, + DiagnosticConsumer *DiagClient) { + bool hasErrorOccurred = false; + llvm::StringMap<bool> Uniquer; + + llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); + llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags( + new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false)); + + for (ArrayRef<StringRef>::iterator + I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) { + StringRef file = *I; + + FileRemapper remapper; + bool err = remapper.initFromFile(file, *Diags, + /*ignoreIfFilesChanged=*/true); + hasErrorOccurred = hasErrorOccurred || err; + if (err) + continue; + + PreprocessorOptions PPOpts; + remapper.applyMappings(PPOpts); + for (PreprocessorOptions::remapped_file_iterator + RI = PPOpts.remapped_file_begin(), RE = PPOpts.remapped_file_end(); + RI != RE; ++RI) { + bool &inserted = Uniquer[RI->first]; + if (inserted) + continue; + inserted = true; + remap.push_back(*RI); + } + } + + return hasErrorOccurred; +} + //===----------------------------------------------------------------------===// // CollectTransformActions. //===----------------------------------------------------------------------===// @@ -504,7 +542,7 @@ bool MigrationProcess::applyTransform(TransformFn trans, CInvok.reset(createInvocationForMigration(OrigCI)); CInvok->getDiagnosticOpts().IgnoreWarnings = true; - Remapper.applyMappings(*CInvok); + Remapper.applyMappings(CInvok->getPreprocessorOpts()); CapturedDiagList capturedDiags; std::vector<SourceLocation> ARCMTMacroLocs; diff --git a/lib/ARCMigrate/CMakeLists.txt b/lib/ARCMigrate/CMakeLists.txt index 1a64b12721..fcb7f72ee2 100644 --- a/lib/ARCMigrate/CMakeLists.txt +++ b/lib/ARCMigrate/CMakeLists.txt @@ -4,6 +4,7 @@ add_clang_library(clangARCMigrate ARCMT.cpp ARCMTActions.cpp FileRemapper.cpp + ObjCMT.cpp PlistReporter.cpp TransAPIUses.cpp TransARCAssign.cpp diff --git a/lib/ARCMigrate/FileRemapper.cpp b/lib/ARCMigrate/FileRemapper.cpp index 0e6e35c748..1e97c9eed5 100644 --- a/lib/ARCMigrate/FileRemapper.cpp +++ b/lib/ARCMigrate/FileRemapper.cpp @@ -8,8 +8,9 @@ //===----------------------------------------------------------------------===// #include "clang/ARCMigrate/FileRemapper.h" -#include "clang/Frontend/CompilerInvocation.h" +#include "clang/Frontend/PreprocessorOptions.h" #include "clang/Basic/FileManager.h" +#include "clang/Basic/Diagnostic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/FileSystem.h" @@ -50,9 +51,15 @@ std::string FileRemapper::getRemapInfoFile(StringRef outputDir) { bool FileRemapper::initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag, bool ignoreIfFilesChanged) { + std::string infoFile = getRemapInfoFile(outputDir); + return initFromFile(infoFile, Diag, ignoreIfFilesChanged); +} + +bool FileRemapper::initFromFile(StringRef filePath, DiagnosticsEngine &Diag, + bool ignoreIfFilesChanged) { assert(FromToMappings.empty() && "initFromDisk should be called before any remap calls"); - std::string infoFile = getRemapInfoFile(outputDir); + std::string infoFile = filePath; bool fileExists = false; llvm::sys::fs::exists(infoFile, fileExists); if (!fileExists) @@ -108,8 +115,15 @@ bool FileRemapper::flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag) { if (fs::create_directory(outputDir, existed) != llvm::errc::success) return report("Could not create directory: " + outputDir, Diag); - std::string errMsg; std::string infoFile = getRemapInfoFile(outputDir); + return flushToFile(infoFile, Diag); +} + +bool FileRemapper::flushToFile(StringRef outputPath, DiagnosticsEngine &Diag) { + using namespace llvm::sys; + + std::string errMsg; + std::string infoFile = outputPath; llvm::raw_fd_ostream infoOut(infoFile.c_str(), errMsg, llvm::raw_fd_ostream::F_Binary); if (!errMsg.empty()) @@ -189,8 +203,7 @@ bool FileRemapper::overwriteOriginal(DiagnosticsEngine &Diag, return false; } -void FileRemapper::applyMappings(CompilerInvocation &CI) const { - PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); +void FileRemapper::applyMappings(PreprocessorOptions &PPOpts) const { for (MappingsTy::const_iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) { @@ -204,8 +217,7 @@ void FileRemapper::applyMappings(CompilerInvocation &CI) const { PPOpts.RetainRemappedFileBuffers = true; } -void FileRemapper::transferMappingsAndClear(CompilerInvocation &CI) { - PreprocessorOptions &PPOpts = CI.getPreprocessorOpts(); +void FileRemapper::transferMappingsAndClear(PreprocessorOptions &PPOpts) { for (MappingsTy::iterator I = FromToMappings.begin(), E = FromToMappings.end(); I != E; ++I) { if (const FileEntry *FE = I->second.dyn_cast<const FileEntry *>()) { diff --git a/lib/ARCMigrate/ObjCMT.cpp b/lib/ARCMigrate/ObjCMT.cpp new file mode 100644 index 0000000000..497377a394 --- /dev/null +++ b/lib/ARCMigrate/ObjCMT.cpp @@ -0,0 +1,226 @@ +//===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/ARCMigrate/ARCMTActions.h" +#include "clang/Frontend/CompilerInstance.h" +#include "clang/Frontend/MultiplexConsumer.h" +#include "clang/AST/RecursiveASTVisitor.h" +#include "clang/AST/NSAPI.h" +#include "clang/AST/ASTConsumer.h" +#include "clang/Edit/Rewriters.h" +#include "clang/Edit/EditedSource.h" +#include "clang/Edit/Commit.h" +#include "clang/Edit/EditsReceiver.h" +#include "clang/Rewrite/Rewriter.h" +#include "clang/Lex/Preprocessor.h" +#include "clang/Basic/FileManager.h" +#include "llvm/ADT/SmallString.h" + +using namespace clang; +using namespace arcmt; + +namespace { + +class ObjCMigrateASTConsumer : public ASTConsumer { + void migrateDecl(Decl *D); + +public: + std::string MigrateDir; + bool MigrateLiterals; + bool MigrateSubscripting; + llvm::OwningPtr<NSAPI> NSAPIObj; + llvm::OwningPtr<edit::EditedSource> Editor; + FileRemapper &Remapper; + FileManager &FileMgr; + const PreprocessingRecord *PPRec; + bool IsOutputFile; + + ObjCMigrateASTConsumer(StringRef migrateDir, + bool migrateLiterals, + bool migrateSubscripting, + FileRemapper &remapper, + FileManager &fileMgr, + const PreprocessingRecord *PPRec, + bool isOutputFile = false) + : MigrateDir(migrateDir), + MigrateLiterals(migrateLiterals), + MigrateSubscripting(migrateSubscripting), + Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), + IsOutputFile(isOutputFile) { } + +protected: + virtual void Initialize(ASTContext &Context) { + NSAPIObj.reset(new NSAPI(Context)); + Editor.reset(new edit::EditedSource(Context.getSourceManager(), + Context.getLangOptions(), + PPRec)); + } + + virtual bool HandleTopLevelDecl(DeclGroupRef DG) { + for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) + migrateDecl(*I); + return true; + } + virtual void HandleInterestingDecl(DeclGroupRef DG) { + // Ignore decls from the PCH. + } + virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { + ObjCMigrateASTConsumer::HandleTopLevelDecl(DG); + } + + virtual void HandleTranslationUnit(ASTContext &Ctx); +}; + +} + +ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction, + StringRef migrateDir, + bool migrateLiterals, + bool migrateSubscripting) + : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir), + MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting), + CompInst(0) { + if (MigrateDir.empty()) + MigrateDir = "."; // user current directory if none is given. +} + +ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, + StringRef InFile) { + ASTConsumer * + WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile); + ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir, + MigrateLiterals, + MigrateSubscripting, + Remapper, + CompInst->getFileManager(), + CompInst->getPreprocessor().getPreprocessingRecord()); + ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer }; + return new MultiplexConsumer(Consumers); +} + +bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) { + Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(), + /*ignoreIfFilesChanges=*/true); + CompInst = &CI; + CI.getDiagnostics().setIgnoreAllWarnings(true); + CI.getPreprocessorOpts().DetailedRecord = true; + CI.getPreprocessorOpts().DetailedRecordConditionalDirectives = true; + return true; +} + +namespace { +class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> { + ObjCMigrateASTConsumer &Consumer; + +public: + ObjCMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { } + + bool shouldVisitTemplateInstantiations() const { return false; } + bool shouldWalkTypesOfTypeLocs() const { return false; } + + bool VisitObjCMessageExpr(ObjCMessageExpr *E) { + if (Consumer.MigrateLiterals) { + edit::Commit commit(*Consumer.Editor); + edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit); + Consumer.Editor->commit(commit); + } + + if (Consumer.MigrateSubscripting) { + edit::Commit commit(*Consumer.Editor); + edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit); + Consumer.Editor->commit(commit); + } + + return true; + } + + bool TraverseObjCMessageExpr(ObjCMessageExpr *E) { + // Do depth first; we want to rewrite the subexpressions first so that if + // we have to move expressions we will move them already rewritten. + for (Stmt::child_range range = E->children(); range; ++range) + if (!TraverseStmt(*range)) + return false; + + return WalkUpFromObjCMessageExpr(E); + } +}; +} + +void ObjCMigrateASTConsumer::migrateDecl(Decl *D) { + if (!D) + return; + if (isa<ObjCMethodDecl>(D)) + return; // Wait for the ObjC container declaration. + + ObjCMigrator(*this).TraverseDecl(D); +} + +namespace { + +class RewritesReceiver : public edit::EditsReceiver { + Rewriter &Rewrite; + +public: + RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { } + + virtual void insert(SourceLocation loc, StringRef text) { + Rewrite.InsertText(loc, text); + } + virtual void replace(CharSourceRange range, StringRef text) { + Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text); + } +}; + +} + +void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { + Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOptions()); + RewritesReceiver Rec(rewriter); + Editor->applyRewrites(Rec); + + for (Rewriter::buffer_iterator + I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) { + FileID FID = I->first; + RewriteBuffer &buf = I->second; + const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID); + assert(file); + llvm::SmallString<512> newText; + llvm::raw_svector_ostream vecOS(newText); + buf.write(vecOS); + vecOS.flush(); + llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy( + StringRef(newText.data(), newText.size()), file->getName()); + llvm::SmallString<64> filePath(file->getName()); + FileMgr.FixupRelativePath(filePath); + Remapper.remap(filePath.str(), memBuf); + } + + if (IsOutputFile) { + Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics()); + } else { + Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics()); + } +} + +bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) { + CI.getPreprocessorOpts().DetailedRecord = true; + CI.getPreprocessorOpts().DetailedRecordConditionalDirectives = true; + return true; +} + +ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, + StringRef InFile) { + return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile, + /*MigrateLiterals=*/true, + /*MigrateSubscripting=*/true, + Remapper, + CI.getFileManager(), + CI.getPreprocessor().getPreprocessingRecord(), + /*isOutputFile=*/true); +} diff --git a/lib/ARCMigrate/TransRetainReleaseDealloc.cpp b/lib/ARCMigrate/TransRetainReleaseDealloc.cpp index 7bb7b5eeea..15669ac973 100644 --- a/lib/ARCMigrate/TransRetainReleaseDealloc.cpp +++ b/lib/ARCMigrate/TransRetainReleaseDealloc.cpp @@ -21,6 +21,8 @@ #include "Internals.h" #include "clang/Sema/SemaDiagnostic.h" #include "clang/AST/ParentMap.h" +#include "clang/Lex/Lexer.h" +#include "clang/Basic/SourceManager.h" using namespace clang; using namespace arcmt; @@ -128,27 +130,105 @@ public: Transaction Trans(Pass.TA); clearDiagnostics(rec->getExprLoc()); - if (E->getMethodFamily() == OMF_release && - isRemovable(E) && isInAtFinally(E)) { + ObjCMessageExpr *Msg = E; + Expr *RecContainer = Msg; + SourceRange RecRange = rec->getSourceRange(); + checkForGCDOrXPC(Msg, RecContainer, rec, RecRange); + + if (Msg->getMethodFamily() == OMF_release && + isRemovable(RecContainer) && isInAtFinally(RecContainer)) { // Change the -release to "receiver = nil" in a finally to avoid a leak // when an exception is thrown. - Pass.TA.replace(E->getSourceRange(), rec->getSourceRange()); + Pass.TA.replace(RecContainer->getSourceRange(), RecRange); std::string str = " = "; str += getNilString(Pass.Ctx); - Pass.TA.insertAfterToken(rec->getLocEnd(), str); + Pass.TA.insertAfterToken(RecRange.getEnd(), str); return true; } - if (!hasSideEffects(E, Pass.Ctx)) { - if (tryRemoving(E)) + if (!hasSideEffects(rec, Pass.Ctx)) { + if (tryRemoving(RecContainer)) return true; } - Pass.TA.replace(E->getSourceRange(), rec->getSourceRange()); + Pass.TA.replace(RecContainer->getSourceRange(), RecRange); return true; } private: + /// \brief Check if the retain/release is due to a GCD/XPC macro that are + /// defined as: + /// + /// #define dispatch_retain(object) ({ dispatch_object_t _o = (object); _dispatch_object_validate(_o); (void)[_o retain]; }) + /// #define dispatch_release(object) ({ dispatch_object_t _o = (object); _dispatch_object_validate(_o); [_o release]; }) + /// #define xpc_retain(object) ({ xpc_object_t _o = (object); _xpc_object_validate(_o); [_o retain]; }) + /// #define xpc_release(object) ({ xpc_object_t _o = (object); _xpc_object_validate(_o); [_o release]; }) + /// + /// and return the top container which is the StmtExpr and the macro argument + /// expression. + void checkForGCDOrXPC(ObjCMessageExpr *Msg, Expr *&RecContainer, + Expr *&Rec, SourceRange &RecRange) { + SourceLocation Loc = Msg->getExprLoc(); + if (!Loc.isMacroID()) + return; + SourceManager &SM = Pass.Ctx.getSourceManager(); + StringRef MacroName = Lexer::getImmediateMacroName(Loc, SM, + Pass.Ctx.getLangOptions()); + bool isGCDOrXPC = llvm::StringSwitch<bool>(MacroName) + .Case("dispatch_retain", true) + .Case("dispatch_release", true) + .Case("xpc_retain", true) + .Case("xpc_release", true) + .Default(false); + if (!isGCDOrXPC) + return; + + StmtExpr *StmtE = 0; + Stmt *S = Msg; + while (S) { + if (StmtExpr *SE = dyn_cast<StmtExpr>(S)) { + StmtE = SE; + break; + } + S = StmtMap->getParent(S); + } + + if (!StmtE) + return; + + Stmt::child_range StmtExprChild = StmtE->children(); + if (!StmtExprChild) + return; + CompoundStmt *CompS = dyn_cast_or_null<CompoundStmt>(*StmtExprChild); + if (!CompS) + return; + + Stmt::child_range CompStmtChild = CompS->children(); + if (!CompStmtChild) + return; + DeclStmt *DeclS = dyn_cast_or_null<DeclStmt>(*CompStmtChild); + if (!DeclS) + return; + if (!DeclS->isSingleDecl()) + return; + VarDecl *VD = dyn_cast_or_null<VarDecl>(DeclS->getSingleDecl()); + if (!VD) + return; + Expr *Init = VD->getInit(); + if (!Init) + return; + + RecContainer = StmtE; + Rec = Init->IgnoreParenImpCasts(); + if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Rec)) + Rec = EWC->getSubExpr()->IgnoreParenImpCasts(); + RecRange = Rec->getSourceRange(); + if (SM.isMacroArgExpansion(RecRange.getBegin())) + RecRange.setBegin(SM.getImmediateSpellingLoc(RecRange.getBegin())); + if (SM.isMacroArgExpansion(RecRange.getEnd())) + RecRange.setEnd(SM.getImmediateSpellingLoc(RecRange.getEnd())); + } + void clearDiagnostics(SourceLocation loc) const { Pass.TA.clearDiagnostic(diag::err_arc_illegal_explicit_message, diag::err_unavailable, diff --git a/lib/Basic/DiagnosticIDs.cpp b/lib/Basic/DiagnosticIDs.cpp index f0e0c9c778..8c33a963c9 100644 --- a/lib/Basic/DiagnosticIDs.cpp +++ b/lib/Basic/DiagnosticIDs.cpp @@ -657,19 +657,6 @@ bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const { } } - // If we have any Fix-Its, make sure that all of the Fix-Its point into - // source locations that aren't macro expansions. If any point into macro - // expansions, remove all of the Fix-Its. - for (unsigned I = 0, N = Diag.FixItHints.size(); I != N; ++I) { - const FixItHint &FixIt = Diag.FixItHints[I]; - if (FixIt.RemoveRange.isInvalid() || - FixIt.RemoveRange.getBegin().isMacroID() || - FixIt.RemoveRange.getEnd().isMacroID()) { - Diag.FixItHints.clear(); - break; - } - } - // Finally, report it. Diag.Client->HandleDiagnostic((DiagnosticsEngine::Level)DiagLevel, Info); if (Diag.Client->IncludeInDiagnosticCounts()) { diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index 7b46c6040a..54d296c3ab 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -6,6 +6,7 @@ add_subdirectory(AST) add_subdirectory(Sema) add_subdirectory(CodeGen) add_subdirectory(Analysis) +add_subdirectory(Edit) add_subdirectory(Rewrite) add_subdirectory(ARCMigrate) add_subdirectory(Driver) diff --git a/lib/Driver/Action.cpp b/lib/Driver/Action.cpp index a9dc17b320..d7b4bc7053 100644 --- a/lib/Driver/Action.cpp +++ b/lib/Driver/Action.cpp @@ -27,6 +27,7 @@ const char *Action::getClassName(ActionClass AC) { case PreprocessJobClass: return "preprocessor"; case PrecompileJobClass: return "precompiler"; case AnalyzeJobClass: return "analyzer"; + case MigrateJobClass: return "migrator"; case CompileJobClass: return "compiler"; case AssembleJobClass: return "assembler"; case LinkJobClass: return "linker"; @@ -78,6 +79,12 @@ AnalyzeJobAction::AnalyzeJobAction(Action *Input, types::ID OutputType) : JobAction(AnalyzeJobClass, Input, OutputType) { } +void MigrateJobAction::anchor() {} + +MigrateJobAction::MigrateJobAction(Action *Input, types::ID OutputType) + : JobAction(MigrateJobClass, Input, OutputType) { +} + void CompileJobAction::anchor() {} CompileJobAction::CompileJobAction(Action *Input, types::ID OutputType) diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp index e71f5a6065..30b7eccc8a 100644 --- a/lib/Driver/Driver.cpp +++ b/lib/Driver/Driver.cpp @@ -141,6 +141,7 @@ const { // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler. } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || + (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || (PhaseArg = DAL.getLastArg(options::OPT__analyze, options::OPT__analyze_auto)) || (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) || @@ -1140,6 +1141,8 @@ Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, return new CompileJobAction(Input, types::TY_RewrittenObjC); } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) { return new AnalyzeJobAction(Input, types::TY_Plist); + } else if (Args.hasArg(options::OPT__migrate)) { + return new MigrateJobAction(Input, types::TY_Remap); } else if (Args.hasArg(options::OPT_emit_ast)) { return new CompileJobAction(Input, types::TY_AST); } else if (IsUsingLTO(Args)) { diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp index c0c9c504b6..b4f5d0b421 100644 --- a/lib/Driver/ToolChain.cpp +++ b/lib/Driver/ToolChain.cpp @@ -54,6 +54,7 @@ void ToolChain::configureObjCRuntime(ObjCRuntime &runtime) const { // Assume a minimal NeXT runtime. runtime.HasARC = false; runtime.HasWeak = false; + runtime.HasSubscripting = false; runtime.HasTerminate = false; return; @@ -61,6 +62,7 @@ void ToolChain::configureObjCRuntime(ObjCRuntime &runtime) const { // Assume a maximal GNU runtime. runtime.HasARC = true; runtime.HasWeak = true; + runtime.HasSubscripting = false; // to be added runtime.HasTerminate = false; // to be added return; } diff --git a/lib/Driver/ToolChains.cpp b/lib/Driver/ToolChains.cpp index 5ff82c7600..a45722315e 100644 --- a/lib/Driver/ToolChains.cpp +++ b/lib/Driver/ToolChains.cpp @@ -227,6 +227,7 @@ Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA, case Action::PreprocessJobClass: T = new tools::darwin::Preprocess(*this); break; case Action::AnalyzeJobClass: + case Action::MigrateJobClass: T = new tools::Clang(*this); break; case Action::PrecompileJobClass: case Action::CompileJobClass: @@ -1409,6 +1410,7 @@ Tool &Generic_GCC::SelectTool(const Compilation &C, case Action::PrecompileJobClass: T = new tools::gcc::Precompile(*this); break; case Action::AnalyzeJobClass: + case Action::MigrateJobClass: T = new tools::Clang(*this); break; case Action::CompileJobClass: T = new tools::gcc::Compile(*this); break; diff --git a/lib/Driver/Tools.cpp b/lib/Driver/Tools.cpp index 38f21c0882..076311a78e 100644 --- a/lib/Driver/Tools.cpp +++ b/lib/Driver/Tools.cpp @@ -1247,6 +1247,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, if (isa<AnalyzeJobAction>(JA)) { assert(JA.getType() == types::TY_Plist && "Invalid output type."); CmdArgs.push_back("-analyze"); + } else if (isa<MigrateJobAction>(JA)) { + CmdArgs.push_back("-migrate"); } else if (isa<PreprocessJobAction>(JA)) { if (Output.getType() == types::TY_Dependencies) CmdArgs.push_back("-Eonly"); @@ -1716,10 +1718,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, Args.AddLastArg(CmdArgs, options::OPT_working_directory); + bool ARCMTEnabled = false; if (!Args.hasArg(options::OPT_fno_objc_arc)) { if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check, options::OPT_ccc_arcmt_modify, options::OPT_ccc_arcmt_migrate)) { + ARCMTEnabled = true; switch (A->getOption().getID()) { default: llvm_unreachable("missed a case"); @@ -1731,7 +1735,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, break; case options::OPT_ccc_arcmt_migrate: CmdArgs.push_back("-arcmt-migrate"); - CmdArgs.push_back("-arcmt-migrate-directory"); + CmdArgs.push_back("-mt-migrate-directory"); CmdArgs.push_back(A->getValue(Args)); Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output); @@ -1741,6 +1745,25 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA, } } + if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) { + if (ARCMTEnabled) { + D.Diag(diag::err_drv_argument_not_allowed_with) + << A->getAsString(Args) << "-ccc-arcmt-migrate"; + } + CmdArgs.push_back("-mt-migrate-directory"); + CmdArgs.push_back(A->getValue(Args)); + + if (!Args.hasArg(options::OPT_objcmt_migrate_literals, + options::OPT_objcmt_migrate_subscripting)) { + // None specified, means enable them all. + CmdArgs.push_back("-objcmt-migrate-literals"); + CmdArgs.push_back("-objcmt-migrate-subscripting"); + } else { + Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals); + Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting); + } + } + // Add preprocessing options like -I, -D, etc. if we are using the // preprocessor. // diff --git a/lib/Driver/WindowsToolChain.cpp b/lib/Driver/WindowsToolChain.cpp index 8a32db2fca..70bd4f1fc3 100644 --- a/lib/Driver/WindowsToolChain.cpp +++ b/lib/Driver/WindowsToolChain.cpp @@ -59,6 +59,7 @@ Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA, case Action::PreprocessJobClass: case Action::PrecompileJobClass: case Action::AnalyzeJobClass: + case Action::MigrateJobClass: case Action::CompileJobClass: T = new tools::Clang(*this); break; case Action::AssembleJobClass: diff --git a/lib/Edit/CMakeLists.txt b/lib/Edit/CMakeLists.txt new file mode 100644 index 0000000000..c87478cf7d --- /dev/null +++ b/lib/Edit/CMakeLists.txt @@ -0,0 +1,7 @@ +set(LLVM_USED_LIBS clangBasic clangAST clangLex) + +add_clang_library(clangEdit + Commit.cpp + EditedSource.cpp + RewriteObjCFoundationAPI.cpp + ) diff --git a/lib/Edit/Commit.cpp b/lib/Edit/Commit.cpp new file mode 100644 index 0000000000..e0250ccf05 --- /dev/null +++ b/lib/Edit/Commit.cpp @@ -0,0 +1,345 @@ +//===----- Commit.cpp - A unit of edits -----------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Edit/Commit.h" +#include "clang/Edit/EditedSource.h" +#include "clang/Lex/Lexer.h" +#include "clang/Lex/PreprocessingRecord.h" +#include "clang/Basic/SourceManager.h" + +using namespace clang; +using namespace edit; + +SourceLocation Commit::Edit::getFileLocation(SourceManager &SM) const { + SourceLocation Loc = SM.getLocForStartOfFile(Offset.getFID()); + Loc = Loc.getLocWithOffset(Offset.getOffset()); + assert(Loc.isFileID()); + return Loc; +} + +CharSourceRange Commit::Edit::getFileRange(SourceManager &SM) const { + SourceLocation Loc = getFileLocation(SM); + return CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(Length)); +} + +CharSourceRange Commit::Edit::getInsertFromRange(SourceManager &SM) const { + SourceLocation Loc = SM.getLocForStartOfFile(InsertFromRangeOffs.getFID()); + Loc = Loc.getLocWithOffset(InsertFromRangeOffs.getOffset()); + assert(Loc.isFileID()); + return CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(Length)); +} + +Commit::Commit(EditedSource &Editor) + : SourceMgr(Editor.getSourceManager()), LangOpts(Editor.getLangOptions()), + PPRec(Editor.getPreprocessingRecord()), + Editor(&Editor), IsCommitable(true) { } + +bool Commit::insert(SourceLocation loc, StringRef text, + bool afterToken, bool beforePreviousInsertions) { + if (text.empty()) + return true; + + FileOffset Offs; + if ((!afterToken && !canInsert(loc, Offs)) || + ( afterToken && !canInsertAfterToken(loc, Offs, loc))) { + IsCommitable = false; + return false; + } + + addInsert(loc, Offs, text, beforePreviousInsertions); + return true; +} + +bool Commit::insertFromRange(SourceLocation loc, + CharSourceRange range, + bool afterToken, bool beforePreviousInsertions) { + FileOffset RangeOffs; + unsigned RangeLen; + if (!canRemoveRange(range, RangeOffs, RangeLen)) { + IsCommitable = false; + return false; + } + + FileOffset Offs; + if ((!afterToken && !canInsert(loc, Offs)) || + ( afterToken && !canInsertAfterToken(loc, Offs, loc))) { + IsCommitable = false; + return false; + } + + if (PPRec && + PPRec->areInDifferentConditionalDirectiveRegion(loc, range.getBegin())) { + IsCommitable = false; + return false; + } + + addInsertFromRange(loc, Offs, RangeOffs, RangeLen, beforePreviousInsertions); + return true; +} + +bool Commit::remove(CharSourceRange range) { + FileOffset Offs; + unsigned Len; + if (!canRemoveRange(range, Offs, Len)) { + IsCommitable = false; + return false; + } + + addRemove(range.getBegin(), Offs, Len); + return true; +} + +bool Commit::insertWrap(StringRef before, CharSourceRange range, + StringRef after) { + bool commitableBefore = insert(range.getBegin(), before, /*afterToken=*/false, + /*beforePreviousInsertions=*/true); + bool commitableAfter; + if (range.isTokenRange()) + commitableAfter = insertAfterToken(range.getEnd(), after); + else + commitableAfter = insert(range.getEnd(), after); + + return commitableBefore && commitableAfter; +} + +bool Commit::replace(CharSourceRange range, StringRef text) { + if (text.empty()) + return remove(range); + + FileOffset Offs; + unsigned Len; + if (!canInsert(range.getBegin(), Offs) || !canRemoveRange(range, Offs, Len)) { + IsCommitable = false; + return false; + } + + addRemove(range.getBegin(), Offs, Len); + addInsert(range.getBegin(), Offs, text, false); + return true; +} + +bool Commit::replaceWithInner(CharSourceRange range, + CharSourceRange replacementRange) { + FileOffset OuterBegin; + unsigned OuterLen; + if (!canRemoveRange(range, OuterBegin, OuterLen)) { + IsCommitable = false; + return false; + } + + FileOffset InnerBegin; + unsigned InnerLen; + if (!canRemoveRange(replacementRange, InnerBegin, InnerLen)) { + IsCommitable = false; + return false; + } + + FileOffset OuterEnd = OuterBegin.getWithOffset(OuterLen); + FileOffset InnerEnd = InnerBegin.getWithOffset(InnerLen); + if (OuterBegin.getFID() != InnerBegin.getFID() || + InnerBegin < OuterBegin || + InnerBegin > OuterEnd || + InnerEnd > OuterEnd) { + IsCommitable = false; + return false; + } + + addRemove(range.getBegin(), + OuterBegin, InnerBegin.getOffset() - OuterBegin.getOffset()); + addRemove(replacementRange.getEnd(), + InnerEnd, OuterEnd.getOffset() - InnerEnd.getOffset()); + return true; +} + +bool Commit::replaceText(SourceLocation loc, StringRef text, + StringRef replacementText) { + if (text.empty() || replacementText.empty()) + return true; + + FileOffset Offs; + unsigned Len; + if (!canReplaceText(loc, replacementText, Offs, Len)) { + IsCommitable = false; + return false; + } + + addRemove(loc, Offs, Len); + addInsert(loc, Offs, text, false); + return true; +} + +void Commit::addInsert(SourceLocation OrigLoc, FileOffset Offs, StringRef text, + bool beforePreviousInsertions) { + if (text.empty()) + return; + + Edit data; + data.Kind = Act_Insert; + data.OrigLoc = OrigLoc; + data.Offset = Offs; + data.Text = text; + data.BeforePrev = beforePreviousInsertions; + CachedEdits.push_back(data); +} + +void Commit::addInsertFromRange(SourceLocation OrigLoc, FileOffset Offs, + FileOffset RangeOffs, unsigned RangeLen, + bool beforePreviousInsertions) { + if (RangeLen == 0) + return; + + Edit data; + data.Kind = Act_InsertFromRange; + data.OrigLoc = OrigLoc; + data.Offset = Offs; + data.InsertFromRangeOffs = RangeOffs; + data.Length = RangeLen; + data.BeforePrev = beforePreviousInsertions; + CachedEdits.push_back(data); +} + +void Commit::addRemove(SourceLocation OrigLoc, + FileOffset Offs, unsigned Len) { + if (Len == 0) + return; + + Edit data; + data.Kind = Act_Remove; + data.OrigLoc = OrigLoc; + data.Offset = Offs; + data.Length = Len; + CachedEdits.push_back(data); +} + +bool Commit::canInsert(SourceLocation loc, FileOffset &offs) { + if (loc.isInvalid()) + return false; + + if (loc.isMacroID()) + isAtStartOfMacroExpansion(loc, &loc); + + const SourceManager &SM = SourceMgr; + while (SM.isMacroArgExpansion(loc)) + loc = SM.getImmediateSpellingLoc(loc); + + if (loc.isMacroID()) + if (!isAtStartOfMacroExpansion(loc, &loc)) + return false; + + if (SM.isInSystemHeader(loc)) + return false; + + std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc); + if (locInfo.first.isInvalid()) + return false; + offs = FileOffset(locInfo.first, locInfo.second); + return canInsertInOffset(loc, offs); +} + +bool Commit::canInsertAfterToken(SourceLocation loc, FileOffset &offs, + SourceLocation &AfterLoc) { + if (loc.isInvalid()) + + return false; + + SourceLocation spellLoc = SourceMgr.getSpellingLoc(loc); + unsigned tokLen = Lexer::MeasureTokenLength(spellLoc, SourceMgr, LangOpts); + AfterLoc = loc.getLocWithOffset(tokLen); + + if (loc.isMacroID()) + isAtEndOfMacroExpansion(loc, &loc); + + const SourceManager &SM = SourceMgr; + while (SM.isMacroArgExpansion(loc)) + loc = SM.getImmediateSpellingLoc(loc); + + if (loc.isMacroID()) + if (!isAtEndOfMacroExpansion(loc, &loc)) + return false; + + if (SM.isInSystemHeader(loc)) + return false; + + loc = Lexer::getLocForEndOfToken(loc, 0, SourceMgr, LangOpts); + if (loc.isInvalid()) + return false; + + std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc); + if (locInfo.first.isInvalid()) + return false; + offs = FileOffset(locInfo.first, locInfo.second); + return canInsertInOffset(loc, offs); +} + +bool Commit::canInsertInOffset(SourceLocation OrigLoc, FileOffset Offs) { + for (unsigned i = 0, e = CachedEdits.size(); i != e; ++i) { + Edit &act = CachedEdits[i]; + if (act.Kind == Act_Remove) { + if (act.Offset.getFID() == Offs.getFID() && + Offs > act.Offset && Offs < act.Offset.getWithOffset(act.Length)) + return false; // position has been removed. + } + } + + if (!Editor) + return true; + return Editor->canInsertInOffset(OrigLoc, Offs); +} + +bool Commit::canRemoveRange(CharSourceRange range, + FileOffset &Offs, unsigned &Len) { + const SourceManager &SM = SourceMgr; + range = Lexer::makeFileCharRange(range, SM, LangOpts); + if (range.isInvalid()) + return false; + + if (range.getBegin().isMacroID() || range.getEnd().isMacroID()) + return false; + if (SM.isInSystemHeader(range.getBegin()) || + SM.isInSystemHeader(range.getEnd())) + return false; + + if (PPRec && PPRec->rangeIntersectsConditionalDirective(range.getAsRange())) + return false; + + std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(range.getBegin()); + std::pair<FileID, unsigned> endInfo = SM.getDecomposedLoc(range.getEnd()); + if (beginInfo.first != endInfo.first || + beginInfo.second > endInfo.second) + return false; + + Offs = FileOffset(beginInfo.first, beginInfo.second); + Len = endInfo.second - beginInfo.second; + return true; +} + +bool Commit::canReplaceText(SourceLocation loc, StringRef text, + FileOffset &Offs, unsigned &Len) { + assert(!text.empty()); + + if (!canInsert(loc, Offs)) + return false; + + // Try to load the file buffer. + bool invalidTemp = false; + StringRef file = SourceMgr.getBufferData(Offs.getFID(), &invalidTemp); + if (invalidTemp) + return false; + + return file.substr(Offs.getOffset()).startswith(text); +} + +bool Commit::isAtStartOfMacroExpansion(SourceLocation loc, + SourceLocation *MacroBegin) const { + return Lexer::isAtStartOfMacroExpansion(loc, SourceMgr, LangOpts, MacroBegin); +} +bool Commit::isAtEndOfMacroExpansion(SourceLocation loc, + SourceLocation *MacroEnd) const { + return Lexer::isAtEndOfMacroExpansion(loc, SourceMgr, LangOpts, MacroEnd); +} diff --git a/lib/Edit/EditedSource.cpp b/lib/Edit/EditedSource.cpp new file mode 100644 index 0000000000..5b7fa4ad1b --- /dev/null +++ b/lib/Edit/EditedSource.cpp @@ -0,0 +1,329 @@ +//===----- EditedSource.cpp - Collection of source edits ------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Edit/EditedSource.h" +#include "clang/Edit/Commit.h" +#include "clang/Edit/EditsReceiver.h" +#include "clang/Lex/Lexer.h" +#include "clang/Basic/SourceManager.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/Twine.h" + +using namespace clang; +using namespace edit; + +void EditsReceiver::remove(CharSourceRange range) { + replace(range, StringRef()); +} + +StringRef EditedSource::copyString(const Twine &twine) { + llvm::SmallString<128> Data; + return copyString(twine.toStringRef(Data)); +} + +bool EditedSource::canInsertInOffset(SourceLocation OrigLoc, FileOffset Offs) { + FileEditsTy::iterator FA = getActionForOffset(Offs); + if (FA != FileEdits.end()) { + if (FA->first != Offs) + return false; // position has been removed. + } + + if (SourceMgr.isMacroArgExpansion(OrigLoc)) { + SourceLocation + DefArgLoc = SourceMgr.getImmediateExpansionRange(OrigLoc).first; + SourceLocation + ExpLoc = SourceMgr.getImmediateExpansionRange(DefArgLoc).first; + llvm::DenseMap<unsigned, SourceLocation>::iterator + I = ExpansionToArgMap.find(ExpLoc.getRawEncoding()); + if (I != ExpansionToArgMap.end() && I->second != DefArgLoc) + return false; // Trying to write in a macro argument input that has + // already been written for another argument of the same macro. + } + + return true; +} + +bool EditedSource::commitInsert(SourceLocation OrigLoc, + FileOffset Offs, StringRef text, + bool beforePreviousInsertions) { + if (!canInsertInOffset(OrigLoc, Offs)) + return false; + if (text.empty()) + return true; + + if (SourceMgr.isMacroArgExpansion(OrigLoc)) { + SourceLocation + DefArgLoc = SourceMgr.getImmediateExpansionRange(OrigLoc).first; + SourceLocation + ExpLoc = SourceMgr.getImmediateExpansionRange(DefArgLoc).first; + ExpansionToArgMap[ExpLoc.getRawEncoding()] = DefArgLoc; + } + + FileEdit &FA = FileEdits[Offs]; + if (FA.Text.empty()) { + FA.Text = copyString(text); + return true; + } + + Twine concat; + if (beforePreviousInsertions) + concat = Twine(text) + FA.Text; + else + concat = Twine(FA.Text) + text; + + FA.Text = copyString(concat); + return true; +} + +bool EditedSource::commitInsertFromRange(SourceLocation OrigLoc, + FileOffset Offs, + FileOffset InsertFromRangeOffs, unsigned Len, + bool beforePreviousInsertions) { + if (Len == 0) + return true; + + llvm::SmallString<128> StrVec; + FileOffset BeginOffs = InsertFromRangeOffs; + FileOffset EndOffs = BeginOffs.getWithOffset(Len); + FileEditsTy::iterator I = FileEdits.upper_bound(BeginOffs); + if (I != FileEdits.begin()) + --I; + + for (; I != FileEdits.end(); ++I) { + FileEdit &FA = I->second; + FileOffset B = I->first; + FileOffset E = B.getWithOffset(FA.RemoveLen); + + if (BeginOffs < E) { + if (BeginOffs >= B) { + BeginOffs = E; + ++I; + } + break; + } + } + + for (; I != FileEdits.end() && EndOffs > I->first; ++I) { + FileEdit &FA = I->second; + FileOffset B = I->first; + FileOffset E = B.getWithOffset(FA.RemoveLen); + + if (BeginOffs < B) { + bool Invalid = false; + StringRef text = getSourceText(BeginOffs, B, Invalid); + if (Invalid) + return false; + StrVec += text; + } + StrVec += FA.Text; + BeginOffs = E; + } + + if (BeginOffs < EndOffs) { + bool Invalid = false; + StringRef text = getSourceText(BeginOffs, EndOffs, Invalid); + if (Invalid) + return false; + StrVec += text; + } + + return commitInsert(OrigLoc, Offs, StrVec.str(), beforePreviousInsertions); +} + +void EditedSource::commitRemove(SourceLocation OrigLoc, + FileOffset BeginOffs, unsigned Len) { + if (Len == 0) + return; + + FileOffset EndOffs = BeginOffs.getWithOffset(Len); + FileEditsTy::iterator I = FileEdits.upper_bound(BeginOffs); + if (I != FileEdits.begin()) + --I; + + for (; I != FileEdits.end(); ++I) { + FileEdit &FA = I->second; + FileOffset B = I->first; + FileOffset E = B.getWithOffset(FA.RemoveLen); + + if (BeginOffs < E) + break; + } + + FileOffset TopBegin, TopEnd; + FileEdit *TopFA = 0; + + if (I == FileEdits.end()) { + FileEditsTy::iterator + NewI = FileEdits.insert(I, std::make_pair(BeginOffs, FileEdit())); + NewI->second.RemoveLen = Len; + return; + } + + FileEdit &FA = I->second; + FileOffset B = I->first; + FileOffset E = B.getWithOffset(FA.RemoveLen); + if (BeginOffs < B) { + FileEditsTy::iterator + NewI = FileEdits.insert(I, std::make_pair(BeginOffs, FileEdit())); + TopBegin = BeginOffs; + TopEnd = EndOffs; + TopFA = &NewI->second; + TopFA->RemoveLen = Len; + } else { + TopBegin = B; + TopEnd = E; + TopFA = &I->second; + if (TopEnd >= EndOffs) + return; + unsigned diff = EndOffs.getOffset() - TopEnd.getOffset(); + TopEnd = EndOffs; + TopFA->RemoveLen += diff; + ++I; + } + + while (I != FileEdits.end()) { + FileEdit &FA = I->second; + FileOffset B = I->first; + FileOffset E = B.getWithOffset(FA.RemoveLen); + + if (B >= TopEnd) + break; + + if (E <= TopEnd) { + FileEdits.erase(I++); + continue; + } + + if (B < TopEnd) { + unsigned diff = E.getOffset() - TopEnd.getOffset(); + TopEnd = E; + TopFA->RemoveLen += diff; + FileEdits.erase(I); + } + + break; + } +} + +bool EditedSource::commit(const Commit &commit) { + if (!commit.isCommitable()) + return false; + + for (edit::Commit::edit_iterator + I = commit.edit_begin(), E = commit.edit_end(); I != E; ++I) { + const edit::Commit::Edit &edit = *I; + switch (edit.Kind) { + case edit::Commit::Act_Insert: + commitInsert(edit.OrigLoc, edit.Offset, edit.Text, edit.BeforePrev); + break; + case edit::Commit::Act_InsertFromRange: + commitInsertFromRange(edit.OrigLoc, edit.Offset, + edit.InsertFromRangeOffs, edit.Length, + edit.BeforePrev); + break; + case edit::Commit::Act_Remove: + commitRemove(edit.OrigLoc, edit.Offset, edit.Length); + break; + } + } + + return true; +} + +static void applyRewrite(EditsReceiver &receiver, + StringRef text, FileOffset offs, unsigned len, + const SourceManager &SM) { + assert(!offs.getFID().isInvalid()); + SourceLocation Loc = SM.getLocForStartOfFile(offs.getFID()); + Loc = Loc.getLocWithOffset(offs.getOffset()); + assert(Loc.isFileID()); + CharSourceRange range = CharSourceRange::getCharRange(Loc, + Loc.getLocWithOffset(len)); + + if (text.empty()) { + assert(len); + receiver.remove(range); + return; + } + + if (len) + receiver.replace(range, text); + else + receiver.insert(Loc, text); +} + +void EditedSource::applyRewrites(EditsReceiver &receiver) { + llvm::SmallString<128> StrVec; + FileOffset CurOffs, CurEnd; + unsigned CurLen; + + if (FileEdits.empty()) + return; + + FileEditsTy::iterator I = FileEdits.begin(); + CurOffs = I->first; + StrVec = I->second.Text; + CurLen = I->second.RemoveLen; + CurEnd = CurOffs.getWithOffset(CurLen); + ++I; + + for (FileEditsTy::iterator E = FileEdits.end(); I != E; ++I) { + FileOffset offs = I->first; + FileEdit act = I->second; + assert(offs >= CurEnd); + + if (offs == CurEnd) { + StrVec += act.Text; + CurLen += act.RemoveLen; + CurEnd.getWithOffset(act.RemoveLen); + continue; + } + + applyRewrite(receiver, StrVec.str(), CurOffs, CurLen, SourceMgr); + CurOffs = offs; + StrVec = act.Text; + CurLen = act.RemoveLen; + CurEnd = CurOffs.getWithOffset(CurLen); + } + + applyRewrite(receiver, StrVec.str(), CurOffs, CurLen, SourceMgr); +} + +void EditedSource::clearRewrites() { + FileEdits.clear(); + StrAlloc.Reset(); +} + +StringRef EditedSource::getSourceText(FileOffset BeginOffs, FileOffset EndOffs, + bool &Invalid) { + assert(BeginOffs.getFID() == EndOffs.getFID()); + assert(BeginOffs <= EndOffs); + SourceLocation BLoc = SourceMgr.getLocForStartOfFile(BeginOffs.getFID()); + BLoc = BLoc.getLocWithOffset(BeginOffs.getOffset()); + assert(BLoc.isFileID()); + SourceLocation + ELoc = BLoc.getLocWithOffset(EndOffs.getOffset() - BeginOffs.getOffset()); + return Lexer::getSourceText(CharSourceRange::getCharRange(BLoc, ELoc), + SourceMgr, LangOpts, &Invalid); +} + +EditedSource::FileEditsTy::iterator +EditedSource::getActionForOffset(FileOffset Offs) { + FileEditsTy::iterator I = FileEdits.upper_bound(Offs); + if (I == FileEdits.begin()) + return FileEdits.end(); + --I; + FileEdit &FA = I->second; + FileOffset B = I->first; + FileOffset E = B.getWithOffset(FA.RemoveLen); + if (Offs >= B && Offs < E) + return I; + + return FileEdits.end(); +} diff --git a/lib/Edit/Makefile b/lib/Edit/Makefile new file mode 100644 index 0000000000..92a67ebc82 --- /dev/null +++ b/lib/Edit/Makefile @@ -0,0 +1,14 @@ +##===- clang/lib/Edit/Makefile -----------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +CLANG_LEVEL := ../.. +LIBRARYNAME := clangEdit + +include $(CLANG_LEVEL)/Makefile + diff --git a/lib/Edit/RewriteObjCFoundationAPI.cpp b/lib/Edit/RewriteObjCFoundationAPI.cpp new file mode 100644 index 0000000000..a092768034 --- /dev/null +++ b/lib/Edit/RewriteObjCFoundationAPI.cpp @@ -0,0 +1,589 @@ +//===--- RewriteObjCFoundationAPI.cpp - Foundation API Rewriter -----------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// Rewrites legacy method calls to modern syntax. +// +//===----------------------------------------------------------------------===// + +#include "clang/Edit/Rewriters.h" +#include "clang/Edit/Commit.h" +#include "clang/Lex/Lexer.h" +#include "clang/AST/ExprObjC.h" +#include "clang/AST/ExprCXX.h" +#include "clang/AST/NSAPI.h" + +using namespace clang; +using namespace edit; + +static bool checkForLiteralCreation(const ObjCMessageExpr *Msg, + IdentifierInfo *&ClassId) { + if (!Msg || Msg->isImplicit() || !Msg->getMethodDecl()) + return false; + + const ObjCInterfaceDecl *Receiver = Msg->getReceiverInterface(); + if (!Receiver) + return false; + ClassId = Receiver->getIdentifier(); + + if (Msg->getReceiverKind() == ObjCMessageExpr::Class) + return true; + + return false; +} + +//===----------------------------------------------------------------------===// +// rewriteObjCRedundantCallWithLiteral. +//===----------------------------------------------------------------------===// + +bool edit::rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit) { + IdentifierInfo *II = 0; + if (!checkForLiteralCreation(Msg, II)) + return false; + if (Msg->getNumArgs() != 1) + return false; + + const Expr *Arg = Msg->getArg(0)->IgnoreParenImpCasts(); + Selector Sel = Msg->getSelector(); + + if ((isa<ObjCStringLiteral>(Arg) && + NS.getNSClassId(NSAPI::ClassId_NSString) == II && + NS.getNSStringSelector(NSAPI::NSStr_stringWithString) == Sel) || + + (isa<ObjCArrayLiteral>(Arg) && + NS.getNSClassId(NSAPI::ClassId_NSArray) == II && + NS.getNSArraySelector(NSAPI::NSArr_arrayWithArray) == Sel) || + + (isa<ObjCDictionaryLiteral>(Arg) && + NS.getNSClassId(NSAPI::ClassId_NSDictionary) == II && + NS.getNSDictionarySelector( + NSAPI::NSDict_dictionaryWithDictionary) == Sel)) { + + commit.replaceWithInner(Msg->getSourceRange(), + Msg->getArg(0)->getSourceRange()); + return true; + } + + return false; +} + +//===----------------------------------------------------------------------===// +// rewriteToObjCSubscriptSyntax. +//===----------------------------------------------------------------------===// + +static void maybePutParensOnReceiver(const Expr *Receiver, Commit &commit) { + Receiver = Receiver->IgnoreImpCasts(); + if (isa<BinaryOperator>(Receiver) || isa<UnaryOperator>(Receiver)) { + SourceRange RecRange = Receiver->getSourceRange(); + commit.insertWrap("(", RecRange, ")"); + } +} + +static bool rewriteToSubscriptGet(const ObjCMessageExpr *Msg, Commit &commit) { + if (Msg->getNumArgs() != 1) + return false; + const Expr *Rec = Msg->getInstanceReceiver(); + if (!Rec) + return false; + + SourceRange MsgRange = Msg->getSourceRange(); + SourceRange RecRange = Rec->getSourceRange(); + SourceRange ArgRange = Msg->getArg(0)->getSourceRange(); + + commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(), + ArgRange.getBegin()), + CharSourceRange::getTokenRange(RecRange)); + commit.replaceWithInner(SourceRange(ArgRange.getBegin(), MsgRange.getEnd()), + ArgRange); + commit.insertWrap("[", ArgRange, "]"); + maybePutParensOnReceiver(Rec, commit); + return true; +} + +static bool rewriteToArraySubscriptSet(const ObjCMessageExpr *Msg, + Commit &commit) { + if (Msg->getNumArgs() != 2) + return false; + const Expr *Rec = Msg->getInstanceReceiver(); + if (!Rec) + return false; + + SourceRange MsgRange = Msg->getSourceRange(); + SourceRange RecRange = Rec->getSourceRange(); + SourceRange Arg0Range = Msg->getArg(0)->getSourceRange(); + SourceRange Arg1Range = Msg->getArg(1)->getSourceRange(); + + commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(), + Arg0Range.getBegin()), + CharSourceRange::getTokenRange(RecRange)); + commit.replaceWithInner(CharSourceRange::getCharRange(Arg0Range.getBegin(), + Arg1Range.getBegin()), + CharSourceRange::getTokenRange(Arg0Range)); + commit.replaceWithInner(SourceRange(Arg1Range.getBegin(), MsgRange.getEnd()), + Arg1Range); + commit.insertWrap("[", CharSourceRange::getCharRange(Arg0Range.getBegin(), + Arg1Range.getBegin()), + "] = "); + maybePutParensOnReceiver(Rec, commit); + return true; +} + +static bool rewriteToDictionarySubscriptSet(const ObjCMessageExpr *Msg, + Commit &commit) { + if (Msg->getNumArgs() != 2) + return false; + const Expr *Rec = Msg->getInstanceReceiver(); + if (!Rec) + return false; + + SourceRange MsgRange = Msg->getSourceRange(); + SourceRange RecRange = Rec->getSourceRange(); + SourceRange Arg0Range = Msg->getArg(0)->getSourceRange(); + SourceRange Arg1Range = Msg->getArg(1)->getSourceRange(); + + SourceLocation LocBeforeVal = Arg0Range.getBegin(); + commit.insertBefore(LocBeforeVal, "] = "); + commit.insertFromRange(LocBeforeVal, Arg1Range, /*afterToken=*/false, + /*beforePreviousInsertions=*/true); + commit.insertBefore(LocBeforeVal, "["); + commit.replaceWithInner(CharSourceRange::getCharRange(MsgRange.getBegin(), + Arg0Range.getBegin()), + CharSourceRange::getTokenRange(RecRange)); + commit.replaceWithInner(SourceRange(Arg0Range.getBegin(), MsgRange.getEnd()), + Arg0Range); + maybePutParensOnReceiver(Rec, commit); + return true; +} + +bool edit::rewriteToObjCSubscriptSyntax(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit) { + if (!Msg || Msg->isImplicit() || + Msg->getReceiverKind() != ObjCMessageExpr::Instance) + return false; + const ObjCMethodDecl *Method = Msg->getMethodDecl(); + if (!Method) + return false; + + const ObjCInterfaceDecl * + IFace = NS.getASTContext().getObjContainingInterface( + const_cast<ObjCMethodDecl *>(Method)); + if (!IFace) + return false; + IdentifierInfo *II = IFace->getIdentifier(); + Selector Sel = Msg->getSelector(); + + if ((II == NS.getNSClassId(NSAPI::ClassId_NSArray) && + Sel == NS.getNSArraySelector(NSAPI::NSArr_objectAtIndex)) || + (II == NS.getNSClassId(NSAPI::ClassId_NSDictionary) && + Sel == NS.getNSDictionarySelector(NSAPI::NSDict_objectForKey))) + return rewriteToSubscriptGet(Msg, commit); + + if (Msg->getNumArgs() != 2) + return false; + + if (II == NS.getNSClassId(NSAPI::ClassId_NSMutableArray) && + Sel == NS.getNSArraySelector(NSAPI::NSMutableArr_replaceObjectAtIndex)) + return rewriteToArraySubscriptSet(Msg, commit); + + if (II == NS.getNSClassId(NSAPI::ClassId_NSMutableDictionary) && + Sel == NS.getNSDictionarySelector(NSAPI::NSMutableDict_setObjectForKey)) + return rewriteToDictionarySubscriptSet(Msg, commit); + + return false; +} + +//===----------------------------------------------------------------------===// +// rewriteToObjCLiteralSyntax. +//===----------------------------------------------------------------------===// + +static bool rewriteToArrayLiteral(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit); +static bool rewriteToDictionaryLiteral(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit); +static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit); + +bool edit::rewriteToObjCLiteralSyntax(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit) { + IdentifierInfo *II = 0; + if (!checkForLiteralCreation(Msg, II)) + return false; + + if (II == NS.getNSClassId(NSAPI::ClassId_NSArray)) + return rewriteToArrayLiteral(Msg, NS, commit); + if (II == NS.getNSClassId(NSAPI::ClassId_NSDictionary)) + return rewriteToDictionaryLiteral(Msg, NS, commit); + if (II == NS.getNSClassId(NSAPI::ClassId_NSNumber)) + return rewriteToNumberLiteral(Msg, NS, commit); + + return false; +} + +//===----------------------------------------------------------------------===// +// rewriteToArrayLiteral. +//===----------------------------------------------------------------------===// + +static bool rewriteToArrayLiteral(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit) { + Selector Sel = Msg->getSelector(); + SourceRange MsgRange = Msg->getSourceRange(); + + if (Sel == NS.getNSArraySelector(NSAPI::NSArr_array)) { + if (Msg->getNumArgs() != 0) + return false; + commit.replace(MsgRange, "@[]"); + return true; + } + + if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObject)) { + if (Msg->getNumArgs() != 1) + return false; + SourceRange ArgRange = Msg->getArg(0)->getSourceRange(); + commit.replaceWithInner(MsgRange, ArgRange); + commit.insertWrap("@[", ArgRange, "]"); + return true; + } + + if (Sel == NS.getNSArraySelector(NSAPI::NSArr_arrayWithObjects)) { + if (Msg->getNumArgs() == 0) + return false; + const Expr *SentinelExpr = Msg->getArg(Msg->getNumArgs() - 1); + if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr)) + return false; + + if (Msg->getNumArgs() == 1) { + commit.replace(MsgRange, "@[]"); + return true; + } + SourceRange ArgRange(Msg->getArg(0)->getLocStart(), + Msg->getArg(Msg->getNumArgs()-2)->getLocEnd()); + commit.replaceWithInner(MsgRange, ArgRange); + commit.insertWrap("@[", ArgRange, "]"); + return true; + } + + return false; +} + +//===----------------------------------------------------------------------===// +// rewriteToDictionaryLiteral. +//===----------------------------------------------------------------------===// + +static bool rewriteToDictionaryLiteral(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit) { + Selector Sel = Msg->getSelector(); + SourceRange MsgRange = Msg->getSourceRange(); + + if (Sel == NS.getNSDictionarySelector(NSAPI::NSDict_dictionary)) { + if (Msg->getNumArgs() != 0) + return false; + commit.replace(MsgRange, "@{}"); + return true; + } + + if (Sel == NS.getNSDictionarySelector( + NSAPI::NSDict_dictionaryWithObjectForKey)) { + if (Msg->getNumArgs() != 2) + return false; + SourceRange ValRange = Msg->getArg(0)->getSourceRange(); + SourceRange KeyRange = Msg->getArg(1)->getSourceRange(); + // Insert key before the value. + commit.insertBefore(ValRange.getBegin(), ": "); + commit.insertFromRange(ValRange.getBegin(), + CharSourceRange::getTokenRange(KeyRange), + /*afterToken=*/false, /*beforePreviousInsertions=*/true); + commit.insertBefore(ValRange.getBegin(), "@{"); + commit.insertAfterToken(ValRange.getEnd(), "}"); + commit.replaceWithInner(MsgRange, ValRange); + return true; + } + + if (Sel == NS.getNSDictionarySelector( + NSAPI::NSDict_dictionaryWithObjectsAndKeys)) { + if (Msg->getNumArgs() % 2 != 1) + return false; + unsigned SentinelIdx = Msg->getNumArgs() - 1; + const Expr *SentinelExpr = Msg->getArg(SentinelIdx); + if (!NS.getASTContext().isSentinelNullExpr(SentinelExpr)) + return false; + + if (Msg->getNumArgs() == 1) { + commit.replace(MsgRange, "@{}"); + return true; + } + + for (unsigned i = 0; i < SentinelIdx; i += 2) { + SourceRange ValRange = Msg->getArg(i)->getSourceRange(); + SourceRange KeyRange = Msg->getArg(i+1)->getSourceRange(); + // Insert value after key. + commit.insertAfterToken(KeyRange.getEnd(), ": "); + commit.insertFromRange(KeyRange.getEnd(), ValRange, /*afterToken=*/true); + commit.remove(CharSourceRange::getCharRange(ValRange.getBegin(), + KeyRange.getBegin())); + } + // Range of arguments up until and including the last key. + // The sentinel and first value are cut off, the value will move after the + // key. + SourceRange ArgRange(Msg->getArg(1)->getLocStart(), + Msg->getArg(SentinelIdx-1)->getLocEnd()); + commit.insertWrap("@{", ArgRange, "}"); + commit.replaceWithInner(MsgRange, ArgRange); + return true; + } + + return false; +} + +//===----------------------------------------------------------------------===// +// rewriteToNumberLiteral. +//===----------------------------------------------------------------------===// + +static bool rewriteToCharLiteral(const ObjCMessageExpr *Msg, + const CharacterLiteral *Arg, + const NSAPI &NS, Commit &commit) { + if (Arg->getKind() != CharacterLiteral::Ascii) + return false; + if (NS.isNSNumberLiteralSelector(NSAPI::NSNumberWithChar, + Msg->getSelector())) { + SourceRange ArgRange = Arg->getSourceRange(); + commit.replaceWithInner(Msg->getSourceRange(), ArgRange); + commit.insert(ArgRange.getBegin(), "@"); + return true; + } + + return false; +} + +static bool rewriteToBoolLiteral(const ObjCMessageExpr *Msg, + const Expr *Arg, + const NSAPI &NS, Commit &commit) { + if (NS.isNSNumberLiteralSelector(NSAPI::NSNumberWithBool, + Msg->getSelector())) { + SourceRange ArgRange = Arg->getSourceRange(); + commit.replaceWithInner(Msg->getSourceRange(), ArgRange); + commit.insert(ArgRange.getBegin(), "@"); + return true; + } + + return false; +} + +namespace { + +struct LiteralInfo { + bool Hex, Octal; + StringRef U, F, L, LL; + CharSourceRange WithoutSuffRange; +}; + +} + +static bool getLiteralInfo(SourceRange literalRange, + bool isFloat, bool isIntZero, + ASTContext &Ctx, LiteralInfo &Info) { + if (literalRange.getBegin().isMacroID() || + literalRange.getEnd().isMacroID()) + return false; + StringRef text = Lexer::getSourceText( + CharSourceRange::getTokenRange(literalRange), + Ctx.getSourceManager(), Ctx.getLangOptions()); + if (text.empty()) + return false; + + llvm::Optional<bool> UpperU, UpperL; + bool UpperF = false; + + struct Suff { + static bool has(StringRef suff, StringRef &text) { + if (text.endswith(suff)) { + text = text.substr(0, text.size()-suff.size()); + return true; + } + return false; + } + }; + + while (1) { + if (Suff::has("u", text)) { + UpperU = false; + } else if (Suff::has("U", text)) { + UpperU = true; + } else if (Suff::has("ll", text)) { + UpperL = false; + } else if (Suff::has("LL", text)) { + UpperL = true; + } else if (Suff::has("l", text)) { + UpperL = false; + } else if (Suff::has("L", text)) { + UpperL = true; + } else if (isFloat && Suff::has("f", text)) { + UpperF = false; + } else if (isFloat && Suff::has("F", text)) { + UpperF = true; + } else + break; + } + + if (!UpperU.hasValue() && !UpperL.hasValue()) + UpperU = UpperL = true; + else if (UpperU.hasValue() && !UpperL.hasValue()) + UpperL = UpperU; + else if (UpperL.hasValue() && !UpperU.hasValue()) + UpperU = UpperL; + + Info.U = *UpperU ? "U" : "u"; + Info.L = *UpperL ? "L" : "l"; + Info.LL = *UpperL ? "LL" : "ll"; + Info.F = UpperF ? "F" : "f"; + + Info.Hex = Info.Octal = false; + if (text.startswith("0x")) + Info.Hex = true; + else if (!isFloat && !isIntZero && text.startswith("0")) + Info.Octal = true; + + SourceLocation B = literalRange.getBegin(); + Info.WithoutSuffRange = + CharSourceRange::getCharRange(B, B.getLocWithOffset(text.size())); + return true; +} + +static bool rewriteToNumberLiteral(const ObjCMessageExpr *Msg, + const NSAPI &NS, Commit &commit) { + if (Msg->getNumArgs() != 1) + return false; + + const Expr *Arg = Msg->getArg(0)->IgnoreParenImpCasts(); + if (const CharacterLiteral *CharE = dyn_cast<CharacterLiteral>(Arg)) + return rewriteToCharLiteral(Msg, CharE, NS, commit); + if (const ObjCBoolLiteralExpr *BE = dyn_cast<ObjCBoolLiteralExpr>(Arg)) + return rewriteToBoolLiteral(Msg, BE, NS, commit); + if (const CXXBoolLiteralExpr *BE = dyn_cast<CXXBoolLiteralExpr>(Arg)) + return rewriteToBoolLiteral(Msg, BE, NS, commit); + + const Expr *literalE = Arg; + if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(literalE)) { + if (UOE->getOpcode() == UO_Plus || UOE->getOpcode() == UO_Minus) + literalE = UOE->getSubExpr(); + } + + // Only integer and floating literals; non-literals or imaginary literal + // cannot be rewritten. + if (!isa<IntegerLiteral>(literalE) && !isa<FloatingLiteral>(literalE)) + return false; + + ASTContext &Ctx = NS.getASTContext(); + Selector Sel = Msg->getSelector(); + llvm::Optional<NSAPI::NSNumberLiteralMethodKind> + MKOpt = NS.getNSNumberLiteralMethodKind(Sel); + if (!MKOpt) + return false; + NSAPI::NSNumberLiteralMethodKind MK = *MKOpt; + + bool CallIsInteger = false, CallIsUnsigned = false; + bool CallIsLong = false, CallIsLongLong = false; + bool CallIsFloating = false, CallIsDouble = false; + + switch (MK) { + // We cannot have these calls with int/float literals. + case NSAPI::NSNumberWithChar: + case NSAPI::NSNumberWithUnsignedChar: + case NSAPI::NSNumberWithShort: + case NSAPI::NSNumberWithUnsignedShort: + case NSAPI::NSNumberWithBool: + return false; + + case NSAPI::NSNumberWithUnsignedInt: + case NSAPI::NSNumberWithUnsignedInteger: + CallIsUnsigned = true; + case NSAPI::NSNumberWithInt: + case NSAPI::NSNumberWithInteger: + CallIsInteger = true; + break; + + case NSAPI::NSNumberWithUnsignedLong: + CallIsUnsigned = true; + case NSAPI::NSNumberWithLong: + CallIsInteger = true; CallIsLong = true; + break; + + case NSAPI::NSNumberWithUnsignedLongLong: + CallIsUnsigned = true; + case NSAPI::NSNumberWithLongLong: + CallIsInteger = true; CallIsLongLong = true; + break; + + case NSAPI::NSNumberWithDouble: + CallIsDouble = true; + case NSAPI::NSNumberWithFloat: + CallIsFloating = true; + break; + } + + SourceRange ArgRange = Arg->getSourceRange(); + QualType ArgTy = Arg->getType(); + QualType CallTy = Msg->getArg(0)->getType(); + + // Check for the easy case, the literal maps directly to the call. + if (Ctx.hasSameType(ArgTy, CallTy)) { + commit.replaceWithInner(Msg->getSourceRange(), ArgRange); + commit.insert(ArgRange.getBegin(), "@"); + return true; + } + + // We will need to modify the literal suffix to get the same type as the call. + // Don't even try if it came from a macro. + if (ArgRange.getBegin().isMacroID()) + return false; + + bool LitIsFloat = ArgTy->isFloatingType(); + // For a float passed to integer call, don't try rewriting. It is difficult + // and a very uncommon case anyway. + if (LitIsFloat && !CallIsFloating) + return false; + + // Try to modify the literal make it the same type as the method call. + // -Modify the suffix, and/or + // -Change integer to float + + LiteralInfo LitInfo; + bool isIntZero = false; + if (const IntegerLiteral *IntE = dyn_cast<IntegerLiteral>(literalE)) + isIntZero = !IntE->getValue().getBoolValue(); + if (!getLiteralInfo(ArgRange, LitIsFloat, isIntZero, Ctx, LitInfo)) + return false; + + // Not easy to do int -> float with hex/octal and uncommon anyway. + if (!LitIsFloat && CallIsFloating && (LitInfo.Hex || LitInfo.Octal)) + return false; + + SourceLocation LitB = LitInfo.WithoutSuffRange.getBegin(); + SourceLocation LitE = LitInfo.WithoutSuffRange.getEnd(); + + commit.replaceWithInner(CharSourceRange::getTokenRange(Msg->getSourceRange()), + LitInfo.WithoutSuffRange); + commit.insert(LitB, "@"); + + if (!LitIsFloat && CallIsFloating) + commit.insert(LitE, ".0"); + + if (CallIsFloating) { + if (!CallIsDouble) + commit.insert(LitE, LitInfo.F); + } else { + if (CallIsUnsigned) + commit.insert(LitE, LitInfo.U); + + if (CallIsLong) + commit.insert(LitE, LitInfo.L); + else if (CallIsLongLong) + commit.insert(LitE, LitInfo.LL); + } + return true; +} diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp index 43ac475211..9391eea32d 100644 --- a/lib/Frontend/CompilerInvocation.cpp +++ b/lib/Frontend/CompilerInvocation.cpp @@ -428,6 +428,7 @@ static const char *getActionName(frontend::ActionKind Kind) { case frontend::RewriteObjC: return "-rewrite-objc"; case frontend::RewriteTest: return "-rewrite-test"; case frontend::RunAnalysis: return "-analyze"; + case frontend::MigrateSource: return "-migrate"; case frontend::RunPreprocessorOnly: return "-Eonly"; } @@ -483,9 +484,9 @@ static void FrontendOptsToArgs(const FrontendOptions &Opts, Res.push_back("-arcmt-migrate"); break; } - if (!Opts.ARCMTMigrateDir.empty()) { - Res.push_back("-arcmt-migrate-directory"); - Res.push_back(Opts.ARCMTMigrateDir); + if (!Opts.MTMigrateDir.empty()) { + Res.push_back("-mt-migrate-directory"); + Res.push_back(Opts.MTMigrateDir); } if (!Opts.ARCMTMigrateReportOut.empty()) { Res.push_back("-arcmt-migrate-report-output"); @@ -494,6 +495,11 @@ static void FrontendOptsToArgs(const FrontendOptions &Opts, if (Opts.ARCMTMigrateEmitARCErrors) Res.push_back("-arcmt-migrate-emit-errors"); + if (Opts.ObjCMTAction & ~FrontendOptions::ObjCMT_Literals) + Res.push_back("-objcmt-migrate-literals"); + if (Opts.ObjCMTAction & ~FrontendOptions::ObjCMT_Subscripting) + Res.push_back("-objcmt-migrate-subscripting"); + bool NeedLang = false; for (unsigned i = 0, e = Opts.Inputs.size(); i != e; ++i) if (FrontendOptions::getInputKindForExtension(Opts.Inputs[i].File) != @@ -828,6 +834,8 @@ static void LangOptsToArgs(const LangOptions &Opts, Res.push_back("-fdebugger-support"); if (Opts.DebuggerCastResultToId) Res.push_back("-fdebugger-cast-result-to-id"); + if (Opts.DebuggerObjCLiteral) + Res.push_back("-fdebugger-objc-literal"); if (Opts.DelayedTemplateParsing) Res.push_back("-fdelayed-template-parsing"); if (Opts.Deprecated) @@ -1376,6 +1384,8 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, Opts.ProgramAction = frontend::RewriteTest; break; case OPT_analyze: Opts.ProgramAction = frontend::RunAnalysis; break; + case OPT_migrate: + Opts.ProgramAction = frontend::MigrateSource; break; case OPT_Eonly: Opts.ProgramAction = frontend::RunPreprocessorOnly; break; } @@ -1432,7 +1442,6 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp); Opts.OverrideRecordLayoutsFile = Args.getLastArgValue(OPT_foverride_record_layout_EQ); - Opts.ARCMTAction = FrontendOptions::ARCMT_None; if (const Arg *A = Args.getLastArg(OPT_arcmt_check, OPT_arcmt_modify, OPT_arcmt_migrate)) { @@ -1450,12 +1459,23 @@ static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, break; } } - Opts.ARCMTMigrateDir = Args.getLastArgValue(OPT_arcmt_migrate_directory); + Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory); Opts.ARCMTMigrateReportOut = Args.getLastArgValue(OPT_arcmt_migrate_report_output); Opts.ARCMTMigrateEmitARCErrors = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors); + if (Args.hasArg(OPT_objcmt_migrate_literals)) + Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals; + if (Args.hasArg(OPT_objcmt_migrate_subscripting)) + Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting; + + if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && + Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { + Diags.Report(diag::err_drv_argument_not_allowed_with) + << "ARC migration" << "ObjC migration"; + } + InputKind DashX = IK_None; if (const Arg *A = Args.getLastArg(OPT_x)) { DashX = llvm::StringSwitch<InputKind>(A->getValue(Args)) @@ -1899,6 +1919,7 @@ static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype); Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support); Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id); + Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal); Opts.AddressSanitizer = Args.hasArg(OPT_faddress_sanitizer); Opts.ThreadSanitizer = Args.hasArg(OPT_fthread_sanitizer); Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack); diff --git a/lib/Frontend/DiagnosticRenderer.cpp b/lib/Frontend/DiagnosticRenderer.cpp index 29f9ed5a7d..6c3bb1d695 100644 --- a/lib/Frontend/DiagnosticRenderer.cpp +++ b/lib/Frontend/DiagnosticRenderer.cpp @@ -12,6 +12,9 @@ #include "clang/Basic/SourceManager.h" #include "clang/Frontend/DiagnosticOptions.h" #include "clang/Lex/Lexer.h" +#include "clang/Edit/EditedSource.h" +#include "clang/Edit/Commit.h" +#include "clang/Edit/EditsReceiver.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/ErrorHandling.h" @@ -127,6 +130,54 @@ DiagnosticRenderer::DiagnosticRenderer(const SourceManager &SM, DiagnosticRenderer::~DiagnosticRenderer() {} +namespace { + +class FixitReceiver : public edit::EditsReceiver { + SmallVectorImpl<FixItHint> &MergedFixits; + +public: + FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits) + : MergedFixits(MergedFixits) { } + virtual void insert(SourceLocation loc, StringRef text) { + MergedFixits.push_back(FixItHint::CreateInsertion(loc, text)); + } + virtual void replace(CharSourceRange range, StringRef text) { + MergedFixits.push_back(FixItHint::CreateReplacement(range, text)); + } +}; + +} + +static void mergeFixits(ArrayRef<FixItHint> FixItHints, + const SourceManager &SM, const LangOptions &LangOpts, + SmallVectorImpl<FixItHint> &MergedFixits) { + edit::Commit commit(SM, LangOpts); + for (ArrayRef<FixItHint>::const_iterator + I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) { + const FixItHint &Hint = *I; + if (Hint.CodeToInsert.empty()) { + if (Hint.InsertFromRange.isValid()) + commit.insertFromRange(Hint.RemoveRange.getBegin(), + Hint.InsertFromRange, /*afterToken=*/false, + Hint.BeforePreviousInsertions); + else + commit.remove(Hint.RemoveRange); + } else { + if (Hint.RemoveRange.isTokenRange() || + Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd()) + commit.replace(Hint.RemoveRange, Hint.CodeToInsert); + else + commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert, + /*afterToken=*/false, Hint.BeforePreviousInsertions); + } + } + + edit::EditedSource Editor(SM, LangOpts); + if (Editor.commit(commit)) { + FixitReceiver Rec(MergedFixits); + Editor.applyRewrites(Rec); + } +} void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc, DiagnosticsEngine::Level Level, @@ -152,6 +203,12 @@ void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc, SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(), Ranges.end()); + llvm::SmallVector<FixItHint, 8> MergedFixits; + if (!FixItHints.empty()) { + mergeFixits(FixItHints, SM, LangOpts, MergedFixits); + FixItHints = MergedFixits; + } + for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) diff --git a/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/lib/FrontendTool/ExecuteCompilerInvocation.cpp index 0841b2cef8..07d2b8d19f 100644 --- a/lib/FrontendTool/ExecuteCompilerInvocation.cpp +++ b/lib/FrontendTool/ExecuteCompilerInvocation.cpp @@ -76,6 +76,7 @@ static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) { case RewriteObjC: return new RewriteObjCAction(); case RewriteTest: return new RewriteTestAction(); case RunAnalysis: return new ento::AnalysisAction(); + case MigrateSource: return new arcmt::MigrateSourceAction(); case RunPreprocessorOnly: return new PreprocessOnlyAction(); } llvm_unreachable("Invalid program action!"); @@ -105,12 +106,18 @@ static FrontendAction *CreateFrontendAction(CompilerInstance &CI) { break; case FrontendOptions::ARCMT_Migrate: Act = new arcmt::MigrateAction(Act, - FEOpts.ARCMTMigrateDir, + FEOpts.MTMigrateDir, FEOpts.ARCMTMigrateReportOut, FEOpts.ARCMTMigrateEmitARCErrors); break; } + if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) { + Act = new arcmt::ObjCMigrateAction(Act, FEOpts.MTMigrateDir, + FEOpts.ObjCMTAction & ~FrontendOptions::ObjCMT_Literals, + FEOpts.ObjCMTAction & ~FrontendOptions::ObjCMT_Subscripting); + } + // If there are any AST files to merge, create a frontend action // adaptor to perform the merge. if (!FEOpts.ASTMergeFiles.empty()) diff --git a/lib/Makefile b/lib/Makefile index 74df7abcef..69c5cd5d83 100755 --- a/lib/Makefile +++ b/lib/Makefile @@ -9,7 +9,7 @@ CLANG_LEVEL := .. PARALLEL_DIRS = Headers Basic Lex Parse AST Sema CodeGen Analysis \ - StaticAnalyzer Rewrite ARCMigrate Serialization Frontend \ + StaticAnalyzer Edit Rewrite ARCMigrate Serialization Frontend \ FrontendTool Index Driver include $(CLANG_LEVEL)/Makefile diff --git a/lib/Rewrite/FixItRewriter.cpp b/lib/Rewrite/FixItRewriter.cpp index caa7d06ac2..3863adb4f1 100644 --- a/lib/Rewrite/FixItRewriter.cpp +++ b/lib/Rewrite/FixItRewriter.cpp @@ -14,6 +14,8 @@ //===----------------------------------------------------------------------===// #include "clang/Rewrite/FixItRewriter.h" +#include "clang/Edit/Commit.h" +#include "clang/Edit/EditsReceiver.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" @@ -29,6 +31,7 @@ FixItRewriter::FixItRewriter(DiagnosticsEngine &Diags, SourceManager &SourceMgr, const LangOptions &LangOpts, FixItOptions *FixItOpts) : Diags(Diags), + Editor(SourceMgr, LangOpts), Rewrite(SourceMgr, LangOpts), FixItOpts(FixItOpts), NumFailures(0), @@ -51,6 +54,24 @@ bool FixItRewriter::WriteFixedFile(FileID ID, raw_ostream &OS) { return false; } +namespace { + +class RewritesReceiver : public edit::EditsReceiver { + Rewriter &Rewrite; + +public: + RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { } + + virtual void insert(SourceLocation loc, StringRef text) { + Rewrite.InsertText(loc, text); + } + virtual void replace(CharSourceRange range, StringRef text) { + Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text); + } +}; + +} + bool FixItRewriter::WriteFixedFiles( std::vector<std::pair<std::string, std::string> > *RewrittenFiles) { if (NumFailures > 0 && !FixItOpts->FixWhatYouCan) { @@ -58,6 +79,9 @@ bool FixItRewriter::WriteFixedFiles( return true; } + RewritesReceiver Rec(Rewrite); + Editor.applyRewrites(Rec); + for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) { const FileEntry *Entry = Rewrite.getSourceMgr().getFileEntryForID(I->first); int fd; @@ -116,16 +140,28 @@ void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, // Make sure that we can perform all of the modifications we // in this diagnostic. - bool CanRewrite = Info.getNumFixItHints() > 0; + edit::Commit commit(Editor); for (unsigned Idx = 0, Last = Info.getNumFixItHints(); Idx < Last; ++Idx) { const FixItHint &Hint = Info.getFixItHint(Idx); - if (Hint.RemoveRange.isValid() && - Rewrite.getRangeSize(Hint.RemoveRange) == -1) { - CanRewrite = false; - break; + + if (Hint.CodeToInsert.empty()) { + if (Hint.InsertFromRange.isValid()) + commit.insertFromRange(Hint.RemoveRange.getBegin(), + Hint.InsertFromRange, /*afterToken=*/false, + Hint.BeforePreviousInsertions); + else + commit.remove(Hint.RemoveRange); + } else { + if (Hint.RemoveRange.isTokenRange() || + Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd()) + commit.replace(Hint.RemoveRange, Hint.CodeToInsert); + else + commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert, + /*afterToken=*/false, Hint.BeforePreviousInsertions); } } + bool CanRewrite = Info.getNumFixItHints() > 0 && commit.isCommitable(); if (!CanRewrite) { if (Info.getNumFixItHints() > 0) @@ -138,27 +174,8 @@ void FixItRewriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, } return; } - - bool Failed = false; - for (unsigned Idx = 0, Last = Info.getNumFixItHints(); - Idx < Last; ++Idx) { - const FixItHint &Hint = Info.getFixItHint(Idx); - - if (Hint.CodeToInsert.empty()) { - // We're removing code. - if (Rewrite.RemoveText(Hint.RemoveRange)) - Failed = true; - continue; - } - - // We're replacing code. - if (Rewrite.ReplaceText(Hint.RemoveRange.getBegin(), - Rewrite.getRangeSize(Hint.RemoveRange), - Hint.CodeToInsert)) - Failed = true; - } - - if (Failed) { + + if (!Editor.commit(commit)) { ++NumFailures; Diag(Info.getLocation(), diag::note_fixit_failed); return; |