24 changes: 12 additions & 12 deletions clang-tools-extra/clangd/CodeComplete.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ struct CompletionCandidate {
}

// The best header to include if include insertion is allowed.
llvm::Optional<llvm::StringRef>
std::optional<llvm::StringRef>
headerToInsertIfAllowed(const CodeCompleteOptions &Opts) const {
if (Opts.InsertIncludes == CodeCompleteOptions::NeverInsert ||
RankedIncludeHeaders.empty())
Expand Down Expand Up @@ -647,7 +647,7 @@ struct SpecifiedScope {
std::vector<std::string> AccessibleScopes;
// The full scope qualifier as typed by the user (without the leading "::").
// Set if the qualifier is not fully resolved by Sema.
llvm::Optional<std::string> UnresolvedQualifier;
std::optional<std::string> UnresolvedQualifier;

// Construct scopes being queried in indexes. The results are deduplicated.
// This method format the scopes to match the index request representation.
Expand Down Expand Up @@ -1232,7 +1232,7 @@ struct SemaCompleteInput {
PathRef FileName;
size_t Offset;
const PreambleData &Preamble;
const llvm::Optional<PreamblePatch> Patch;
const std::optional<PreamblePatch> Patch;
const ParseInputs &ParseInput;
};

Expand Down Expand Up @@ -1454,24 +1454,24 @@ class CodeCompleteFlow {
int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
bool Incomplete = false; // Would more be available with a higher limit?
CompletionPrefix HeuristicPrefix;
llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
std::optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Range ReplacedRange;
std::vector<std::string> QueryScopes; // Initialized once Sema runs.
// Initialized once QueryScopes is initialized, if there are scopes.
llvm::Optional<ScopeDistance> ScopeProximity;
llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
std::optional<ScopeDistance> ScopeProximity;
std::optional<OpaqueType> PreferredType; // Initialized once Sema runs.
// Whether to query symbols from any scope. Initialized once Sema runs.
bool AllScopes = false;
llvm::StringSet<> ContextWords;
// Include-insertion and proximity scoring rely on the include structure.
// This is available after Sema has run.
llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
std::optional<IncludeInserter> Inserter; // Available during runWithSema.
std::optional<URIDistance> FileProximity; // Initialized once Sema runs.
/// Speculative request based on the cached request and the filter text before
/// the cursor.
/// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
/// set and contains a cached request.
llvm::Optional<FuzzyFindRequest> SpecReq;
std::optional<FuzzyFindRequest> SpecReq;

public:
// A CodeCompleteFlow object is only useful for calling run() exactly once.
Expand Down Expand Up @@ -1834,7 +1834,7 @@ class CodeCompleteFlow {
return std::move(Top).items();
}

llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) {
std::optional<float> fuzzyScore(const CompletionCandidate &C) {
// Macros can be very spammy, so we only support prefix completion.
if (((C.SemaResult &&
C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
Expand Down Expand Up @@ -1949,7 +1949,7 @@ class CodeCompleteFlow {
}

CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
llvm::Optional<CodeCompletionBuilder> Builder;
std::optional<CodeCompletionBuilder> Builder;
for (const auto &Item : Bundle) {
CodeCompletionString *SemaCCS =
Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
Expand Down Expand Up @@ -2062,7 +2062,7 @@ CodeCompleteResult codeCompleteComment(PathRef FileName, unsigned Offset,
// If Offset is inside what looks like argument comment (e.g.
// "/*^" or "/* foo^"), returns new offset pointing to the start of the /*
// (place where semaCodeComplete should run).
llvm::Optional<unsigned>
std::optional<unsigned>
maybeFunctionArgumentCommentStart(llvm::StringRef Content) {
while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
Content = Content.drop_back();
Expand Down
12 changes: 6 additions & 6 deletions clang-tools-extra/clangd/CodeComplete.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ struct CodeCompleteOptions {
/// If none, the implementation may choose an appropriate behavior.
/// (In practice, ClangdLSPServer enables bundling if the client claims
/// to supports signature help).
llvm::Optional<bool> BundleOverloads;
std::optional<bool> BundleOverloads;

/// Limit the number of results returned (0 means no limit).
/// If more results are available, we set CompletionList.isIncomplete.
Expand Down Expand Up @@ -175,7 +175,7 @@ struct CodeCompletion {
// Type to be displayed for this completion.
std::string ReturnType;
// The parsed documentation comment.
llvm::Optional<markup::Document> Documentation;
std::optional<markup::Document> Documentation;
CompletionItemKind Kind = CompletionItemKind::Missing;
// This completion item may represent several symbols that can be inserted in
// the same way, such as function overloads. In this case BundleSize > 1, and
Expand All @@ -194,7 +194,7 @@ struct CodeCompletion {
// Empty for non-symbol completions, or when not known.
std::string Header;
// Present if Header should be inserted to use this item.
llvm::Optional<TextEdit> Insertion;
std::optional<TextEdit> Insertion;
};
// All possible include headers ranked by preference. By default, the first
// include is used.
Expand Down Expand Up @@ -247,7 +247,7 @@ struct CodeCompleteResult {
// Example: foo.pb^ -> foo.push_back()
// ~~
// Typically matches the textEdit.range of Completions, but not guaranteed to.
llvm::Optional<Range> CompletionRange;
std::optional<Range> CompletionRange;
// Usually the source will be parsed with a real C++ parser.
// But heuristics may be used instead if e.g. the preamble is not ready.
bool RanParser = true;
Expand All @@ -260,10 +260,10 @@ raw_ostream &operator<<(raw_ostream &, const CodeCompleteResult &);
struct SpeculativeFuzzyFind {
/// A cached request from past code completions.
/// Set by caller of `codeComplete()`.
llvm::Optional<FuzzyFindRequest> CachedReq;
std::optional<FuzzyFindRequest> CachedReq;
/// The actual request used by `codeComplete()`.
/// Set by `codeComplete()`. This can be used by callers to update cache.
llvm::Optional<FuzzyFindRequest> NewReq;
std::optional<FuzzyFindRequest> NewReq;
/// The result is consumed by `codeComplete()` if speculation succeeded.
/// NOTE: the destructor will wait for the async call to finish.
std::future<std::pair<bool /*Incomplete*/, SymbolSlab>> Result;
Expand Down
8 changes: 4 additions & 4 deletions clang-tools-extra/clangd/CompileCommands.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ namespace {

// Query apple's `xcrun` launcher, which is the source of truth for "how should"
// clang be invoked on this system.
llvm::Optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
std::optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
auto Xcrun = llvm::sys::findProgramByName("xcrun");
if (!Xcrun) {
log("Couldn't find xcrun. Hopefully you have a non-apple toolchain...");
Expand Down Expand Up @@ -118,7 +118,7 @@ std::string detectClangPath() {

// On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang.
// The effect of this is to set -isysroot correctly. We do the same.
llvm::Optional<std::string> detectSysroot() {
std::optional<std::string> detectSysroot() {
#ifndef __APPLE__
return std::nullopt;
#endif
Expand All @@ -141,7 +141,7 @@ std::string detectStandardResourceDir() {
// Where possible it should be an absolute path with sensible directory, but
// with the original basename.
static std::string resolveDriver(llvm::StringRef Driver, bool FollowSymlink,
llvm::Optional<std::string> ClangPath) {
std::optional<std::string> ClangPath) {
auto SiblingOf = [&](llvm::StringRef AbsPath) {
llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
llvm::sys::path::append(Result, llvm::sys::path::filename(Driver));
Expand Down Expand Up @@ -256,7 +256,7 @@ void CommandMangler::operator()(tooling::CompileCommand &Command,
// In practice only the extension of the file matters, so do this only when
// it differs.
llvm::StringRef FileExtension = llvm::sys::path::extension(File);
llvm::Optional<std::string> TransferFrom;
std::optional<std::string> TransferFrom;
auto SawInput = [&](llvm::StringRef Input) {
if (llvm::sys::path::extension(Input) != FileExtension)
TransferFrom.emplace(Input);
Expand Down
6 changes: 3 additions & 3 deletions clang-tools-extra/clangd/CompileCommands.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ namespace clangd {
// - injecting -isysroot flags on mac as the system clang does
struct CommandMangler {
// Absolute path to clang.
llvm::Optional<std::string> ClangPath;
std::optional<std::string> ClangPath;
// Directory containing builtin headers.
llvm::Optional<std::string> ResourceDir;
std::optional<std::string> ResourceDir;
// Root for searching for standard library (passed to -isysroot).
llvm::Optional<std::string> Sysroot;
std::optional<std::string> Sysroot;
SystemIncludeExtractorFn SystemIncludeExtractor;

// A command-mangler that doesn't know anything about the system.
Expand Down
10 changes: 5 additions & 5 deletions clang-tools-extra/clangd/ConfigCompile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ struct FragmentCompiler {
std::string FragmentDirectory;
bool Trusted = false;

llvm::Optional<llvm::Regex>
std::optional<llvm::Regex>
compileRegex(const Located<std::string> &Text,
llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags) {
std::string Anchored = "^(" + *Text + ")$";
Expand Down Expand Up @@ -142,7 +142,7 @@ struct FragmentCompiler {
FragmentCompiler &Outer;
llvm::StringRef EnumName;
const Located<std::string> &Input;
llvm::Optional<T> Result;
std::optional<T> Result;
llvm::SmallVector<llvm::StringLiteral> ValidValues;

public:
Expand All @@ -158,7 +158,7 @@ struct FragmentCompiler {
return *this;
}

llvm::Optional<T> value() {
std::optional<T> value() {
if (!Result)
Outer.diag(
Warning,
Expand All @@ -173,7 +173,7 @@ struct FragmentCompiler {
// Attempt to parse a specified string into an enum.
// Yields std::nullopt and produces a diagnostic on failure.
//
// Optional<T> Value = compileEnum<En>("Foo", Frag.Foo)
// std::optional<T> Value = compileEnum<En>("Foo", Frag.Foo)
// .map("Foo", Enum::Foo)
// .map("Bar", Enum::Bar)
// .value();
Expand Down Expand Up @@ -291,7 +291,7 @@ struct FragmentCompiler {
}

if (F.CompilationDatabase) {
llvm::Optional<Config::CDBSearchSpec> Spec;
std::optional<Config::CDBSearchSpec> Spec;
if (**F.CompilationDatabase == "Ancestors") {
Spec.emplace();
Spec->Policy = Config::CDBSearchSpec::Ancestors;
Expand Down
6 changes: 3 additions & 3 deletions clang-tools-extra/clangd/Diagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -907,9 +907,9 @@ llvm::StringRef normalizeSuppressedCode(llvm::StringRef Code) {
return Code;
}

llvm::Optional<std::string> getDiagnosticDocURI(Diag::DiagSource Source,
unsigned ID,
llvm::StringRef Name) {
std::optional<std::string> getDiagnosticDocURI(Diag::DiagSource Source,
unsigned ID,
llvm::StringRef Name) {
switch (Source) {
case Diag::Unknown:
break;
Expand Down
12 changes: 6 additions & 6 deletions clang-tools-extra/clangd/Diagnostics.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ struct DiagBase {
// May be relative, absolute or even artificially constructed.
std::string File;
// Absolute path to containing file, if available.
llvm::Optional<std::string> AbsFile;
std::optional<std::string> AbsFile;

clangd::Range Range;
DiagnosticsEngine::Level Severity = DiagnosticsEngine::Note;
Expand Down Expand Up @@ -128,8 +128,8 @@ CodeAction toCodeAction(const Fix &D, const URIForFile &File);
int getSeverity(DiagnosticsEngine::Level L);

/// Returns a URI providing more information about a particular diagnostic.
llvm::Optional<std::string> getDiagnosticDocURI(Diag::DiagSource, unsigned ID,
llvm::StringRef Name);
std::optional<std::string> getDiagnosticDocURI(Diag::DiagSource, unsigned ID,
llvm::StringRef Name);

/// StoreDiags collects the diagnostics that can later be reported by
/// clangd. It groups all notes for a diagnostic into a single Diag
Expand Down Expand Up @@ -171,9 +171,9 @@ class StoreDiags : public DiagnosticConsumer {
LevelAdjuster Adjuster = nullptr;
DiagCallback DiagCB = nullptr;
std::vector<Diag> Output;
llvm::Optional<LangOptions> LangOpts;
llvm::Optional<Diag> LastDiag;
llvm::Optional<FullSourceLoc> LastDiagLoc; // Valid only when LastDiag is set.
std::optional<LangOptions> LangOpts;
std::optional<Diag> LastDiag;
std::optional<FullSourceLoc> LastDiagLoc; // Valid only when LastDiag is set.
bool LastDiagOriginallyError = false; // Valid only when LastDiag is set.
SourceManager *OrigSrcMgr = nullptr;

Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/DraftStore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
namespace clang {
namespace clangd {

llvm::Optional<DraftStore::Draft> DraftStore::getDraft(PathRef File) const {
std::optional<DraftStore::Draft> DraftStore::getDraft(PathRef File) const {
std::lock_guard<std::mutex> Lock(Mutex);

auto It = Drafts.find(File);
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/DraftStore.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class DraftStore {

/// \return Contents of the stored document.
/// For untracked files, a std::nullopt is returned.
llvm::Optional<Draft> getDraft(PathRef File) const;
std::optional<Draft> getDraft(PathRef File) const;

/// \return List of names of the drafts in this store.
std::vector<Path> getActiveFiles() const;
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/DumpAST.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ class DumpVisitor : public RecursiveASTVisitor<DumpVisitor> {
// Range: most nodes have getSourceRange(), with a couple of exceptions.
// We only return it if it's valid at both ends and there are no macros.

template <typename T> llvm::Optional<Range> getRange(const T &Node) {
template <typename T> std::optional<Range> getRange(const T &Node) {
SourceRange SR = getSourceRange(Node);
auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(SR));
if (!Spelled)
Expand Down
10 changes: 4 additions & 6 deletions clang-tools-extra/clangd/ExpectedTypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ static const Type *toEquivClass(ASTContext &Ctx, QualType T) {
return T.getTypePtr();
}

static llvm::Optional<QualType>
typeOfCompletion(const CodeCompletionResult &R) {
static std::optional<QualType> typeOfCompletion(const CodeCompletionResult &R) {
const NamedDecl *D = R.Declaration;
// Templates do not have a type on their own, look at the templated decl.
if (auto *Template = dyn_cast_or_null<TemplateDecl>(D))
Expand All @@ -63,7 +62,7 @@ typeOfCompletion(const CodeCompletionResult &R) {
}
} // namespace

llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
std::optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
if (T.isNull())
return std::nullopt;
const Type *C = toEquivClass(Ctx, T);
Expand All @@ -77,12 +76,11 @@ llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {

OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {}

llvm::Optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx,
QualType Type) {
std::optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx, QualType Type) {
return encode(Ctx, Type);
}

llvm::Optional<OpaqueType>
std::optional<OpaqueType>
OpaqueType::fromCompletionResult(ASTContext &Ctx,
const CodeCompletionResult &R) {
auto T = typeOfCompletion(R);
Expand Down
6 changes: 3 additions & 3 deletions clang-tools-extra/clangd/ExpectedTypes.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ namespace clangd {
class OpaqueType {
public:
/// Create a type from a code completion result.
static llvm::Optional<OpaqueType>
static std::optional<OpaqueType>
fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R);
/// Construct an instance from a clang::QualType. This is usually a
/// PreferredType from a clang's completion context.
static llvm::Optional<OpaqueType> fromType(ASTContext &Ctx, QualType Type);
static std::optional<OpaqueType> fromType(ASTContext &Ctx, QualType Type);

/// Get the raw byte representation of the type. You can only rely on the
/// types being equal iff their raw representation is the same. The particular
Expand All @@ -55,7 +55,7 @@ class OpaqueType {
}

private:
static llvm::Optional<OpaqueType> encode(ASTContext &Ctx, QualType Type);
static std::optional<OpaqueType> encode(ASTContext &Ctx, QualType Type);
explicit OpaqueType(std::string Data);

std::string Data;
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/FS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS,
StatCache.insert({PathStore, std::move(S)});
}

llvm::Optional<llvm::vfs::Status>
std::optional<llvm::vfs::Status>
PreambleFileStatusCache::lookup(llvm::StringRef File) const {
// Canonicalize to match the cached form.
// Lookup tends to be first by absolute path, so no need to make absolute.
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/FS.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class PreambleFileStatusCache {
void update(const llvm::vfs::FileSystem &FS, llvm::vfs::Status S);

/// \p Path is a path stored in preamble.
llvm::Optional<llvm::vfs::Status> lookup(llvm::StringRef Path) const;
std::optional<llvm::vfs::Status> lookup(llvm::StringRef Path) const;

/// Returns a VFS that collects file status.
/// Only cache stats for files that exist because
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/FeatureModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ class FeatureModule {
using OutgoingMethod = llvm::unique_function<void(const P &, Callback<R>)>;

private:
llvm::Optional<Facilities> Fac;
std::optional<Facilities> Fac;
};

/// A FeatureModuleSet is a collection of feature modules installed in clangd.
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/FindSymbols.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ std::string getSymbolDetail(ASTContext &Ctx, const NamedDecl &ND) {
return std::move(OS.str());
}

llvm::Optional<DocumentSymbol> declToSym(ASTContext &Ctx, const NamedDecl &ND) {
std::optional<DocumentSymbol> declToSym(ASTContext &Ctx, const NamedDecl &ND) {
auto &SM = Ctx.getSourceManager();

SourceLocation BeginLoc = SM.getSpellingLoc(SM.getFileLoc(ND.getBeginLoc()));
Expand Down
20 changes: 10 additions & 10 deletions clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ DirectoryBasedGlobalCompilationDatabase::
DirectoryBasedGlobalCompilationDatabase::
~DirectoryBasedGlobalCompilationDatabase() = default;

llvm::Optional<tooling::CompileCommand>
std::optional<tooling::CompileCommand>
DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const {
CDBLookupRequest Req;
Req.FileName = File;
Expand Down Expand Up @@ -398,7 +398,7 @@ DirectoryBasedGlobalCompilationDatabase::getDirectoryCaches(
return Ret;
}

llvm::Optional<DirectoryBasedGlobalCompilationDatabase::CDBLookupResult>
std::optional<DirectoryBasedGlobalCompilationDatabase::CDBLookupResult>
DirectoryBasedGlobalCompilationDatabase::lookupCDB(
CDBLookupRequest Request) const {
assert(llvm::sys::path::is_absolute(Request.FileName) &&
Expand Down Expand Up @@ -476,7 +476,7 @@ class DirectoryBasedGlobalCompilationDatabase::BroadcastThread {
Context Ctx;
};
std::deque<Task> Queue;
llvm::Optional<Task> ActiveTask;
std::optional<Task> ActiveTask;
std::thread Thread; // Must be last member.

// Thread body: this is just the basic queue procesing boilerplate.
Expand Down Expand Up @@ -725,7 +725,7 @@ bool DirectoryBasedGlobalCompilationDatabase::blockUntilIdle(
return Broadcaster->blockUntilIdle(Timeout);
}

llvm::Optional<ProjectInfo>
std::optional<ProjectInfo>
DirectoryBasedGlobalCompilationDatabase::getProjectInfo(PathRef File) const {
CDBLookupRequest Req;
Req.FileName = File;
Expand All @@ -744,9 +744,9 @@ OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base,
: DelegatingCDB(Base), Mangler(std::move(Mangler)),
FallbackFlags(std::move(FallbackFlags)) {}

llvm::Optional<tooling::CompileCommand>
std::optional<tooling::CompileCommand>
OverlayCDB::getCompileCommand(PathRef File) const {
llvm::Optional<tooling::CompileCommand> Cmd;
std::optional<tooling::CompileCommand> Cmd;
{
std::lock_guard<std::mutex> Lock(Mutex);
auto It = Commands.find(removeDots(File));
Expand All @@ -772,8 +772,8 @@ tooling::CompileCommand OverlayCDB::getFallbackCommand(PathRef File) const {
return Cmd;
}

void OverlayCDB::setCompileCommand(
PathRef File, llvm::Optional<tooling::CompileCommand> Cmd) {
void OverlayCDB::setCompileCommand(PathRef File,
std::optional<tooling::CompileCommand> Cmd) {
// We store a canonical version internally to prevent mismatches between set
// and get compile commands. Also it assures clients listening to broadcasts
// doesn't receive different names for the same file.
Expand Down Expand Up @@ -801,14 +801,14 @@ DelegatingCDB::DelegatingCDB(std::unique_ptr<GlobalCompilationDatabase> Base)
BaseOwner = std::move(Base);
}

llvm::Optional<tooling::CompileCommand>
std::optional<tooling::CompileCommand>
DelegatingCDB::getCompileCommand(PathRef File) const {
if (!Base)
return std::nullopt;
return Base->getCompileCommand(File);
}

llvm::Optional<ProjectInfo> DelegatingCDB::getProjectInfo(PathRef File) const {
std::optional<ProjectInfo> DelegatingCDB::getProjectInfo(PathRef File) const {
if (!Base)
return std::nullopt;
return Base->getProjectInfo(File);
Expand Down
18 changes: 9 additions & 9 deletions clang-tools-extra/clangd/GlobalCompilationDatabase.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ class GlobalCompilationDatabase {
virtual ~GlobalCompilationDatabase() = default;

/// If there are any known-good commands for building this file, returns one.
virtual llvm::Optional<tooling::CompileCommand>
virtual std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const = 0;

/// Finds the closest project to \p File.
virtual llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const {
virtual std::optional<ProjectInfo> getProjectInfo(PathRef File) const {
return std::nullopt;
}

Expand Down Expand Up @@ -72,10 +72,10 @@ class DelegatingCDB : public GlobalCompilationDatabase {
DelegatingCDB(const GlobalCompilationDatabase *Base);
DelegatingCDB(std::unique_ptr<GlobalCompilationDatabase> Base);

llvm::Optional<tooling::CompileCommand>
std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override;

llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override;
std::optional<ProjectInfo> getProjectInfo(PathRef File) const override;

tooling::CompileCommand getFallbackCommand(PathRef File) const override;

Expand Down Expand Up @@ -116,12 +116,12 @@ class DirectoryBasedGlobalCompilationDatabase
/// Scans File's parents looking for compilation databases.
/// Any extra flags will be added.
/// Might trigger OnCommandChanged, if CDB wasn't broadcasted yet.
llvm::Optional<tooling::CompileCommand>
std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override;

/// Returns the path to first directory containing a compilation database in
/// \p File's parents.
llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override;
std::optional<ProjectInfo> getProjectInfo(PathRef File) const override;

bool blockUntilIdle(Deadline Timeout) const override;

Expand Down Expand Up @@ -150,7 +150,7 @@ class DirectoryBasedGlobalCompilationDatabase
std::shared_ptr<const tooling::CompilationDatabase> CDB;
ProjectInfo PI;
};
llvm::Optional<CDBLookupResult> lookupCDB(CDBLookupRequest Request) const;
std::optional<CDBLookupResult> lookupCDB(CDBLookupRequest Request) const;

class BroadcastThread;
std::unique_ptr<BroadcastThread> Broadcaster;
Expand Down Expand Up @@ -186,14 +186,14 @@ class OverlayCDB : public DelegatingCDB {
std::vector<std::string> FallbackFlags = {},
CommandMangler Mangler = nullptr);

llvm::Optional<tooling::CompileCommand>
std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override;
tooling::CompileCommand getFallbackCommand(PathRef File) const override;

/// Sets or clears the compilation command for a particular file.
void
setCompileCommand(PathRef File,
llvm::Optional<tooling::CompileCommand> CompilationCommand);
std::optional<tooling::CompileCommand> CompilationCommand);

private:
mutable std::mutex Mutex;
Expand Down
8 changes: 4 additions & 4 deletions clang-tools-extra/clangd/HeaderSourceSwitch.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
namespace clang {
namespace clangd {

llvm::Optional<Path> getCorrespondingHeaderOrSource(
std::optional<Path> getCorrespondingHeaderOrSource(
PathRef OriginalFile, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
".c++", ".m", ".mm"};
Expand Down Expand Up @@ -64,9 +64,9 @@ llvm::Optional<Path> getCorrespondingHeaderOrSource(
return std::nullopt;
}

llvm::Optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
ParsedAST &AST,
const SymbolIndex *Index) {
std::optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
ParsedAST &AST,
const SymbolIndex *Index) {
if (!Index) {
// FIXME: use the AST to do the inference.
return std::nullopt;
Expand Down
8 changes: 4 additions & 4 deletions clang-tools-extra/clangd/HeaderSourceSwitch.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ namespace clangd {

/// Given a header file, returns the best matching source file, and vice visa.
/// It only uses the filename heuristics to do the inference.
llvm::Optional<Path> getCorrespondingHeaderOrSource(
std::optional<Path> getCorrespondingHeaderOrSource(
PathRef OriginalFile, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS);

/// Given a header file, returns the best matching source file, and vice visa.
/// The heuristics incorporate with the AST and the index (if provided).
llvm::Optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
ParsedAST &AST,
const SymbolIndex *Index);
std::optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
ParsedAST &AST,
const SymbolIndex *Index);

/// Returns all indexable decls that are present in the main file of the AST.
/// Exposed for unittests.
Expand Down
8 changes: 4 additions & 4 deletions clang-tools-extra/clangd/Headers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ void IncludeStructure::collect(const CompilerInstance &CI) {
CI.getPreprocessor().addPPCallbacks(std::move(Collector));
}

llvm::Optional<IncludeStructure::HeaderID>
std::optional<IncludeStructure::HeaderID>
IncludeStructure::getID(const FileEntry *Entry) const {
// HeaderID of the main file is always 0;
if (Entry == MainFileEntry) {
Expand Down Expand Up @@ -315,7 +315,7 @@ bool IncludeInserter::shouldInsertInclude(
return !Included(DeclaringHeader) && !Included(InsertedHeader.File);
}

llvm::Optional<std::string>
std::optional<std::string>
IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
llvm::StringRef IncludingFile) const {
assert(InsertedHeader.valid());
Expand Down Expand Up @@ -345,10 +345,10 @@ IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
return Suggested;
}

llvm::Optional<TextEdit>
std::optional<TextEdit>
IncludeInserter::insert(llvm::StringRef VerbatimHeader,
tooling::IncludeDirective Directive) const {
llvm::Optional<TextEdit> Edit;
std::optional<TextEdit> Edit;
if (auto Insertion =
Inserter.insert(VerbatimHeader.trim("\"<>"),
VerbatimHeader.startswith("<"), Directive))
Expand Down
10 changes: 5 additions & 5 deletions clang-tools-extra/clangd/Headers.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ struct Inclusion {
unsigned HashOffset = 0; // Byte offset from start of file to #.
int HashLine = 0; // Line number containing the directive, 0-indexed.
SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
llvm::Optional<unsigned> HeaderID;
std::optional<unsigned> HeaderID;
bool BehindPragmaKeep = false; // Has IWYU pragma: keep right after.
};
llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Inclusion &);
Expand Down Expand Up @@ -143,7 +143,7 @@ class IncludeStructure {
// file builds.
enum class HeaderID : unsigned {};

llvm::Optional<HeaderID> getID(const FileEntry *Entry) const;
std::optional<HeaderID> getID(const FileEntry *Entry) const;
HeaderID getOrCreateID(FileEntryRef Entry);

StringRef getRealPath(HeaderID ID) const {
Expand Down Expand Up @@ -243,14 +243,14 @@ class IncludeInserter {
///
/// \return A quoted "path" or <path> to be included, or std::nullopt if it
/// couldn't be shortened.
llvm::Optional<std::string>
std::optional<std::string>
calculateIncludePath(const HeaderFile &InsertedHeader,
llvm::StringRef IncludingFile) const;

/// Calculates an edit that inserts \p VerbatimHeader into code. If the header
/// is already included, this returns std::nullopt.
llvm::Optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
tooling::IncludeDirective Directive) const;
std::optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
tooling::IncludeDirective Directive) const;

private:
StringRef FileName;
Expand Down
18 changes: 9 additions & 9 deletions clang-tools-extra/clangd/Hover.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -402,8 +402,8 @@ static llvm::FormattedNumber printHex(const llvm::APSInt &V) {
return llvm::format_hex(Bits, 0);
}

llvm::Optional<std::string> printExprValue(const Expr *E,
const ASTContext &Ctx) {
std::optional<std::string> printExprValue(const Expr *E,
const ASTContext &Ctx) {
// InitListExpr has two forms, syntactic and semantic. They are the same thing
// (refer to a same AST node) in most cases.
// When they are different, RAV returns the syntactic form, and we should feed
Expand Down Expand Up @@ -451,8 +451,8 @@ llvm::Optional<std::string> printExprValue(const Expr *E,
return Constant.Val.getAsString(Ctx, T);
}

llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
const ASTContext &Ctx) {
std::optional<std::string> printExprValue(const SelectionTree::Node *N,
const ASTContext &Ctx) {
for (; N; N = N->Parent) {
// Try to evaluate the first evaluatable enclosing expression.
if (const Expr *E = N->ASTNode.get<Expr>()) {
Expand All @@ -471,7 +471,7 @@ llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
return std::nullopt;
}

llvm::Optional<StringRef> fieldName(const Expr *E) {
std::optional<StringRef> fieldName(const Expr *E) {
const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
return std::nullopt;
Expand All @@ -482,7 +482,7 @@ llvm::Optional<StringRef> fieldName(const Expr *E) {
}

// If CMD is of the form T foo() { return FieldName; } then returns "FieldName".
llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
std::optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
assert(CMD->hasBody());
if (CMD->getNumParams() != 0 || CMD->isVariadic())
return std::nullopt;
Expand All @@ -501,7 +501,7 @@ llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
// void foo(T arg) { FieldName = std::move(arg); }
// R foo(T arg) { FieldName = std::move(arg); return *this; }
// then returns "FieldName"
llvm::Optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
std::optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
assert(CMD->hasBody());
if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
return std::nullopt;
Expand Down Expand Up @@ -1283,8 +1283,8 @@ markup::Document HoverInfo::present() const {

// If the backtick at `Offset` starts a probable quoted range, return the range
// (including the quotes).
llvm::Optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
unsigned Offset) {
std::optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
unsigned Offset) {
assert(Line[Offset] == '`');

// The open-quote is usually preceded by whitespace.
Expand Down
30 changes: 15 additions & 15 deletions clang-tools-extra/clangd/Hover.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ struct HoverInfo {
/// Pretty-printed type
std::string Type;
/// Desugared type
llvm::Optional<std::string> AKA;
std::optional<std::string> AKA;
};

/// Represents parameters of a function, a template or a macro.
Expand All @@ -44,11 +44,11 @@ struct HoverInfo {
struct Param {
/// The printable parameter type, e.g. "int", or "typename" (in
/// TemplateParameters), might be std::nullopt for macro parameters.
llvm::Optional<PrintedType> Type;
std::optional<PrintedType> Type;
/// std::nullopt for unnamed parameters.
std::optional<std::string> Name;
/// std::nullopt if no default is provided.
llvm::Optional<std::string> Default;
std::optional<std::string> Default;
};

/// For a variable named Bar, declared in clang::clangd::Foo::getFoo the
Expand All @@ -61,13 +61,13 @@ struct HoverInfo {
/// auto/decltype.
/// Contains all of the enclosing namespaces, empty string means global
/// namespace.
llvm::Optional<std::string> NamespaceScope;
std::optional<std::string> NamespaceScope;
/// Remaining named contexts in symbol's qualified name, empty string means
/// symbol is not local.
std::string LocalScope;
/// Name of the symbol, does not contain any "::".
std::string Name;
llvm::Optional<Range> SymRange;
std::optional<Range> SymRange;
index::SymbolKind Kind = index::SymbolKind::Unknown;
std::string Documentation;
/// Source code containing the definition of the symbol.
Expand All @@ -78,24 +78,24 @@ struct HoverInfo {
std::string AccessSpecifier;
/// Printable variable type.
/// Set only for variables.
llvm::Optional<PrintedType> Type;
std::optional<PrintedType> Type;
/// Set for functions and lambdas.
llvm::Optional<PrintedType> ReturnType;
std::optional<PrintedType> ReturnType;
/// Set for functions, lambdas and macros with parameters.
llvm::Optional<std::vector<Param>> Parameters;
std::optional<std::vector<Param>> Parameters;
/// Set for all templates(function, class, variable).
llvm::Optional<std::vector<Param>> TemplateParameters;
std::optional<std::vector<Param>> TemplateParameters;
/// Contains the evaluated value of the symbol if available.
llvm::Optional<std::string> Value;
std::optional<std::string> Value;
/// Contains the byte-size of fields and types where it's interesting.
llvm::Optional<uint64_t> Size;
std::optional<uint64_t> Size;
/// Contains the offset of fields within the enclosing class.
llvm::Optional<uint64_t> Offset;
std::optional<uint64_t> Offset;
/// Contains the padding following a field within the enclosing class.
llvm::Optional<uint64_t> Padding;
std::optional<uint64_t> Padding;
// Set when symbol is inside function call. Contains information extracted
// from the callee definition about the argument this is passed as.
llvm::Optional<Param> CalleeArgInfo;
std::optional<Param> CalleeArgInfo;
struct PassType {
// How the variable is passed to callee.
enum PassMode { Ref, ConstRef, Value };
Expand All @@ -106,7 +106,7 @@ struct HoverInfo {
bool Converted = false;
};
// Set only if CalleeArgInfo is set.
llvm::Optional<PassType> CallPassType;
std::optional<PassType> CallPassType;

/// Produce a user-readable information.
markup::Document present() const;
Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/IncludeCleaner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ ReferencedLocations findReferencedLocations(ParsedAST &AST) {
ReferencedFiles findReferencedFiles(
const ReferencedLocations &Locs, const SourceManager &SM,
llvm::function_ref<FileID(FileID)> HeaderResponsible,
llvm::function_ref<Optional<StringRef>(FileID)> UmbrellaHeader) {
llvm::function_ref<std::optional<StringRef>(FileID)> UmbrellaHeader) {
std::vector<SourceLocation> Sorted{Locs.User.begin(), Locs.User.end()};
llvm::sort(Sorted); // Group by FileID.
ReferencedFilesBuilder Builder(SM);
Expand Down Expand Up @@ -390,7 +390,7 @@ ReferencedFiles findReferencedFiles(const ReferencedLocations &Locs,
[&SM, &Includes](FileID ID) {
return headerResponsible(ID, SM, Includes);
},
[&SM, &CanonIncludes](FileID ID) -> Optional<StringRef> {
[&SM, &CanonIncludes](FileID ID) -> std::optional<StringRef> {
auto Entry = SM.getFileEntryRefForID(ID);
if (!Entry)
return std::nullopt;
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/IncludeCleaner.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ struct ReferencedFiles {
ReferencedFiles findReferencedFiles(
const ReferencedLocations &Locs, const SourceManager &SM,
llvm::function_ref<FileID(FileID)> HeaderResponsible,
llvm::function_ref<Optional<StringRef>(FileID)> UmbrellaHeader);
llvm::function_ref<std::optional<StringRef>(FileID)> UmbrellaHeader);
ReferencedFiles findReferencedFiles(const ReferencedLocations &Locs,
const IncludeStructure &Includes,
const CanonicalIncludes &CanonIncludes,
Expand Down
32 changes: 16 additions & 16 deletions clang-tools-extra/clangd/IncludeFixer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ namespace clang {
namespace clangd {
namespace {

llvm::Optional<llvm::StringRef> getArgStr(const clang::Diagnostic &Info,
unsigned Index) {
std::optional<llvm::StringRef> getArgStr(const clang::Diagnostic &Info,
unsigned Index) {
switch (Info.getArgKind(Index)) {
case DiagnosticsEngine::ak_c_string:
return llvm::StringRef(Info.getArgCStr(Index));
Expand All @@ -62,7 +62,7 @@ llvm::Optional<llvm::StringRef> getArgStr(const clang::Diagnostic &Info,
}
}

std::vector<Fix> only(llvm::Optional<Fix> F) {
std::vector<Fix> only(std::optional<Fix> F) {
if (F)
return {std::move(*F)};
return {};
Expand Down Expand Up @@ -248,7 +248,7 @@ std::vector<Fix> IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel,
return {};
}

llvm::Optional<Fix> IncludeFixer::insertHeader(llvm::StringRef Spelled,
std::optional<Fix> IncludeFixer::insertHeader(llvm::StringRef Spelled,
llvm::StringRef Symbol,
tooling::IncludeDirective Directive) const {
Fix F;
Expand Down Expand Up @@ -282,7 +282,7 @@ std::vector<Fix> IncludeFixer::fixIncompleteType(const Type &T) const {
auto ID = getSymbolID(TD);
if (!ID)
return {};
llvm::Optional<const SymbolSlab *> Symbols = lookupCached(ID);
std::optional<const SymbolSlab *> Symbols = lookupCached(ID);
if (!Symbols)
return {};
const SymbolSlab &Syms = **Symbols;
Expand Down Expand Up @@ -347,7 +347,7 @@ std::vector<Fix> IncludeFixer::fixesForSymbols(const SymbolSlab &Syms) const {
// "::X::Y" that is qualified by unresolved name "clangd":
// clang::clangd::X::Y
// ~
llvm::Optional<std::string> qualifiedByUnresolved(const SourceManager &SM,
std::optional<std::string> qualifiedByUnresolved(const SourceManager &SM,
SourceLocation Loc,
const LangOptions &LangOpts) {
std::string Result;
Expand All @@ -373,15 +373,15 @@ struct CheapUnresolvedName {
// This is the part of what was typed that was resolved, and it's in its
// resolved form not its typed form (think `namespace clang { clangd::x }` -->
// `clang::clangd::`).
llvm::Optional<std::string> ResolvedScope;
std::optional<std::string> ResolvedScope;

// Unresolved part of the scope. When the unresolved name is a specifier, we
// use the name that comes after it as the alternative name to resolve and use
// the specifier as the extra scope in the accessible scopes.
llvm::Optional<std::string> UnresolvedScope;
std::optional<std::string> UnresolvedScope;
};

llvm::Optional<std::string> getSpelledSpecifier(const CXXScopeSpec &SS,
std::optional<std::string> getSpelledSpecifier(const CXXScopeSpec &SS,
const SourceManager &SM) {
// Support specifiers written within a single macro argument.
if (!SM.isWrittenInSameFile(SS.getBeginLoc(), SS.getEndLoc()))
Expand All @@ -395,7 +395,7 @@ llvm::Optional<std::string> getSpelledSpecifier(const CXXScopeSpec &SS,

// Extracts unresolved name and scope information around \p Unresolved.
// FIXME: try to merge this with the scope-wrangling code in CodeComplete.
llvm::Optional<CheapUnresolvedName> extractUnresolvedNameCheaply(
std::optional<CheapUnresolvedName> extractUnresolvedNameCheaply(
const SourceManager &SM, const DeclarationNameInfo &Unresolved,
CXXScopeSpec *SS, const LangOptions &LangOpts, bool UnresolvedIsSpecifier) {
CheapUnresolvedName Result;
Expand All @@ -406,7 +406,7 @@ llvm::Optional<CheapUnresolvedName> extractUnresolvedNameCheaply(
Result.ResolvedScope = "";
} else if (const auto *NS = Nested->getAsNamespace()) {
std::string SpecifiedNS = printNamespaceScope(*NS);
llvm::Optional<std::string> Spelling = getSpelledSpecifier(*SS, SM);
std::optional<std::string> Spelling = getSpelledSpecifier(*SS, SM);

// Check the specifier spelled in the source.
// If the resolved scope doesn't end with the spelled scope, the
Expand Down Expand Up @@ -491,7 +491,7 @@ collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S,

class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource {
public:
UnresolvedNameRecorder(llvm::Optional<UnresolvedName> &LastUnresolvedName)
UnresolvedNameRecorder(std::optional<UnresolvedName> &LastUnresolvedName)
: LastUnresolvedName(LastUnresolvedName) {}

void InitializeSema(Sema &S) override { this->SemaPtr = &S; }
Expand Down Expand Up @@ -544,7 +544,7 @@ class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource {
private:
Sema *SemaPtr = nullptr;

llvm::Optional<UnresolvedName> &LastUnresolvedName;
std::optional<UnresolvedName> &LastUnresolvedName;
};

llvm::IntrusiveRefCntPtr<ExternalSemaSource>
Expand All @@ -565,13 +565,13 @@ std::vector<Fix> IncludeFixer::fixUnresolvedName() const {
Req.RestrictForCodeCompletion = true;
Req.Limit = 100;

if (llvm::Optional<const SymbolSlab *> Syms = fuzzyFindCached(Req))
if (std::optional<const SymbolSlab *> Syms = fuzzyFindCached(Req))
return fixesForSymbols(**Syms);

return {};
}

llvm::Optional<const SymbolSlab *>
std::optional<const SymbolSlab *>
IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const {
auto ReqStr = llvm::formatv("{0}", toJSON(Req)).str();
auto I = FuzzyFindCache.find(ReqStr);
Expand All @@ -594,7 +594,7 @@ IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const {
return &E.first->second;
}

llvm::Optional<const SymbolSlab *>
std::optional<const SymbolSlab *>
IncludeFixer::lookupCached(const SymbolID &ID) const {
LookupRequest Req;
Req.IDs.insert(ID);
Expand Down
14 changes: 7 additions & 7 deletions clang-tools-extra/clangd/IncludeFixer.h
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ class IncludeFixer {
/// Generates header insertion fixes for all symbols. Fixes are deduplicated.
std::vector<Fix> fixesForSymbols(const SymbolSlab &Syms) const;

llvm::Optional<Fix>
insertHeader(llvm::StringRef Name, llvm::StringRef Symbol = "",
tooling::IncludeDirective Directive =
tooling::IncludeDirective::Include) const;
std::optional<Fix> insertHeader(llvm::StringRef Name,
llvm::StringRef Symbol = "",
tooling::IncludeDirective Directive =
tooling::IncludeDirective::Include) const;

struct UnresolvedName {
std::string Name; // E.g. "X" in foo::X.
Expand All @@ -84,7 +84,7 @@ class IncludeFixer {

// These collect the last unresolved name so that we can associate it with the
// diagnostic.
llvm::Optional<UnresolvedName> LastUnresolvedName;
std::optional<UnresolvedName> LastUnresolvedName;

// There can be multiple diagnostics that are caused by the same unresolved
// name or incomplete type in one parse, especially when code is
Expand All @@ -93,9 +93,9 @@ class IncludeFixer {
mutable llvm::StringMap<SymbolSlab> FuzzyFindCache;
mutable llvm::DenseMap<SymbolID, SymbolSlab> LookupCache;
// Returns std::nullopt if the number of index requests has reached the limit.
llvm::Optional<const SymbolSlab *>
std::optional<const SymbolSlab *>
fuzzyFindCached(const FuzzyFindRequest &Req) const;
llvm::Optional<const SymbolSlab *> lookupCached(const SymbolID &ID) const;
std::optional<const SymbolSlab *> lookupCached(const SymbolID &ID) const;
};

} // namespace clangd
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/InlayHints.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,7 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
}

// Get the range of the main file that *exactly* corresponds to R.
llvm::Optional<Range> getHintRange(SourceRange R) {
std::optional<Range> getHintRange(SourceRange R) {
const auto &SM = AST.getSourceManager();
auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
// TokenBuffer will return null if e.g. R corresponds to only part of a
Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/JSONTransport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,12 @@ bool JSONTransport::handleMessage(llvm::json::Value Message,
// Message must be an object with "jsonrpc":"2.0".
auto *Object = Message.getAsObject();
if (!Object ||
Object->getString("jsonrpc") != llvm::Optional<llvm::StringRef>("2.0")) {
Object->getString("jsonrpc") != std::optional<llvm::StringRef>("2.0")) {
elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
return false;
}
// ID may be any JSON value. If absent, this is a notification.
llvm::Optional<llvm::json::Value> ID;
std::optional<llvm::json::Value> ID;
if (auto *I = Object->get("id"))
ID = std::move(*I);
auto Method = Object->getString("method");
Expand Down
14 changes: 7 additions & 7 deletions clang-tools-extra/clangd/ParsedAST.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ void applyWarningOptions(llvm::ArrayRef<std::string> ExtraArgs,

} // namespace

llvm::Optional<ParsedAST>
std::optional<ParsedAST>
ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
std::unique_ptr<clang::CompilerInvocation> CI,
llvm::ArrayRef<Diag> CompilerInvocationDiags,
Expand Down Expand Up @@ -376,7 +376,7 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
[&](const auto &L) { L->sawDiagnostic(D, Diag); });
});

llvm::Optional<PreamblePatch> Patch;
std::optional<PreamblePatch> Patch;
bool PreserveDiags = true;
// We might use an ignoring diagnostic consumer if they are going to be
// dropped later on to not pay for extra latency by processing them.
Expand Down Expand Up @@ -465,10 +465,10 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
// In practice almost all checks work well without modifications.
std::vector<std::unique_ptr<tidy::ClangTidyCheck>> CTChecks;
ast_matchers::MatchFinder CTFinder;
llvm::Optional<tidy::ClangTidyContext> CTContext;
std::optional<tidy::ClangTidyContext> CTContext;
// Must outlive FixIncludes.
auto BuildDir = VFS->getCurrentWorkingDirectory();
llvm::Optional<IncludeFixer> FixIncludes;
std::optional<IncludeFixer> FixIncludes;
llvm::DenseMap<diag::kind, DiagnosticsEngine::Level> OverriddenSeverity;
// No need to run clang-tidy or IncludeFixerif we are not going to surface
// diagnostics.
Expand Down Expand Up @@ -653,7 +653,7 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
// CompilerInstance won't run this callback, do it directly.
ASTDiags.EndSourceFile();

llvm::Optional<std::vector<Diag>> Diags;
std::optional<std::vector<Diag>> Diags;
// FIXME: Also skip generation of diagnostics alltogether to speed up ast
// builds when we are patching a stale preamble.
if (PreserveDiags) {
Expand Down Expand Up @@ -770,7 +770,7 @@ ParsedAST::ParsedAST(PathRef TUPath, llvm::StringRef Version,
syntax::TokenBuffer Tokens, MainFileMacros Macros,
std::vector<PragmaMark> Marks,
std::vector<Decl *> LocalTopLevelDecls,
llvm::Optional<std::vector<Diag>> Diags,
std::optional<std::vector<Diag>> Diags,
IncludeStructure Includes, CanonicalIncludes CanonIncludes)
: TUPath(TUPath), Version(Version), Preamble(std::move(Preamble)),
Clang(std::move(Clang)), Action(std::move(Action)),
Expand All @@ -783,7 +783,7 @@ ParsedAST::ParsedAST(PathRef TUPath, llvm::StringRef Version,
assert(this->Action);
}

llvm::Optional<llvm::StringRef> ParsedAST::preambleVersion() const {
std::optional<llvm::StringRef> ParsedAST::preambleVersion() const {
if (!Preamble)
return std::nullopt;
return llvm::StringRef(Preamble->Version);
Expand Down
10 changes: 5 additions & 5 deletions clang-tools-extra/clangd/ParsedAST.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class ParsedAST {
/// Attempts to run Clang and store the parsed AST.
/// If \p Preamble is non-null it is reused during parsing.
/// This function does not check if preamble is valid to reuse.
static llvm::Optional<ParsedAST>
static std::optional<ParsedAST>
build(llvm::StringRef Filename, const ParseInputs &Inputs,
std::unique_ptr<clang::CompilerInvocation> CI,
llvm::ArrayRef<Diag> CompilerInvocationDiags,
Expand Down Expand Up @@ -88,7 +88,7 @@ class ParsedAST {
/// (These should be const, but RecursiveASTVisitor requires Decl*).
ArrayRef<Decl *> getLocalTopLevelDecls();

const llvm::Optional<std::vector<Diag>> &getDiagnostics() const {
const std::optional<std::vector<Diag>> &getDiagnostics() const {
return Diags;
}

Expand All @@ -115,7 +115,7 @@ class ParsedAST {

/// Returns the version of the ParseInputs used to build Preamble part of this
/// AST. Might be std::nullopt if no Preamble is used.
llvm::Optional<llvm::StringRef> preambleVersion() const;
std::optional<llvm::StringRef> preambleVersion() const;

const HeuristicResolver *getHeuristicResolver() const {
return Resolver.get();
Expand All @@ -128,7 +128,7 @@ class ParsedAST {
std::unique_ptr<FrontendAction> Action, syntax::TokenBuffer Tokens,
MainFileMacros Macros, std::vector<PragmaMark> Marks,
std::vector<Decl *> LocalTopLevelDecls,
llvm::Optional<std::vector<Diag>> Diags, IncludeStructure Includes,
std::optional<std::vector<Diag>> Diags, IncludeStructure Includes,
CanonicalIncludes CanonIncludes);

Path TUPath;
Expand All @@ -155,7 +155,7 @@ class ParsedAST {
std::vector<PragmaMark> Marks;
// Data, stored after parsing. std::nullopt if AST was built with a stale
// preamble.
llvm::Optional<std::vector<Diag>> Diags;
std::optional<std::vector<Diag>> Diags;
// Top-level decls inside the current file. Not that this does not include
// top-level decls from the preamble.
std::vector<Decl *> LocalTopLevelDecls;
Expand Down
42 changes: 21 additions & 21 deletions clang-tools-extra/clangd/Protocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, MarkupKind);
struct ClientCapabilities {
/// The supported set of SymbolKinds for workspace/symbol.
/// workspace.symbol.symbolKind.valueSet
llvm::Optional<SymbolKindBitset> WorkspaceSymbolKinds;
std::optional<SymbolKindBitset> WorkspaceSymbolKinds;

/// Whether the client accepts diagnostics with codeActions attached inline.
/// textDocument.publishDiagnostics.codeActionsInline.
Expand Down Expand Up @@ -469,7 +469,7 @@ struct ClientCapabilities {

/// The supported set of CompletionItemKinds for textDocument/completion.
/// textDocument.completion.completionItemKind.valueSet
llvm::Optional<CompletionItemKindBitset> CompletionItemKinds;
std::optional<CompletionItemKindBitset> CompletionItemKinds;

/// The documentation format that should be used for textDocument/completion.
/// textDocument.completion.completionItem.documentationFormat
Expand All @@ -490,7 +490,7 @@ struct ClientCapabilities {
bool TheiaSemanticHighlighting = false;

/// Supported encodings for LSP character offsets. (clangd extension).
llvm::Optional<std::vector<OffsetEncoding>> offsetEncoding;
std::optional<std::vector<OffsetEncoding>> offsetEncoding;

/// The content format that should be used for Hover requests.
/// textDocument.hover.contentEncoding
Expand Down Expand Up @@ -651,30 +651,30 @@ struct WorkDoneProgressReport {
///
/// Clients that don't support cancellation or don't support control
/// the button's enablement state are allowed to ignore the setting.
llvm::Optional<bool> cancellable;
std::optional<bool> cancellable;

/// Optional, more detailed associated progress message. Contains
/// complementary information to the `title`.
///
/// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
/// If unset, the previous progress message (if any) is still valid.
llvm::Optional<std::string> message;
std::optional<std::string> message;

/// Optional progress percentage to display (value 100 is considered 100%).
/// If not provided infinite progress is assumed and clients are allowed
/// to ignore the `percentage` value in subsequent in report notifications.
///
/// The value should be steadily rising. Clients are free to ignore values
/// that are not following this rule.
llvm::Optional<unsigned> percentage;
std::optional<unsigned> percentage;
};
llvm::json::Value toJSON(const WorkDoneProgressReport &);
//
/// Signals the end of progress reporting.
struct WorkDoneProgressEnd {
/// Optional, a final message indicating to for example indicate the outcome
/// of the operation.
llvm::Optional<std::string> message;
std::optional<std::string> message;
};
llvm::json::Value toJSON(const WorkDoneProgressEnd &);

Expand Down Expand Up @@ -879,7 +879,7 @@ struct Diagnostic {
std::string code;

/// An optional property to describe the error code.
llvm::Optional<CodeDescription> codeDescription;
std::optional<CodeDescription> codeDescription;

/// A human-readable string describing the source of this
/// diagnostic, e.g. 'typescript' or 'super lint'.
Expand Down Expand Up @@ -1019,13 +1019,13 @@ struct CodeAction {

/// The kind of the code action.
/// Used to filter code actions.
llvm::Optional<std::string> kind;
std::optional<std::string> kind;
const static llvm::StringLiteral QUICKFIX_KIND;
const static llvm::StringLiteral REFACTOR_KIND;
const static llvm::StringLiteral INFO_KIND;

/// The diagnostics that this code action resolves.
llvm::Optional<std::vector<Diagnostic>> diagnostics;
std::optional<std::vector<Diagnostic>> diagnostics;

/// Marks this as a preferred action. Preferred actions are used by the
/// `auto fix` command and can be targeted by keybindings.
Expand All @@ -1035,11 +1035,11 @@ struct CodeAction {
bool isPreferred = false;

/// The workspace edit this code action performs.
llvm::Optional<WorkspaceEdit> edit;
std::optional<WorkspaceEdit> edit;

/// A command this code action executes. If a code action provides an edit
/// and a command, first the edit is executed and then the command.
llvm::Optional<Command> command;
std::optional<Command> command;
};
llvm::json::Value toJSON(const CodeAction &);

Expand Down Expand Up @@ -1097,7 +1097,7 @@ struct SymbolInformation {
/// This can be used to re-rank results as the user types, using client-side
/// fuzzy-matching (that score should be multiplied with this one).
/// This is a clangd extension, set only for workspace/symbol responses.
llvm::Optional<float> score;
std::optional<float> score;
};
llvm::json::Value toJSON(const SymbolInformation &);
llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolInformation &);
Expand All @@ -1118,9 +1118,9 @@ struct SymbolDetails {

SymbolID ID;

llvm::Optional<Location> declarationRange;
std::optional<Location> declarationRange;

llvm::Optional<Location> definitionRange;
std::optional<Location> definitionRange;
};
llvm::json::Value toJSON(const SymbolDetails &);
llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolDetails &);
Expand Down Expand Up @@ -1202,7 +1202,7 @@ struct Hover {

/// An optional range is a range inside a text document
/// that is used to visualize a hover, e.g. by changing the background color.
llvm::Optional<Range> range;
std::optional<Range> range;
};
llvm::json::Value toJSON(const Hover &H);

Expand Down Expand Up @@ -1261,7 +1261,7 @@ struct CompletionItem {
///
/// Note: The range of the edit must be a single line range and it must
/// contain the position at which completion has been requested.
llvm::Optional<TextEdit> textEdit;
std::optional<TextEdit> textEdit;

/// An optional array of additional text edits that are applied when selecting
/// this completion. Edits must not overlap with the main edit nor with
Expand Down Expand Up @@ -1312,7 +1312,7 @@ struct ParameterInformation {
/// label.
/// Offsets are computed by lspLength(), which counts UTF-16 code units by
/// default but that can be overriden, see its documentation for details.
llvm::Optional<std::pair<unsigned, unsigned>> labelOffsets;
std::optional<std::pair<unsigned, unsigned>> labelOffsets;

/// The documentation of this parameter. Optional.
std::string documentation;
Expand Down Expand Up @@ -1731,9 +1731,9 @@ llvm::json::Value toJSON(const SemanticTokensEdit &);
struct SemanticTokensOrDelta {
std::string resultId;
/// Set if we computed edits relative to a previous set of tokens.
llvm::Optional<std::vector<SemanticTokensEdit>> edits;
std::optional<std::vector<SemanticTokensEdit>> edits;
/// Set if we computed a fresh set of tokens.
llvm::Optional<std::vector<SemanticToken>> tokens; // encoded as integer array
std::optional<std::vector<SemanticToken>> tokens; // encoded as integer array
};
llvm::json::Value toJSON(const SemanticTokensOrDelta &);

Expand Down Expand Up @@ -1870,7 +1870,7 @@ struct ASTNode {
std::string arcana;
/// The range of the original source file covered by this node.
/// May be missing for implicit nodes, or those created by macro expansion.
llvm::Optional<Range> range;
std::optional<Range> range;
/// Nodes nested within this one, such as the operands of a BinaryOperator.
std::vector<ASTNode> children;
};
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/Quality.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ static float scopeProximityScore(unsigned ScopeDistance) {
return std::max(0.65, 2.0 * std::pow(0.6, ScopeDistance / 2.0));
}

static llvm::Optional<llvm::StringRef>
static std::optional<llvm::StringRef>
wordMatching(llvm::StringRef Name, const llvm::StringSet<> *ContextWords) {
if (ContextWords)
for (const auto &Word : ContextWords->keys())
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/Quality.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ struct SymbolRelevanceSignals {

// Scope proximity is only considered (both index and sema) when this is set.
ScopeDistance *ScopeProximityMatch = nullptr;
llvm::Optional<llvm::StringRef> SymbolScope;
std::optional<llvm::StringRef> SymbolScope;
// A symbol from sema should be accessible from the current scope.
bool SemaSaysInScope = false;

Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/Selection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ class SelectionTester {
}

// Decomposes Loc and returns the offset if the file ID is SelFile.
llvm::Optional<unsigned> offsetInSelFile(SourceLocation Loc) const {
std::optional<unsigned> offsetInSelFile(SourceLocation Loc) const {
// Decoding Loc with SM.getDecomposedLoc is relatively expensive.
// But SourceLocations for a file are numerically contiguous, so we
// can use cheap integer operations instead.
Expand Down Expand Up @@ -1060,7 +1060,7 @@ bool SelectionTree::createEach(ASTContext &AST,
SelectionTree SelectionTree::createRight(ASTContext &AST,
const syntax::TokenBuffer &Tokens,
unsigned int Begin, unsigned int End) {
llvm::Optional<SelectionTree> Result;
std::optional<SelectionTree> Result;
createEach(AST, Tokens, Begin, End, [&](SelectionTree T) {
Result = std::move(T);
return true;
Expand Down
29 changes: 15 additions & 14 deletions clang-tools-extra/clangd/SemanticHighlighting.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,10 @@ bool isUniqueDefinition(const NamedDecl *Decl) {
isa<ObjCImplDecl>(Decl);
}

llvm::Optional<HighlightingKind> kindForType(const Type *TP,
const HeuristicResolver *Resolver);
llvm::Optional<HighlightingKind>
kindForDecl(const NamedDecl *D, const HeuristicResolver *Resolver) {
std::optional<HighlightingKind> kindForType(const Type *TP,
const HeuristicResolver *Resolver);
std::optional<HighlightingKind> kindForDecl(const NamedDecl *D,
const HeuristicResolver *Resolver) {
if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
if (auto *Target = USD->getTargetDecl())
D = Target;
Expand Down Expand Up @@ -164,8 +164,8 @@ kindForDecl(const NamedDecl *D, const HeuristicResolver *Resolver) {
}
return std::nullopt;
}
llvm::Optional<HighlightingKind>
kindForType(const Type *TP, const HeuristicResolver *Resolver) {
std::optional<HighlightingKind> kindForType(const Type *TP,
const HeuristicResolver *Resolver) {
if (!TP)
return std::nullopt;
if (TP->isBuiltinType()) // Builtins are special, they do not have decls.
Expand Down Expand Up @@ -332,8 +332,8 @@ unsigned evaluateHighlightPriority(const HighlightingToken &Tok) {
//
// In particular, heuristically resolved dependent names get their heuristic
// kind, plus the dependent modifier.
llvm::Optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
const HighlightingToken &B) {
std::optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
const HighlightingToken &B) {
unsigned Priority1 = evaluateHighlightPriority(A);
unsigned Priority2 = evaluateHighlightPriority(B);
if (Priority1 == Priority2 && A.Kind != B.Kind)
Expand All @@ -342,13 +342,14 @@ llvm::Optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
Result.Modifiers = A.Modifiers | B.Modifiers;
return Result;
}
llvm::Optional<HighlightingToken>
std::optional<HighlightingToken>
resolveConflict(ArrayRef<HighlightingToken> Tokens) {
if (Tokens.size() == 1)
return Tokens[0];

assert(Tokens.size() >= 2);
Optional<HighlightingToken> Winner = resolveConflict(Tokens[0], Tokens[1]);
std::optional<HighlightingToken> Winner =
resolveConflict(Tokens[0], Tokens[1]);
for (size_t I = 2; Winner && I < Tokens.size(); ++I)
Winner = resolveConflict(*Winner, Tokens[I]);
return Winner;
Expand Down Expand Up @@ -474,7 +475,7 @@ class HighlightingsBuilder {
const HeuristicResolver *getResolver() const { return Resolver; }

private:
llvm::Optional<Range> getRangeForSourceLocation(SourceLocation Loc) {
std::optional<Range> getRangeForSourceLocation(SourceLocation Loc) {
Loc = getHighlightableSpellingToken(Loc, SourceMgr);
if (Loc.isInvalid())
return std::nullopt;
Expand All @@ -496,7 +497,7 @@ class HighlightingsBuilder {
HighlightingToken InvalidHighlightingToken;
};

llvm::Optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
std::optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
const DeclContext *DC = D->getDeclContext();
// Injected "Foo" within the class "Foo" has file scope, not class scope.
if (auto *R = dyn_cast_or_null<RecordDecl>(D))
Expand Down Expand Up @@ -524,7 +525,7 @@ llvm::Optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
return HighlightingModifier::GlobalScope;
}

llvm::Optional<HighlightingModifier> scopeModifier(const Type *T) {
std::optional<HighlightingModifier> scopeModifier(const Type *T) {
if (!T)
return std::nullopt;
if (T->isBuiltinType())
Expand Down Expand Up @@ -672,7 +673,7 @@ class CollectExtraHighlightings
return;
}

llvm::Optional<SourceLocation> Location;
std::optional<SourceLocation> Location;

// FIXME Add "unwrapping" for ArraySubscriptExpr,
// e.g. highlight `a` in `a[i]`
Expand Down
6 changes: 3 additions & 3 deletions clang-tools-extra/clangd/SemanticSelection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ void addIfDistinct(const Range &R, std::vector<Range> &Result) {
}
}

llvm::Optional<FoldingRange> toFoldingRange(SourceRange SR,
const SourceManager &SM) {
std::optional<FoldingRange> toFoldingRange(SourceRange SR,
const SourceManager &SM) {
const auto Begin = SM.getDecomposedLoc(SR.getBegin()),
End = SM.getDecomposedLoc(SR.getEnd());
// Do not produce folding ranges if either range ends is not within the main
Expand All @@ -58,7 +58,7 @@ llvm::Optional<FoldingRange> toFoldingRange(SourceRange SR,
return Range;
}

llvm::Optional<FoldingRange>
std::optional<FoldingRange>
extractFoldingRange(const syntax::Node *Node,
const syntax::TokenBufferTokenManager &TM) {
if (const auto *Stmt = dyn_cast<syntax::CompoundStatement>(Node)) {
Expand Down
24 changes: 12 additions & 12 deletions clang-tools-extra/clangd/SourceCode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -422,9 +422,9 @@ bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) {
return FID == SM.getMainFileID() || FID == SM.getPreambleFileID();
}

llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
const LangOptions &LangOpts,
SourceRange R) {
std::optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
const LangOptions &LangOpts,
SourceRange R) {
SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
if (!isValidFileRange(SM, R1))
return std::nullopt;
Expand Down Expand Up @@ -512,8 +512,8 @@ std::vector<TextEdit> replacementsToEdits(llvm::StringRef Code,
return Edits;
}

llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
const SourceManager &SourceMgr) {
std::optional<std::string> getCanonicalPath(const FileEntry *F,
const SourceManager &SourceMgr) {
if (!F)
return std::nullopt;

Expand Down Expand Up @@ -570,7 +570,7 @@ FileDigest digest(llvm::StringRef Content) {
return Result;
}

llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
std::optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
bool Invalid = false;
llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
if (Invalid)
Expand Down Expand Up @@ -924,9 +924,9 @@ static bool isLikelyIdentifier(llvm::StringRef Word, llvm::StringRef Before,
return false;
}

llvm::Optional<SpelledWord> SpelledWord::touching(SourceLocation SpelledLoc,
const syntax::TokenBuffer &TB,
const LangOptions &LangOpts) {
std::optional<SpelledWord> SpelledWord::touching(SourceLocation SpelledLoc,
const syntax::TokenBuffer &TB,
const LangOptions &LangOpts) {
const auto &SM = TB.sourceManager();
auto Touching = syntax::spelledTokensTouching(SpelledLoc, TB);
for (const auto &T : Touching) {
Expand Down Expand Up @@ -974,8 +974,8 @@ llvm::Optional<SpelledWord> SpelledWord::touching(SourceLocation SpelledLoc,
return Result;
}

llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
Preprocessor &PP) {
std::optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
Preprocessor &PP) {
if (SpelledTok.kind() != tok::identifier)
return std::nullopt;
SourceLocation Loc = SpelledTok.location();
Expand Down Expand Up @@ -1196,7 +1196,7 @@ EligibleRegion getEligiblePoints(llvm::StringRef Code,
}

bool isHeaderFile(llvm::StringRef FileName,
llvm::Optional<LangOptions> LangOpts) {
std::optional<LangOptions> LangOpts) {
// Respect the langOpts, for non-file-extension cases, e.g. standard library
// files.
if (LangOpts && LangOpts->IsHeaderFile)
Expand Down
24 changes: 12 additions & 12 deletions clang-tools-extra/clangd/SourceCode.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ namespace clangd {
// of hashing function at every place that needs to store this information.
using FileDigest = std::array<uint8_t, 8>;
FileDigest digest(StringRef Content);
Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);
std::optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);

// This context variable controls the behavior of functions in this file
// that convert between LSP offsets and native clang byte offsets.
Expand Down Expand Up @@ -111,9 +111,9 @@ bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM);
/// User input (e.g. cursor position) is expressed as a file location, so this
/// function can be viewed as a way to normalize the ranges used in the clang
/// AST so that they are comparable with ranges coming from the user input.
llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
const LangOptions &LangOpts,
SourceRange R);
std::optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
const LangOptions &LangOpts,
SourceRange R);

/// Returns true iff all of the following conditions hold:
/// - start and end locations are valid,
Expand Down Expand Up @@ -163,8 +163,8 @@ TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M,
/// This function should be used when paths needs to be used outside the
/// component that generate it, so that paths are normalized as much as
/// possible.
llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
const SourceManager &SourceMgr);
std::optional<std::string> getCanonicalPath(const FileEntry *F,
const SourceManager &SourceMgr);

/// Choose the clang-format style we should apply to a certain file.
/// This will usually use FS to look for .clang-format directories.
Expand Down Expand Up @@ -252,9 +252,9 @@ struct SpelledWord {
const syntax::Token *ExpandedToken = nullptr;

// Find the unique word that contains SpelledLoc or starts/ends there.
static llvm::Optional<SpelledWord> touching(SourceLocation SpelledLoc,
const syntax::TokenBuffer &TB,
const LangOptions &LangOpts);
static std::optional<SpelledWord> touching(SourceLocation SpelledLoc,
const syntax::TokenBuffer &TB,
const LangOptions &LangOpts);
};

/// Return true if the \p TokenName is in the list of reversed keywords of the
Expand Down Expand Up @@ -315,13 +315,13 @@ struct DefinedMacro {
};
/// Gets the macro referenced by \p SpelledTok. It must be a spelled token
/// aligned to the beginning of an identifier.
llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
Preprocessor &PP);
std::optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
Preprocessor &PP);

/// Infers whether this is a header from the FileName and LangOpts (if
/// presents).
bool isHeaderFile(llvm::StringRef FileName,
llvm::Optional<LangOptions> LangOpts = std::nullopt);
std::optional<LangOptions> LangOpts = std::nullopt);

/// Returns true if the given location is in a generated protobuf file.
bool isProtoFile(SourceLocation Loc, const SourceManager &SourceMgr);
Expand Down
8 changes: 4 additions & 4 deletions clang-tools-extra/clangd/SystemIncludeExtractor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ bool isValidTarget(llvm::StringRef Triple) {
return bool(Target);
}

llvm::Optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
std::optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
DriverInfo Info;
const char SIS[] = "#include <...> search starts here:";
const char SIE[] = "End of search list.";
Expand Down Expand Up @@ -136,7 +136,7 @@ llvm::Optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
return std::move(Info);
}

llvm::Optional<DriverInfo>
std::optional<DriverInfo>
extractSystemIncludesAndTarget(llvm::SmallString<128> Driver,
llvm::StringRef Lang,
llvm::ArrayRef<std::string> CommandLine,
Expand Down Expand Up @@ -226,7 +226,7 @@ extractSystemIncludesAndTarget(llvm::SmallString<128> Driver,
return std::nullopt;
}

llvm::Optional<DriverInfo> Info =
std::optional<DriverInfo> Info =
parseDriverOutput(BufOrError->get()->getBuffer());
if (!Info)
return std::nullopt;
Expand Down Expand Up @@ -361,7 +361,7 @@ class SystemIncludeExtractor {

private:
// Caches includes extracted from a driver. Key is driver:lang.
Memoize<llvm::StringMap<llvm::Optional<DriverInfo>>> QueriedDrivers;
Memoize<llvm::StringMap<std::optional<DriverInfo>>> QueriedDrivers;
llvm::Regex QueryDriverRegex;
};
} // namespace
Expand Down
40 changes: 20 additions & 20 deletions clang-tools-extra/clangd/TUScheduler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ class ASTWorker;

static clang::clangd::Key<std::string> FileBeingProcessed;

llvm::Optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
std::optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
if (auto *File = Context::current().get(FileBeingProcessed))
return llvm::StringRef(*File);
return std::nullopt;
Expand Down Expand Up @@ -184,7 +184,7 @@ class TUScheduler::ASTCache {
/// the cache anymore. If nullptr was cached for \p K, this function will
/// return a null unique_ptr wrapped into an optional.
/// If \p AccessMetric is set records whether there was a hit or miss.
llvm::Optional<std::unique_ptr<ParsedAST>>
std::optional<std::unique_ptr<ParsedAST>>
take(Key K, const trace::Metric *AccessMetric = nullptr) {
// Record metric after unlocking the mutex.
std::unique_lock<std::mutex> Lock(Mut);
Expand All @@ -201,7 +201,7 @@ class TUScheduler::ASTCache {
// GCC 4.8 fails to compile `return V;`, as it tries to call the copy
// constructor of unique_ptr, so we call the move ctor explicitly to avoid
// this miscompile.
return llvm::Optional<std::unique_ptr<ParsedAST>>(std::move(V));
return std::optional<std::unique_ptr<ParsedAST>>(std::move(V));
}

private:
Expand Down Expand Up @@ -465,7 +465,7 @@ class PreambleThread {

void run() {
while (true) {
llvm::Optional<PreambleThrottlerRequest> Throttle;
std::optional<PreambleThrottlerRequest> Throttle;
{
std::unique_lock<std::mutex> Lock(Mutex);
assert(!CurrentReq && "Already processing a request?");
Expand All @@ -476,7 +476,7 @@ class PreambleThread {

{
Throttle.emplace(FileName, Throttler, ReqCV);
llvm::Optional<trace::Span> Tracer;
std::optional<trace::Span> Tracer;
// If acquire succeeded synchronously, avoid status jitter.
if (!Throttle->satisfied()) {
Tracer.emplace("PreambleThrottle");
Expand Down Expand Up @@ -564,8 +564,8 @@ class PreambleThread {

mutable std::mutex Mutex;
bool Done = false; /* GUARDED_BY(Mutex) */
llvm::Optional<Request> NextReq; /* GUARDED_BY(Mutex) */
llvm::Optional<Request> CurrentReq; /* GUARDED_BY(Mutex) */
std::optional<Request> NextReq; /* GUARDED_BY(Mutex) */
std::optional<Request> CurrentReq; /* GUARDED_BY(Mutex) */
// Signaled whenever a thread populates NextReq or worker thread builds a
// Preamble.
mutable std::condition_variable ReqCV; /* GUARDED_BY(Mutex) */
Expand Down Expand Up @@ -681,7 +681,7 @@ class ASTWorker {

/// Adds a new task to the end of the request queue.
void startTask(llvm::StringRef Name, llvm::unique_function<void()> Task,
llvm::Optional<UpdateType> Update,
std::optional<UpdateType> Update,
TUScheduler::ASTActionInvalidation);
/// Runs a task synchronously.
void runTask(llvm::StringRef Name, llvm::function_ref<void()> Task);
Expand All @@ -699,8 +699,8 @@ class ASTWorker {
std::string Name;
steady_clock::time_point AddTime;
Context Ctx;
llvm::Optional<Context> QueueCtx;
llvm::Optional<UpdateType> Update;
std::optional<Context> QueueCtx;
std::optional<UpdateType> Update;
TUScheduler::ASTActionInvalidation InvalidationPolicy;
Canceler Invalidate;
};
Expand Down Expand Up @@ -734,15 +734,15 @@ class ASTWorker {
/// Set to true to signal run() to finish processing.
bool Done; /* GUARDED_BY(Mutex) */
std::deque<Request> Requests; /* GUARDED_BY(Mutex) */
llvm::Optional<Request> CurrentRequest; /* GUARDED_BY(Mutex) */
std::optional<Request> CurrentRequest; /* GUARDED_BY(Mutex) */
/// Signalled whenever a new request has been scheduled or processing of a
/// request has completed.
mutable std::condition_variable RequestsCV;
std::shared_ptr<const ASTSignals> LatestASTSignals; /* GUARDED_BY(Mutex) */
/// Latest build preamble for current TU.
/// None means no builds yet, null means there was an error while building.
/// Only written by ASTWorker's thread.
llvm::Optional<std::shared_ptr<const PreambleData>> LatestPreamble;
std::optional<std::shared_ptr<const PreambleData>> LatestPreamble;
std::deque<Request> PreambleRequests; /* GUARDED_BY(Mutex) */
/// Signaled whenever LatestPreamble changes state or there's a new
/// PreambleRequest.
Expand Down Expand Up @@ -965,7 +965,7 @@ void ASTWorker::runWithAST(
auto Task = [=, Action = std::move(Action)]() mutable {
if (auto Reason = isCancelled())
return Action(llvm::make_error<CancelledError>(Reason));
llvm::Optional<std::unique_ptr<ParsedAST>> AST =
std::optional<std::unique_ptr<ParsedAST>> AST =
IdleASTs.take(this, &ASTAccessForRead);
if (!AST) {
StoreDiags CompilerInvocationDiagConsumer;
Expand All @@ -977,7 +977,7 @@ void ASTWorker::runWithAST(
// FIXME: We might need to build a patched ast once preamble thread starts
// running async. Currently getPossiblyStalePreamble below will always
// return a compatible preamble as ASTWorker::update blocks.
llvm::Optional<ParsedAST> NewAST;
std::optional<ParsedAST> NewAST;
if (Invocation) {
NewAST = ParsedAST::build(FileName, FileInputs, std::move(Invocation),
CompilerInvocationDiagConsumer.take(),
Expand Down Expand Up @@ -1184,11 +1184,11 @@ void ASTWorker::generateDiagnostics(
// We might be able to reuse the last we've built for a read request.
// FIXME: It might be better to not reuse this AST. That way queued AST builds
// won't be required for diags.
llvm::Optional<std::unique_ptr<ParsedAST>> AST =
std::optional<std::unique_ptr<ParsedAST>> AST =
IdleASTs.take(this, &ASTAccessForDiag);
if (!AST || !InputsAreLatest) {
auto RebuildStartTime = DebouncePolicy::clock::now();
llvm::Optional<ParsedAST> NewAST = ParsedAST::build(
std::optional<ParsedAST> NewAST = ParsedAST::build(
FileName, Inputs, std::move(Invocation), CIDiags, *LatestPreamble);
auto RebuildDuration = DebouncePolicy::clock::now() - RebuildStartTime;
++ASTBuildCount;
Expand Down Expand Up @@ -1307,7 +1307,7 @@ void ASTWorker::runTask(llvm::StringRef Name, llvm::function_ref<void()> Task) {

void ASTWorker::startTask(llvm::StringRef Name,
llvm::unique_function<void()> Task,
llvm::Optional<UpdateType> Update,
std::optional<UpdateType> Update,
TUScheduler::ASTActionInvalidation Invalidation) {
if (RunSync) {
assert(!Done && "running a task after stop()");
Expand Down Expand Up @@ -1338,7 +1338,7 @@ void ASTWorker::startTask(llvm::StringRef Name,
}
// Trace the time the request spends in the queue, and the requests that
// it's going to wait for.
llvm::Optional<Context> QueueCtx;
std::optional<Context> QueueCtx;
if (trace::enabled()) {
// Tracers that follow threads and need strict nesting will see a tiny
// instantaneous event "we're enqueueing", and sometime later it runs.
Expand Down Expand Up @@ -1385,8 +1385,8 @@ void ASTWorker::run() {
}

// Tracing: we have a next request, attribute this sleep to it.
llvm::Optional<WithContext> Ctx;
llvm::Optional<trace::Span> Tracer;
std::optional<WithContext> Ctx;
std::optional<trace::Span> Tracer;
if (!Requests.empty()) {
Ctx.emplace(Requests.front().Ctx.clone());
Tracer.emplace("Debounce");
Expand Down
6 changes: 3 additions & 3 deletions clang-tools-extra/clangd/TUScheduler.h
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ class TUScheduler {
// FIXME: remove this when there is proper index support via build system
// integration.
// FIXME: move to ClangdServer via createProcessingContext.
static llvm::Optional<llvm::StringRef> getFileBeingProcessedInContext();
static std::optional<llvm::StringRef> getFileBeingProcessedInContext();

void profile(MemoryTree &MT) const;

Expand All @@ -371,8 +371,8 @@ class TUScheduler {
std::unique_ptr<HeaderIncluderCache> HeaderIncluders;
// None when running tasks synchronously and non-None when running tasks
// asynchronously.
llvm::Optional<AsyncTaskRunner> PreambleTasks;
llvm::Optional<AsyncTaskRunner> WorkerThreads;
std::optional<AsyncTaskRunner> PreambleTasks;
std::optional<AsyncTaskRunner> WorkerThreads;
// Used to create contexts for operations that are not bound to a particular
// file (e.g. index queries).
std::string LastActiveFile;
Expand Down
44 changes: 22 additions & 22 deletions clang-tools-extra/clangd/XRefs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ void logIfOverflow(const SymbolLocation &Loc) {
// TUPath is used to resolve the path of URI.
// FIXME: figure out a good home for it, and share the implementation with
// FindSymbols.
llvm::Optional<Location> toLSPLocation(const SymbolLocation &Loc,
llvm::StringRef TUPath) {
std::optional<Location> toLSPLocation(const SymbolLocation &Loc,
llvm::StringRef TUPath) {
if (!Loc)
return std::nullopt;
auto Uri = URI::parse(Loc.FileURI);
Expand Down Expand Up @@ -206,8 +206,8 @@ getDeclAtPosition(ParsedAST &AST, SourceLocation Pos, DeclRelationSet Relations,

// Expects Loc to be a SpellingLocation, will bail out otherwise as it can't
// figure out a filename.
llvm::Optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
llvm::StringRef TUPath) {
std::optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
llvm::StringRef TUPath) {
const auto &SM = AST.getSourceManager();
const FileEntry *F = SM.getFileEntryForID(SM.getFileID(Loc));
if (!F)
Expand All @@ -228,9 +228,9 @@ llvm::Optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
}

// Treat #included files as symbols, to enable go-to-definition on them.
llvm::Optional<LocatedSymbol> locateFileReferent(const Position &Pos,
ParsedAST &AST,
llvm::StringRef MainFilePath) {
std::optional<LocatedSymbol> locateFileReferent(const Position &Pos,
ParsedAST &AST,
llvm::StringRef MainFilePath) {
for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
if (!Inc.Resolved.empty() && Inc.HashLine == Pos.line) {
LocatedSymbol File;
Expand All @@ -247,7 +247,7 @@ llvm::Optional<LocatedSymbol> locateFileReferent(const Position &Pos,

// Macros are simple: there's no declaration/definition distinction.
// As a consequence, there's no need to look them up in the index either.
llvm::Optional<LocatedSymbol>
std::optional<LocatedSymbol>
locateMacroReferent(const syntax::Token &TouchedIdentifier, ParsedAST &AST,
llvm::StringRef MainFilePath) {
if (auto M = locateMacroAt(TouchedIdentifier, AST.getPreprocessor())) {
Expand Down Expand Up @@ -1201,8 +1201,8 @@ DocumentHighlight toHighlight(const ReferenceFinder::Reference &Ref,
return DH;
}

llvm::Optional<DocumentHighlight> toHighlight(SourceLocation Loc,
const syntax::TokenBuffer &TB) {
std::optional<DocumentHighlight> toHighlight(SourceLocation Loc,
const syntax::TokenBuffer &TB) {
Loc = TB.sourceManager().getFileLoc(Loc);
if (const auto *Tok = TB.spelledTokenAt(Loc)) {
DocumentHighlight Result;
Expand Down Expand Up @@ -1303,7 +1303,7 @@ void getOverriddenMethods(const CXXMethodDecl *CMD,
}
}

llvm::Optional<std::string>
std::optional<std::string>
stringifyContainerForMainFileRef(const Decl *Container) {
// FIXME We might also want to display the signature here
// When doing so, remember to also add the Signature to index results!
Expand All @@ -1329,7 +1329,7 @@ ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit,

const auto *IdentifierAtCursor =
syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
llvm::Optional<DefinedMacro> Macro;
std::optional<DefinedMacro> Macro;
if (IdentifierAtCursor)
Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor());
if (Macro) {
Expand Down Expand Up @@ -1607,7 +1607,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
}

template <typename HierarchyItem>
static llvm::Optional<HierarchyItem>
static std::optional<HierarchyItem>
declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
ASTContext &Ctx = ND.getASTContext();
auto &SM = Ctx.getSourceManager();
Expand Down Expand Up @@ -1649,7 +1649,7 @@ declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
return HI;
}

static llvm::Optional<TypeHierarchyItem>
static std::optional<TypeHierarchyItem>
declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
auto Result = declToHierarchyItem<TypeHierarchyItem>(ND, TUPath);
if (Result) {
Expand All @@ -1663,7 +1663,7 @@ declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
return Result;
}

static llvm::Optional<CallHierarchyItem>
static std::optional<CallHierarchyItem>
declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
auto Result = declToHierarchyItem<CallHierarchyItem>(ND, TUPath);
if (!Result)
Expand All @@ -1676,8 +1676,8 @@ declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
}

template <typename HierarchyItem>
static llvm::Optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
PathRef TUPath) {
static std::optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
PathRef TUPath) {
auto Loc = symbolToLocation(S, TUPath);
if (!Loc) {
elog("Failed to convert symbol to hierarchy item: {0}", Loc.takeError());
Expand All @@ -1695,7 +1695,7 @@ static llvm::Optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
return HI;
}

static llvm::Optional<TypeHierarchyItem>
static std::optional<TypeHierarchyItem>
symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath) {
auto Result = symbolToHierarchyItem<TypeHierarchyItem>(S, TUPath);
if (Result) {
Expand All @@ -1705,7 +1705,7 @@ symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath) {
return Result;
}

static llvm::Optional<CallHierarchyItem>
static std::optional<CallHierarchyItem>
symbolToCallHierarchyItem(const Symbol &S, PathRef TUPath) {
auto Result = symbolToHierarchyItem<CallHierarchyItem>(S, TUPath);
if (!Result)
Expand All @@ -1723,7 +1723,7 @@ static void fillSubTypes(const SymbolID &ID,
Req.Subjects.insert(ID);
Req.Predicate = RelationKind::BaseOf;
Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
if (Optional<TypeHierarchyItem> ChildSym =
if (std::optional<TypeHierarchyItem> ChildSym =
symbolToTypeHierarchyItem(Object, TUPath)) {
if (Levels > 1) {
ChildSym->children.emplace();
Expand Down Expand Up @@ -1755,7 +1755,7 @@ static void fillSuperTypes(const CXXRecordDecl &CXXRD, llvm::StringRef TUPath,
}

for (const CXXRecordDecl *ParentDecl : typeParents(&CXXRD)) {
if (Optional<TypeHierarchyItem> ParentSym =
if (std::optional<TypeHierarchyItem> ParentSym =
declToTypeHierarchyItem(*ParentDecl, TUPath)) {
fillSuperTypes(*ParentDecl, TUPath, *ParentSym, RPSet);
Item.data.parents->emplace_back(ParentSym->data);
Expand Down Expand Up @@ -2087,7 +2087,7 @@ getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels,
CXXRD = CTSD->getTemplateInstantiationPattern();
}

Optional<TypeHierarchyItem> Result =
std::optional<TypeHierarchyItem> Result =
declToTypeHierarchyItem(*CXXRD, AST.tuPath());
if (!Result)
continue;
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/XRefs.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ struct LocatedSymbol {
// The canonical or best declaration: where most users find its interface.
Location PreferredDeclaration;
// Where the symbol is defined, if known. May equal PreferredDeclaration.
llvm::Optional<Location> Definition;
std::optional<Location> Definition;
// SymbolID of the located symbol if available.
SymbolID ID;
};
Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/index/Background.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ BackgroundQueue::Task BackgroundIndex::changedFilesTask(
BackgroundQueue::Task T([this, ChangedFiles] {
trace::Span Tracer("BackgroundIndexEnqueue");

llvm::Optional<WithContext> WithProvidedContext;
std::optional<WithContext> WithProvidedContext;
if (ContextProvider)
WithProvidedContext.emplace(ContextProvider(/*Path=*/""));

Expand Down Expand Up @@ -157,7 +157,7 @@ BackgroundQueue::Task BackgroundIndex::indexFileTask(std::string Path) {
std::string Tag = filenameWithoutExtension(Path).str();
uint64_t Key = llvm::xxHash64(Path);
BackgroundQueue::Task T([this, Path(std::move(Path))] {
llvm::Optional<WithContext> WithProvidedContext;
std::optional<WithContext> WithProvidedContext;
if (ContextProvider)
WithProvidedContext.emplace(ContextProvider(Path));
auto Cmd = CDB.getCompileCommand(Path);
Expand Down
6 changes: 3 additions & 3 deletions clang-tools-extra/clangd/index/Background.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class BackgroundIndexStorage {
// CDBDirectory is the first directory containing a CDB in parent directories
// of a file, or user cache directory if none was found, e.g. stdlib headers.
static Factory createDiskBackedStorageFactory(
std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo);
std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo);
};

// A priority queue of tasks which can be run on (external) worker threads.
Expand Down Expand Up @@ -112,7 +112,7 @@ class BackgroundQueue {
// Only affects tasks that run after the call.
static void preventThreadStarvationInTests();
[[nodiscard]] bool
blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds);
blockUntilIdleForTest(std::optional<double> TimeoutSeconds);

private:
void notifyProgress() const; // Requires lock Mu
Expand Down Expand Up @@ -174,7 +174,7 @@ class BackgroundIndex : public SwapIndex {

// Wait until the queue is empty, to allow deterministic testing.
[[nodiscard]] bool
blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10) {
blockUntilIdleForTest(std::optional<double> TimeoutSeconds = 10) {
return Queue.blockUntilIdleForTest(TimeoutSeconds);
}

Expand Down
6 changes: 3 additions & 3 deletions clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class NullStorage : public BackgroundIndexStorage {
class DiskBackedIndexStorageManager {
public:
DiskBackedIndexStorageManager(
std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo)
std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo)
: IndexStorageMapMu(std::make_unique<std::mutex>()),
GetProjectInfo(std::move(GetProjectInfo)) {
llvm::SmallString<128> FallbackDir;
Expand Down Expand Up @@ -136,14 +136,14 @@ class DiskBackedIndexStorageManager {
llvm::StringMap<std::unique_ptr<BackgroundIndexStorage>> IndexStorageMap;
std::unique_ptr<std::mutex> IndexStorageMapMu;

std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo;
std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo;
};

} // namespace

BackgroundIndexStorage::Factory
BackgroundIndexStorage::createDiskBackedStorageFactory(
std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo) {
std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo) {
return DiskBackedIndexStorageManager(std::move(GetProjectInfo));
}

Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/index/BackgroundQueue.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ void BackgroundQueue::preventThreadStarvationInTests() {

void BackgroundQueue::work(std::function<void()> OnIdle) {
while (true) {
llvm::Optional<Task> Task;
std::optional<Task> Task;
{
std::unique_lock<std::mutex> Lock(Mu);
CV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); });
Expand Down Expand Up @@ -134,7 +134,7 @@ void BackgroundQueue::boost(llvm::StringRef Tag, unsigned NewPriority) {
}

bool BackgroundQueue::blockUntilIdleForTest(
llvm::Optional<double> TimeoutSeconds) {
std::optional<double> TimeoutSeconds) {
std::unique_lock<std::mutex> Lock(Mu);
return wait(Lock, CV, timeoutSeconds(TimeoutSeconds),
[&] { return Queue.empty() && Stat.Active == 0; });
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/index/FileIndex.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ std::vector<llvm::StringRef> FileShardedIndex::getAllSources() const {
return Result;
}

llvm::Optional<IndexFileIn>
std::optional<IndexFileIn>
FileShardedIndex::getShard(llvm::StringRef Uri) const {
auto It = Shards.find(Uri);
if (It == Shards.end())
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/index/FileIndex.h
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ struct FileShardedIndex {
/// a copy of all the relevant data.
/// Returned index will always have Symbol/Refs/Relation Slabs set, even if
/// they are empty.
llvm::Optional<IndexFileIn> getShard(llvm::StringRef Uri) const;
std::optional<IndexFileIn> getShard(llvm::StringRef Uri) const;

private:
// Contains all the information that belongs to a single file.
Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/index/Index.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ struct RefsRequest {
/// If set, limit the number of refers returned from the index. The index may
/// choose to return less than this, e.g. it tries to avoid returning stale
/// results.
llvm::Optional<uint32_t> Limit;
std::optional<uint32_t> Limit;
/// If set, populates the container of the reference.
/// Index implementations may chose to populate containers no matter what.
bool WantContainer = false;
Expand All @@ -82,7 +82,7 @@ struct RelationsRequest {
llvm::DenseSet<SymbolID> Subjects;
RelationKind Predicate;
/// If set, limit the number of relations returned from the index.
llvm::Optional<uint32_t> Limit;
std::optional<uint32_t> Limit;
};

/// Describes what data is covered by an index.
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/index/IndexAction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ namespace clang {
namespace clangd {
namespace {

llvm::Optional<std::string> toURI(OptionalFileEntryRef File) {
std::optional<std::string> toURI(OptionalFileEntryRef File) {
if (!File)
return std::nullopt;
auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
Expand Down
10 changes: 5 additions & 5 deletions clang-tools-extra/clangd/index/Serialization.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,13 @@ enum class IndexFileFormat {

// Holds the contents of an index file that was read.
struct IndexFileIn {
llvm::Optional<SymbolSlab> Symbols;
llvm::Optional<RefSlab> Refs;
llvm::Optional<RelationSlab> Relations;
std::optional<SymbolSlab> Symbols;
std::optional<RefSlab> Refs;
std::optional<RelationSlab> Relations;
// Keys are URIs of the source files.
llvm::Optional<IncludeGraph> Sources;
std::optional<IncludeGraph> Sources;
// This contains only the Directory and CommandLine.
llvm::Optional<tooling::CompileCommand> Cmd;
std::optional<tooling::CompileCommand> Cmd;
};
// Parse an index file. The input must be a RIFF or YAML file.
llvm::Expected<IndexFileIn> readIndexFile(llvm::StringRef, SymbolOrigin);
Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/index/StdLib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,8 @@ bool StdLibSet::isBest(const LangOptions &LO) const {
Best[langFromOpts(LO)].load(std::memory_order_acquire);
}

llvm::Optional<StdLibLocation> StdLibSet::add(const LangOptions &LO,
const HeaderSearch &HS) {
std::optional<StdLibLocation> StdLibSet::add(const LangOptions &LO,
const HeaderSearch &HS) {
Lang L = langFromOpts(LO);
int OldVersion = Best[L].load(std::memory_order_acquire);
int NewVersion = standardFromOpts(LO);
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/index/StdLib.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class StdLibSet {
// Returns the location where the standard library was found.
//
// This function is threadsafe.
llvm::Optional<StdLibLocation> add(const LangOptions &, const HeaderSearch &);
std::optional<StdLibLocation> add(const LangOptions &, const HeaderSearch &);

// Indicates whether a built index should be used.
// It should not be used if a newer version has subsequently been added.
Expand Down
16 changes: 8 additions & 8 deletions clang-tools-extra/clangd/index/SymbolCollector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ RefKind toRefKind(index::SymbolRoleSet Roles, bool Spelled = false) {
return Result;
}

llvm::Optional<RelationKind> indexableRelation(const index::SymbolRelation &R) {
std::optional<RelationKind> indexableRelation(const index::SymbolRelation &R) {
if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationBaseOf))
return RelationKind::BaseOf;
if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationOverrideOf))
Expand Down Expand Up @@ -178,10 +178,10 @@ bool isSpelled(SourceLocation Loc, const NamedDecl &ND) {
class SymbolCollector::HeaderFileURICache {
struct FrameworkUmbrellaSpelling {
// Spelling for the public umbrella header, e.g. <Foundation/Foundation.h>
llvm::Optional<std::string> PublicHeader;
std::optional<std::string> PublicHeader;
// Spelling for the private umbrella header, e.g.
// <Foundation/Foundation_Private.h>
llvm::Optional<std::string> PrivateHeader;
std::optional<std::string> PrivateHeader;
};
// Weird double-indirect access to PP, which might not be ready yet when
// HeaderFiles is created but will be by the time it's used.
Expand Down Expand Up @@ -263,7 +263,7 @@ class SymbolCollector::HeaderFileURICache {
bool IsPrivateHeader;
};

llvm::Optional<FrameworkHeaderPath>
std::optional<FrameworkHeaderPath>
splitFrameworkHeaderPath(llvm::StringRef Path) {
using namespace llvm::sys;
path::reverse_iterator I = path::rbegin(Path);
Expand Down Expand Up @@ -296,7 +296,7 @@ class SymbolCollector::HeaderFileURICache {
// <Foundation/Foundation_Private.h> instead of
// <Foundation/NSObject_Private.h> which should be used instead of directly
// importing the header.
llvm::Optional<std::string> getFrameworkUmbrellaSpelling(
std::optional<std::string> getFrameworkUmbrellaSpelling(
llvm::StringRef Framework, SrcMgr::CharacteristicKind HeadersDirKind,
HeaderSearch &HS, FrameworkHeaderPath &HeaderPath) {
auto Res = CacheFrameworkToUmbrellaHeaderSpelling.try_emplace(Framework);
Expand Down Expand Up @@ -340,7 +340,7 @@ class SymbolCollector::HeaderFileURICache {
// named `Framework`, e.g. `NSObject.h` in framework `Foundation` would
// give <Foundation/Foundation.h> if the umbrella header exists, otherwise
// <Foundation/NSObject.h>.
llvm::Optional<llvm::StringRef> getFrameworkHeaderIncludeSpelling(
std::optional<llvm::StringRef> getFrameworkHeaderIncludeSpelling(
const FileEntry *FE, llvm::StringRef Framework, HeaderSearch &HS) {
auto Res = CachePathToFrameworkSpelling.try_emplace(FE->getName());
auto *CachedHeaderSpelling = &Res.first->second;
Expand Down Expand Up @@ -414,7 +414,7 @@ class SymbolCollector::HeaderFileURICache {
};

// Return the symbol location of the token at \p TokLoc.
llvm::Optional<SymbolLocation>
std::optional<SymbolLocation>
SymbolCollector::getTokenLocation(SourceLocation TokLoc) {
const auto &SM = ASTCtx->getSourceManager();
auto *FE = SM.getFileEntryForID(SM.getFileID(TokLoc));
Expand Down Expand Up @@ -941,7 +941,7 @@ const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND, SymbolID ID,
std::string ReturnType = getReturnType(*CCS);
S.ReturnType = ReturnType;

llvm::Optional<OpaqueType> TypeStorage;
std::optional<OpaqueType> TypeStorage;
if (S.Flags & Symbol::IndexedForCodeCompletion) {
TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
if (TypeStorage)
Expand Down
4 changes: 2 additions & 2 deletions clang-tools-extra/clangd/index/SymbolCollector.h
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ class SymbolCollector : public index::IndexDataConsumer {
void processRelations(const NamedDecl &ND, const SymbolID &ID,
ArrayRef<index::SymbolRelation> Relations);

llvm::Optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc);
std::optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc);

llvm::Optional<std::string> getIncludeHeader(const Symbol &S, FileID);
std::optional<std::string> getIncludeHeader(const Symbol &S, FileID);

SymbolID getSymbolIDCached(const Decl *D);
SymbolID getSymbolIDCached(const llvm::StringRef MacroName,
Expand Down
12 changes: 6 additions & 6 deletions clang-tools-extra/clangd/index/YAMLSerialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@ using RefBundle =
std::pair<clang::clangd::SymbolID, std::vector<clang::clangd::Ref>>;
// This is a pale imitation of std::variant<Symbol, RefBundle, Relation>
struct VariantEntry {
llvm::Optional<clang::clangd::Symbol> Symbol;
llvm::Optional<RefBundle> Refs;
llvm::Optional<clang::clangd::Relation> Relation;
llvm::Optional<clang::clangd::IncludeGraphNode> Source;
llvm::Optional<clang::tooling::CompileCommand> Cmd;
std::optional<clang::clangd::Symbol> Symbol;
std::optional<RefBundle> Refs;
std::optional<clang::clangd::Relation> Relation;
std::optional<clang::clangd::IncludeGraphNode> Source;
std::optional<clang::tooling::CompileCommand> Cmd;
};
// A class helps YAML to serialize the 32-bit encoded position (Line&Column),
// as YAMLIO can't directly map bitfields.
Expand Down Expand Up @@ -480,7 +480,7 @@ llvm::Expected<IndexFileIn> readYAML(llvm::StringRef Data,
llvm::UniqueStringSaver Strings(Arena);
llvm::yaml::Input Yin(Data, &Strings);
IncludeGraph Sources;
llvm::Optional<tooling::CompileCommand> Cmd;
std::optional<tooling::CompileCommand> Cmd;
while (Yin.setCurrentDocument()) {
llvm::yaml::EmptyContext Ctx;
VariantEntry Variant;
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/index/dex/Dex.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ bool Dex::fuzzyFind(const FuzzyFindRequest &Req,
for (const auto &IDAndScore : IDAndScores) {
const DocID SymbolDocID = IDAndScore.first;
const auto *Sym = Symbols[SymbolDocID];
const llvm::Optional<float> Score = Filter.match(Sym->Name);
const std::optional<float> Score = Filter.match(Sym->Name);
if (!Score)
continue;
// Combine Fuzzy Matching score, precomputed symbol quality and boosting
Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,6 @@ int main(int argc, const char *argv[]) {
return runCommand(ExecCommand, *Index) ? 0 : 1;

llvm::LineEditor LE("dexp");
while (llvm::Optional<std::string> Request = LE.readLine())
while (std::optional<std::string> Request = LE.readLine())
runCommand(std::move(*Request), *Index);
}
Loading