diff options
Diffstat (limited to 'clang-tools-extra')
128 files changed, 414 insertions, 370 deletions
diff --git a/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp b/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp index e80ba52c..a25e3e5 100644 --- a/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp +++ b/clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp @@ -23,7 +23,7 @@ inline std::string joinNamespaces(const llvm::SmallVectorImpl<StringRef> &Namespaces) { if (Namespaces.empty()) return ""; - std::string Result = Namespaces.front(); + std::string Result(Namespaces.front()); for (auto I = Namespaces.begin() + 1, E = Namespaces.end(); I != E; ++I) Result += ("::" + *I).str(); return Result; @@ -184,7 +184,7 @@ void addReplacementOrDie( const SourceManager &SM, std::map<std::string, tooling::Replacements> *FileToReplacements) { const auto R = createReplacement(Start, End, ReplacementText, SM); - auto Err = (*FileToReplacements)[R.getFilePath()].add(R); + auto Err = (*FileToReplacements)[std::string(R.getFilePath())].add(R); if (Err) llvm_unreachable(llvm::toString(std::move(Err)).c_str()); } @@ -213,18 +213,18 @@ std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName, DeclName = DeclName.ltrim(':'); NsName = NsName.ltrim(':'); if (DeclName.find(':') == llvm::StringRef::npos) - return DeclName; + return std::string(DeclName); auto NsNameSplitted = splitSymbolName(NsName); auto DeclNsSplitted = splitSymbolName(DeclName); llvm::StringRef UnqualifiedDeclName = DeclNsSplitted.pop_back_val(); // If the Decl is in global namespace, there is no need to shorten it. if (DeclNsSplitted.empty()) - return UnqualifiedDeclName; + return std::string(UnqualifiedDeclName); // If NsName is the global namespace, we can simply use the DeclName sans // leading "::". if (NsNameSplitted.empty()) - return DeclName; + return std::string(DeclName); if (NsNameSplitted.front() != DeclNsSplitted.front()) { // The DeclName must be fully-qualified, but we still need to decide if a @@ -233,7 +233,7 @@ std::string getShortestQualifiedNameInNamespace(llvm::StringRef DeclName, // to avoid conflict. if (llvm::is_contained(NsNameSplitted, DeclNsSplitted.front())) return ("::" + DeclName).str(); - return DeclName; + return std::string(DeclName); } // Since there is already an overlap namespace, we know that `DeclName` can be // shortened, so we reduce the longest common prefix. @@ -711,7 +711,7 @@ void ChangeNamespaceTool::moveOldNamespace( MoveNs.InsertionOffset = SM.getFileOffset(SM.getSpellingLoc(InsertionLoc)); MoveNs.FID = SM.getFileID(Start); MoveNs.SourceMgr = Result.SourceManager; - MoveNamespaces[SM.getFilename(Start)].push_back(MoveNs); + MoveNamespaces[std::string(SM.getFilename(Start))].push_back(MoveNs); } // Removes a class forward declaration from the code in the moved namespace and @@ -762,7 +762,7 @@ void ChangeNamespaceTool::moveClassForwardDeclaration( InsertForwardDeclaration InsertFwd; InsertFwd.InsertionOffset = Insertion.getOffset(); InsertFwd.ForwardDeclText = Insertion.getReplacementText().str(); - InsertFwdDecls[Insertion.getFilePath()].push_back(InsertFwd); + InsertFwdDecls[std::string(Insertion.getFilePath())].push_back(InsertFwd); } // Replaces a qualified symbol (in \p DeclCtx) that refers to a declaration \p @@ -816,7 +816,7 @@ void ChangeNamespaceTool::replaceQualifiedSymbolInDeclContext( ->getQualifiedNameAsString())) { FromDeclNameRef = FromDeclNameRef.drop_front(2); if (FromDeclNameRef.size() < ReplaceName.size()) - ReplaceName = FromDeclNameRef; + ReplaceName = std::string(FromDeclNameRef); } } // Checks if there is any namespace alias declarations that can shorten the diff --git a/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp b/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp index a97be99..d54fe73 100644 --- a/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp +++ b/clang-tools-extra/clang-change-namespace/tool/ClangChangeNamespace.cpp @@ -91,7 +91,7 @@ llvm::ErrorOr<std::vector<std::string>> GetWhiteListedSymbolPatterns() { llvm::StringRef Content = File.get()->getBuffer(); Content.split(Lines, '\n', /*MaxSplit=*/-1, /*KeepEmpty=*/false); for (auto Line : Lines) - Patterns.push_back(Line.trim()); + Patterns.push_back(std::string(Line.trim())); return Patterns; } diff --git a/clang-tools-extra/clang-doc/Representation.cpp b/clang-tools-extra/clang-doc/Representation.cpp index 29b6807..56d975a 100644 --- a/clang-tools-extra/clang-doc/Representation.cpp +++ b/clang-tools-extra/clang-doc/Representation.cpp @@ -286,9 +286,9 @@ ClangDocContext::ClangDocContext(tooling::ExecutionContext *ECtx, if (SourceRoot.empty()) // If no SourceRoot was provided the current path is used as the default llvm::sys::fs::current_path(SourceRootDir); - this->SourceRoot = SourceRootDir.str(); + this->SourceRoot = std::string(SourceRootDir.str()); if (!RepositoryUrl.empty()) { - this->RepositoryUrl = RepositoryUrl; + this->RepositoryUrl = std::string(RepositoryUrl); if (!RepositoryUrl.empty() && RepositoryUrl.find("http://") != 0 && RepositoryUrl.find("https://") != 0) this->RepositoryUrl->insert(0, "https://"); diff --git a/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp b/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp index ed349d3..eae0d84 100644 --- a/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp +++ b/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp @@ -232,7 +232,7 @@ int main(int argc, const char **argv) { llvm::sys::path::native(AssetsPath, IndexJS); llvm::sys::path::append(IndexJS, "index.js"); CDCtx.UserStylesheets.insert(CDCtx.UserStylesheets.begin(), - DefaultStylesheet.str()); + std::string(DefaultStylesheet.str())); CDCtx.FilesToCopy.emplace_back(IndexJS.str()); } diff --git a/clang-tools-extra/clang-include-fixer/InMemorySymbolIndex.cpp b/clang-tools-extra/clang-include-fixer/InMemorySymbolIndex.cpp index e785893..93b534d 100644 --- a/clang-tools-extra/clang-include-fixer/InMemorySymbolIndex.cpp +++ b/clang-tools-extra/clang-include-fixer/InMemorySymbolIndex.cpp @@ -16,12 +16,12 @@ namespace include_fixer { InMemorySymbolIndex::InMemorySymbolIndex( const std::vector<SymbolAndSignals> &Symbols) { for (const auto &Symbol : Symbols) - LookupTable[Symbol.Symbol.getName()].push_back(Symbol); + LookupTable[std::string(Symbol.Symbol.getName())].push_back(Symbol); } std::vector<SymbolAndSignals> InMemorySymbolIndex::search(llvm::StringRef Identifier) { - auto I = LookupTable.find(Identifier); + auto I = LookupTable.find(std::string(Identifier)); if (I != LookupTable.end()) return I->second; return {}; diff --git a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp index 374fcf2..1a76566 100644 --- a/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp +++ b/clang-tools-extra/clang-include-fixer/IncludeFixer.cpp @@ -302,7 +302,7 @@ std::string IncludeFixerSemaSource::minimizeInclude( StringRef Include, const clang::SourceManager &SourceManager, clang::HeaderSearch &HeaderSearch) const { if (!MinimizeIncludePaths) - return Include; + return std::string(Include); // Get the FileEntry for the include. StringRef StrippedInclude = Include.trim("\"<>"); @@ -311,7 +311,7 @@ std::string IncludeFixerSemaSource::minimizeInclude( // If the file doesn't exist return the path from the database. // FIXME: This should never happen. if (!Entry) - return Include; + return std::string(Include); bool IsSystem = false; std::string Suggestion = @@ -352,7 +352,8 @@ IncludeFixerSemaSource::query(StringRef Query, StringRef ScopedQualifiers, if (!GenerateDiagnostics && !QuerySymbolInfos.empty()) { if (ScopedQualifiers == QuerySymbolInfos.front().ScopedQualifiers && Query == QuerySymbolInfos.front().RawIdentifier) { - QuerySymbolInfos.push_back({Query.str(), ScopedQualifiers, Range}); + QuerySymbolInfos.push_back( + {Query.str(), std::string(ScopedQualifiers), Range}); } return {}; } @@ -367,7 +368,8 @@ IncludeFixerSemaSource::query(StringRef Query, StringRef ScopedQualifiers, CI->getSourceManager().getLocForStartOfFile( CI->getSourceManager().getMainFileID())); - QuerySymbolInfos.push_back({Query.str(), ScopedQualifiers, Range}); + QuerySymbolInfos.push_back( + {Query.str(), std::string(ScopedQualifiers), Range}); // Query the symbol based on C++ name Lookup rules. // Firstly, lookup the identifier with scoped namespace contexts; diff --git a/clang-tools-extra/clang-include-fixer/IncludeFixer.h b/clang-tools-extra/clang-include-fixer/IncludeFixer.h index ccab65d..1ec1c50 100644 --- a/clang-tools-extra/clang-include-fixer/IncludeFixer.h +++ b/clang-tools-extra/clang-include-fixer/IncludeFixer.h @@ -92,7 +92,9 @@ public: GenerateDiagnostics(GenerateDiagnostics) {} void setCompilerInstance(CompilerInstance *CI) { this->CI = CI; } - void setFilePath(StringRef FilePath) { this->FilePath = FilePath; } + void setFilePath(StringRef FilePath) { + this->FilePath = std::string(FilePath); + } /// Callback for incomplete types. If we encounter a forward declaration we /// have the fully qualified name ready. Just query that. diff --git a/clang-tools-extra/clang-include-fixer/IncludeFixerContext.cpp b/clang-tools-extra/clang-include-fixer/IncludeFixerContext.cpp index 9bc20f1..073cee4 100644 --- a/clang-tools-extra/clang-include-fixer/IncludeFixerContext.cpp +++ b/clang-tools-extra/clang-include-fixer/IncludeFixerContext.cpp @@ -29,7 +29,7 @@ std::string createQualifiedNameForReplacement( // No need to add missing qualifiers if SymbolIdentifier has a global scope // operator "::". if (RawSymbolName.startswith("::")) - return RawSymbolName; + return std::string(RawSymbolName); std::string QualifiedName = MatchedSymbol.getQualifiedName(); diff --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp index bb6a3fa..a2a98a2 100644 --- a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp +++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp @@ -251,7 +251,8 @@ void FindAllSymbols::run(const MatchFinder::MatchResult &Result) { const SourceManager *SM = Result.SourceManager; if (auto Symbol = CreateSymbolInfo(ND, *SM, Collector)) { - Filename = SM->getFileEntryForID(SM->getMainFileID())->getName(); + Filename = + std::string(SM->getFileEntryForID(SM->getMainFileID())->getName()); FileSymbols[*Symbol] += Signals; } } diff --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/HeaderMapCollector.h b/clang-tools-extra/clang-include-fixer/find-all-symbols/HeaderMapCollector.h index ed2a6d6..300e4f7 100644 --- a/clang-tools-extra/clang-include-fixer/find-all-symbols/HeaderMapCollector.h +++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/HeaderMapCollector.h @@ -29,7 +29,7 @@ public: void addHeaderMapping(llvm::StringRef OrignalHeaderPath, llvm::StringRef MappingHeaderPath) { - HeaderMappingTable[OrignalHeaderPath] = MappingHeaderPath; + HeaderMappingTable[OrignalHeaderPath] = std::string(MappingHeaderPath); }; /// Check if there is a mapping from \p Header or a regex pattern that matches diff --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/PathConfig.cpp b/clang-tools-extra/clang-include-fixer/find-all-symbols/PathConfig.cpp index 4f1ebc7..c12e4cf 100644 --- a/clang-tools-extra/clang-include-fixer/find-all-symbols/PathConfig.cpp +++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/PathConfig.cpp @@ -34,7 +34,7 @@ std::string getIncludePath(const SourceManager &SM, SourceLocation Loc, SmallString<256> CleanedFilePath = FilePath; llvm::sys::path::remove_dots(CleanedFilePath, /*remove_dot_dot=*/false); - return CleanedFilePath.str(); + return std::string(CleanedFilePath.str()); } } // namespace find_all_symbols diff --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/SymbolInfo.h b/clang-tools-extra/clang-include-fixer/find-all-symbols/SymbolInfo.h index 9648d88..7f8fa90 100644 --- a/clang-tools-extra/clang-include-fixer/find-all-symbols/SymbolInfo.h +++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/SymbolInfo.h @@ -74,7 +74,7 @@ public: SymbolInfo(llvm::StringRef Name, SymbolKind Type, llvm::StringRef FilePath, const std::vector<Context> &Contexts); - void SetFilePath(llvm::StringRef Path) { FilePath = Path; } + void SetFilePath(llvm::StringRef Path) { FilePath = std::string(Path); } /// Get symbol name. llvm::StringRef getName() const { return Name; } diff --git a/clang-tools-extra/clang-include-fixer/plugin/IncludeFixerPlugin.cpp b/clang-tools-extra/clang-include-fixer/plugin/IncludeFixerPlugin.cpp index 3406a25..7908a89 100644 --- a/clang-tools-extra/clang-include-fixer/plugin/IncludeFixerPlugin.cpp +++ b/clang-tools-extra/clang-include-fixer/plugin/IncludeFixerPlugin.cpp @@ -60,7 +60,8 @@ public: Input = Arg.substr(strlen("-input=")); } - std::string InputFile = CI.getFrontendOpts().Inputs[0].getFile(); + std::string InputFile = + std::string(CI.getFrontendOpts().Inputs[0].getFile()); auto CreateYamlIdx = [=]() -> std::unique_ptr<include_fixer::SymbolIndex> { llvm::ErrorOr<std::unique_ptr<include_fixer::YamlSymbolIndex>> SymbolIdx( nullptr); diff --git a/clang-tools-extra/clang-move/Move.cpp b/clang-tools-extra/clang-move/Move.cpp index 1405217..ebeb5d0 100644 --- a/clang-tools-extra/clang-move/Move.cpp +++ b/clang-tools-extra/clang-move/Move.cpp @@ -65,7 +65,7 @@ std::string CleanPath(StringRef PathRef) { llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true); // FIXME: figure out why this is necessary. llvm::sys::path::native(Path); - return Path.str(); + return std::string(Path.str()); } // Make the Path absolute using the CurrentDir if the Path is not an absolute @@ -785,13 +785,13 @@ void ClangMoveTool::removeDeclsInOldFiles() { continue; } auto CleanReplacements = format::cleanupAroundReplacements( - Code, Context->FileToReplacements[FilePath], *Style); + Code, Context->FileToReplacements[std::string(FilePath)], *Style); if (!CleanReplacements) { llvm::errs() << llvm::toString(CleanReplacements.takeError()) << "\n"; continue; } - Context->FileToReplacements[FilePath] = *CleanReplacements; + Context->FileToReplacements[std::string(FilePath)] = *CleanReplacements; } } @@ -870,7 +870,7 @@ void ClangMoveTool::moveAll(SourceManager &SM, StringRef OldFile, else if (Context->Spec.NewHeader == NewFile && OldHeaderIncludeRangeInHeader.isValid()) ReplaceOldInclude(OldHeaderIncludeRangeInHeader); - Context->FileToReplacements[NewFile] = std::move(AllCode); + Context->FileToReplacements[std::string(NewFile)] = std::move(AllCode); } } diff --git a/clang-tools-extra/clang-move/tool/ClangMove.cpp b/clang-tools-extra/clang-move/tool/ClangMove.cpp index 214c4f6..7e16dc2 100644 --- a/clang-tools-extra/clang-move/tool/ClangMove.cpp +++ b/clang-tools-extra/clang-move/tool/ClangMove.cpp @@ -124,7 +124,8 @@ int main(int argc, const char **argv) { Twine(EC.message())); move::ClangMoveContext Context{Spec, Tool.getReplacements(), - InitialDirectory.str(), Style, DumpDecls}; + std::string(InitialDirectory.str()), Style, + DumpDecls}; move::DeclarationReporter Reporter; move::ClangMoveActionFactory Factory(&Context, &Reporter); diff --git a/clang-tools-extra/clang-query/QueryParser.cpp b/clang-tools-extra/clang-query/QueryParser.cpp index 896145b..ecc189a 100644 --- a/clang-tools-extra/clang-query/QueryParser.cpp +++ b/clang-tools-extra/clang-query/QueryParser.cpp @@ -82,7 +82,8 @@ template <typename T> struct QueryParser::LexOrCompleteWord { CaseStr.substr(0, WordCompletionPos) == Word.substr(0, WordCompletionPos)) P->Completions.push_back(LineEditor::Completion( - (CaseStr.substr(WordCompletionPos) + " ").str(), CaseStr)); + (CaseStr.substr(WordCompletionPos) + " ").str(), + std::string(CaseStr))); return *this; } diff --git a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp index 714a214..f3bcc2a 100644 --- a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp +++ b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp @@ -36,7 +36,8 @@ using llvm::SmallSetVector; static const RecordDecl *findDefinition(StringRef RecordName, ASTContext &Context) { auto Results = - match(recordDecl(hasName(RecordName), isDefinition()).bind("recordDecl"), + match(recordDecl(hasName(std::string(RecordName)), isDefinition()) + .bind("recordDecl"), Context); if (Results.empty()) { llvm::errs() << "Definition of " << RecordName << " not found\n"; @@ -89,7 +90,7 @@ addReplacement(SourceRange Old, SourceRange New, const ASTContext &Context, tooling::Replacement R(Context.getSourceManager(), CharSourceRange::getTokenRange(Old), NewText, Context.getLangOpts()); - consumeError(Replacements[R.getFilePath()].add(R)); + consumeError(Replacements[std::string(R.getFilePath())].add(R)); } /// Find all member fields used in the given init-list initializer expr diff --git a/clang-tools-extra/clang-tidy/ClangTidy.cpp b/clang-tools-extra/clang-tidy/ClangTidy.cpp index 40aaf40..4746b49 100644 --- a/clang-tools-extra/clang-tidy/ClangTidy.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidy.cpp @@ -596,7 +596,7 @@ void exportReplacements(const llvm::StringRef MainFilePath, const std::vector<ClangTidyError> &Errors, raw_ostream &OS) { TranslationUnitDiagnostics TUD; - TUD.MainSourceFile = MainFilePath; + TUD.MainSourceFile = std::string(MainFilePath); for (const auto &Error : Errors) { tooling::Diagnostic Diag = Error; TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag); diff --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp index fbf1176..cc817d8 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp @@ -39,7 +39,7 @@ std::string ClangTidyCheck::OptionsView::get(StringRef LocalName, const auto &Iter = CheckOptions.find(NamePrefix + LocalName.str()); if (Iter != CheckOptions.end()) return Iter->second; - return Default; + return std::string(Default); } std::string @@ -52,13 +52,13 @@ ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName, Iter = CheckOptions.find(LocalName.str()); if (Iter != CheckOptions.end()) return Iter->second; - return Default; + return std::string(Default); } void ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const { - Options[NamePrefix + LocalName.str()] = Value; + Options[NamePrefix + LocalName.str()] = std::string(Value); } void ClangTidyCheck::OptionsView::store(ClangTidyOptions::OptionMap &Options, diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp index a5b6834..5a4021c 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp @@ -172,7 +172,7 @@ void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) { } void ClangTidyContext::setCurrentFile(StringRef File) { - CurrentFile = File; + CurrentFile = std::string(File); CurrentOptions = getOptionsForFile(CurrentFile); CheckFilter = std::make_unique<CachedGlobList>(*getOptions().Checks); WarningAsErrorFilter = @@ -202,7 +202,7 @@ ClangTidyOptions ClangTidyContext::getOptionsForFile(StringRef File) const { void ClangTidyContext::setEnableProfiling(bool P) { Profile = P; } void ClangTidyContext::setProfileStoragePrefix(StringRef Prefix) { - ProfilePrefix = Prefix; + ProfilePrefix = std::string(Prefix); } llvm::Optional<ClangTidyProfiling::StorageParams> @@ -224,8 +224,8 @@ bool ClangTidyContext::treatAsError(StringRef CheckName) const { } std::string ClangTidyContext::getCheckName(unsigned DiagnosticID) const { - std::string ClangWarningOption = - DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(DiagnosticID); + std::string ClangWarningOption = std::string( + DiagEngine->getDiagnosticIDs()->getWarningOptionForDiag(DiagnosticID)); if (!ClangWarningOption.empty()) return "clang-diagnostic-" + ClangWarningOption; llvm::DenseMap<unsigned, std::string>::const_iterator I = @@ -661,7 +661,7 @@ void ClangTidyDiagnosticConsumer::removeIncompatibleErrors() { for (const auto &Replace : FileAndReplace.second) { unsigned Begin = Replace.getOffset(); unsigned End = Begin + Replace.getLength(); - const std::string &FilePath = Replace.getFilePath(); + const std::string &FilePath = std::string(Replace.getFilePath()); // FIXME: Handle empty intervals, such as those from insertions. if (Begin == End) continue; diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h index 0d39296..28d923d 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h @@ -154,7 +154,7 @@ public: /// Should be called when starting to process new translation unit. void setCurrentBuildDirectory(StringRef BuildDirectory) { - CurrentBuildDirectory = BuildDirectory; + CurrentBuildDirectory = std::string(BuildDirectory); } /// Returns build directory of the current translation unit. diff --git a/clang-tools-extra/clang-tidy/ClangTidyModule.cpp b/clang-tools-extra/clang-tidy/ClangTidyModule.cpp index ff83e7e..6e44f72 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyModule.cpp @@ -17,7 +17,7 @@ namespace tidy { void ClangTidyCheckFactories::registerCheckFactory(StringRef Name, CheckFactory Factory) { - Factories[Name] = std::move(Factory); + Factories[std::string(Name)] = std::move(Factory); } std::vector<std::unique_ptr<ClangTidyCheck>> diff --git a/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp index c3b4191..6e678c9 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp @@ -31,7 +31,7 @@ getScaleForFactory(llvm::StringRef FactoryName) { {"Minutes", DurationScale::Minutes}, {"Hours", DurationScale::Hours}}); - auto ScaleIter = ScaleMap.find(FactoryName); + auto ScaleIter = ScaleMap.find(std::string(FactoryName)); if (ScaleIter == ScaleMap.end()) return llvm::None; diff --git a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp index 3466cdbb..d4db021 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp @@ -91,7 +91,8 @@ rewriteInverseTimeCall(const MatchFinder::MatchResult &Result, DurationScale Scale, const Expr &Node) { llvm::StringRef InverseFunction = getTimeInverseForScale(Scale); if (const auto *MaybeCallArg = selectFirst<const Expr>( - "e", match(callExpr(callee(functionDecl(hasName(InverseFunction))), + "e", match(callExpr(callee(functionDecl( + hasName(std::string(InverseFunction)))), hasArgument(0, expr().bind("e"))), Node, *Result.Context))) { return tooling::fixit::getText(*MaybeCallArg, *Result.Context).str(); diff --git a/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp b/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp index a386665..78ef1cc 100644 --- a/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp @@ -108,11 +108,11 @@ void TimeSubtractionCheck::registerMatchers(MatchFinder *Finder) { // a 'Duration'. If we know the result is a 'Duration', we can then infer // that the second operand must be a 'Time'. auto CallMatcher = - callExpr( - callee(functionDecl(hasName(getDurationFactoryForScale(*Scale)))), - hasArgument(0, binaryOperator(hasOperatorName("-"), - hasLHS(TimeInverseMatcher)) - .bind("binop"))) + callExpr(callee(functionDecl( + hasName(std::string(getDurationFactoryForScale(*Scale))))), + hasArgument(0, binaryOperator(hasOperatorName("-"), + hasLHS(TimeInverseMatcher)) + .bind("binop"))) .bind("outer_call"); Finder->addMatcher(CallMatcher, this); @@ -160,8 +160,8 @@ void TimeSubtractionCheck::check(const MatchFinder::MatchResult &Result) { // latter case (addressed first), we also need to worry about parenthesis. const auto *MaybeCallArg = selectFirst<const CallExpr>( "arg", match(expr(hasAncestor( - callExpr(callee(functionDecl(hasName( - getDurationFactoryForScale(*Scale))))) + callExpr(callee(functionDecl(hasName(std::string( + getDurationFactoryForScale(*Scale)))))) .bind("arg"))), *BinOp, *Result.Context)); if (MaybeCallArg && MaybeCallArg->getArg(0)->IgnoreImpCasts() == BinOp && diff --git a/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp index 95babc7..fffb8a5c 100644 --- a/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp @@ -58,9 +58,9 @@ void InaccurateEraseCheck::check(const MatchFinder::MatchResult &Result) { if (!Loc.isMacroID() && EndExpr) { const auto *AlgCall = Result.Nodes.getNodeAs<CallExpr>("alg"); - std::string ReplacementText = Lexer::getSourceText( + std::string ReplacementText = std::string(Lexer::getSourceText( CharSourceRange::getTokenRange(EndExpr->getSourceRange()), - *Result.SourceManager, getLangOpts()); + *Result.SourceManager, getLangOpts())); const SourceLocation EndLoc = Lexer::getLocForEndOfToken( AlgCall->getEndLoc(), 0, *Result.SourceManager, getLangOpts()); Hint = FixItHint::CreateInsertion(EndLoc, ", " + ReplacementText); diff --git a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp index c771ba8..5a70537 100644 --- a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp @@ -136,7 +136,7 @@ static bool isAtLeastOneCondVarChanged(const FunctionDecl *Func, static std::string getCondVarNames(const Stmt *Cond) { if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) { if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) - return Var->getName(); + return std::string(Var->getName()); } std::string Result; diff --git a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp index e49688b..9347dac 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp @@ -652,9 +652,10 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) { anyOf(DestUnknownDecl, hasDescendant(DestUnknownDecl)))); auto NullTerminatorExpr = binaryOperator( - hasLHS(anyOf(hasDescendant(declRefExpr( - to(varDecl(equalsBoundNode(DestVarDeclName))))), - hasDescendant(declRefExpr(equalsBoundNode(DestExprName))))), + hasLHS(anyOf(hasDescendant(declRefExpr(to(varDecl( + equalsBoundNode(std::string(DestVarDeclName)))))), + hasDescendant(declRefExpr( + equalsBoundNode(std::string(DestExprName)))))), hasRHS(ignoringImpCasts( anyOf(characterLiteral(equals(0U)), integerLiteral(equals(0)))))); diff --git a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp index c1b27a8..55d8884 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp @@ -119,7 +119,7 @@ getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace, Optional<FailureInfo> Info; auto AppendFailure = [&](StringRef Kind, std::string &&Fixup) { if (!Info) { - Info = FailureInfo{Kind, std::move(Fixup)}; + Info = FailureInfo{std::string(Kind), std::move(Fixup)}; } else { Info->KindName += Kind; Info->Fixup = std::move(Fixup); @@ -143,7 +143,7 @@ getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace, if (!(hasReservedDoubleUnderscore(Name, LangOpts) || startsWithUnderscoreCapital(Name) || startsWithUnderscoreInGlobalNamespace(Name, IsInGlobalNamespace))) - return FailureInfo{NonReservedTag, getNonReservedFixup(Name)}; + return FailureInfo{NonReservedTag, getNonReservedFixup(std::string(Name))}; return None; } diff --git a/clang-tools-extra/clang-tidy/cert/MutatingCopyCheck.cpp b/clang-tools-extra/clang-tidy/cert/MutatingCopyCheck.cpp index a20a890..6add035 100644 --- a/clang-tools-extra/clang-tidy/cert/MutatingCopyCheck.cpp +++ b/clang-tools-extra/clang-tidy/cert/MutatingCopyCheck.cpp @@ -25,7 +25,8 @@ void MutatingCopyCheck::registerMatchers(MatchFinder *Finder) { return; const auto MemberExprOrSourceObject = anyOf( - memberExpr(), declRefExpr(to(decl(equalsBoundNode(SourceDeclName))))); + memberExpr(), + declRefExpr(to(decl(equalsBoundNode(std::string(SourceDeclName)))))); const auto IsPartOfSource = allOf(unless(hasDescendant(expr(unless(MemberExprOrSourceObject)))), diff --git a/clang-tools-extra/clang-tidy/google/AvoidNSObjectNewCheck.cpp b/clang-tools-extra/clang-tidy/google/AvoidNSObjectNewCheck.cpp index 1b147ac..0186ed8 100644 --- a/clang-tools-extra/clang-tidy/google/AvoidNSObjectNewCheck.cpp +++ b/clang-tools-extra/clang-tidy/google/AvoidNSObjectNewCheck.cpp @@ -80,12 +80,13 @@ static FixItHint getCallFixItHint(const ObjCMessageExpr *Expr, StringRef ClassName = FoundClassFactory->first; StringRef FactorySelector = FoundClassFactory->second; std::string NewCall = - llvm::formatv("[{0} {1}]", ClassName, FactorySelector); + std::string(llvm::formatv("[{0} {1}]", ClassName, FactorySelector)); return FixItHint::CreateReplacement(Expr->getSourceRange(), NewCall); } if (isInitMethodAvailable(Expr->getReceiverInterface())) { - std::string NewCall = llvm::formatv("[[{0} alloc] init]", Receiver); + std::string NewCall = + std::string(llvm::formatv("[[{0} alloc] init]", Receiver)); return FixItHint::CreateReplacement(Expr->getSourceRange(), NewCall); } diff --git a/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp b/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp index 27307c0..2db2300 100644 --- a/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp +++ b/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp @@ -242,10 +242,10 @@ static bool derivedTypeHasReplacementMethod(const MatchFinder::MatchResult &Result, llvm::StringRef ReplacementMethod) { const auto *Class = Result.Nodes.getNodeAs<CXXRecordDecl>("class"); - return !match(cxxRecordDecl( - unless(isExpansionInFileMatching( - "gtest/gtest(-typed-test)?\\.h$")), - hasMethod(cxxMethodDecl(hasName(ReplacementMethod)))), + return !match(cxxRecordDecl(unless(isExpansionInFileMatching( + "gtest/gtest(-typed-test)?\\.h$")), + hasMethod(cxxMethodDecl( + hasName(std::string(ReplacementMethod))))), *Class, *Result.Context) .empty(); } diff --git a/clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp b/clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp index 8b32d8d..27e29de 100644 --- a/clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp +++ b/clang-tools-extra/clang-tidy/llvm/HeaderGuardCheck.cpp @@ -36,7 +36,7 @@ std::string LLVMHeaderGuardCheck::getHeaderGuard(StringRef Filename, // Unlike LLVM svn, LLVM git monorepo is named llvm-project, so we replace // "/llvm-project/" with the cannonical "/llvm/". const static StringRef LLVMProject = "/llvm-project/"; - size_t PosLLVMProject = Guard.rfind(LLVMProject); + size_t PosLLVMProject = Guard.rfind(std::string(LLVMProject)); if (PosLLVMProject != StringRef::npos) Guard = Guard.replace(PosLLVMProject, LLVMProject.size(), "/llvm/"); diff --git a/clang-tools-extra/clang-tidy/llvm/IncludeOrderCheck.cpp b/clang-tools-extra/clang-tidy/llvm/IncludeOrderCheck.cpp index 009a5a6..834a49a 100644 --- a/clang-tools-extra/clang-tidy/llvm/IncludeOrderCheck.cpp +++ b/clang-tools-extra/clang-tidy/llvm/IncludeOrderCheck.cpp @@ -81,7 +81,8 @@ void IncludeOrderPPCallbacks::InclusionDirective( SrcMgr::CharacteristicKind FileType) { // We recognize the first include as a special main module header and want // to leave it in the top position. - IncludeDirective ID = {HashLoc, FilenameRange, FileName, IsAngled, false}; + IncludeDirective ID = {HashLoc, FilenameRange, std::string(FileName), + IsAngled, false}; if (LookForMainModule && !IsAngled) { ID.IsMainModule = true; LookForMainModule = false; diff --git a/clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp b/clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp index 9363fa901..8c24cb4 100644 --- a/clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/UniqueptrResetReleaseCheck.cpp @@ -104,12 +104,12 @@ void UniqueptrResetReleaseCheck::check(const MatchFinder::MatchResult &Result) { const auto *ResetCall = Result.Nodes.getNodeAs<CXXMemberCallExpr>("reset_call"); - std::string LeftText = clang::Lexer::getSourceText( + std::string LeftText = std::string(clang::Lexer::getSourceText( CharSourceRange::getTokenRange(Left->getSourceRange()), - *Result.SourceManager, getLangOpts()); - std::string RightText = clang::Lexer::getSourceText( + *Result.SourceManager, getLangOpts())); + std::string RightText = std::string(clang::Lexer::getSourceText( CharSourceRange::getTokenRange(Right->getSourceRange()), - *Result.SourceManager, getLangOpts()); + *Result.SourceManager, getLangOpts())); if (ResetMember->isArrow()) LeftText = "*" + LeftText; diff --git a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp index c9313db..a80bad7 100644 --- a/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp @@ -149,7 +149,8 @@ initializeBindArgumentForCallExpr(const MatchFinder::MatchResult &Result, if (isCallExprNamed(CE, "boost::ref") || isCallExprNamed(CE, "std::ref")) { B.Kind = BK_Other; B.CM = CM_ByRef; - B.UsageIdentifier = getSourceTextForExpr(Result, CE->getArg(0)); + B.UsageIdentifier = + std::string(getSourceTextForExpr(Result, CE->getArg(0))); } else { B.Kind = BK_CallExpr; B.CM = CM_InitExpression; @@ -188,7 +189,7 @@ static bool tryCaptureAsLocalVariable(const MatchFinder::MatchResult &Result, return false; B.CM = CM_ByValue; - B.UsageIdentifier = getSourceTextForExpr(Result, E); + B.UsageIdentifier = std::string(getSourceTextForExpr(Result, E)); B.CaptureIdentifier = B.UsageIdentifier; return true; } @@ -204,7 +205,7 @@ static bool tryCaptureAsMemberVariable(const MatchFinder::MatchResult &Result, E = E->IgnoreImplicit(); if (isa<CXXThisExpr>(E)) { B.CM = CM_ByValue; - B.UsageIdentifier = getSourceTextForExpr(Result, E); + B.UsageIdentifier = std::string(getSourceTextForExpr(Result, E)); B.CaptureIdentifier = "this"; return true; } @@ -217,7 +218,7 @@ static bool tryCaptureAsMemberVariable(const MatchFinder::MatchResult &Result, return false; B.CM = CM_ByValue; - B.UsageIdentifier = getSourceTextForExpr(Result, E); + B.UsageIdentifier = std::string(getSourceTextForExpr(Result, E)); B.CaptureIdentifier = "this"; return true; } @@ -252,7 +253,7 @@ buildBindArguments(const MatchFinder::MatchResult &Result, SmallVector<StringRef, 2> Matches; if (MatchPlaceholder.match(B.SourceTokens, &Matches)) { B.Kind = BK_Placeholder; - B.PlaceHolderIndex = std::stoi(Matches[1]); + B.PlaceHolderIndex = std::stoi(std::string(Matches[1])); B.UsageIdentifier = "PH" + llvm::utostr(B.PlaceHolderIndex); B.CaptureIdentifier = B.UsageIdentifier; continue; @@ -503,9 +504,10 @@ getLambdaProperties(const MatchFinder::MatchResult &Result) { LP.Callable.SourceTokens = getSourceTextForExpr(Result, CalleeExpr); if (LP.Callable.Materialization == CMK_VariableRef) { LP.Callable.CM = CM_ByValue; - LP.Callable.UsageIdentifier = getSourceTextForExpr(Result, CalleeExpr); - LP.Callable.CaptureIdentifier = - getSourceTextForExpr(Result, ignoreTemporariesAndPointers(CalleeExpr)); + LP.Callable.UsageIdentifier = + std::string(getSourceTextForExpr(Result, CalleeExpr)); + LP.Callable.CaptureIdentifier = std::string( + getSourceTextForExpr(Result, ignoreTemporariesAndPointers(CalleeExpr))); } else if (LP.Callable.Materialization == CMK_CallExpression) { LP.Callable.CM = CM_InitExpression; LP.Callable.UsageIdentifier = "Func"; diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp index f359702..7c0ae02 100644 --- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp @@ -748,7 +748,8 @@ void LoopConvertCheck::determineRangeDescriptor( ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop, LoopFixerKind FixerKind, const Expr *ContainerExpr, const UsageResult &Usages, RangeDescriptor &Descriptor) { - Descriptor.ContainerString = getContainerString(Context, Loop, ContainerExpr); + Descriptor.ContainerString = + std::string(getContainerString(Context, Loop, ContainerExpr)); if (FixerKind == LFK_Iterator) getIteratorLoopQualifiers(Context, Nodes, Descriptor); diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp index 6cb4276..237b2bd 100644 --- a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp +++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp @@ -851,20 +851,20 @@ std::string VariableNamer::createIndexName() { size_t Len = ContainerName.size(); if (Len > 1 && ContainerName.endswith(Style == NS_UpperCase ? "S" : "s")) { - IteratorName = ContainerName.substr(0, Len - 1); + IteratorName = std::string(ContainerName.substr(0, Len - 1)); // E.g.: (auto thing : things) if (!declarationExists(IteratorName) || IteratorName == OldIndex->getName()) return IteratorName; } if (Len > 2 && ContainerName.endswith(Style == NS_UpperCase ? "S_" : "s_")) { - IteratorName = ContainerName.substr(0, Len - 2); + IteratorName = std::string(ContainerName.substr(0, Len - 2)); // E.g.: (auto thing : things_) if (!declarationExists(IteratorName) || IteratorName == OldIndex->getName()) return IteratorName; } - return OldIndex->getName(); + return std::string(OldIndex->getName()); } /// Determines whether or not the name \a Symbol conflicts with @@ -899,7 +899,7 @@ bool VariableNamer::declarationExists(StringRef Symbol) { // of DeclContext::lookup()). Why is this? // Finally, determine if the symbol was used in the loop or a child context. - DeclFinderASTVisitor DeclFinder(Symbol, GeneratedDecls); + DeclFinderASTVisitor DeclFinder(std::string(Symbol), GeneratedDecls); return DeclFinder.findUsages(SourceStmt); } diff --git a/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp b/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp index 607dc5f..4b98f12 100644 --- a/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ShrinkToFitCheck.cpp @@ -62,15 +62,15 @@ void ShrinkToFitCheck::check(const MatchFinder::MatchResult &Result) { const LangOptions &Opts = getLangOpts(); std::string ReplacementText; if (const auto *UnaryOp = llvm::dyn_cast<UnaryOperator>(Container)) { - ReplacementText = + ReplacementText = std::string( Lexer::getSourceText(CharSourceRange::getTokenRange( UnaryOp->getSubExpr()->getSourceRange()), - *Result.SourceManager, Opts); + *Result.SourceManager, Opts)); ReplacementText += "->shrink_to_fit()"; } else { - ReplacementText = Lexer::getSourceText( + ReplacementText = std::string(Lexer::getSourceText( CharSourceRange::getTokenRange(Container->getSourceRange()), - *Result.SourceManager, Opts); + *Result.SourceManager, Opts)); ReplacementText += ".shrink_to_fit()"; } diff --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp index 4dc53dd..71cb030 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp @@ -464,7 +464,8 @@ void UseTrailingReturnTypeCheck::check(const MatchFinder::MatchResult &Result) { CharAfterReturnType.empty() || !std::isspace(CharAfterReturnType[0]); std::string Auto = NeedSpaceAfterAuto ? "auto " : "auto"; - std::string ReturnType = tooling::fixit::getText(ReturnTypeCVRange, Ctx); + std::string ReturnType = + std::string(tooling::fixit::getText(ReturnTypeCVRange, Ctx)); keepSpecifiers(ReturnType, Auto, ReturnTypeCVRange, *F, Fr, Ctx, SM, LangOpts); diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp index ce8d00f..164c9fe9 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp @@ -98,9 +98,9 @@ void UseUsingCheck::check(const MatchFinder::MatchResult &Result) { // If typedef contains a full struct/class declaration, extract its full text. if (LastCxxDeclRange.isValid() && ReplaceRange.fullyContains(LastCxxDeclRange)) { bool Invalid; - Type = + Type = std::string( Lexer::getSourceText(CharSourceRange::getTokenRange(LastCxxDeclRange), - *Result.SourceManager, getLangOpts(), &Invalid); + *Result.SourceManager, getLangOpts(), &Invalid)); if (Invalid) return; } diff --git a/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.cpp b/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.cpp index a9661e0..f305ddf 100644 --- a/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.cpp +++ b/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.cpp @@ -128,7 +128,7 @@ static bool isBuiltinTypeMatching(const BuiltinType *Builtin, {BuiltinType::LongDouble, "MPI_LONG_DOUBLE"}}; if (!isMPITypeMatching(BuiltinMatches, Builtin->getKind(), MPIDatatype)) { - BufferTypeName = Builtin->getName(LO); + BufferTypeName = std::string(Builtin->getName(LO)); return false; } @@ -219,7 +219,7 @@ static bool isTypedefTypeMatching(const TypedefType *const Typedef, const auto it = FixedWidthMatches.find(Typedef->getDecl()->getName()); // Check if the typedef is known and not matching the MPI datatype. if (it != FixedWidthMatches.end() && it->getValue() != MPIDatatype) { - BufferTypeName = Typedef->getDecl()->getName(); + BufferTypeName = std::string(Typedef->getDecl()->getName()); return false; } return true; @@ -271,7 +271,8 @@ void TypeMismatchCheck::check(const MatchFinder::MatchResult &Result) { const Type *ArgType = argumentType(CE, BufferIdx); // Skip unknown MPI datatypes and void pointers. - if (!isStandardMPIDatatype(MPIDatatype) || ArgType->isVoidType()) + if (!isStandardMPIDatatype(std::string(MPIDatatype)) || + ArgType->isVoidType()) return; BufferTypes.push_back(ArgType); @@ -309,16 +310,17 @@ void TypeMismatchCheck::checkArguments(ArrayRef<const Type *> BufferTypes, bool Error = false; if (const auto *Typedef = BT->getAs<TypedefType>()) { - Error = !isTypedefTypeMatching(Typedef, BufferTypeName, MPIDatatypes[i]); + Error = !isTypedefTypeMatching(Typedef, BufferTypeName, + std::string(MPIDatatypes[i])); } else if (const auto *Complex = BT->getAs<ComplexType>()) { - Error = - !isCComplexTypeMatching(Complex, BufferTypeName, MPIDatatypes[i], LO); + Error = !isCComplexTypeMatching(Complex, BufferTypeName, + std::string(MPIDatatypes[i]), LO); } else if (const auto *Template = BT->getAs<TemplateSpecializationType>()) { Error = !isCXXComplexTypeMatching(Template, BufferTypeName, - MPIDatatypes[i], LO); + std::string(MPIDatatypes[i]), LO); } else if (const auto *Builtin = BT->getAs<BuiltinType>()) { - Error = - !isBuiltinTypeMatching(Builtin, BufferTypeName, MPIDatatypes[i], LO); + Error = !isBuiltinTypeMatching(Builtin, BufferTypeName, + std::string(MPIDatatypes[i]), LO); } if (Error) { diff --git a/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp b/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp index e985fe8..776a8ca 100644 --- a/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp +++ b/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp @@ -94,7 +94,7 @@ void InefficientVectorOperationCheck::AddMatcher( const auto TargetVarDecl = varDecl(hasInitializer(DefaultConstructorCall)).bind(VarDeclName); const auto TargetVarDefStmt = - declStmt(hasSingleDecl(equalsBoundNode(VarDeclName))) + declStmt(hasSingleDecl(equalsBoundNode(std::string(VarDeclName)))) .bind(VarDeclStmtName); const auto AppendCallExpr = @@ -253,7 +253,7 @@ void InefficientVectorOperationCheck::check( StringRef LoopEndSource = Lexer::getSourceText( CharSourceRange::getTokenRange(LoopEndExpr->getSourceRange()), SM, Context->getLangOpts()); - ReserveSize = LoopEndSource; + ReserveSize = std::string(LoopEndSource); } auto Diag = diag(AppendCall->getBeginLoc(), diff --git a/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp b/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp index aff11bd..cbd6fdd 100644 --- a/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp +++ b/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp @@ -65,7 +65,7 @@ public: // FIXME: This is very limited at the moment. for (StringRef Arg : Args) if (Arg.startswith("-checks=")) - OverrideOptions.Checks = Arg.substr(strlen("-checks=")); + OverrideOptions.Checks = std::string(Arg.substr(strlen("-checks="))); auto Options = std::make_unique<FileOptionsProvider>( GlobalOptions, DefaultOptions, OverrideOptions); diff --git a/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp b/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp index fe0e1c0..1086340 100644 --- a/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp @@ -111,9 +111,9 @@ void ContainerSizeEmptyCheck::check(const MatchFinder::MatchResult &Result) { ? MemberCall->getImplicitObjectArgument() : (Pointee ? Pointee : Result.Nodes.getNodeAs<Expr>("STLObject")); FixItHint Hint; - std::string ReplacementText = + std::string ReplacementText = std::string( Lexer::getSourceText(CharSourceRange::getTokenRange(E->getSourceRange()), - *Result.SourceManager, getLangOpts()); + *Result.SourceManager, getLangOpts())); if (BinCmp && IsBinaryOrTernary(E)) { // Not just a DeclRefExpr, so parenthesize to be on the safe side. ReplacementText = "(" + ReplacementText + ")"; diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp index 119502e..0171964 100644 --- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp @@ -256,7 +256,7 @@ static std::string fixupWithCase(StringRef Name, } if (Words.empty()) - return Name; + return std::string(Name); std::string Fixup; switch (Case) { diff --git a/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp b/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp index 4a7c456..9580373 100644 --- a/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp @@ -72,7 +72,7 @@ getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources, if (T->is(tok::raw_identifier)) { StringRef ID = T->getRawIdentifier(); if (ID != "namespace" && ID != "inline") - Result.append(ID); + Result.append(std::string(ID)); } else if (T->is(tok::coloncolon)) { Result.append("::"); } else { // Any other kind of token is unexpected here. diff --git a/clang-tools-extra/clang-tidy/readability/RedundantPreprocessorCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantPreprocessorCheck.cpp index 295d22d..0870f2d 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantPreprocessorCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantPreprocessorCheck.cpp @@ -83,7 +83,7 @@ private: if (Store) // This is an actual directive to be remembered. - Stack.push_back({Loc, MacroName}); + Stack.push_back({Loc, std::string(MacroName)}); } ClangTidyCheck &Check; diff --git a/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp index f7b0dfc..7883491 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp @@ -46,8 +46,8 @@ formatDereference(const ast_matchers::MatchFinder::MatchResult &Result, if (const auto *Op = dyn_cast<clang::UnaryOperator>(&ExprNode)) { if (Op->getOpcode() == UO_AddrOf) { // Strip leading '&'. - return tooling::fixit::getText(*Op->getSubExpr()->IgnoreParens(), - *Result.Context); + return std::string(tooling::fixit::getText( + *Op->getSubExpr()->IgnoreParens(), *Result.Context)); } } StringRef Text = tooling::fixit::getText(ExprNode, *Result.Context); diff --git a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp index 38a6324..74ef565 100644 --- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp @@ -131,7 +131,7 @@ std::string asBool(StringRef text, bool NeedsStaticCast) { if (NeedsStaticCast) return ("static_cast<bool>(" + text + ")").str(); - return text; + return std::string(text); } bool needsNullPtrComparison(const Expr *E) { diff --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp index c6927cc..738766c 100644 --- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp +++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp @@ -367,7 +367,7 @@ int clangTidyMain(int argc, const char **argv) { FileName = PathList.front(); } - SmallString<256> FilePath = MakeAbsolute(FileName); + SmallString<256> FilePath = MakeAbsolute(std::string(FileName)); ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FilePath); std::vector<std::string> EnabledChecks = diff --git a/clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp b/clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp index 4890a1c..13107c25 100644 --- a/clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp +++ b/clang-tools-extra/clang-tidy/utils/HeaderGuard.cpp @@ -21,7 +21,7 @@ namespace utils { static std::string cleanPath(StringRef Path) { SmallString<256> Result = Path; llvm::sys::path::remove_dots(Result, true); - return Result.str(); + return std::string(Result.str()); } namespace { @@ -186,7 +186,7 @@ public: CPPVar)); return CPPVar; } - return CurHeaderGuard; + return std::string(CurHeaderGuard); } /// Checks the comment after the #endif of a header guard and fixes it diff --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp index e0d02f3..c267789 100644 --- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp +++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp @@ -50,7 +50,7 @@ IncludeInserter::CreateIncludeInsertion(FileID FileID, StringRef Header, bool IsAngled) { // We assume the same Header will never be included both angled and not // angled. - if (!InsertedHeaders[FileID].insert(Header).second) + if (!InsertedHeaders[FileID].insert(std::string(Header)).second) return llvm::None; if (IncludeSorterByFile.find(FileID) == IncludeSorterByFile.end()) { diff --git a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp index d1fc9bd..82f103a 100644 --- a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp +++ b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp @@ -43,11 +43,11 @@ NamespaceAliaser::createAlias(ASTContext &Context, const Stmt &Statement, // FIXME: Also doesn't consider file or class-scope aliases. const auto *ExistingAlias = selectFirst<NamedDecl>( - "alias", - match(functionDecl(hasBody(compoundStmt(has(declStmt( - has(namespaceAliasDecl(hasTargetNamespace(hasName(Namespace))) - .bind("alias"))))))), - *Function, Context)); + "alias", match(functionDecl(hasBody(compoundStmt(has(declStmt( + has(namespaceAliasDecl(hasTargetNamespace(hasName( + std::string(Namespace)))) + .bind("alias"))))))), + *Function, Context)); if (ExistingAlias != nullptr) { AddedAliases[Function][Namespace.str()] = ExistingAlias->getName().str(); diff --git a/clang-tools-extra/clang-tidy/utils/OptionsUtils.cpp b/clang-tools-extra/clang-tidy/utils/OptionsUtils.cpp index 36f4b6f..8a7f1c30 100644 --- a/clang-tools-extra/clang-tidy/utils/OptionsUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/OptionsUtils.cpp @@ -22,7 +22,7 @@ std::vector<std::string> parseStringList(StringRef Option) { for (StringRef &Name : Names) { Name = Name.trim(); if (!Name.empty()) - Result.push_back(Name); + Result.push_back(std::string(Name)); } return Result; } diff --git a/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp b/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp index e852532a..934bee2 100644 --- a/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp +++ b/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp @@ -58,7 +58,7 @@ Optional<FixItHint> UsingInserter::createUsingDeclaration( return None; } // Find conflicting declarations and references. - auto ConflictingDecl = namedDecl(hasName(UnqualifiedName)); + auto ConflictingDecl = namedDecl(hasName(std::string(UnqualifiedName))); bool HasConflictingDeclaration = !match(findAll(ConflictingDecl), *Function, Context).empty(); bool HasConflictingDeclRef = diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp b/clang-tools-extra/clangd/ClangdLSPServer.cpp index 982e05f..880359f 100644 --- a/clang-tools-extra/clangd/ClangdLSPServer.cpp +++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp @@ -48,10 +48,10 @@ CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File, CA.title = T.Title; switch (T.Intent) { case Tweak::Refactor: - CA.kind = CodeAction::REFACTOR_KIND; + CA.kind = std::string(CodeAction::REFACTOR_KIND); break; case Tweak::Info: - CA.kind = CodeAction::INFO_KIND; + CA.kind = std::string(CodeAction::INFO_KIND); break; } // This tweak may have an expensive second stage, we only run it if the user @@ -61,7 +61,7 @@ CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File, // directly. CA.command.emplace(); CA.command->title = T.Title; - CA.command->command = Command::CLANGD_APPLY_TWEAK; + CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK); CA.command->tweakArgs.emplace(); CA.command->tweakArgs->file = File; CA.command->tweakArgs->tweakID = T.ID; @@ -100,7 +100,8 @@ std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() { // HighlightingKind is using as the index. for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind; ++KindValue) - LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))}); + LookupTable.push_back( + {std::string(toTextMateScope((HighlightingKind)(KindValue)))}); return LookupTable; } @@ -471,7 +472,7 @@ void ClangdLSPServer::onInitialize(const InitializeParams &Params, ClangdServerOpts.SemanticHighlighting = Params.capabilities.SemanticHighlighting; if (Params.rootUri && *Params.rootUri) - ClangdServerOpts.WorkspaceRoot = Params.rootUri->file(); + ClangdServerOpts.WorkspaceRoot = std::string(Params.rootUri->file()); else if (Params.rootPath && !Params.rootPath->empty()) ClangdServerOpts.WorkspaceRoot = *Params.rootPath; if (Server) @@ -764,7 +765,7 @@ void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params, void ClangdLSPServer::onRename(const RenameParams &Params, Callback<WorkspaceEdit> Reply) { - Path File = Params.textDocument.uri.file(); + Path File = std::string(Params.textDocument.uri.file()); llvm::Optional<std::string> Code = DraftMgr.getDraft(File); if (!Code) return Reply(llvm::make_error<LSPError>( @@ -867,7 +868,7 @@ flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols, std::function<void(const DocumentSymbol &, llvm::StringRef)> Process = [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) { SymbolInformation SI; - SI.containerName = ParentName ? "" : *ParentName; + SI.containerName = std::string(ParentName ? "" : *ParentName); SI.name = S.name; SI.kind = S.kind; SI.location.range = S.range; @@ -908,7 +909,7 @@ static llvm::Optional<Command> asCommand(const CodeAction &Action) { if (Action.command) { Cmd = *Action.command; } else if (Action.edit) { - Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND; + Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND); Cmd.workspaceEdit = *Action.edit; } else { return None; diff --git a/clang-tools-extra/clangd/ClangdServer.cpp b/clang-tools-extra/clangd/ClangdServer.cpp index fd2aded..7ead45c 100644 --- a/clang-tools-extra/clangd/ClangdServer.cpp +++ b/clang-tools-extra/clangd/ClangdServer.cpp @@ -174,7 +174,7 @@ void ClangdServer::addDocument(PathRef File, llvm::StringRef Contents, // Compile command is set asynchronously during update, as it can be slow. ParseInputs Inputs; Inputs.FS = FS; - Inputs.Contents = Contents; + Inputs.Contents = std::string(Contents); Inputs.Opts = std::move(Opts); Inputs.Index = Index; bool NewFile = WorkScheduler.update(File, Inputs, WantDiags); @@ -478,8 +478,8 @@ void ClangdServer::switchSourceHeader( // the same directory. // 2) if 1) fails, we use the AST&Index approach, it is slower but supports // different code layout. - if (auto CorrespondingFile = - getCorrespondingHeaderOrSource(Path, FSProvider.getFileSystem())) + if (auto CorrespondingFile = getCorrespondingHeaderOrSource( + std::string(Path), FSProvider.getFileSystem())) return CB(std::move(CorrespondingFile)); auto Action = [Path = Path.str(), CB = std::move(CB), this](llvm::Expected<InputsAndAST> InpAST) mutable { diff --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp index 045b78d..830d4b2 100644 --- a/clang-tools-extra/clangd/CodeComplete.cpp +++ b/clang-tools-extra/clangd/CodeComplete.cpp @@ -261,14 +261,14 @@ struct CodeCompletionBuilder { if (C.SemaResult) { assert(ASTCtx); Completion.Origin |= SymbolOrigin::AST; - Completion.Name = llvm::StringRef(SemaCCS->getTypedText()); + Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText())); if (Completion.Scope.empty()) { if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) || (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern)) if (const auto *D = C.SemaResult->getDeclaration()) if (const auto *ND = dyn_cast<NamedDecl>(D)) - Completion.Scope = - splitQualifiedName(printQualifiedName(*ND)).first; + Completion.Scope = std::string( + splitQualifiedName(printQualifiedName(*ND)).first); } Completion.Kind = toCompletionItemKind( C.SemaResult->Kind, C.SemaResult->Declaration, ContextKind); @@ -291,11 +291,11 @@ struct CodeCompletionBuilder { if (C.IndexResult) { Completion.Origin |= C.IndexResult->Origin; if (Completion.Scope.empty()) - Completion.Scope = C.IndexResult->Scope; + Completion.Scope = std::string(C.IndexResult->Scope); if (Completion.Kind == CompletionItemKind::Missing) Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind); if (Completion.Name.empty()) - Completion.Name = C.IndexResult->Name; + Completion.Name = std::string(C.IndexResult->Name); // If the completion was visible to Sema, no qualifier is needed. This // avoids unneeded qualifiers in cases like with `using ns::X`. if (Completion.RequiredQualifier.empty() && !C.SemaResult) { @@ -306,14 +306,14 @@ struct CodeCompletionBuilder { Qualifier.size() < ShortestQualifier.size()) ShortestQualifier = Qualifier; } - Completion.RequiredQualifier = ShortestQualifier; + Completion.RequiredQualifier = std::string(ShortestQualifier); } Completion.Deprecated |= (C.IndexResult->Flags & Symbol::Deprecated); } if (C.IdentifierResult) { Completion.Origin |= SymbolOrigin::Identifier; Completion.Kind = CompletionItemKind::Text; - Completion.Name = C.IdentifierResult->Name; + Completion.Name = std::string(C.IdentifierResult->Name); } // Turn absolute path into a literal string that can be #included. @@ -367,13 +367,13 @@ struct CodeCompletionBuilder { &Completion.RequiredQualifier, IsPattern); S.ReturnType = getReturnType(*SemaCCS); } else if (C.IndexResult) { - S.Signature = C.IndexResult->Signature; - S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix; - S.ReturnType = C.IndexResult->ReturnType; + S.Signature = std::string(C.IndexResult->Signature); + S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix); + S.ReturnType = std::string(C.IndexResult->ReturnType); } if (ExtractDocumentation && Completion.Documentation.empty()) { if (C.IndexResult) - Completion.Documentation = C.IndexResult->Documentation; + Completion.Documentation = std::string(C.IndexResult->Documentation); else if (C.SemaResult) Completion.Documentation = getDocComment(*ASTCtx, *C.SemaResult, /*CommentsFromHeader=*/false); @@ -565,7 +565,7 @@ getQueryScopes(CodeCompletionContext &CCContext, const Sema &CCSema, StringRef SpelledSpecifier = HeuristicPrefix.Qualifier; if (SpelledSpecifier.consume_front("::")) Scopes.AccessibleScopes = {""}; - Scopes.UnresolvedQualifier = SpelledSpecifier; + Scopes.UnresolvedQualifier = std::string(SpelledSpecifier); return {Scopes.scopesForIndexQuery(), false}; } // The enclosing namespace must be first, it gets a quality boost. @@ -590,7 +590,7 @@ getQueryScopes(CodeCompletionContext &CCContext, const Sema &CCSema, CCSema.SourceMgr, clang::LangOptions()); if (SpelledSpecifier.consume_front("::")) Scopes.AccessibleScopes = {""}; - Scopes.UnresolvedQualifier = SpelledSpecifier; + Scopes.UnresolvedQualifier = std::string(SpelledSpecifier); // Sema excludes the trailing "::". if (!Scopes.UnresolvedQualifier->empty()) *Scopes.UnresolvedQualifier += "::"; @@ -859,7 +859,7 @@ public: } Index->lookup(IndexRequest, [&](const Symbol &S) { if (!S.Documentation.empty()) - FetchedDocs[S.ID] = S.Documentation; + FetchedDocs[S.ID] = std::string(S.Documentation); }); log("SigHelp: requested docs for {0} symbols from the index, got {1} " "symbols with non-empty docs in the response", @@ -925,7 +925,7 @@ private: ParameterInformation Info; Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset); // FIXME: only set 'labelOffsets' when all clients migrate out of it. - Info.labelString = ChunkText; + Info.labelString = std::string(ChunkText); Signature.parameters.push_back(std::move(Info)); } @@ -1054,7 +1054,7 @@ bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer, ParseInputs ParseInput; ParseInput.CompileCommand = Input.Command; ParseInput.FS = VFS; - ParseInput.Contents = Input.Contents; + ParseInput.Contents = std::string(Input.Contents); ParseInput.Opts = ParseOptions(); IgnoreDiagnostics IgnoreDiags; @@ -1069,7 +1069,7 @@ bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer, CI->getLangOpts()->SpellChecking = false; // Setup code completion. FrontendOpts.CodeCompleteOpts = Options; - FrontendOpts.CodeCompletionAt.FileName = Input.FileName; + FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName); std::tie(FrontendOpts.CodeCompletionAt.Line, FrontendOpts.CodeCompletionAt.Column) = offsetToClangLineColumn(Input.Contents, Input.Offset); @@ -1167,7 +1167,7 @@ std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index, // source code. FuzzyFindRequest speculativeFuzzyFindRequestForCompletion( FuzzyFindRequest CachedReq, const CompletionPrefix &HeuristicPrefix) { - CachedReq.Query = HeuristicPrefix.Name; + CachedReq.Query = std::string(HeuristicPrefix.Name); return CachedReq; } @@ -1377,9 +1377,10 @@ public: AllScopes = Opts.AllScopes; else if (HeuristicPrefix.Qualifier.startswith("::")) { Scopes.AccessibleScopes = {""}; - Scopes.UnresolvedQualifier = HeuristicPrefix.Qualifier.drop_front(2); + Scopes.UnresolvedQualifier = + std::string(HeuristicPrefix.Qualifier.drop_front(2)); } else - Scopes.UnresolvedQualifier = HeuristicPrefix.Qualifier; + Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier); // First scope is the (modified) enclosing scope. QueryScopes = Scopes.scopesForIndexQuery(); ScopeProximity.emplace(QueryScopes); @@ -1478,14 +1479,14 @@ private: FuzzyFindRequest Req; if (Opts.Limit) Req.Limit = Opts.Limit; - Req.Query = Filter->pattern(); + Req.Query = std::string(Filter->pattern()); Req.RestrictForCodeCompletion = true; Req.Scopes = QueryScopes; Req.AnyScope = AllScopes; // FIXME: we should send multiple weighted paths here. - Req.ProximityPaths.push_back(FileName); + Req.ProximityPaths.push_back(std::string(FileName)); if (PreferredType) - Req.PreferredTypes.push_back(PreferredType->raw()); + Req.PreferredTypes.push_back(std::string(PreferredType->raw())); vlog("Code complete: fuzzyFind({0:2})", toJSON(Req)); if (SpecFuzzyFind) @@ -1807,8 +1808,9 @@ CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const { RequiredQualifier + Name + Signature; LSP.kind = Kind; - LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize) - : ReturnType; + LSP.detail = BundleSize > 1 + ? std::string(llvm::formatv("[{0} overloads]", BundleSize)) + : ReturnType; LSP.deprecated = Deprecated; if (InsertInclude) LSP.detail += "\n" + InsertInclude->Header; diff --git a/clang-tools-extra/clangd/CompileCommands.cpp b/clang-tools-extra/clangd/CompileCommands.cpp index f11b123..ae343d5 100644 --- a/clang-tools-extra/clangd/CompileCommands.cpp +++ b/clang-tools-extra/clangd/CompileCommands.cpp @@ -65,7 +65,7 @@ std::string resolve(std::string Path) { log("Failed to resolve possible symlink {0}", Path); return Path; } - return Resolved.str(); + return std::string(Resolved.str()); } // Get a plausible full `clang` path. @@ -97,7 +97,7 @@ std::string detectClangPath() { SmallString<128> ClangPath; ClangPath = llvm::sys::path::parent_path(ClangdExecutable); llvm::sys::path::append(ClangPath, "clang"); - return ClangPath.str(); + return std::string(ClangPath.str()); } // On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang. @@ -171,7 +171,7 @@ void CommandMangler::adjust(std::vector<std::string> &Cmd) const { llvm::SmallString<128> QualifiedDriver = llvm::sys::path::parent_path(*ClangPath); llvm::sys::path::append(QualifiedDriver, Driver); - Driver = QualifiedDriver.str(); + Driver = std::string(QualifiedDriver.str()); } } } diff --git a/clang-tools-extra/clangd/Diagnostics.cpp b/clang-tools-extra/clangd/Diagnostics.cpp index ad8f6c8..380ce25 100644 --- a/clang-tools-extra/clangd/Diagnostics.cpp +++ b/clang-tools-extra/clangd/Diagnostics.cpp @@ -154,8 +154,8 @@ bool adjustDiagFromHeader(Diag &D, const clang::Diagnostic &Info, const auto *FE = SM.getFileEntryForID(SM.getFileID(DiagLoc)); D.Notes.emplace_back(); Note &N = D.Notes.back(); - N.AbsFile = FE->tryGetRealPathName(); - N.File = FE->getName(); + N.AbsFile = std::string(FE->tryGetRealPathName()); + N.File = std::string(FE->getName()); N.Message = "error occurred here"; N.Range = diagnosticRange(Info, LangOpts); @@ -320,7 +320,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const Diag &D) { CodeAction toCodeAction(const Fix &F, const URIForFile &File) { CodeAction Action; Action.title = F.Message; - Action.kind = CodeAction::QUICKFIX_KIND; + Action.kind = std::string(CodeAction::QUICKFIX_KIND); Action.edit.emplace(); Action.edit->changes.emplace(); (*Action.edit->changes)[File.uri()] = {F.Edits.begin(), F.Edits.end()}; @@ -430,7 +430,7 @@ std::vector<Diag> StoreDiags::take(const clang::tidy::ClangTidyContext *Tidy) { // Almost always an error, with a name like err_enum_class_reference. // Drop the err_ prefix for brevity. Name.consume_front("err_"); - Diag.Name = Name; + Diag.Name = std::string(Name); } Diag.Source = Diag::Clang; continue; @@ -500,7 +500,7 @@ static void fillNonLocationData(DiagnosticsEngine::Level DiagLevel, llvm::SmallString<64> Message; Info.FormatDiagnostic(Message); - D.Message = Message.str(); + D.Message = std::string(Message.str()); D.Severity = DiagLevel; D.Category = DiagnosticIDs::getCategoryNameFromID( DiagnosticIDs::getCategoryNumberForDiag(Info.getID())) @@ -544,7 +544,7 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, D.InsideMainFile = InsideMainFile; D.Range = diagnosticRange(Info, *LangOpts); - D.File = SM.getFilename(Info.getLocation()); + D.File = std::string(SM.getFilename(Info.getLocation())); D.AbsFile = getCanonicalPath( SM.getFileEntryForID(SM.getFileID(Info.getLocation())), SM); return D; @@ -599,7 +599,8 @@ void StoreDiags::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, } if (Message.empty()) // either !SytheticMessage, or we failed to make one. Info.FormatDiagnostic(Message); - LastDiag->Fixes.push_back(Fix{Message.str(), std::move(Edits)}); + LastDiag->Fixes.push_back( + Fix{std::string(Message.str()), std::move(Edits)}); return true; }; diff --git a/clang-tools-extra/clangd/DraftStore.cpp b/clang-tools-extra/clangd/DraftStore.cpp index dcf4813..d4a5d0c 100644 --- a/clang-tools-extra/clangd/DraftStore.cpp +++ b/clang-tools-extra/clangd/DraftStore.cpp @@ -28,7 +28,7 @@ std::vector<Path> DraftStore::getActiveFiles() const { std::vector<Path> ResultVector; for (auto DraftIt = Drafts.begin(); DraftIt != Drafts.end(); DraftIt++) - ResultVector.push_back(DraftIt->getKey()); + ResultVector.push_back(std::string(DraftIt->getKey())); return ResultVector; } @@ -36,7 +36,7 @@ std::vector<Path> DraftStore::getActiveFiles() const { void DraftStore::addDraft(PathRef File, llvm::StringRef Contents) { std::lock_guard<std::mutex> Lock(Mutex); - Drafts[File] = Contents; + Drafts[File] = std::string(Contents); } llvm::Expected<std::string> DraftStore::updateDraft( diff --git a/clang-tools-extra/clangd/ExpectedTypes.cpp b/clang-tools-extra/clangd/ExpectedTypes.cpp index a82a64c..e0a4e47 100644 --- a/clang-tools-extra/clangd/ExpectedTypes.cpp +++ b/clang-tools-extra/clangd/ExpectedTypes.cpp @@ -73,7 +73,7 @@ llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) { llvm::SmallString<128> Encoded; if (index::generateUSRForType(QualType(C, 0), Ctx, Encoded)) return None; - return OpaqueType(Encoded.str()); + return OpaqueType(std::string(Encoded.str())); } OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {} diff --git a/clang-tools-extra/clangd/FS.cpp b/clang-tools-extra/clangd/FS.cpp index 4f04fb0..6eea602 100644 --- a/clang-tools-extra/clangd/FS.cpp +++ b/clang-tools-extra/clangd/FS.cpp @@ -19,7 +19,7 @@ PreambleFileStatusCache::PreambleFileStatusCache(llvm::StringRef MainFilePath){ assert(llvm::sys::path::is_absolute(MainFilePath)); llvm::SmallString<256> MainFileCanonical(MainFilePath); llvm::sys::path::remove_dots(MainFileCanonical, /*remove_dot_dot=*/true); - this->MainFilePath = MainFileCanonical.str(); + this->MainFilePath = std::string(MainFileCanonical.str()); } void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS, diff --git a/clang-tools-extra/clangd/FindSymbols.cpp b/clang-tools-extra/clangd/FindSymbols.cpp index 1ce4222..ee6e256 100644 --- a/clang-tools-extra/clangd/FindSymbols.cpp +++ b/clang-tools-extra/clangd/FindSymbols.cpp @@ -73,14 +73,14 @@ getWorkspaceSymbols(llvm::StringRef Query, int Limit, auto Names = splitQualifiedName(Query); FuzzyFindRequest Req; - Req.Query = Names.second; + Req.Query = std::string(Names.second); // FuzzyFind doesn't want leading :: qualifier bool IsGlobalQuery = Names.first.consume_front("::"); // Restrict results to the scope in the query string if present (global or // not). if (IsGlobalQuery || !Names.first.empty()) - Req.Scopes = {Names.first}; + Req.Scopes = {std::string(Names.first)}; else Req.AnyScope = true; if (Limit) @@ -96,11 +96,11 @@ getWorkspaceSymbols(llvm::StringRef Query, int Limit, } SymbolKind SK = indexSymbolKindToSymbolKind(Sym.SymInfo.Kind); - std::string Scope = Sym.Scope; + std::string Scope = std::string(Sym.Scope); llvm::StringRef ScopeRef = Scope; ScopeRef.consume_back("::"); SymbolInformation Info = {(Sym.Name + Sym.TemplateSpecializationArgs).str(), - SK, *Loc, ScopeRef}; + SK, *Loc, std::string(ScopeRef)}; SymbolQualitySignals Quality; Quality.merge(Sym); diff --git a/clang-tools-extra/clangd/FindTarget.cpp b/clang-tools-extra/clangd/FindTarget.cpp index 352674eb..2392586 100644 --- a/clang-tools-extra/clangd/FindTarget.cpp +++ b/clang-tools-extra/clangd/FindTarget.cpp @@ -46,7 +46,7 @@ using ast_type_traits::DynTypedNode; LLVM_ATTRIBUTE_UNUSED std::string nodeToString(const ast_type_traits::DynTypedNode &N) { - std::string S = N.getNodeKind().asStringRef(); + std::string S = std::string(N.getNodeKind().asStringRef()); { llvm::raw_string_ostream OS(S); OS << ": "; diff --git a/clang-tools-extra/clangd/Format.cpp b/clang-tools-extra/clangd/Format.cpp index f34a16d..06b4b84 100644 --- a/clang-tools-extra/clangd/Format.cpp +++ b/clang-tools-extra/clangd/Format.cpp @@ -326,7 +326,7 @@ formatIncremental(llvm::StringRef OriginalCode, unsigned OriginalCursor, tooling::Replacements Final; unsigned FinalCursor = OriginalCursor; #ifndef NDEBUG - std::string FinalCode = OriginalCode; + std::string FinalCode = std::string(OriginalCode); dlog("Initial code: {0}", FinalCode); #endif for (auto Pass : diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp index 34a0346..f2a6083 100644 --- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp +++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp @@ -50,7 +50,7 @@ GlobalCompilationDatabase::getFallbackCommand(PathRef File) const { auto FileExtension = llvm::sys::path::extension(File); if (FileExtension.empty() || FileExtension == ".h") Argv.push_back("-xobjective-c++-header"); - Argv.push_back(File); + Argv.push_back(std::string(File)); tooling::CompileCommand Cmd(llvm::sys::path::parent_path(File), llvm::sys::path::filename(File), std::move(Argv), /*Output=*/""); @@ -95,7 +95,7 @@ static std::string maybeCaseFoldPath(PathRef Path) { #if defined(_WIN32) || defined(__APPLE__) return Path.lower(); #else - return Path; + return std::string(Path); #endif } @@ -117,7 +117,7 @@ DirectoryBasedGlobalCompilationDatabase::getCDBInDirLocked(PathRef Dir) const { CachedCDB &Entry = R.first->second; std::string Error = ""; Entry.CDB = tooling::CompilationDatabase::loadFromDirectory(Dir, Error); - Entry.Path = Dir; + Entry.Path = std::string(Dir); } return R.first->second; } diff --git a/clang-tools-extra/clangd/HeaderSourceSwitch.cpp b/clang-tools-extra/clangd/HeaderSourceSwitch.cpp index f90e46a..1490d3e 100644 --- a/clang-tools-extra/clangd/HeaderSourceSwitch.cpp +++ b/clang-tools-extra/clangd/HeaderSourceSwitch.cpp @@ -121,7 +121,7 @@ llvm::Optional<Path> getCorrespondingHeaderOrSource(const Path &OriginalFile, // candidates. Best = It; } - return Path(Best->first()); + return Path(std::string(Best->first())); } std::vector<const Decl *> getIndexableLocalDecls(ParsedAST &AST) { diff --git a/clang-tools-extra/clangd/Headers.cpp b/clang-tools-extra/clangd/Headers.cpp index 525f770..e94a768 100644 --- a/clang-tools-extra/clangd/Headers.cpp +++ b/clang-tools-extra/clangd/Headers.cpp @@ -41,7 +41,7 @@ public: Inc.R = halfOpenToRange(SM, FilenameRange); Inc.Written = (IsAngled ? "<" + FileName + ">" : "\"" + FileName + "\"").str(); - Inc.Resolved = File ? File->tryGetRealPathName() : ""; + Inc.Resolved = std::string(File ? File->tryGetRealPathName() : ""); Inc.HashOffset = SM.getFileOffset(HashLoc); Inc.FileKind = FileKind; } @@ -120,7 +120,7 @@ void IncludeStructure::recordInclude(llvm::StringRef IncludingName, llvm::StringRef IncludedRealName) { auto Child = fileIndex(IncludedName); if (!IncludedRealName.empty() && RealPathNames[Child].empty()) - RealPathNames[Child] = IncludedRealName; + RealPathNames[Child] = std::string(IncludedRealName); auto Parent = fileIndex(IncludingName); IncludeChildren[Parent].push_back(Child); } diff --git a/clang-tools-extra/clangd/Hover.cpp b/clang-tools-extra/clangd/Hover.cpp index 834c9d0..803efdf 100644 --- a/clang-tools-extra/clangd/Hover.cpp +++ b/clang-tools-extra/clangd/Hover.cpp @@ -245,8 +245,9 @@ void enhanceFromIndex(HoverInfo &Hover, const NamedDecl &ND, return; LookupRequest Req; Req.IDs.insert(*ID); - Index->lookup( - Req, [&](const Symbol &S) { Hover.Documentation = S.Documentation; }); + Index->lookup(Req, [&](const Symbol &S) { + Hover.Documentation = std::string(S.Documentation); + }); } // Populates Type, ReturnType, and Parameters for function-like decls. @@ -410,7 +411,7 @@ HoverInfo getHoverContents(QualType T, ASTContext &ASTCtx, HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) { HoverInfo HI; SourceManager &SM = AST.getSourceManager(); - HI.Name = Macro.Name; + HI.Name = std::string(Macro.Name); HI.Kind = index::SymbolKind::Macro; // FIXME: Populate documentation // FIXME: Pupulate parameters @@ -473,7 +474,7 @@ llvm::Optional<HoverInfo> getHoverContents(const Expr *E, ParsedAST &AST) { Policy.SuppressTagKeyword = true; HI.Type = printType(E->getType(), Policy); HI.Value = *Val; - HI.Name = getNameForExpr(E); + HI.Name = std::string(getNameForExpr(E)); return HI; } return llvm::None; @@ -545,7 +546,7 @@ markup::Document HoverInfo::present() const { // https://github.com/microsoft/vscode/issues/88417 for details. markup::Paragraph &Header = Output.addHeading(3); if (Kind != index::SymbolKind::Unknown) - Header.appendText(index::getSymbolKindString(Kind)); + Header.appendText(std::string(index::getSymbolKindString(Kind))); assert(!Name.empty() && "hover triggered on a nameless symbol"); Header.appendCode(Name); diff --git a/clang-tools-extra/clangd/IncludeFixer.cpp b/clang-tools-extra/clangd/IncludeFixer.cpp index 17280d6..45fb07a 100644 --- a/clang-tools-extra/clangd/IncludeFixer.cpp +++ b/clang-tools-extra/clangd/IncludeFixer.cpp @@ -173,10 +173,10 @@ std::vector<Fix> IncludeFixer::fixesForSymbols(const SymbolSlab &Syms) const { if (!I.second) continue; if (auto Edit = Inserter->insert(ToInclude->first)) - Fixes.push_back( - Fix{llvm::formatv("Add include {0} for symbol {1}{2}", - ToInclude->first, Sym.Scope, Sym.Name), - {std::move(*Edit)}}); + Fixes.push_back(Fix{std::string(llvm::formatv( + "Add include {0} for symbol {1}{2}", + ToInclude->first, Sym.Scope, Sym.Name)), + {std::move(*Edit)}}); } } else { vlog("Failed to calculate include insertion for {0} into {1}: {2}", Inc, @@ -295,7 +295,7 @@ llvm::Optional<CheapUnresolvedName> extractUnresolvedNameCheaply( // it as extra scope. With "index" being a specifier, we append "index::" // to the extra scope. Result.UnresolvedScope->append((Result.Name + Split.first).str()); - Result.Name = Split.second; + Result.Name = std::string(Split.second); } } return Result; diff --git a/clang-tools-extra/clangd/JSONTransport.cpp b/clang-tools-extra/clangd/JSONTransport.cpp index 6351b80..43be9f7 100644 --- a/clang-tools-extra/clangd/JSONTransport.cpp +++ b/clang-tools-extra/clangd/JSONTransport.cpp @@ -34,7 +34,8 @@ llvm::json::Object encodeError(llvm::Error E) { } llvm::Error decodeError(const llvm::json::Object &O) { - std::string Msg = O.getString("message").getValueOr("Unspecified error"); + std::string Msg = + std::string(O.getString("message").getValueOr("Unspecified error")); if (auto Code = O.getInteger("code")) return llvm::make_error<LSPError>(std::move(Msg), ErrorCode(*Code)); return llvm::make_error<llvm::StringError>(std::move(Msg), diff --git a/clang-tools-extra/clangd/ParsedAST.cpp b/clang-tools-extra/clangd/ParsedAST.cpp index 4236a97..c8c06fd 100644 --- a/clang-tools-extra/clangd/ParsedAST.cpp +++ b/clang-tools-extra/clangd/ParsedAST.cpp @@ -229,8 +229,9 @@ ParsedAST::build(std::unique_ptr<clang::CompilerInvocation> CI, Preamble ? &Preamble->Preamble : nullptr; StoreDiags ASTDiags; - std::string Content = Buffer->getBuffer(); - std::string Filename = Buffer->getBufferIdentifier(); // Absolute. + std::string Content = std::string(Buffer->getBuffer()); + std::string Filename = + std::string(Buffer->getBufferIdentifier()); // Absolute. auto Clang = prepareCompilerInstance(std::move(CI), PreamblePCH, std::move(Buffer), VFS, ASTDiags); diff --git a/clang-tools-extra/clangd/PathMapping.cpp b/clang-tools-extra/clangd/PathMapping.cpp index e130f38..8740d58 100644 --- a/clang-tools-extra/clangd/PathMapping.cpp +++ b/clang-tools-extra/clangd/PathMapping.cpp @@ -149,7 +149,7 @@ private: llvm::Expected<std::string> parsePath(llvm::StringRef Path) { namespace path = llvm::sys::path; if (path::is_absolute(Path, path::Style::posix)) { - return Path; + return std::string(Path); } else if (path::is_absolute(Path, path::Style::windows)) { std::string Converted = path::convert_to_slash(Path, path::Style::windows); if (Converted.front() != '/') diff --git a/clang-tools-extra/clangd/Protocol.cpp b/clang-tools-extra/clangd/Protocol.cpp index 87f7656..aabf0fa 100644 --- a/clang-tools-extra/clangd/Protocol.cpp +++ b/clang-tools-extra/clangd/Protocol.cpp @@ -37,7 +37,7 @@ URIForFile URIForFile::canonicalize(llvm::StringRef AbsPath, elog("URIForFile: failed to resolve path {0} with TU path {1}: " "{2}.\nUsing unresolved path.", AbsPath, TUPath, Resolved.takeError()); - return URIForFile(AbsPath); + return URIForFile(std::string(AbsPath)); } return URIForFile(std::move(*Resolved)); } diff --git a/clang-tools-extra/clangd/QueryDriverDatabase.cpp b/clang-tools-extra/clangd/QueryDriverDatabase.cpp index 4953da5..e4f5c48 100644 --- a/clang-tools-extra/clangd/QueryDriverDatabase.cpp +++ b/clang-tools-extra/clangd/QueryDriverDatabase.cpp @@ -243,11 +243,13 @@ public: { std::lock_guard<std::mutex> Lock(Mu); - auto It = DriverToIncludesCache.find(Key); + auto It = DriverToIncludesCache.find( + {std::string(Key.first), std::string(Key.second)}); if (It != DriverToIncludesCache.end()) SystemIncludes = It->second; else - DriverToIncludesCache[Key] = SystemIncludes = + DriverToIncludesCache[{std::string(Key.first), + std::string(Key.second)}] = SystemIncludes = extractSystemIncludes(Key.first, Key.second, QueryDriverRegex); } diff --git a/clang-tools-extra/clangd/SourceCode.cpp b/clang-tools-extra/clangd/SourceCode.cpp index 15403d2..67cea92 100644 --- a/clang-tools-extra/clangd/SourceCode.cpp +++ b/clang-tools-extra/clangd/SourceCode.cpp @@ -608,7 +608,7 @@ TextEdit replacementToEdit(llvm::StringRef Code, Range ReplacementRange = { offsetToPosition(Code, R.getOffset()), offsetToPosition(Code, R.getOffset() + R.getLength())}; - return {ReplacementRange, R.getReplacementText()}; + return {ReplacementRange, std::string(R.getReplacementText())}; } std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code, @@ -801,12 +801,12 @@ void parseNamespaceEvents(llvm::StringRef Code, switch (State) { case UsingNamespace: case UsingNamespaceName: - NSName.append(Tok.getRawIdentifier()); + NSName.append(std::string(Tok.getRawIdentifier())); State = UsingNamespaceName; break; case Namespace: case NamespaceName: - NSName.append(Tok.getRawIdentifier()); + NSName.append(std::string(Tok.getRawIdentifier())); State = NamespaceName; break; case Using: @@ -928,11 +928,11 @@ std::vector<std::string> visibleNamespaces(llvm::StringRef Code, std::vector<std::string> Found; for (llvm::StringRef Enclosing : ancestorNamespaces(Current)) { - Found.push_back(Enclosing); + Found.push_back(std::string(Enclosing)); auto It = UsingDirectives.find(Enclosing); if (It != UsingDirectives.end()) for (const auto &Used : It->second) - Found.push_back(Used.getKey()); + Found.push_back(std::string(Used.getKey())); } llvm::sort(Found, [&](const std::string &LHS, const std::string &RHS) { diff --git a/clang-tools-extra/clangd/TUScheduler.cpp b/clang-tools-extra/clangd/TUScheduler.cpp index c4f9e6e..9ea1582 100644 --- a/clang-tools-extra/clangd/TUScheduler.cpp +++ b/clang-tools-extra/clangd/TUScheduler.cpp @@ -644,7 +644,7 @@ void ASTWorker::startTask(llvm::StringRef Name, std::lock_guard<std::mutex> Lock(Mutex); assert(!Done && "running a task after stop()"); Requests.push_back( - {std::move(Task), Name, steady_clock::now(), + {std::move(Task), std::string(Name), steady_clock::now(), Context::current().derive(kFileBeingProcessed, FileName), UpdateType}); } RequestsCV.notify_all(); @@ -986,31 +986,32 @@ void TUScheduler::runWithPreamble(llvm::StringRef Name, PathRef File, } std::shared_ptr<const ASTWorker> Worker = It->second->Worker.lock(); - auto Task = [Worker, Consistency, Name = Name.str(), File = File.str(), - Contents = It->second->Contents, - Command = Worker->getCurrentCompileCommand(), - Ctx = Context::current().derive(kFileBeingProcessed, File), - ConsistentPreamble = std::move(ConsistentPreamble), - Action = std::move(Action), this]() mutable { - std::shared_ptr<const PreambleData> Preamble; - if (ConsistentPreamble.valid()) { - Preamble = ConsistentPreamble.get(); - } else { - if (Consistency != PreambleConsistency::StaleOrAbsent) { - // Wait until the preamble is built for the first time, if preamble is - // required. This avoids extra work of processing the preamble headers - // in parallel multiple times. - Worker->waitForFirstPreamble(); - } - Preamble = Worker->getPossiblyStalePreamble(); - } + auto Task = + [Worker, Consistency, Name = Name.str(), File = File.str(), + Contents = It->second->Contents, + Command = Worker->getCurrentCompileCommand(), + Ctx = Context::current().derive(kFileBeingProcessed, std::string(File)), + ConsistentPreamble = std::move(ConsistentPreamble), + Action = std::move(Action), this]() mutable { + std::shared_ptr<const PreambleData> Preamble; + if (ConsistentPreamble.valid()) { + Preamble = ConsistentPreamble.get(); + } else { + if (Consistency != PreambleConsistency::StaleOrAbsent) { + // Wait until the preamble is built for the first time, if preamble + // is required. This avoids extra work of processing the preamble + // headers in parallel multiple times. + Worker->waitForFirstPreamble(); + } + Preamble = Worker->getPossiblyStalePreamble(); + } - std::lock_guard<Semaphore> BarrierLock(Barrier); - WithContext Guard(std::move(Ctx)); - trace::Span Tracer(Name); - SPAN_ATTACH(Tracer, "file", File); - Action(InputsAndPreamble{Contents, Command, Preamble.get()}); - }; + std::lock_guard<Semaphore> BarrierLock(Barrier); + WithContext Guard(std::move(Ctx)); + trace::Span Tracer(Name); + SPAN_ATTACH(Tracer, "file", File); + Action(InputsAndPreamble{Contents, Command, Preamble.get()}); + }; PreambleTasks->runAsync("task:" + llvm::sys::path::filename(File), std::move(Task)); @@ -1021,8 +1022,8 @@ TUScheduler::getUsedBytesPerFile() const { std::vector<std::pair<Path, std::size_t>> Result; Result.reserve(Files.size()); for (auto &&PathAndFile : Files) - Result.push_back( - {PathAndFile.first(), PathAndFile.second->Worker->getUsedBytes()}); + Result.push_back({std::string(PathAndFile.first()), + PathAndFile.second->Worker->getUsedBytes()}); return Result; } @@ -1031,7 +1032,7 @@ std::vector<Path> TUScheduler::getFilesWithCachedAST() const { for (auto &&PathAndFile : Files) { if (!PathAndFile.second->Worker->isASTCached()) continue; - Result.push_back(PathAndFile.first()); + Result.push_back(std::string(PathAndFile.first())); } return Result; } diff --git a/clang-tools-extra/clangd/URI.cpp b/clang-tools-extra/clangd/URI.cpp index f8a9f59..1a125e7 100644 --- a/clang-tools-extra/clangd/URI.cpp +++ b/clang-tools-extra/clangd/URI.cpp @@ -255,7 +255,7 @@ llvm::Expected<std::string> URI::resolvePath(llvm::StringRef AbsPath, return S->getAbsolutePath(U->Authority, U->Body, HintPath); } // Fallback to file: scheme which doesn't do any canonicalization. - return AbsPath; + return std::string(AbsPath); } llvm::Expected<std::string> URI::includeSpelling(const URI &Uri) { diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp index ac62393..6e625d8 100644 --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -201,7 +201,7 @@ std::vector<LocatedSymbol> locateSymbolAt(ParsedAST &AST, Position Pos, for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) { if (!Inc.Resolved.empty() && Inc.R.start.line == Pos.line) { LocatedSymbol File; - File.Name = llvm::sys::path::filename(Inc.Resolved); + File.Name = std::string(llvm::sys::path::filename(Inc.Resolved)); File.PreferredDeclaration = { URIForFile::canonicalize(Inc.Resolved, *MainFilePath), Range{}}; File.Definition = File.PreferredDeclaration; @@ -219,7 +219,7 @@ std::vector<LocatedSymbol> locateSymbolAt(ParsedAST &AST, Position Pos, if (auto Loc = makeLocation(AST.getASTContext(), M->Info->getDefinitionLoc(), *MainFilePath)) { LocatedSymbol Macro; - Macro.Name = M->Name; + Macro.Name = std::string(M->Name); Macro.PreferredDeclaration = *Loc; Macro.Definition = Loc; Result.push_back(std::move(Macro)); @@ -530,8 +530,9 @@ std::vector<SymbolDetails> getSymbolInfo(ParsedAST &AST, Position Pos) { for (const NamedDecl *D : getDeclAtPosition(AST, Loc, Relations)) { SymbolDetails NewSymbol; std::string QName = printQualifiedName(*D); - std::tie(NewSymbol.containerName, NewSymbol.name) = - splitQualifiedName(QName); + auto SplitQName = splitQualifiedName(QName); + NewSymbol.containerName = std::string(SplitQName.first); + NewSymbol.name = std::string(SplitQName.second); if (NewSymbol.containerName.empty()) { if (const auto *ParentND = @@ -540,7 +541,7 @@ std::vector<SymbolDetails> getSymbolInfo(ParsedAST &AST, Position Pos) { } llvm::SmallString<32> USR; if (!index::generateUSRForDecl(D, USR)) { - NewSymbol.USR = USR.str(); + NewSymbol.USR = std::string(USR.str()); NewSymbol.ID = SymbolID(NewSymbol.USR); } Results.push_back(std::move(NewSymbol)); @@ -548,11 +549,11 @@ std::vector<SymbolDetails> getSymbolInfo(ParsedAST &AST, Position Pos) { if (auto M = locateMacroAt(Loc, AST.getPreprocessor())) { SymbolDetails NewMacro; - NewMacro.name = M->Name; + NewMacro.name = std::string(M->Name); llvm::SmallString<32> USR; if (!index::generateUSRForMacro(NewMacro.name, M->Info->getDefinitionLoc(), SM, USR)) { - NewMacro.USR = USR.str(); + NewMacro.USR = std::string(USR.str()); NewMacro.ID = SymbolID(NewMacro.USR); } Results.push_back(std::move(NewMacro)); @@ -624,7 +625,7 @@ symbolToTypeHierarchyItem(const Symbol &S, const SymbolIndex *Index, return llvm::None; } TypeHierarchyItem THI; - THI.name = S.Name; + THI.name = std::string(S.Name); THI.kind = indexSymbolKindToSymbolKind(S.SymInfo.Kind); THI.deprecated = (S.Flags & Symbol::Deprecated); THI.selectionRange = Loc->range; diff --git a/clang-tools-extra/clangd/index/Background.cpp b/clang-tools-extra/clangd/index/Background.cpp index dd198f0..ab80113 100644 --- a/clang-tools-extra/clangd/index/Background.cpp +++ b/clang-tools-extra/clangd/index/Background.cpp @@ -202,7 +202,7 @@ BackgroundIndex::indexFileTask(tooling::CompileCommand Cmd) { elog("Indexing {0} failed: {1}", FileName, std::move(Error)); }); T.QueuePri = IndexFile; - T.Tag = filenameWithoutExtension(Cmd.Filename); + T.Tag = std::string(filenameWithoutExtension(Cmd.Filename)); return T; } diff --git a/clang-tools-extra/clangd/index/BackgroundIndexLoader.cpp b/clang-tools-extra/clangd/index/BackgroundIndexLoader.cpp index ff690f9..08bf07d 100644 --- a/clang-tools-extra/clangd/index/BackgroundIndexLoader.cpp +++ b/clang-tools-extra/clangd/index/BackgroundIndexLoader.cpp @@ -59,7 +59,7 @@ BackgroundIndexLoader::loadShard(PathRef StartSourceFile, PathRef DependentTU) { return {LS, Edges}; LS.AbsolutePath = StartSourceFile.str(); - LS.DependentTU = DependentTU; + LS.DependentTU = std::string(DependentTU); BackgroundIndexStorage *Storage = IndexStorageFactory(LS.AbsolutePath); auto Shard = Storage->loadShard(StartSourceFile); if (!Shard || !Shard->Sources) { diff --git a/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp b/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp index 48510e1..b07728e 100644 --- a/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp +++ b/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp @@ -33,7 +33,7 @@ std::string getShardPathFromFilePath(llvm::StringRef ShardRoot, llvm::sys::path::append(ShardRootSS, llvm::sys::path::filename(FilePath) + "." + llvm::toHex(digest(FilePath)) + ".idx"); - return ShardRootSS.str(); + return std::string(ShardRootSS.str()); } // Uses disk as a storage for index shards. Creates a directory called @@ -47,7 +47,7 @@ public: DiskBackedIndexStorage(llvm::StringRef Directory) { llvm::SmallString<128> CDBDirectory(Directory); llvm::sys::path::append(CDBDirectory, ".clangd", "index"); - DiskShardRoot = CDBDirectory.str(); + DiskShardRoot = std::string(CDBDirectory.str()); std::error_code OK; std::error_code EC = llvm::sys::fs::create_directories(DiskShardRoot); if (EC != OK) { diff --git a/clang-tools-extra/clangd/index/CanonicalIncludes.cpp b/clang-tools-extra/clangd/index/CanonicalIncludes.cpp index 0025a7c..a3b1334 100644 --- a/clang-tools-extra/clangd/index/CanonicalIncludes.cpp +++ b/clang-tools-extra/clangd/index/CanonicalIncludes.cpp @@ -21,7 +21,7 @@ const char IWYUPragma[] = "// IWYU pragma: private, include "; void CanonicalIncludes::addMapping(llvm::StringRef Path, llvm::StringRef CanonicalPath) { - FullPathMapping[Path] = CanonicalPath; + FullPathMapping[Path] = std::string(CanonicalPath); } /// The maximum number of path components in a key from StdSuffixHeaderMapping. diff --git a/clang-tools-extra/clangd/index/FileIndex.cpp b/clang-tools-extra/clangd/index/FileIndex.cpp index 179e143..7641aa5 100644 --- a/clang-tools-extra/clangd/index/FileIndex.cpp +++ b/clang-tools-extra/clangd/index/FileIndex.cpp @@ -67,7 +67,8 @@ static SlabTuple indexSymbols(ASTContext &AST, std::shared_ptr<Preprocessor> PP, const auto &SM = AST.getSourceManager(); const auto *MainFileEntry = SM.getFileEntryForID(SM.getMainFileID()); - std::string FileName = MainFileEntry ? MainFileEntry->getName() : ""; + std::string FileName = + std::string(MainFileEntry ? MainFileEntry->getName() : ""); auto Syms = Collector.takeSymbols(); auto Refs = Collector.takeRefs(); diff --git a/clang-tools-extra/clangd/index/Serialization.cpp b/clang-tools-extra/clangd/index/Serialization.cpp index 219c896..440fdc6 100644 --- a/clang-tools-extra/clangd/index/Serialization.cpp +++ b/clang-tools-extra/clangd/index/Serialization.cpp @@ -169,7 +169,7 @@ public: std::string RawTable; for (llvm::StringRef S : Sorted) { - RawTable.append(S); + RawTable.append(std::string(S)); RawTable.push_back(0); } if (llvm::zlib::isAvailable()) { @@ -501,7 +501,7 @@ llvm::Expected<IndexFileIn> readRIFF(llvm::StringRef Data) { InternedCompileCommand Cmd = readCompileCommand(CmdReader, Strings->Strings); Result.Cmd.emplace(); - Result.Cmd->Directory = Cmd.Directory; + Result.Cmd->Directory = std::string(Cmd.Directory); Result.Cmd->CommandLine.reserve(Cmd.CommandLine.size()); for (llvm::StringRef C : Cmd.CommandLine) Result.Cmd->CommandLine.emplace_back(C); diff --git a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp index 81e435f..66477ad 100644 --- a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp +++ b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp @@ -55,13 +55,13 @@ std::vector<SymbolID> getSymbolIDsFromIndex(llvm::StringRef QualifiedName, bool IsGlobalScope = QualifiedName.consume_front("::"); auto Names = splitQualifiedName(QualifiedName); if (IsGlobalScope || !Names.first.empty()) - Request.Scopes = {Names.first}; + Request.Scopes = {std::string(Names.first)}; else // QualifiedName refers to a symbol in global scope (e.g. "GlobalSymbol"), // add the global scope to the request. Request.Scopes = {""}; - Request.Query = Names.second; + Request.Query = std::string(Names.second); std::vector<SymbolID> SymIDs; Index->fuzzyFind(Request, [&](const Symbol &Sym) { std::string SymQualifiedName = (Sym.Scope + Sym.Name).str(); diff --git a/clang-tools-extra/clangd/refactor/Tweak.h b/clang-tools-extra/clangd/refactor/Tweak.h index 14f9ffc..ca4d43d 100644 --- a/clang-tools-extra/clangd/refactor/Tweak.h +++ b/clang-tools-extra/clangd/refactor/Tweak.h @@ -81,7 +81,7 @@ public: static Effect showMessage(StringRef S) { Effect E; - E.ShowMessage = S; + E.ShowMessage = std::string(S); return E; } diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp index 3d345cd..8f396e3 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp @@ -250,7 +250,7 @@ renameParameters(const FunctionDecl *Dest, const FunctionDecl *Source) { // with previous token, e.g. foo(int^) shouldn't turn into foo(intx). NewName = " "; } - NewName.append(SourceParam->getName()); + NewName.append(std::string(SourceParam->getName())); ParamToNewName[DestParam->getCanonicalDecl()] = std::move(NewName); }; diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp index a6fcc72..bdfd0e4 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp @@ -64,10 +64,11 @@ const FunctionDecl *getSelectedFunction(const SelectionTree::Node *SelNode) { llvm::Optional<Path> getSourceFile(llvm::StringRef FileName, const Tweak::Selection &Sel) { if (auto Source = getCorrespondingHeaderOrSource( - FileName, + std::string(FileName), &Sel.AST->getSourceManager().getFileManager().getVirtualFileSystem())) return *Source; - return getCorrespondingHeaderOrSource(FileName, *Sel.AST, Sel.Index); + return getCorrespondingHeaderOrSource(std::string(FileName), *Sel.AST, + Sel.Index); } // Synthesize a DeclContext for TargetNS from CurContext. TargetNS must be empty diff --git a/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp b/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp index f681400..616e100 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp @@ -42,7 +42,8 @@ public: } Expected<Effect> apply(const Selection &Inputs) override; std::string title() const override { - return llvm::formatv("Dump {0} AST", Node->getNodeKind().asStringRef()); + return std::string( + llvm::formatv("Dump {0} AST", Node->getNodeKind().asStringRef())); } Intent intent() const override { return Info; } bool hidden() const override { return true; } @@ -148,9 +149,9 @@ public: return Effect::showMessage(std::move(OS.str())); } std::string title() const override { - return llvm::formatv( + return std::string(llvm::formatv( "Show {0} layout", - TypeWithKeyword::getTagTypeKindName(Record->getTagKind())); + TypeWithKeyword::getTagTypeKindName(Record->getTagKind()))); } Intent intent() const override { return Info; } // FIXME: this is interesting to most users. However: diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExpandMacro.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExpandMacro.cpp index eb15d03..59a53f97 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/ExpandMacro.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/ExpandMacro.cpp @@ -98,7 +98,7 @@ bool ExpandMacro::prepare(const Selection &Inputs) { auto Expansion = Inputs.AST->getTokens().expansionStartingAt(T); if (!Expansion) return false; - this->MacroName = T->text(Inputs.AST->getSourceManager()); + this->MacroName = std::string(T->text(Inputs.AST->getSourceManager())); this->Expansion = *Expansion; return true; } @@ -126,7 +126,7 @@ Expected<Tweak::Effect> ExpandMacro::apply(const Selection &Inputs) { } std::string ExpandMacro::title() const { - return llvm::formatv("Expand macro '{0}'", MacroName); + return std::string(llvm::formatv("Expand macro '{0}'", MacroName)); } } // namespace diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp index da8e6e0..52905c3 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp @@ -347,16 +347,16 @@ std::string NewFunction::renderParametersForCall() const { } std::string NewFunction::renderCall() const { - return llvm::formatv( - "{0}{1}({2}){3}", CallerReturnsValue ? "return " : "", Name, - renderParametersForCall(), - (SemicolonPolicy.isNeededInOriginalFunction() ? ";" : "")); + return std::string( + llvm::formatv("{0}{1}({2}){3}", CallerReturnsValue ? "return " : "", Name, + renderParametersForCall(), + (SemicolonPolicy.isNeededInOriginalFunction() ? ";" : ""))); } std::string NewFunction::renderDefinition(const SourceManager &SM) const { - return llvm::formatv("{0} {1}({2}) {\n{3}\n}\n", - printType(ReturnType, *EnclosingFuncContext), Name, - renderParametersForDefinition(), getFuncBody(SM)); + return std::string(llvm::formatv( + "{0} {1}({2}) {\n{3}\n}\n", printType(ReturnType, *EnclosingFuncContext), + Name, renderParametersForDefinition(), getFuncBody(SM))); } std::string NewFunction::getFuncBody(const SourceManager &SM) const { @@ -578,8 +578,9 @@ bool createParameters(NewFunction &ExtractedFunc, // pointers, etc by reference. bool IsPassedByReference = true; // We use the index of declaration as the ordering priority for parameters. - ExtractedFunc.Parameters.push_back( - {VD->getName(), TypeInfo, IsPassedByReference, DeclInfo.DeclIndex}); + ExtractedFunc.Parameters.push_back({std::string(VD->getName()), TypeInfo, + IsPassedByReference, + DeclInfo.DeclIndex}); } llvm::sort(ExtractedFunc.Parameters); return true; diff --git a/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp b/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp index d2edde3..e054e33 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp @@ -199,7 +199,8 @@ Expected<Tweak::Effect> RemoveUsingNamespace::apply(const Selection &Inputs) { } std::string RemoveUsingNamespace::title() const { - return llvm::formatv("Remove using namespace, re-qualify names instead."); + return std::string( + llvm::formatv("Remove using namespace, re-qualify names instead.")); } } // namespace } // namespace clangd diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp index c0c4c18..6dc6be3 100644 --- a/clang-tools-extra/clangd/tool/ClangdMain.cpp +++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp @@ -591,7 +591,7 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var "--compile-commands-dir to an absolute path: " << EC.message() << ". The argument will be ignored.\n"; } else { - CompileCommandsDirPath = Path.str(); + CompileCommandsDirPath = std::string(Path.str()); } } else { llvm::errs() diff --git a/clang-tools-extra/clangd/unittests/ClangdTests.cpp b/clang-tools-extra/clangd/unittests/ClangdTests.cpp index fbc6e64..627b9b2 100644 --- a/clang-tools-extra/clangd/unittests/ClangdTests.cpp +++ b/clang-tools-extra/clangd/unittests/ClangdTests.cpp @@ -146,7 +146,8 @@ protected: MockCompilationDatabase CDB; ClangdServer Server(CDB, FS, ClangdServer::optsForTest(), &DiagConsumer); for (const auto &FileWithContents : ExtraFiles) - FS.Files[testPath(FileWithContents.first)] = FileWithContents.second; + FS.Files[testPath(FileWithContents.first)] = + std::string(FileWithContents.second); auto SourceFilename = testPath(SourceFileRelPath); Server.addDocument(SourceFilename, SourceContents); @@ -1020,7 +1021,8 @@ TEST_F(ClangdVFSTest, FallbackWhenWaitingForCompileCommand) { // something goes wrong. CanReturnCommand.wait(); auto FileName = llvm::sys::path::filename(File); - std::vector<std::string> CommandLine = {"clangd", "-ffreestanding", File}; + std::vector<std::string> CommandLine = {"clangd", "-ffreestanding", + std::string(File)}; return {tooling::CompileCommand(llvm::sys::path::parent_path(File), FileName, std::move(CommandLine), "")}; } diff --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp index b055d1c..1a9950ae 100644 --- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp +++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp @@ -1073,7 +1073,7 @@ MATCHER_P(SigDoc, Doc, "") { return arg.documentation == Doc; } /// foo([[int p1]], [[double p2]]) -> void Matcher<SignatureInformation> Sig(llvm::StringRef AnnotatedLabel) { llvm::Annotations A(AnnotatedLabel); - std::string Label = A.code(); + std::string Label = std::string(A.code()); std::vector<ExpectedParameter> Parameters; for (auto Range : A.ranges()) { Parameters.emplace_back(); diff --git a/clang-tools-extra/clangd/unittests/DexTests.cpp b/clang-tools-extra/clangd/unittests/DexTests.cpp index 9402c3c..53abb26 100644 --- a/clang-tools-extra/clangd/unittests/DexTests.cpp +++ b/clang-tools-extra/clangd/unittests/DexTests.cpp @@ -739,10 +739,10 @@ TEST(DexTest, PreferredTypesBoosting) { // The best candidate can change depending on the preferred type. Req.Limit = 1; - Req.PreferredTypes = {Sym1.Type}; + Req.PreferredTypes = {std::string(Sym1.Type)}; EXPECT_THAT(match(I, Req), ElementsAre("t1")); - Req.PreferredTypes = {Sym2.Type}; + Req.PreferredTypes = {std::string(Sym2.Type)}; EXPECT_THAT(match(I, Req), ElementsAre("t2")); } diff --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp index 79d51fa..1e3720a 100644 --- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp +++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp @@ -208,7 +208,7 @@ TEST(DiagnosticsTest, DeduplicatedClangTidyDiagnostics) { func(2.0); } )cpp"); - TU.Code = Test.code(); + TU.Code = std::string(Test.code()); // The check doesn't handle template instantiations which ends up emitting // duplicated messages, verify that we deduplicate them. EXPECT_THAT( @@ -433,7 +433,7 @@ TEST(DiagnosticsTest, ToLSP) { D.InsideMainFile = true; D.Severity = DiagnosticsEngine::Error; D.File = "foo/bar/main.cpp"; - D.AbsFile = MainFile.file(); + D.AbsFile = std::string(MainFile.file()); clangd::Note NoteInMain; NoteInMain.Message = "declared somewhere in the main file"; @@ -441,7 +441,7 @@ TEST(DiagnosticsTest, ToLSP) { NoteInMain.Severity = DiagnosticsEngine::Remark; NoteInMain.File = "../foo/bar/main.cpp"; NoteInMain.InsideMainFile = true; - NoteInMain.AbsFile = MainFile.file(); + NoteInMain.AbsFile = std::string(MainFile.file()); D.Notes.push_back(NoteInMain); @@ -451,7 +451,7 @@ TEST(DiagnosticsTest, ToLSP) { NoteInHeader.Severity = DiagnosticsEngine::Note; NoteInHeader.File = "../foo/baz/header.h"; NoteInHeader.InsideMainFile = false; - NoteInHeader.AbsFile = HeaderFile.file(); + NoteInHeader.AbsFile = std::string(HeaderFile.file()); D.Notes.push_back(NoteInHeader); clangd::Fix F; @@ -738,7 +738,7 @@ $insert[[]]namespace ns { void g() { ns::$[[scope]]::X_Y(); } )cpp"); TestTU TU; - TU.Code = Test.code(); + TU.Code = std::string(Test.code()); // FIXME: Figure out why this is needed and remove it, PR43662. TU.ExtraArgs.push_back("-fno-ms-compatibility"); auto Index = buildIndexWithSymbol( @@ -764,7 +764,7 @@ void f() { } )cpp"); TestTU TU; - TU.Code = Test.code(); + TU.Code = std::string(Test.code()); // FIXME: Figure out why this is needed and remove it, PR43662. TU.ExtraArgs.push_back("-fno-ms-compatibility"); auto Index = buildIndexWithSymbol( diff --git a/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp b/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp index f9bfef3..7d62e83 100644 --- a/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp +++ b/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp @@ -66,7 +66,7 @@ protected: std::map<std::string, EquivClass> Classes; for (llvm::StringRef Name : DeclNames) { auto Type = OpaqueType::fromType(ASTCtx(), typeOf(Name)); - Classes[Type->raw()].insert(Name); + Classes[std::string(Type->raw())].insert(std::string(Name)); } return Classes; } diff --git a/clang-tools-extra/clangd/unittests/FileIndexTests.cpp b/clang-tools-extra/clangd/unittests/FileIndexTests.cpp index a65352d..e472dd9 100644 --- a/clang-tools-extra/clangd/unittests/FileIndexTests.cpp +++ b/clang-tools-extra/clangd/unittests/FileIndexTests.cpp @@ -149,7 +149,7 @@ void update(FileIndex &M, llvm::StringRef Basename, llvm::StringRef Code) { TestTU File; File.Filename = (Basename + ".cpp").str(); File.HeaderFilename = (Basename + ".h").str(); - File.HeaderCode = Code; + File.HeaderCode = std::string(Code); auto AST = File.build(); M.updatePreamble(File.Filename, AST.getASTContext(), AST.getPreprocessorPtr(), AST.getCanonicalIncludes()); @@ -326,14 +326,14 @@ TEST(FileIndexTest, Refs) { // Add test.cc TestTU Test; Test.HeaderCode = HeaderCode; - Test.Code = MainCode.code(); + Test.Code = std::string(MainCode.code()); Test.Filename = "test.cc"; auto AST = Test.build(); Index.updateMain(Test.Filename, AST); // Add test2.cc TestTU Test2; Test2.HeaderCode = HeaderCode; - Test2.Code = MainCode.code(); + Test2.Code = std::string(MainCode.code()); Test2.Filename = "test2.cc"; AST = Test2.build(); Index.updateMain(Test2.Filename, AST); @@ -360,8 +360,8 @@ TEST(FileIndexTest, MacroRefs) { FileIndex Index; // Add test.cc TestTU Test; - Test.HeaderCode = HeaderCode.code(); - Test.Code = MainCode.code(); + Test.HeaderCode = std::string(HeaderCode.code()); + Test.Code = std::string(MainCode.code()); Test.Filename = "test.cc"; auto AST = Test.build(); Index.updateMain(Test.Filename, AST); @@ -411,7 +411,7 @@ TEST(FileIndexTest, ReferencesInMainFileWithPreamble) { [[Foo]] foo; } )cpp"); - TU.Code = Main.code(); + TU.Code = std::string(Main.code()); auto AST = TU.build(); FileIndex Index; Index.updateMain(testPath(TU.Filename), AST); diff --git a/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp b/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp index f2e67d0..f934345 100644 --- a/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp +++ b/clang-tools-extra/clangd/unittests/FindSymbolsTests.cpp @@ -72,7 +72,7 @@ protected: void addFile(llvm::StringRef FileName, llvm::StringRef Contents) { auto Path = testPath(FileName); - FSProvider.Files[Path] = Contents; + FSProvider.Files[Path] = std::string(Contents); Server.addDocument(Path, Contents); } }; @@ -324,7 +324,7 @@ protected: } void addFile(llvm::StringRef FilePath, llvm::StringRef Contents) { - FSProvider.Files[FilePath] = Contents; + FSProvider.Files[FilePath] = std::string(Contents); Server.addDocument(FilePath, Contents); } }; diff --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp index 3960ef1..22aeed6 100644 --- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp +++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp @@ -42,7 +42,7 @@ struct PrintedDecl { llvm::StringRef FirstLine = llvm::StringRef(OS.str()).take_until([](char C) { return C == '\n'; }); FirstLine = FirstLine.rtrim(" {"); - Name = FirstLine.rtrim(" {"); + Name = std::string(FirstLine.rtrim(" {")); } std::string Name; @@ -584,7 +584,7 @@ protected: /// See actual tests for examples of annotation format. AllRefs annotateReferencesInFoo(llvm::StringRef Code) { TestTU TU; - TU.Code = Code; + TU.Code = std::string(Code); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. @@ -644,7 +644,7 @@ protected: std::string DumpedReferences; for (unsigned I = 0; I < Refs.size(); ++I) - DumpedReferences += llvm::formatv("{0}: {1}\n", I, Refs[I]); + DumpedReferences += std::string(llvm::formatv("{0}: {1}\n", I, Refs[I])); return AllRefs{std::move(AnnotatedCode), std::move(DumpedReferences)}; } diff --git a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp index 5e728a5..a6835a0 100644 --- a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp +++ b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp @@ -55,7 +55,8 @@ TEST(GlobalCompilationDatabaseTest, FallbackCommand) { } static tooling::CompileCommand cmd(llvm::StringRef File, llvm::StringRef Arg) { - return tooling::CompileCommand(testRoot(), File, {"clang", Arg, File}, ""); + return tooling::CompileCommand( + testRoot(), File, {"clang", std::string(Arg), std::string(File)}, ""); } class OverlayCDBTest : public ::testing::Test { diff --git a/clang-tools-extra/clangd/unittests/HeadersTests.cpp b/clang-tools-extra/clangd/unittests/HeadersTests.cpp index d07312c..1d7c828 100644 --- a/clang-tools-extra/clangd/unittests/HeadersTests.cpp +++ b/clang-tools-extra/clangd/unittests/HeadersTests.cpp @@ -85,7 +85,7 @@ protected: if (Preferred.empty()) Preferred = Original; auto ToHeaderFile = [](llvm::StringRef Header) { - return HeaderFile{Header, + return HeaderFile{std::string(Header), /*Verbatim=*/!llvm::sys::path::is_absolute(Header)}; }; diff --git a/clang-tools-extra/clangd/unittests/IndexActionTests.cpp b/clang-tools-extra/clangd/unittests/IndexActionTests.cpp index 4ca86e8..235b60a 100644 --- a/clang-tools-extra/clangd/unittests/IndexActionTests.cpp +++ b/clang-tools-extra/clangd/unittests/IndexActionTests.cpp @@ -85,7 +85,7 @@ public: "-xc++", "-std=c++11", "-iquote", testRoot()}; Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end()); - Args.push_back(MainFilePath); + Args.push_back(std::string(MainFilePath)); tooling::ToolInvocation Invocation( Args, std::move(Action), Files.get(), @@ -100,7 +100,7 @@ public: void addFile(llvm::StringRef Path, llvm::StringRef Content) { InMemoryFileSystem->addFile(Path, 0, llvm::MemoryBuffer::getMemBuffer(Content)); - FilePaths.push_back(Path); + FilePaths.push_back(std::string(Path)); } protected: diff --git a/clang-tools-extra/clangd/unittests/IndexTests.cpp b/clang-tools-extra/clangd/unittests/IndexTests.cpp index dcbfc4c..f04ac8a 100644 --- a/clang-tools-extra/clangd/unittests/IndexTests.cpp +++ b/clang-tools-extra/clangd/unittests/IndexTests.cpp @@ -364,7 +364,7 @@ TEST(MergeIndexTest, Refs) { Annotations Test1Code(R"(class $Foo[[Foo]];)"); TestTU Test; Test.HeaderCode = HeaderCode; - Test.Code = Test1Code.code(); + Test.Code = std::string(Test1Code.code()); Test.Filename = "test.cc"; auto AST = Test.build(); Dyn.updateMain(Test.Filename, AST); @@ -381,7 +381,7 @@ TEST(MergeIndexTest, Refs) { Annotations Test2Code(R"(class $Foo[[Foo]] {};)"); TestTU Test2; Test2.HeaderCode = HeaderCode; - Test2.Code = Test2Code.code(); + Test2.Code = std::string(Test2Code.code()); Test2.Filename = "test2.cc"; StaticAST = Test2.build(); StaticIndex.updateMain(Test2.Filename, StaticAST); diff --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp b/clang-tools-extra/clangd/unittests/RenameTests.cpp index 620cdd0..95b9601 100644 --- a/clang-tools-extra/clangd/unittests/RenameTests.cpp +++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp @@ -49,7 +49,7 @@ std::unique_ptr<RefSlab> buildRefSlab(const Annotations &Code, llvm::StringRef Path) { RefSlab::Builder Builder; TestTU TU; - TU.HeaderCode = Code.code(); + TU.HeaderCode = std::string(Code.code()); auto Symbols = TU.headerSymbols(); const auto &SymbolID = findSymbol(Symbols, SymbolName).ID; std::string PathURI = URI::create(Path).toString(); @@ -666,7 +666,7 @@ TEST(CrossFileRenameTests, DirtyBuffer) { MainCode = Annotations("void [[Bar]]() { [[B^ar]](); }"); TU = TestTU::withCode(MainCode.code()); // Set a file "bar.cc" on disk. - TU.AdditionalFiles["bar.cc"] = BarCode.code(); + TU.AdditionalFiles["bar.cc"] = std::string(BarCode.code()); AST = TU.build(); Results = rename({MainCode.point(), NewName, AST, MainFilePath, Index.get(), /*CrossFile=*/true, GetDirtyBuffer}); @@ -713,7 +713,7 @@ TEST(CrossFileRenameTests, DeduplicateRefsFromIndex) { auto BarPath = testPath("bar.cc"); auto TU = TestTU::withCode(MainCode.code()); // Set a file "bar.cc" on disk. - TU.AdditionalFiles["bar.cc"] = BarCode.code(); + TU.AdditionalFiles["bar.cc"] = std::string(BarCode.code()); auto AST = TU.build(); std::string BarPathURI = URI::create(BarPath).toString(); Ref XRefInBarCC = refWithRange(BarCode.range(), BarPathURI); @@ -895,8 +895,8 @@ TEST(CrossFileRenameTests, WithUpToDateIndex) { std::string FooCCPath = testPath("foo.cc"); MockFSProvider FS; - FS.Files[FooHPath] = FooH.code(); - FS.Files[FooCCPath] = FooCC.code(); + FS.Files[FooHPath] = std::string(FooH.code()); + FS.Files[FooCCPath] = std::string(FooCC.code()); auto ServerOpts = ClangdServer::optsForTest(); ServerOpts.CrossFileRename = true; diff --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp b/clang-tools-extra/clangd/unittests/SelectionTests.cpp index e8c2bd6..c74ce44 100644 --- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp +++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp @@ -374,7 +374,7 @@ TEST(SelectionTest, CommonAncestor) { Annotations Test(C.Code); TestTU TU; - TU.Code = Test.code(); + TU.Code = std::string(Test.code()); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. diff --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp index a74f75f..1bedc2f 100644 --- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp +++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp @@ -90,8 +90,9 @@ std::string annotate(llvm::StringRef Input, assert(NextChar <= StartOffset); Result += Input.substr(NextChar, StartOffset - NextChar); - Result += llvm::formatv("${0}[[{1}]]", T.Kind, - Input.substr(StartOffset, EndOffset - StartOffset)); + Result += std::string( + llvm::formatv("${0}[[{1}]]", T.Kind, + Input.substr(StartOffset, EndOffset - StartOffset))); NextChar = EndOffset; } Result += Input.substr(NextChar); @@ -104,7 +105,7 @@ void checkHighlightings(llvm::StringRef Code, AdditionalFiles = {}) { Annotations Test(Code); TestTU TU; - TU.Code = Test.code(); + TU.Code = std::string(Test.code()); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. diff --git a/clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp b/clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp index 8f580f8..3356a09 100644 --- a/clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp +++ b/clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp @@ -159,7 +159,7 @@ TEST(SemanticSelection, RunViaClangDServer) { }]]]] )cpp"; Annotations SourceAnnotations(SourceContents); - FS.Files[FooCpp] = SourceAnnotations.code(); + FS.Files[FooCpp] = std::string(SourceAnnotations.code()); Server.addDocument(FooCpp, SourceAnnotations.code()); auto Ranges = runSemanticRanges(Server, FooCpp, SourceAnnotations.point()); diff --git a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp index b5876b15..b3757d9 100644 --- a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp +++ b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp @@ -115,8 +115,8 @@ public: void build(llvm::StringRef HeaderCode, llvm::StringRef Code = "") { File.HeaderFilename = HeaderName; File.Filename = FileName; - File.HeaderCode = HeaderCode; - File.Code = Code; + File.HeaderCode = std::string(HeaderCode); + File.Code = std::string(Code); AST = File.build(); } diff --git a/clang-tools-extra/clangd/unittests/SyncAPI.cpp b/clang-tools-extra/clangd/unittests/SyncAPI.cpp index 130a76b..5e97927 100644 --- a/clang-tools-extra/clangd/unittests/SyncAPI.cpp +++ b/clang-tools-extra/clangd/unittests/SyncAPI.cpp @@ -125,7 +125,7 @@ runDocumentSymbols(ClangdServer &Server, PathRef File) { SymbolSlab runFuzzyFind(const SymbolIndex &Index, llvm::StringRef Query) { FuzzyFindRequest Req; - Req.Query = Query; + Req.Query = std::string(Query); Req.AnyScope = true; return runFuzzyFind(Index, Req); } diff --git a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp index 5b8085e..1e1cef0 100644 --- a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp +++ b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp @@ -57,7 +57,7 @@ protected: llvm::StringRef Contents, WantDiagnostics WD, llvm::unique_function<void()> CB) { WithContextValue Ctx(llvm::make_scope_exit(std::move(CB))); - S.update(File, getInputs(File, Contents), WD); + S.update(File, getInputs(File, std::string(Contents)), WD); } static Key<llvm::unique_function<void(PathRef File, std::vector<Diag>)>> @@ -112,7 +112,7 @@ protected: void updateWithDiags(TUScheduler &S, PathRef File, llvm::StringRef Contents, WantDiagnostics WD, llvm::unique_function<void(std::vector<Diag>)> CB) { - return updateWithDiags(S, File, getInputs(File, Contents), WD, + return updateWithDiags(S, File, getInputs(File, std::string(Contents)), WD, std::move(CB)); } diff --git a/clang-tools-extra/clangd/unittests/TestFS.cpp b/clang-tools-extra/clangd/unittests/TestFS.cpp index 872b4d0..aad08f2 100644 --- a/clang-tools-extra/clangd/unittests/TestFS.cpp +++ b/clang-tools-extra/clangd/unittests/TestFS.cpp @@ -42,7 +42,7 @@ MockCompilationDatabase::MockCompilationDatabase(llvm::StringRef Directory, llvm::Optional<ProjectInfo> MockCompilationDatabase::getProjectInfo(PathRef File) const { - return ProjectInfo{Directory}; + return ProjectInfo{std::string(Directory)}; } llvm::Optional<tooling::CompileCommand> @@ -57,12 +57,12 @@ MockCompilationDatabase::getCompileCommand(PathRef File) const { CommandLine.insert(CommandLine.begin(), "clang"); if (RelPathPrefix.empty()) { // Use the absolute path in the compile command. - CommandLine.push_back(File); + CommandLine.push_back(std::string(File)); } else { // Build a relative path using RelPathPrefix. llvm::SmallString<32> RelativeFilePath(RelPathPrefix); llvm::sys::path::append(RelativeFilePath, FileName); - CommandLine.push_back(RelativeFilePath.str()); + CommandLine.push_back(std::string(RelativeFilePath.str())); } return {tooling::CompileCommand(Directory != llvm::StringRef() @@ -86,7 +86,7 @@ std::string testPath(PathRef File) { llvm::sys::path::native(NativeFile); llvm::SmallString<32> Path; llvm::sys::path::append(Path, testRoot(), NativeFile); - return Path.str(); + return std::string(Path.str()); } /// unittest: is a scheme that refers to files relative to testRoot(). diff --git a/clang-tools-extra/clangd/unittests/TestTU.h b/clang-tools-extra/clangd/unittests/TestTU.h index c535645..4668543 100644 --- a/clang-tools-extra/clangd/unittests/TestTU.h +++ b/clang-tools-extra/clangd/unittests/TestTU.h @@ -32,13 +32,13 @@ namespace clangd { struct TestTU { static TestTU withCode(llvm::StringRef Code) { TestTU TU; - TU.Code = Code; + TU.Code = std::string(Code); return TU; } static TestTU withHeaderCode(llvm::StringRef HeaderCode) { TestTU TU; - TU.HeaderCode = HeaderCode; + TU.HeaderCode = std::string(HeaderCode); return TU; } diff --git a/clang-tools-extra/clangd/unittests/TweakTesting.cpp b/clang-tools-extra/clangd/unittests/TweakTesting.cpp index 7f9f75c..33779f4 100644 --- a/clang-tools-extra/clangd/unittests/TweakTesting.cpp +++ b/clang-tools-extra/clangd/unittests/TweakTesting.cpp @@ -70,9 +70,9 @@ MATCHER_P7(TweakIsAvailable, TweakID, Ctx, Header, ExtraArgs, ExtraFiles, Index, Annotations Input(WrappedCode); auto Selection = rangeOrPoint(Input); TestTU TU; - TU.Filename = FileName; + TU.Filename = std::string(FileName); TU.HeaderCode = Header; - TU.Code = Input.code(); + TU.Code = std::string(Input.code()); TU.ExtraArgs = ExtraArgs; TU.AdditionalFiles = std::move(ExtraFiles); ParsedAST AST = TU.build(); @@ -93,10 +93,10 @@ std::string TweakTest::apply(llvm::StringRef MarkedCode, auto Selection = rangeOrPoint(Input); TestTU TU; - TU.Filename = FileName; + TU.Filename = std::string(FileName); TU.HeaderCode = Header; TU.AdditionalFiles = std::move(ExtraFiles); - TU.Code = Input.code(); + TU.Code = std::string(Input.code()); TU.ExtraArgs = ExtraArgs; ParsedAST AST = TU.build(); Tweak::Selection S(Index.get(), AST, Selection.first, Selection.second); @@ -121,7 +121,7 @@ std::string TweakTest::apply(llvm::StringRef MarkedCode, return "bad edits: " + llvm::toString(NewText.takeError()); llvm::StringRef Unwrapped = unwrap(Context, *NewText); if (It.first() == testPath(TU.Filename)) - EditedMainFile = Unwrapped; + EditedMainFile = std::string(Unwrapped); else { if (!EditedFiles) ADD_FAILURE() << "There were changes to additional files, but client " diff --git a/clang-tools-extra/clangd/unittests/TweakTests.cpp b/clang-tools-extra/clangd/unittests/TweakTests.cpp index 2a99521..68f87a7 100644 --- a/clang-tools-extra/clangd/unittests/TweakTests.cpp +++ b/clang-tools-extra/clangd/unittests/TweakTests.cpp @@ -2214,7 +2214,7 @@ TEST_F(DefineOutlineTest, QualifyFunctionName) { }; llvm::StringMap<std::string> EditedFiles; for (auto &Case : Cases) { - ExtraFiles["Test.cpp"] = Case.TestSource; + ExtraFiles["Test.cpp"] = std::string(Case.TestSource); EXPECT_EQ(apply(Case.TestHeader, &EditedFiles), Case.ExpectedHeader); EXPECT_THAT(EditedFiles, testing::ElementsAre(FileWithContents( testPath("Test.cpp"), Case.ExpectedSource))) diff --git a/clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp b/clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp index 6bbcfff..73e124d 100644 --- a/clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp +++ b/clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp @@ -527,7 +527,7 @@ SymbolID findSymbolIDByName(SymbolIndex *Index, llvm::StringRef Name, llvm::StringRef TemplateArgs = "") { SymbolID Result; FuzzyFindRequest Request; - Request.Query = Name; + Request.Query = std::string(Name); Request.AnyScope = true; bool GotResult = false; Index->fuzzyFind(Request, [&](const Symbol &S) { diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/clang-tools-extra/clangd/unittests/XRefsTests.cpp index 617c5bc..1579765 100644 --- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp +++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp @@ -149,8 +149,8 @@ TEST(LocateSymbol, WithIndex) { )cpp"); TestTU TU; - TU.Code = SymbolCpp.code(); - TU.HeaderCode = SymbolHeader.code(); + TU.Code = std::string(SymbolCpp.code()); + TU.HeaderCode = std::string(SymbolHeader.code()); auto Index = TU.index(); auto LocateWithIndex = [&Index](const Annotations &Main) { auto AST = TestTU::withCode(Main.code()).build(); @@ -197,7 +197,7 @@ TEST(LocateSymbol, WithIndexPreferredLocation) { void $f[[func]]() {}; )cpp"); TestTU TU; - TU.HeaderCode = SymbolHeader.code(); + TU.HeaderCode = std::string(SymbolHeader.code()); TU.HeaderFilename = "x.proto"; // Prefer locations in codegen files. auto Index = TU.index(); @@ -503,7 +503,7 @@ TEST(LocateSymbol, All) { WantDef = T.range("def"); TestTU TU; - TU.Code = T.code(); + TU.Code = std::string(T.code()); // FIXME: Auto-completion in a template requires disabling delayed template // parsing. @@ -558,7 +558,7 @@ TEST(LocateSymbol, Warnings) { WantDef = T.range("def"); TestTU TU; - TU.Code = T.code(); + TU.Code = std::string(T.code()); auto AST = TU.build(); auto Results = locateSymbolAt(AST, T.point()); @@ -694,9 +694,10 @@ int [[bar_not_preamble]]; auto FooCpp = testPath("src/foo.cpp"); FS.Files[FooCpp] = ""; auto HeaderInPreambleH = testPath("src/header_in_preamble.h"); - FS.Files[HeaderInPreambleH] = HeaderInPreambleAnnotations.code(); + FS.Files[HeaderInPreambleH] = std::string(HeaderInPreambleAnnotations.code()); auto HeaderNotInPreambleH = testPath("src/header_not_in_preamble.h"); - FS.Files[HeaderNotInPreambleH] = HeaderNotInPreambleAnnotations.code(); + FS.Files[HeaderNotInPreambleH] = + std::string(HeaderNotInPreambleAnnotations.code()); runAddDocument(Server, FooCpp, SourceAnnotations.code()); @@ -736,14 +737,14 @@ TEST(GoToInclude, All) { #in$5^clude "$6^foo.h"$7^ )cpp"; Annotations SourceAnnotations(SourceContents); - FS.Files[FooCpp] = SourceAnnotations.code(); + FS.Files[FooCpp] = std::string(SourceAnnotations.code()); auto FooH = testPath("foo.h"); const char *HeaderContents = R"cpp([[]]#pragma once int a; )cpp"; Annotations HeaderAnnotations(HeaderContents); - FS.Files[FooH] = HeaderAnnotations.code(); + FS.Files[FooH] = std::string(HeaderAnnotations.code()); Server.addDocument(FooH, HeaderAnnotations.code()); Server.addDocument(FooCpp, SourceAnnotations.code()); @@ -785,7 +786,7 @@ TEST(GoToInclude, All) { #import "^foo.h" )objc"); auto FooM = testPath("foo.m"); - FS.Files[FooM] = ObjC.code(); + FS.Files[FooM] = std::string(ObjC.code()); Server.addDocument(FooM, ObjC.code()); Locations = runLocateSymbolAt(Server, FooM, ObjC.point()); @@ -805,11 +806,11 @@ TEST(LocateSymbol, WithPreamble) { Annotations FooWithHeader(R"cpp(#include "fo^o.h")cpp"); Annotations FooWithoutHeader(R"cpp(double [[fo^o]]();)cpp"); - FS.Files[FooCpp] = FooWithHeader.code(); + FS.Files[FooCpp] = std::string(FooWithHeader.code()); auto FooH = testPath("foo.h"); Annotations FooHeader(R"cpp([[]])cpp"); - FS.Files[FooH] = FooHeader.code(); + FS.Files[FooH] = std::string(FooHeader.code()); runAddDocument(Server, FooCpp, FooWithHeader.code()); // LocateSymbol goes to a #include file: the result comes from the preamble. @@ -1010,7 +1011,7 @@ TEST(FindReferences, NeedsIndexForSymbols) { const char *Header = "int foo();"; Annotations Main("int main() { [[f^oo]](); }"); TestTU TU; - TU.Code = Main.code(); + TU.Code = std::string(Main.code()); TU.HeaderCode = Header; auto AST = TU.build(); @@ -1024,7 +1025,7 @@ TEST(FindReferences, NeedsIndexForSymbols) { // References from indexed files are included. TestTU IndexedTU; - IndexedTU.Code = IndexedMain.code(); + IndexedTU.Code = std::string(IndexedMain.code()); IndexedTU.Filename = "Indexed.cpp"; IndexedTU.HeaderCode = Header; EXPECT_THAT( @@ -1049,7 +1050,7 @@ TEST(FindReferences, NeedsIndexForMacro) { } )cpp"); TestTU TU; - TU.Code = Main.code(); + TU.Code = std::string(Main.code()); TU.HeaderCode = Header; auto AST = TU.build(); @@ -1066,7 +1067,7 @@ TEST(FindReferences, NeedsIndexForMacro) { // References from indexed files are included. TestTU IndexedTU; - IndexedTU.Code = IndexedMain.code(); + IndexedTU.Code = std::string(IndexedMain.code()); IndexedTU.Filename = "Indexed.cpp"; IndexedTU.HeaderCode = Header; EXPECT_THAT( @@ -1198,7 +1199,7 @@ TEST(DocumentLinks, All) { )cpp"); TestTU TU; - TU.Code = MainCpp.code(); + TU.Code = std::string(MainCpp.code()); TU.AdditionalFiles = {{"foo.h", ""}, {"bar.h", ""}}; auto AST = TU.build(); diff --git a/clang-tools-extra/modularize/CoverageChecker.cpp b/clang-tools-extra/modularize/CoverageChecker.cpp index 6cfeb0e..9df53d2 100644 --- a/clang-tools-extra/modularize/CoverageChecker.cpp +++ b/clang-tools-extra/modularize/CoverageChecker.cpp @@ -282,7 +282,7 @@ CoverageChecker::collectUmbrellaHeaderHeaders(StringRef UmbrellaHeaderName) { Compilations.reset(new FixedCompilationDatabase(Twine(PathBuf), CommandLine)); std::vector<std::string> HeaderPath; - HeaderPath.push_back(UmbrellaHeaderName); + HeaderPath.push_back(std::string(UmbrellaHeaderName)); // Create the tool and run the compilation. ClangTool Tool(*Compilations, HeaderPath); diff --git a/clang-tools-extra/modularize/Modularize.cpp b/clang-tools-extra/modularize/Modularize.cpp index 749afdf..5076bd9 100644 --- a/clang-tools-extra/modularize/Modularize.cpp +++ b/clang-tools-extra/modularize/Modularize.cpp @@ -813,7 +813,7 @@ int main(int Argc, const char **Argv) { Argv0 = Argv[0]; // Save program arguments for use in module.modulemap comment. - CommandLine = sys::path::stem(sys::path::filename(Argv0)); + CommandLine = std::string(sys::path::stem(sys::path::filename(Argv0))); for (int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) { CommandLine.append(" "); CommandLine.append(Argv[ArgIndex]); @@ -948,7 +948,7 @@ int main(int Argc, const char **Argv) { for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) { errs() << " " << FI->File->getName() << ":" << FI->Line << ":" << FI->Column << "\n"; - ModUtil->addUniqueProblemFile(FI->File->getName()); + ModUtil->addUniqueProblemFile(std::string(FI->File->getName())); } HadErrors = 1; } @@ -978,7 +978,7 @@ int main(int Argc, const char **Argv) { } HadErrors = 1; - ModUtil->addUniqueProblemFile(H->first->getName()); + ModUtil->addUniqueProblemFile(std::string(H->first->getName())); errs() << "error: header '" << H->first->getName() << "' has different contents depending on how it was included.\n"; for (unsigned I = 0, N = H->second.size(); I != N; ++I) { diff --git a/clang-tools-extra/modularize/ModularizeUtilities.cpp b/clang-tools-extra/modularize/ModularizeUtilities.cpp index f11273d..200370c 100644 --- a/clang-tools-extra/modularize/ModularizeUtilities.cpp +++ b/clang-tools-extra/modularize/ModularizeUtilities.cpp @@ -196,7 +196,7 @@ std::error_code ModularizeUtilities::loadSingleHeaderListsAndDependencies( // Get canonical form. HeaderFileName = getCanonicalPath(HeaderFileName); // Save the resulting header file path and dependencies. - HeaderFileNames.push_back(HeaderFileName.str()); + HeaderFileNames.push_back(std::string(HeaderFileName.str())); Dependencies[HeaderFileName.str()] = Dependents; } return std::error_code(); @@ -249,7 +249,7 @@ std::error_code ModularizeUtilities::loadProblemHeaderList( // Get canonical form. HeaderFileName = getCanonicalPath(HeaderFileName); // Save the resulting header file path. - ProblemFileNames.push_back(HeaderFileName.str()); + ProblemFileNames.push_back(std::string(HeaderFileName.str())); } return std::error_code(); } @@ -457,7 +457,7 @@ std::string ModularizeUtilities::getCanonicalPath(StringRef FilePath) { std::replace(Tmp.begin(), Tmp.end(), '\\', '/'); StringRef Tmp2(Tmp); if (Tmp2.startswith("./")) - Tmp = Tmp2.substr(2); + Tmp = std::string(Tmp2.substr(2)); return Tmp; } @@ -487,7 +487,7 @@ std::string ModularizeUtilities::getDirectoryFromPath(StringRef Path) { sys::path::remove_filename(Directory); if (Directory.size() == 0) return "."; - return Directory.str(); + return std::string(Directory.str()); } // Add unique problem file. diff --git a/clang-tools-extra/modularize/ModuleAssistant.cpp b/clang-tools-extra/modularize/ModuleAssistant.cpp index 0cd7e9f0..1dba973 100644 --- a/clang-tools-extra/modularize/ModuleAssistant.cpp +++ b/clang-tools-extra/modularize/ModuleAssistant.cpp @@ -139,7 +139,7 @@ static const char *const ReservedNames[] = { // Prepends a '_' to the name if and only if the name is a keyword. static std::string ensureNoCollisionWithReservedName(llvm::StringRef MightBeReservedName) { - std::string SafeName = MightBeReservedName; + std::string SafeName(MightBeReservedName); for (int Index = 0; ReservedNames[Index] != nullptr; ++Index) { if (MightBeReservedName == ReservedNames[Index]) { SafeName.insert(0, "_"); @@ -153,7 +153,7 @@ ensureNoCollisionWithReservedName(llvm::StringRef MightBeReservedName) { // Prepends a '_' to the name if and only if the name is a keyword. static std::string ensureVaidModuleName(llvm::StringRef MightBeInvalidName) { - std::string SafeName = MightBeInvalidName; + std::string SafeName(MightBeInvalidName); std::replace(SafeName.begin(), SafeName.end(), '-', '_'); std::replace(SafeName.begin(), SafeName.end(), '.', '_'); if (isdigit(SafeName[0])) @@ -176,9 +176,9 @@ static bool addModuleDescription(Module *RootModule, llvm::sys::path::native(HeaderFilePath, NativePath); llvm::sys::path::native(HeaderPrefix, NativePrefix); if (NativePath.startswith(NativePrefix)) - FilePath = NativePath.substr(NativePrefix.size() + 1); + FilePath = std::string(NativePath.substr(NativePrefix.size() + 1)); else - FilePath = HeaderFilePath; + FilePath = std::string(HeaderFilePath); int Count = FileDependents.size(); // Headers that go into modules must not depend on other files being // included first. If there are any dependents, warn user and omit. @@ -197,7 +197,7 @@ static bool addModuleDescription(Module *RootModule, I != E; ++I) { if ((*I)[0] == '.') continue; - std::string Stem = llvm::sys::path::stem(*I); + std::string Stem(llvm::sys::path::stem(*I)); Stem = ensureNoCollisionWithReservedName(Stem); Stem = ensureVaidModuleName(Stem); Module *SubModule = CurrentModule->findSubModule(Stem); diff --git a/clang-tools-extra/unittests/clang-include-fixer/IncludeFixerTest.cpp b/clang-tools-extra/unittests/clang-include-fixer/IncludeFixerTest.cpp index b210171..c89b18f 100644 --- a/clang-tools-extra/unittests/clang-include-fixer/IncludeFixerTest.cpp +++ b/clang-tools-extra/unittests/clang-include-fixer/IncludeFixerTest.cpp @@ -29,7 +29,8 @@ static bool runOnCode(tooling::ToolAction *ToolAction, StringRef Code, new FileManager(FileSystemOptions(), InMemoryFileSystem)); // FIXME: Investigate why -fms-compatibility breaks tests. std::vector<std::string> Args = {"include_fixer", "-fsyntax-only", - "-fno-ms-compatibility", FileName}; + "-fno-ms-compatibility", + std::string(FileName)}; Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end()); tooling::ToolInvocation Invocation( Args, ToolAction, Files.get(), @@ -102,7 +103,7 @@ static std::string runIncludeFixer( runOnCode(&Factory, Code, FakeFileName, ExtraArgs); assert(FixerContexts.size() == 1); if (FixerContexts.front().getHeaderInfos().empty()) - return Code; + return std::string(Code); auto Replaces = createIncludeFixerReplacements(Code, FixerContexts.front()); EXPECT_TRUE(static_cast<bool>(Replaces)) << llvm::toString(Replaces.takeError()) << "\n"; diff --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h b/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h index 5e62a19..eb138b2 100644 --- a/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h +++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyTest.h @@ -98,7 +98,8 @@ runCheckOnCode(StringRef Code, std::vector<ClangTidyError> *Errors = nullptr, std::vector<std::string> Args(1, "clang-tidy"); Args.push_back("-fsyntax-only"); Args.push_back("-fno-delayed-template-parsing"); - std::string extension(llvm::sys::path::extension(Filename.str())); + std::string extension( + std::string(llvm::sys::path::extension(Filename.str()))); if (extension == ".m" || extension == ".mm") { Args.push_back("-fobjc-abi-version=2"); Args.push_back("-fobjc-arc"); diff --git a/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp b/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp index 28ea7e2..ebf5f59 100644 --- a/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp @@ -33,9 +33,10 @@ RewriteRule invertIf() { RewriteRule Rule = tooling::makeRule( ifStmt(hasCondition(expr().bind(C)), hasThen(stmt().bind(T)), hasElse(stmt().bind(E))), - change( - statement(RewriteRule::RootID), - cat("if(!(", node(C), ")) ", statement(E), " else ", statement(T))), + change(statement(std::string(RewriteRule::RootID)), + cat("if(!(", node(std::string(C)), ")) ", + statement(std::string(E)), " else ", + statement(std::string(T)))), cat("negate condition and reverse `then` and `else` branches")); return Rule; } |