Make llvm::StringRef to std::string conversions explicit.

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.
This commit is contained in:
Benjamin Kramer 2020-01-28 20:23:46 +01:00
parent 5eaf44f99f
commit adcd026838
895 changed files with 3319 additions and 3014 deletions

View File

@ -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

View File

@ -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;
}

View File

@ -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://");

View File

@ -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());
}

View File

@ -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 {};

View File

@ -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;

View File

@ -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.

View File

@ -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();

View File

@ -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;
}
}

View File

@ -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

View File

@ -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

View File

@ -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; }

View File

@ -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);

View File

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

View File

@ -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);

View File

@ -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;
}

View File

@ -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

View File

@ -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);

View File

@ -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,

View File

@ -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;

View File

@ -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.

View File

@ -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>>

View File

@ -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;

View File

@ -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();

View File

@ -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 &&

View File

@ -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);

View File

@ -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;

View File

@ -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))))));

View File

@ -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;
}

View File

@ -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)))),

View File

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

View File

@ -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();
}

View File

@ -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/");

View File

@ -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;

View File

@ -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;

View File

@ -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";

View File

@ -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);

View File

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

View File

@ -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()";
}

View File

@ -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);

View File

@ -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;
}

View File

@ -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) {

View File

@ -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(),

View File

@ -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);

View File

@ -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 + ")";

View File

@ -256,7 +256,7 @@ static std::string fixupWithCase(StringRef Name,
}
if (Words.empty())
return Name;
return std::string(Name);
std::string Fixup;
switch (Case) {

View File

@ -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.

View File

@ -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;

View File

@ -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);

View File

@ -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) {

View File

@ -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 =

View File

@ -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

View File

@ -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()) {

View File

@ -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();

View File

@ -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;
}

View File

@ -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 =

View File

@ -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;

View File

@ -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 {

View File

@ -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;

View File

@ -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());
}
}
}

View File

@ -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;
};

View File

@ -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(

View File

@ -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)) {}

View File

@ -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,

View File

@ -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);

View File

@ -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 << ": ";

View File

@ -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 :

View File

@ -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;
}

View File

@ -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) {

View File

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

View File

@ -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);

View File

@ -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;

View File

@ -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),

View File

@ -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);

View File

@ -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() != '/')

View File

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

View File

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

View File

@ -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) {

View File

@ -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;
}

View File

@ -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) {

View File

@ -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;

View File

@ -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;
}

View File

@ -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) {

View File

@ -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) {

View File

@ -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.

View File

@ -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();

View File

@ -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);

View File

@ -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();

View File

@ -81,7 +81,7 @@ public:
static Effect showMessage(StringRef S) {
Effect E;
E.ShowMessage = S;
E.ShowMessage = std::string(S);
return E;
}

View File

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

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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;

View File

@ -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

View File

@ -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()

View File

@ -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), "")};
}

View File

@ -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();

View File

@ -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"));
}

View File

@ -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(

Some files were not shown because too many files have changed in this diff Show More