Skip to content

Commit

Permalink
Make llvm::StringRef to std::string conversions explicit.
Browse files Browse the repository at this point in the history
This is how it should've been and brings it more in line with
std::string_view. There should be no functional change here.

This is mostly mechanical from a custom clang-tidy check, with a lot of
manual fixups. It uncovers a lot of minor inefficiencies.

This doesn't actually modify StringRef yet, I'll do that in a follow-up.
  • Loading branch information
d0k committed Jan 28, 2020
1 parent 5eaf44f commit adcd026
Show file tree
Hide file tree
Showing 895 changed files with 3,319 additions and 3,014 deletions.
18 changes: 9 additions & 9 deletions clang-tools-extra/clang-change-namespace/ChangeNamespace.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
}
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clang-doc/Representation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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://");
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clang-doc/tool/ClangDocMain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}

Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clang-include-fixer/InMemorySymbolIndex.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {};
Expand Down
10 changes: 6 additions & 4 deletions clang-tools-extra/clang-include-fixer/IncludeFixer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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("\"<>");
Expand All @@ -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 =
Expand Down Expand Up @@ -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 {};
}
Expand All @@ -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;
Expand Down
4 changes: 3 additions & 1 deletion clang-tools-extra/clang-include-fixer/IncludeFixer.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ class IncludeFixerSemaSource : public clang::ExternalSemaSource {
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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class HeaderMapCollector {

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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class SymbolInfo {
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; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ class ClangIncludeFixerPluginAction : public PluginASTAction {
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);
Expand Down
8 changes: 4 additions & 4 deletions clang-tools-extra/clang-move/Move.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}
}

Expand Down Expand Up @@ -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);
}
}

Expand Down
3 changes: 2 additions & 1 deletion clang-tools-extra/clang-move/tool/ClangMove.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
3 changes: 2 additions & 1 deletion clang-tools-extra/clang-query/QueryParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clang-tidy/ClangTidy.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 3 additions & 3 deletions clang-tools-extra/clang-tidy/ClangTidyCheck.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down
10 changes: 5 additions & 5 deletions clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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>
Expand All @@ -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 =
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class ClangTidyContext {

/// 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.
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clang-tidy/ClangTidyModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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>>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Loading

0 comments on commit adcd026

Please sign in to comment.