[clang-tools-extra] Use std::optional instead of llvm::Optional (NFC)

This patch replaces (llvm::|)Optional< with std::optional<.  I'll post
a separate patch to clean up the "using" declarations, #include
"llvm/ADT/Optional.h", etc.

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
This commit is contained in:
Kazu Hirata 2023-01-07 20:19:42 -08:00
parent 71f557355d
commit f71ffd3b73
209 changed files with 808 additions and 801 deletions

View File

@ -156,7 +156,7 @@ groupReplacements(const TUReplacements &TUs, const TUDiagnostics &TUDs,
auto AddToGroup = [&](const tooling::Replacement &R,
const tooling::TranslationUnitDiagnostics *SourceTU,
const llvm::Optional<std::string> BuildDir) {
const std::optional<std::string> BuildDir) {
// Use the file manager to deduplicate paths. FileEntries are
// automatically canonicalized. Since relative paths can come from different
// build directories, make them absolute immediately.

View File

@ -309,7 +309,7 @@ static std::unique_ptr<TagNode> genLink(const Twine &Text, const Twine &Link) {
static std::unique_ptr<HTMLNode>
genReference(const Reference &Type, StringRef CurrentDirectory,
llvm::Optional<StringRef> JumpToSection = std::nullopt) {
std::optional<StringRef> JumpToSection = std::nullopt) {
if (Type.Path.empty()) {
if (!JumpToSection)
return std::make_unique<TextNode>(Type.Name);
@ -438,7 +438,7 @@ genReferencesBlock(const std::vector<Reference> &References,
static std::unique_ptr<TagNode>
writeFileDefinition(const Location &L,
llvm::Optional<StringRef> RepositoryUrl = std::nullopt) {
std::optional<StringRef> RepositoryUrl = std::nullopt) {
if (!L.IsFileInRootDir || !RepositoryUrl)
return std::make_unique<TagNode>(
HTMLTag::TAG_P, "Defined at line " + std::to_string(L.LineNumber) +

View File

@ -21,7 +21,7 @@
namespace clang {
namespace find_all_symbols {
llvm::Optional<SymbolInfo>
std::optional<SymbolInfo>
FindAllMacros::CreateMacroSymbol(const Token &MacroNameTok,
const MacroInfo *info) {
std::string FilePath =

View File

@ -45,8 +45,8 @@ public:
void EndOfMainFile() override;
private:
llvm::Optional<SymbolInfo> CreateMacroSymbol(const Token &MacroNameTok,
const MacroInfo *MD);
std::optional<SymbolInfo> CreateMacroSymbol(const Token &MacroNameTok,
const MacroInfo *MD);
// Not a callback, just a common path for all usage types.
void MacroUsed(const Token &Name, const MacroDefinition &MD);

View File

@ -70,7 +70,7 @@ std::vector<SymbolInfo::Context> GetContexts(const NamedDecl *ND) {
return Contexts;
}
llvm::Optional<SymbolInfo>
std::optional<SymbolInfo>
CreateSymbolInfo(const NamedDecl *ND, const SourceManager &SM,
const HeaderMapCollector *Collector) {
SymbolInfo::SymbolKind Type;

View File

@ -184,7 +184,7 @@ bool MatchQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const {
std::vector<BoundNodes> Matches;
DynTypedMatcher MaybeBoundMatcher = Matcher;
if (QS.BindRoot) {
llvm::Optional<DynTypedMatcher> M = Matcher.tryBind("root");
std::optional<DynTypedMatcher> M = Matcher.tryBind("root");
if (M)
MaybeBoundMatcher = *M;
}

View File

@ -276,7 +276,7 @@ QueryRef QueryParser::doParse() {
Diagnostics Diag;
auto MatcherSource = Line.ltrim();
auto OrigMatcherSource = MatcherSource;
Optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
std::optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
MatcherSource, nullptr, &QS.NamedValues, &Diag);
if (!Matcher) {
return makeInvalidQueryFromDiagnostics(Diag);

View File

@ -169,7 +169,7 @@ int main(int argc, const char **argv) {
LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
return QueryParser::complete(Line, Pos, QS);
});
while (llvm::Optional<std::string> Line = LE.readLine()) {
while (std::optional<std::string> Line = LE.readLine()) {
QueryRef Q = QueryParser::parse(*Line, QS);
Q->run(llvm::outs(), QS);
llvm::outs().flush();

View File

@ -52,7 +52,7 @@ ClangTidyCheck::OptionsView::OptionsView(
: NamePrefix((CheckName + ".").str()), CheckOptions(CheckOptions),
Context(Context) {}
llvm::Optional<StringRef>
std::optional<StringRef>
ClangTidyCheck::OptionsView::get(StringRef LocalName) const {
if (Context->getOptionsCollector())
Context->getOptionsCollector()->insert((NamePrefix + LocalName).str());
@ -81,7 +81,7 @@ findPriorityOption(const ClangTidyOptions::OptionMap &Options,
return IterGlobal;
}
llvm::Optional<StringRef>
std::optional<StringRef>
ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName,
Context->getOptionsCollector());
@ -90,8 +90,8 @@ ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
return std::nullopt;
}
static Optional<bool> getAsBool(StringRef Value,
const llvm::Twine &LookupName) {
static std::optional<bool> getAsBool(StringRef Value,
const llvm::Twine &LookupName) {
if (std::optional<bool> Parsed = llvm::yaml::parseBool(Value))
return *Parsed;
@ -104,9 +104,9 @@ static Optional<bool> getAsBool(StringRef Value,
}
template <>
llvm::Optional<bool>
std::optional<bool>
ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const {
if (llvm::Optional<StringRef> ValueOr = get(LocalName)) {
if (std::optional<StringRef> ValueOr = get(LocalName)) {
if (auto Result = getAsBool(*ValueOr, NamePrefix + LocalName))
return Result;
diagnoseBadBooleanOption(NamePrefix + LocalName, *ValueOr);
@ -115,7 +115,7 @@ ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const {
}
template <>
llvm::Optional<bool>
std::optional<bool>
ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const {
auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName,
Context->getOptionsCollector());
@ -146,7 +146,7 @@ void ClangTidyCheck::OptionsView::store<bool>(
store(Options, LocalName, Value ? StringRef("true") : StringRef("false"));
}
llvm::Optional<int64_t> ClangTidyCheck::OptionsView::getEnumInt(
std::optional<int64_t> ClangTidyCheck::OptionsView::getEnumInt(
StringRef LocalName, ArrayRef<NameAndValue> Mapping, bool CheckGlobal,
bool IgnoreCase) const {
if (!CheckGlobal && Context->getOptionsCollector())

View File

@ -156,7 +156,7 @@ public:
/// Reads the option with the check-local name \p LocalName from the
/// ``CheckOptions``. If the corresponding key is not present, return
/// ``std::nullopt``.
llvm::Optional<StringRef> get(StringRef LocalName) const;
std::optional<StringRef> get(StringRef LocalName) const;
/// Read a named option from the ``Context``.
///
@ -171,7 +171,7 @@ public:
/// global ``CheckOptions``. Gets local option first. If local is not
/// present, falls back to get global option. If global option is not
/// present either, return ``std::nullopt``.
llvm::Optional<StringRef> getLocalOrGlobal(StringRef LocalName) const;
std::optional<StringRef> getLocalOrGlobal(StringRef LocalName) const;
/// Read a named option from the ``Context``.
///
@ -191,9 +191,9 @@ public:
/// If the corresponding key can't be parsed as a ``T``, emit a
/// diagnostic and return ``std::nullopt``.
template <typename T>
std::enable_if_t<std::is_integral<T>::value, llvm::Optional<T>>
std::enable_if_t<std::is_integral<T>::value, std::optional<T>>
get(StringRef LocalName) const {
if (llvm::Optional<StringRef> Value = get(LocalName)) {
if (std::optional<StringRef> Value = get(LocalName)) {
T Result{};
if (!StringRef(*Value).getAsInteger(10, Result))
return Result;
@ -228,9 +228,9 @@ public:
/// If the corresponding key can't be parsed as a ``T``, emit a
/// diagnostic and return ``std::nullopt``.
template <typename T>
std::enable_if_t<std::is_integral<T>::value, llvm::Optional<T>>
std::enable_if_t<std::is_integral<T>::value, std::optional<T>>
getLocalOrGlobal(StringRef LocalName) const {
llvm::Optional<StringRef> ValueOr = get(LocalName);
std::optional<StringRef> ValueOr = get(LocalName);
bool IsGlobal = false;
if (!ValueOr) {
IsGlobal = true;
@ -275,9 +275,9 @@ public:
/// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
/// supply the mapping required to convert between ``T`` and a string.
template <typename T>
std::enable_if_t<std::is_enum<T>::value, llvm::Optional<T>>
std::enable_if_t<std::is_enum<T>::value, std::optional<T>>
get(StringRef LocalName, bool IgnoreCase = false) const {
if (llvm::Optional<int64_t> ValueOr =
if (std::optional<int64_t> ValueOr =
getEnumInt(LocalName, typeEraseMapping<T>(), false, IgnoreCase))
return static_cast<T>(*ValueOr);
return std::nullopt;
@ -315,9 +315,9 @@ public:
/// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
/// supply the mapping required to convert between ``T`` and a string.
template <typename T>
std::enable_if_t<std::is_enum<T>::value, llvm::Optional<T>>
std::enable_if_t<std::is_enum<T>::value, std::optional<T>>
getLocalOrGlobal(StringRef LocalName, bool IgnoreCase = false) const {
if (llvm::Optional<int64_t> ValueOr =
if (std::optional<int64_t> ValueOr =
getEnumInt(LocalName, typeEraseMapping<T>(), true, IgnoreCase))
return static_cast<T>(*ValueOr);
return std::nullopt;
@ -379,9 +379,9 @@ public:
private:
using NameAndValue = std::pair<int64_t, StringRef>;
llvm::Optional<int64_t> getEnumInt(StringRef LocalName,
ArrayRef<NameAndValue> Mapping,
bool CheckGlobal, bool IgnoreCase) const;
std::optional<int64_t> getEnumInt(StringRef LocalName,
ArrayRef<NameAndValue> Mapping,
bool CheckGlobal, bool IgnoreCase) const;
template <typename T>
std::enable_if_t<std::is_enum<T>::value, std::vector<NameAndValue>>
@ -434,7 +434,7 @@ protected:
/// If the corresponding key can't be parsed as a bool, emit a
/// diagnostic and return ``std::nullopt``.
template <>
llvm::Optional<bool>
std::optional<bool>
ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const;
/// Read a named option from the ``Context`` and parse it as a bool.
@ -446,7 +446,7 @@ ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const;
/// If the corresponding key can't be parsed as a bool, emit a
/// diagnostic and return \p Default.
template <>
llvm::Optional<bool>
std::optional<bool>
ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const;
/// Stores an option with the check-local name \p LocalName with

View File

@ -256,7 +256,7 @@ void ClangTidyContext::setProfileStoragePrefix(StringRef Prefix) {
ProfilePrefix = std::string(Prefix);
}
llvm::Optional<ClangTidyProfiling::StorageParams>
std::optional<ClangTidyProfiling::StorageParams>
ClangTidyContext::getProfileStorageParams() const {
if (ProfilePrefix.empty())
return std::nullopt;

View File

@ -170,7 +170,7 @@ public:
/// Control storage of profile date.
void setProfileStoragePrefix(StringRef ProfilePrefix);
llvm::Optional<ClangTidyProfiling::StorageParams>
std::optional<ClangTidyProfiling::StorageParams>
getProfileStorageParams() const;
/// Should be called when starting to process new translation unit.

View File

@ -290,7 +290,7 @@ void FileOptionsBaseProvider::addRawFileOptions(
StringRef Path = llvm::sys::path::parent_path(AbsolutePath);
for (StringRef CurrentPath = Path; !CurrentPath.empty();
CurrentPath = llvm::sys::path::parent_path(CurrentPath)) {
llvm::Optional<OptionsSource> Result;
std::optional<OptionsSource> Result;
auto Iter = CachedOptions.find(CurrentPath);
if (Iter != CachedOptions.end())
@ -360,7 +360,7 @@ FileOptionsProvider::getRawOptions(StringRef FileName) {
return RawOptions;
}
llvm::Optional<OptionsSource>
std::optional<OptionsSource>
FileOptionsBaseProvider::tryReadConfigFile(StringRef Directory) {
assert(!Directory.empty());

View File

@ -40,7 +40,7 @@ public:
return;
// FIXME: Why is this happening? We might be losing contents here.
llvm::Optional<StringRef> Data = ContentCache.getBufferDataIfLoaded();
std::optional<StringRef> Data = ContentCache.getBufferDataIfLoaded();
if (!Data)
return;

View File

@ -46,8 +46,8 @@ enum class NoLintType { NoLint, NoLintNextLine, NoLintBegin, NoLintEnd };
// Convert a string like "NOLINTNEXTLINE" to its enum `Type::NoLintNextLine`.
// Return `std::nullopt` if the string is unrecognized.
static Optional<NoLintType> strToNoLintType(StringRef Str) {
auto Type = llvm::StringSwitch<Optional<NoLintType>>(Str)
static std::optional<NoLintType> strToNoLintType(StringRef Str) {
auto Type = llvm::StringSwitch<std::optional<NoLintType>>(Str)
.Case("NOLINT", NoLintType::NoLint)
.Case("NOLINTNEXTLINE", NoLintType::NoLintNextLine)
.Case("NOLINTBEGIN", NoLintType::NoLintBegin)
@ -82,7 +82,8 @@ public:
// to NOLINT(*).
// - An empty string means nothing is suppressed - equivalent to NOLINT().
// - Negative globs ignored (which would effectively disable the suppression).
NoLintToken(NoLintType Type, size_t Pos, const Optional<std::string> &Checks)
NoLintToken(NoLintType Type, size_t Pos,
const std::optional<std::string> &Checks)
: Type(Type), Pos(Pos), ChecksGlob(std::make_unique<CachedGlobList>(
Checks.value_or("*"),
/*KeepNegativeGlobs=*/false)) {
@ -97,13 +98,13 @@ public:
size_t Pos;
// If this NOLINT specifies checks, return the checks.
Optional<std::string> checks() const { return Checks; }
std::optional<std::string> checks() const { return Checks; }
// Whether this NOLINT applies to the provided check.
bool suppresses(StringRef Check) const { return ChecksGlob->contains(Check); }
private:
Optional<std::string> Checks;
std::optional<std::string> Checks;
std::unique_ptr<CachedGlobList> ChecksGlob;
};
@ -128,13 +129,13 @@ static SmallVector<NoLintToken> getNoLints(StringRef Buffer) {
++Pos;
// Is this a recognized NOLINT type?
const Optional<NoLintType> NoLintType =
const std::optional<NoLintType> NoLintType =
strToNoLintType(Buffer.slice(NoLintPos, Pos));
if (!NoLintType)
continue;
// Get checks, if specified.
Optional<std::string> Checks;
std::optional<std::string> Checks;
if (Pos < Buffer.size() && Buffer[Pos] == '(') {
size_t ClosingBracket = Buffer.find_first_of("\n)", ++Pos);
if (ClosingBracket != StringRef::npos && Buffer[ClosingBracket] == ')') {
@ -305,8 +306,8 @@ static bool withinNoLintBlock(ArrayRef<NoLintBlockToken> NoLintBlocks,
}
// Get the file contents as a string.
static Optional<StringRef> getBuffer(const SourceManager &SrcMgr, FileID File,
bool AllowIO) {
static std::optional<StringRef> getBuffer(const SourceManager &SrcMgr,
FileID File, bool AllowIO) {
return AllowIO ? SrcMgr.getBufferDataOrNone(File)
: SrcMgr.getBufferDataIfLoaded(File);
}
@ -326,12 +327,12 @@ bool NoLintDirectiveHandler::Impl::diagHasNoLint(
// We will only see NOLINTs in user-authored sources. No point reading the
// file if it is a <built-in>.
Optional<StringRef> FileName = SrcMgr.getNonBuiltinFilenameForID(File);
std::optional<StringRef> FileName = SrcMgr.getNonBuiltinFilenameForID(File);
if (!FileName)
return false;
// Get file contents.
Optional<StringRef> Buffer = getBuffer(SrcMgr, File, AllowIO);
std::optional<StringRef> Buffer = getBuffer(SrcMgr, File, AllowIO);
if (!Buffer)
return false;

View File

@ -39,7 +39,7 @@ void DurationAdditionCheck::check(const MatchFinder::MatchResult &Result) {
if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
return;
llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(
std::optional<DurationScale> Scale = getScaleForTimeInverse(
Result.Nodes.getNodeAs<clang::FunctionDecl>("function_decl")->getName());
if (!Scale)
return;

View File

@ -31,7 +31,7 @@ void DurationComparisonCheck::registerMatchers(MatchFinder *Finder) {
void DurationComparisonCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
llvm::Optional<DurationScale> Scale = getScaleForDurationInverse(
std::optional<DurationScale> Scale = getScaleForDurationInverse(
Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
if (!Scale)
return;

View File

@ -45,7 +45,7 @@ void DurationConversionCastCheck::check(
const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg");
StringRef ConversionFuncName = FuncDecl->getName();
llvm::Optional<DurationScale> Scale =
std::optional<DurationScale> Scale =
getScaleForDurationInverse(ConversionFuncName);
if (!Scale)
return;

View File

@ -55,7 +55,7 @@ void DurationFactoryFloatCheck::check(const MatchFinder::MatchResult &Result) {
if (Arg->getBeginLoc().isMacroID())
return;
llvm::Optional<std::string> SimpleArg = stripFloatCast(Result, *Arg);
std::optional<std::string> SimpleArg = stripFloatCast(Result, *Arg);
if (!SimpleArg)
SimpleArg = stripFloatLiteralFraction(Result, *Arg);

View File

@ -22,9 +22,9 @@ namespace abseil {
// Given the name of a duration factory function, return the appropriate
// `DurationScale` for that factory. If no factory can be found for
// `FactoryName`, return `std::nullopt`.
static llvm::Optional<DurationScale>
static std::optional<DurationScale>
getScaleForFactory(llvm::StringRef FactoryName) {
return llvm::StringSwitch<llvm::Optional<DurationScale>>(FactoryName)
return llvm::StringSwitch<std::optional<DurationScale>>(FactoryName)
.Case("Nanoseconds", DurationScale::Nanoseconds)
.Case("Microseconds", DurationScale::Microseconds)
.Case("Milliseconds", DurationScale::Milliseconds)
@ -48,7 +48,7 @@ static double getValue(const IntegerLiteral *IntLit,
// Given the scale of a duration and a `Multiplier`, determine if `Multiplier`
// would produce a new scale. If so, return a tuple containing the new scale
// and a suitable Multiplier for that scale, otherwise `std::nullopt`.
static llvm::Optional<std::tuple<DurationScale, double>>
static std::optional<std::tuple<DurationScale, double>>
getNewScaleSingleStep(DurationScale OldScale, double Multiplier) {
switch (OldScale) {
case DurationScale::Hours:
@ -95,10 +95,10 @@ getNewScaleSingleStep(DurationScale OldScale, double Multiplier) {
// Given the scale of a duration and a `Multiplier`, determine if `Multiplier`
// would produce a new scale. If so, return it, otherwise `std::nullopt`.
static llvm::Optional<DurationScale> getNewScale(DurationScale OldScale,
double Multiplier) {
static std::optional<DurationScale> getNewScale(DurationScale OldScale,
double Multiplier) {
while (Multiplier != 1.0) {
llvm::Optional<std::tuple<DurationScale, double>> Result =
std::optional<std::tuple<DurationScale, double>> Result =
getNewScaleSingleStep(OldScale, Multiplier);
if (!Result)
break;
@ -155,14 +155,14 @@ void DurationFactoryScaleCheck::check(const MatchFinder::MatchResult &Result) {
}
const auto *CallDecl = Result.Nodes.getNodeAs<FunctionDecl>("call_decl");
llvm::Optional<DurationScale> MaybeScale =
std::optional<DurationScale> MaybeScale =
getScaleForFactory(CallDecl->getName());
if (!MaybeScale)
return;
DurationScale Scale = *MaybeScale;
const Expr *Remainder;
llvm::Optional<DurationScale> NewScale;
std::optional<DurationScale> NewScale;
// We next handle the cases of multiplication and division.
if (const auto *MultBinOp =
@ -195,7 +195,7 @@ void DurationFactoryScaleCheck::check(const MatchFinder::MatchResult &Result) {
// For division, we only check the RHS.
const auto *FloatLit = llvm::cast<FloatingLiteral>(DivBinOp->getRHS());
llvm::Optional<DurationScale> NewScale =
std::optional<DurationScale> NewScale =
getNewScale(Scale, 1.0 / FloatLit->getValueAsApproximateDouble());
if (NewScale) {
const Expr *Remainder = DivBinOp->getLHS();

View File

@ -27,7 +27,7 @@ struct DurationScale2IndexFunctor {
};
/// Returns an integer if the fractional part of a `FloatingLiteral` is `0`.
static llvm::Optional<llvm::APSInt>
static std::optional<llvm::APSInt>
truncateIfIntegral(const FloatingLiteral &FloatLiteral) {
double Value = FloatLiteral.getValueAsApproximateDouble();
if (std::fmod(Value, 1) == 0) {
@ -70,7 +70,7 @@ getDurationInverseForScale(DurationScale Scale) {
/// If `Node` is a call to the inverse of `Scale`, return that inverse's
/// argument, otherwise std::nullopt.
static llvm::Optional<std::string>
static std::optional<std::string>
rewriteInverseDurationCall(const MatchFinder::MatchResult &Result,
DurationScale Scale, const Expr &Node) {
const std::pair<llvm::StringRef, llvm::StringRef> &InverseFunctions =
@ -89,7 +89,7 @@ rewriteInverseDurationCall(const MatchFinder::MatchResult &Result,
/// If `Node` is a call to the inverse of `Scale`, return that inverse's
/// argument, otherwise std::nullopt.
static llvm::Optional<std::string>
static std::optional<std::string>
rewriteInverseTimeCall(const MatchFinder::MatchResult &Result,
DurationScale Scale, const Expr &Node) {
llvm::StringRef InverseFunction = getTimeInverseForScale(Scale);
@ -185,7 +185,7 @@ bool isLiteralZero(const MatchFinder::MatchResult &Result, const Expr &Node) {
return false;
}
llvm::Optional<std::string>
std::optional<std::string>
stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
const Expr &Node) {
if (const Expr *MaybeCastArg = selectFirst<const Expr>(
@ -205,12 +205,12 @@ stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
return std::nullopt;
}
llvm::Optional<std::string>
std::optional<std::string>
stripFloatLiteralFraction(const MatchFinder::MatchResult &Result,
const Expr &Node) {
if (const auto *LitFloat = llvm::dyn_cast<FloatingLiteral>(&Node))
// Attempt to simplify a `Duration` factory call with a literal argument.
if (llvm::Optional<llvm::APSInt> IntValue = truncateIfIntegral(*LitFloat))
if (std::optional<llvm::APSInt> IntValue = truncateIfIntegral(*LitFloat))
return toString(*IntValue, /*radix=*/10);
return std::nullopt;
@ -219,11 +219,11 @@ stripFloatLiteralFraction(const MatchFinder::MatchResult &Result,
std::string simplifyDurationFactoryArg(const MatchFinder::MatchResult &Result,
const Expr &Node) {
// Check for an explicit cast to `float` or `double`.
if (llvm::Optional<std::string> MaybeArg = stripFloatCast(Result, Node))
if (std::optional<std::string> MaybeArg = stripFloatCast(Result, Node))
return *MaybeArg;
// Check for floats without fractional components.
if (llvm::Optional<std::string> MaybeArg =
if (std::optional<std::string> MaybeArg =
stripFloatLiteralFraction(Result, Node))
return *MaybeArg;
@ -231,7 +231,7 @@ std::string simplifyDurationFactoryArg(const MatchFinder::MatchResult &Result,
return tooling::fixit::getText(Node, *Result.Context).str();
}
llvm::Optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
static const llvm::StringMap<DurationScale> ScaleMap(
{{"ToDoubleHours", DurationScale::Hours},
{"ToInt64Hours", DurationScale::Hours},
@ -253,7 +253,7 @@ llvm::Optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
return ScaleIter->second;
}
llvm::Optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name) {
std::optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name) {
static const llvm::StringMap<DurationScale> ScaleMap(
{{"ToUnixHours", DurationScale::Hours},
{"ToUnixMinutes", DurationScale::Minutes},
@ -275,7 +275,7 @@ std::string rewriteExprFromNumberToDuration(
const Expr &RootNode = *Node->IgnoreParenImpCasts();
// First check to see if we can undo a complementary function call.
if (llvm::Optional<std::string> MaybeRewrite =
if (std::optional<std::string> MaybeRewrite =
rewriteInverseDurationCall(Result, Scale, RootNode))
return *MaybeRewrite;
@ -293,7 +293,7 @@ std::string rewriteExprFromNumberToTime(
const Expr &RootNode = *Node->IgnoreParenImpCasts();
// First check to see if we can undo a complementary function call.
if (llvm::Optional<std::string> MaybeRewrite =
if (std::optional<std::string> MaybeRewrite =
rewriteInverseTimeCall(Result, Scale, RootNode))
return *MaybeRewrite;

View File

@ -44,7 +44,7 @@ bool isLiteralZero(const ast_matchers::MatchFinder::MatchResult &Result,
///
/// If `Node` represents an explicit cast to a floating point type, return
/// the textual context of the cast argument, otherwise `std::nullopt`.
llvm::Optional<std::string>
std::optional<std::string>
stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
const Expr &Node);
@ -52,7 +52,7 @@ stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
///
/// If `Node` represents a floating point literal with a zero fractional part,
/// return the textual context of the integral part, otherwise `std::nullopt`.
llvm::Optional<std::string>
std::optional<std::string>
stripFloatLiteralFraction(const ast_matchers::MatchFinder::MatchResult &Result,
const Expr &Node);
@ -65,11 +65,11 @@ simplifyDurationFactoryArg(const ast_matchers::MatchFinder::MatchResult &Result,
/// Given the name of an inverse Duration function (e.g., `ToDoubleSeconds`),
/// return its `DurationScale`, or `std::nullopt` if a match is not found.
llvm::Optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name);
std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name);
/// Given the name of an inverse Time function (e.g., `ToUnixSeconds`),
/// return its `DurationScale`, or `std::nullopt` if a match is not found.
llvm::Optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name);
std::optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name);
/// Given a `Scale` return the fully qualified inverse functions for it.
/// The first returned value is the inverse for `double`, and the second

View File

@ -38,7 +38,7 @@ void DurationSubtractionCheck::check(const MatchFinder::MatchResult &Result) {
if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
return;
llvm::Optional<DurationScale> Scale =
std::optional<DurationScale> Scale =
getScaleForDurationInverse(FuncDecl->getName());
if (!Scale)
return;

View File

@ -22,8 +22,8 @@ namespace {
AST_MATCHER(StringLiteral, lengthIsOne) { return Node.getLength() == 1; }
llvm::Optional<std::string> makeCharacterLiteral(const StringLiteral *Literal,
const ASTContext &Context) {
std::optional<std::string> makeCharacterLiteral(const StringLiteral *Literal,
const ASTContext &Context) {
assert(Literal->getLength() == 1 &&
"Only single character string should be matched");
assert(Literal->getCharByteWidth() == 1 &&
@ -106,7 +106,7 @@ void FasterStrsplitDelimiterCheck::check(
if (Literal->getBeginLoc().isMacroID() || Literal->getEndLoc().isMacroID())
return;
llvm::Optional<std::string> Replacement =
std::optional<std::string> Replacement =
makeCharacterLiteral(Literal, *Result.Context);
if (!Replacement)
return;

View File

@ -32,7 +32,7 @@ void TimeComparisonCheck::registerMatchers(MatchFinder *Finder) {
void TimeComparisonCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(
std::optional<DurationScale> Scale = getScaleForTimeInverse(
Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
if (!Scale)
return;

View File

@ -97,7 +97,7 @@ void TimeSubtractionCheck::registerMatchers(MatchFinder *Finder) {
for (const char *ScaleName :
{"Hours", "Minutes", "Seconds", "Millis", "Micros", "Nanos"}) {
std::string TimeInverse = (llvm::Twine("ToUnix") + ScaleName).str();
llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(TimeInverse);
std::optional<DurationScale> Scale = getScaleForTimeInverse(TimeInverse);
assert(Scale && "Unknown scale encountered");
auto TimeInverseMatcher = callExpr(callee(
@ -135,7 +135,7 @@ void TimeSubtractionCheck::check(const MatchFinder::MatchResult &Result) {
if (insideMacroDefinition(Result, BinOp->getSourceRange()))
return;
llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(InverseName);
std::optional<DurationScale> Scale = getScaleForTimeInverse(InverseName);
if (!Scale)
return;

View File

@ -35,7 +35,7 @@ void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) {
KeyValue.first->hasMacroDefinition();
};
const auto TryExpandAsInteger =
[](Preprocessor::macro_iterator It) -> Optional<unsigned> {
[](Preprocessor::macro_iterator It) -> std::optional<unsigned> {
if (It == PP->macro_end())
return std::nullopt;
const MacroInfo *MI = PP->getMacroInfo(It->first);

View File

@ -28,7 +28,7 @@ public:
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;
Optional<unsigned> SigtermValue;
std::optional<unsigned> SigtermValue;
};
} // namespace bugprone

View File

@ -953,7 +953,7 @@ static inline bool isDerivedToBase(const CXXRecordDecl *Derived,
Base->isCompleteDefinition() && Derived->isDerivedFrom(Base);
}
static Optional<QualType>
static std::optional<QualType>
approximateStandardConversionSequence(const TheCheck &Check, QualType From,
QualType To, const ASTContext &Ctx) {
LLVM_DEBUG(llvm::dbgs() << ">>> approximateStdConv for LType:\n";
@ -1128,7 +1128,7 @@ public:
/// Selects the best conversion function that is applicable from the
/// prepared set of potential conversion functions taken.
Optional<PreparedConversion> operator()() const {
std::optional<PreparedConversion> operator()() const {
if (FlaggedConversions.empty()) {
LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Empty.\n");
return {};
@ -1138,7 +1138,7 @@ public:
return FlaggedConversions.front();
}
Optional<PreparedConversion> BestConversion;
std::optional<PreparedConversion> BestConversion;
unsigned short HowManyGoodConversions = 0;
for (const auto &Prepared : FlaggedConversions) {
LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Candidate flags: "
@ -1192,7 +1192,7 @@ private:
} // namespace
static Optional<ConversionSequence>
static std::optional<ConversionSequence>
tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD,
QualType ToType) {
if (!RD || !RD->isCompleteDefinition())
@ -1218,7 +1218,7 @@ tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD,
ConversionSet.addConversion(Con, Con->getConversionType(), ToType);
}
if (Optional<UserDefinedConversionSelector::PreparedConversion>
if (std::optional<UserDefinedConversionSelector::PreparedConversion>
SelectedConversion = ConversionSet()) {
QualType RecordType{RD->getTypeForDecl(), 0};
@ -1243,7 +1243,7 @@ tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD,
return {};
}
static Optional<ConversionSequence>
static std::optional<ConversionSequence>
tryConvertingConstructors(const TheCheck &Check, QualType FromType,
const CXXRecordDecl *RD) {
if (!RD || !RD->isCompleteDefinition())
@ -1269,7 +1269,7 @@ tryConvertingConstructors(const TheCheck &Check, QualType FromType,
ConversionSet.addConversion(Con, FromType, Con->getParamDecl(0)->getType());
}
if (Optional<UserDefinedConversionSelector::PreparedConversion>
if (std::optional<UserDefinedConversionSelector::PreparedConversion>
SelectedConversion = ConversionSet()) {
QualType RecordType{RD->getTypeForDecl(), 0};
@ -1324,7 +1324,7 @@ approximateImplicitConversion(const TheCheck &Check, QualType LType,
ConversionSequence ImplicitSeq{LType, RType};
QualType WorkType = LType;
Optional<QualType> AfterFirstStdConv =
std::optional<QualType> AfterFirstStdConv =
approximateStandardConversionSequence(Check, LType, RType, Ctx);
if (AfterFirstStdConv) {
LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Standard "
@ -1344,7 +1344,7 @@ approximateImplicitConversion(const TheCheck &Check, QualType LType,
bool FoundConversionOperator = false, FoundConvertingCtor = false;
if (const auto *LRD = WorkType->getAsCXXRecordDecl()) {
Optional<ConversionSequence> ConversionOperatorResult =
std::optional<ConversionSequence> ConversionOperatorResult =
tryConversionOperators(Check, LRD, RType);
if (ConversionOperatorResult) {
LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found "
@ -1359,7 +1359,7 @@ approximateImplicitConversion(const TheCheck &Check, QualType LType,
// Use the original "LType" here, and not WorkType, because the
// conversion to the converting constructors' parameters will be
// modelled in the recursive call.
Optional<ConversionSequence> ConvCtorResult =
std::optional<ConversionSequence> ConvCtorResult =
tryConvertingConstructors(Check, LType, RRD);
if (ConvCtorResult) {
LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found "
@ -1676,7 +1676,7 @@ public:
if (!CalledFn)
continue;
llvm::Optional<unsigned> TargetIdx;
std::optional<unsigned> TargetIdx;
unsigned NumFnParams = CalledFn->getNumParams();
for (unsigned Idx = 0; Idx < NumFnParams; ++Idx)
if (CalledFn->getParamDecl(Idx) == PassedToParam)

View File

@ -60,7 +60,7 @@ void ImplicitWideningOfMultiplicationResultCheck::storeOptions(
Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
}
llvm::Optional<FixItHint>
std::optional<FixItHint>
ImplicitWideningOfMultiplicationResultCheck::includeStddefHeader(
SourceLocation File) {
return IncludeInserter.createIncludeInsertion(

View File

@ -26,7 +26,7 @@ class ImplicitWideningOfMultiplicationResultCheck : public ClangTidyCheck {
bool ShouldUseCXXStaticCast;
bool ShouldUseCXXHeader;
llvm::Optional<FixItHint> includeStddefHeader(SourceLocation File);
std::optional<FixItHint> includeStddefHeader(SourceLocation File);
void handleImplicitCastExpr(const ImplicitCastExpr *ICE);
void handlePointerOffsetting(const Expr *E);

View File

@ -676,15 +676,15 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) {
//===--------------------------------------------------------------------===//
struct CallContext {
CallContext(StringRef Name, Optional<unsigned> DestinationPos,
Optional<unsigned> SourcePos, unsigned LengthPos,
CallContext(StringRef Name, std::optional<unsigned> DestinationPos,
std::optional<unsigned> SourcePos, unsigned LengthPos,
bool WithIncrease)
: Name(Name), DestinationPos(DestinationPos), SourcePos(SourcePos),
LengthPos(LengthPos), WithIncrease(WithIncrease){};
StringRef Name;
Optional<unsigned> DestinationPos;
Optional<unsigned> SourcePos;
std::optional<unsigned> DestinationPos;
std::optional<unsigned> SourcePos;
unsigned LengthPos;
bool WithIncrease;
};
@ -797,7 +797,7 @@ void NotNullTerminatedResultCheck::check(
return;
if (WantToUseSafeFunctions && PP->isMacroDefined("__STDC_LIB_EXT1__")) {
Optional<bool> AreSafeFunctionsWanted;
std::optional<bool> AreSafeFunctionsWanted;
Preprocessor::macro_iterator It = PP->macro_begin();
while (It != PP->macro_end() && !AreSafeFunctionsWanted) {

View File

@ -69,7 +69,7 @@ static bool hasReservedDoubleUnderscore(StringRef Name,
return Name.startswith("__");
}
static Optional<std::string>
static std::optional<std::string>
getDoubleUnderscoreFixup(StringRef Name, const LangOptions &LangOpts) {
if (hasReservedDoubleUnderscore(Name, LangOpts))
return collapseConsecutive(Name, '_');
@ -80,7 +80,7 @@ static bool startsWithUnderscoreCapital(StringRef Name) {
return Name.size() >= 2 && Name[0] == '_' && std::isupper(Name[1]);
}
static Optional<std::string> getUnderscoreCapitalFixup(StringRef Name) {
static std::optional<std::string> getUnderscoreCapitalFixup(StringRef Name) {
if (startsWithUnderscoreCapital(Name))
return std::string(Name.drop_front(1));
return std::nullopt;
@ -91,7 +91,7 @@ static bool startsWithUnderscoreInGlobalNamespace(StringRef Name,
return IsInGlobalNamespace && Name.size() >= 1 && Name[0] == '_';
}
static Optional<std::string>
static std::optional<std::string>
getUnderscoreGlobalNamespaceFixup(StringRef Name, bool IsInGlobalNamespace) {
if (startsWithUnderscoreInGlobalNamespace(Name, IsInGlobalNamespace))
return std::string(Name.drop_front(1));
@ -107,7 +107,7 @@ static std::string getNonReservedFixup(std::string Name) {
return Name;
}
static Optional<RenamerClangTidyCheck::FailureInfo>
static std::optional<RenamerClangTidyCheck::FailureInfo>
getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace,
const LangOptions &LangOpts, bool Invert,
ArrayRef<StringRef> AllowedIdentifiers) {
@ -121,7 +121,7 @@ getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace,
using FailureInfo = RenamerClangTidyCheck::FailureInfo;
if (!Invert) {
Optional<FailureInfo> Info;
std::optional<FailureInfo> Info;
auto AppendFailure = [&](StringRef Kind, std::string &&Fixup) {
if (!Info) {
Info = FailureInfo{std::string(Kind), std::move(Fixup)};
@ -153,7 +153,7 @@ getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace,
return std::nullopt;
}
Optional<RenamerClangTidyCheck::FailureInfo>
std::optional<RenamerClangTidyCheck::FailureInfo>
ReservedIdentifierCheck::getDeclFailureInfo(const NamedDecl *Decl,
const SourceManager &) const {
assert(Decl && Decl->getIdentifier() && !Decl->getName().empty() &&
@ -164,7 +164,7 @@ ReservedIdentifierCheck::getDeclFailureInfo(const NamedDecl *Decl,
getLangOpts(), Invert, AllowedIdentifiers);
}
Optional<RenamerClangTidyCheck::FailureInfo>
std::optional<RenamerClangTidyCheck::FailureInfo>
ReservedIdentifierCheck::getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &) const {
return getFailureInfoImpl(MacroNameTok.getIdentifierInfo()->getName(), true,

View File

@ -41,10 +41,10 @@ public:
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
private:
llvm::Optional<FailureInfo>
std::optional<FailureInfo>
getDeclFailureInfo(const NamedDecl *Decl,
const SourceManager &SM) const override;
llvm::Optional<FailureInfo>
std::optional<FailureInfo>
getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &SM) const override;
DiagInfo getDiagInfo(const NamingCheckId &ID,

View File

@ -81,7 +81,7 @@ void SuspiciousIncludePPCallbacks::InclusionDirective(
SourceLocation DiagLoc = FilenameRange.getBegin().getLocWithOffset(1);
const Optional<StringRef> IFE =
const std::optional<StringRef> IFE =
utils::getFileExtension(FileName, Check.ImplementationFileExtensions);
if (!IFE)
return;

View File

@ -17,8 +17,8 @@ namespace clang {
namespace tidy {
namespace bugprone {
static llvm::Optional<uint64_t> tryEvaluateSizeExpr(const Expr *SizeExpr,
const ASTContext &Ctx) {
static std::optional<uint64_t> tryEvaluateSizeExpr(const Expr *SizeExpr,
const ASTContext &Ctx) {
Expr::EvalResult Result;
if (SizeExpr->EvaluateAsRValue(Result, Ctx))
return Ctx.toBits(
@ -42,7 +42,7 @@ void SuspiciousMemoryComparisonCheck::check(
const Expr *SizeExpr = CE->getArg(2);
assert(SizeExpr != nullptr && "Third argument of memcmp is mandatory.");
llvm::Optional<uint64_t> ComparedBits = tryEvaluateSizeExpr(SizeExpr, Ctx);
std::optional<uint64_t> ComparedBits = tryEvaluateSizeExpr(SizeExpr, Ctx);
for (unsigned int ArgIndex = 0; ArgIndex < 2; ++ArgIndex) {
const Expr *ArgExpr = CE->getArg(ArgIndex);

View File

@ -36,7 +36,7 @@ using llvm::Optional;
static constexpr llvm::StringLiteral FuncID("fun");
static Optional<std::vector<SourceLocation>>
static std::optional<std::vector<SourceLocation>>
analyzeFunction(const FunctionDecl &FuncDecl, ASTContext &ASTCtx,
UncheckedOptionalAccessModelOptions ModelOptions) {
using dataflow::ControlFlowContext;
@ -54,8 +54,8 @@ analyzeFunction(const FunctionDecl &FuncDecl, ASTContext &ASTCtx,
UncheckedOptionalAccessModel Analysis(ASTCtx);
UncheckedOptionalAccessDiagnoser Diagnoser(ModelOptions);
std::vector<SourceLocation> Diagnostics;
Expected<std::vector<
Optional<DataflowAnalysisState<UncheckedOptionalAccessModel::Lattice>>>>
Expected<std::vector<std::optional<
DataflowAnalysisState<UncheckedOptionalAccessModel::Lattice>>>>
BlockToOutputState = dataflow::runDataflowAnalysis(
*Context, Analysis, Env,
[&ASTCtx, &Diagnoser, &Diagnostics](
@ -97,7 +97,7 @@ void UncheckedOptionalAccessCheck::check(
if (FuncDecl->isTemplated())
return;
if (Optional<std::vector<SourceLocation>> Errors =
if (std::optional<std::vector<SourceLocation>> Errors =
analyzeFunction(*FuncDecl, *Result.Context, ModelOptions))
for (const SourceLocation &Loc : *Errors)
diag(Loc, "unchecked access to optional value");

View File

@ -19,7 +19,8 @@ namespace tidy {
namespace bugprone {
/// Warns when the code is unwrapping a `std::optional<T>`, `absl::optional<T>`,
/// or `base::Optional<T>` object without assuring that it contains a value.
/// or `base::std::optional<T>` object without assuring that it contains a
/// value.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/unchecked-optional-access.html

View File

@ -260,7 +260,7 @@ void UseAfterMoveFinder::getDeclRefs(
llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
DeclRefs->clear();
for (const auto &Elem : *Block) {
Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
if (!S)
continue;
@ -356,7 +356,7 @@ void UseAfterMoveFinder::getReinits(
Stmts->clear();
DeclRefs->clear();
for (const auto &Elem : *Block) {
Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
if (!S)
continue;

View File

@ -80,7 +80,7 @@ void InitVariablesCheck::check(const MatchFinder::MatchResult &Result) {
return;
QualType TypePtr = MatchedDecl->getType();
llvm::Optional<const char *> InitializationString;
std::optional<const char *> InitializationString;
bool AddMathInclude = false;
if (TypePtr->isEnumeralType())

View File

@ -71,7 +71,7 @@ void ProBoundsConstantArrayIndexCheck::check(
if (IndexExpr->isValueDependent())
return; // We check in the specialization.
Optional<llvm::APSInt> Index =
std::optional<llvm::APSInt> Index =
IndexExpr->getIntegerConstantExpr(*Result.Context);
if (!Index) {
SourceRange BaseRange;

View File

@ -48,7 +48,7 @@ void VirtualClassDestructorCheck::registerMatchers(MatchFinder *Finder) {
this);
}
static Optional<CharSourceRange>
static std::optional<CharSourceRange>
getVirtualKeywordRange(const CXXDestructorDecl &Destructor,
const SourceManager &SM, const LangOptions &LangOpts) {
if (Destructor.getLocation().isMacroID())
@ -62,7 +62,8 @@ getVirtualKeywordRange(const CXXDestructorDecl &Destructor,
/// Range ends with \c StartOfNextToken so that any whitespace after \c
/// virtual is included.
Optional<Token> NextToken = Lexer::findNextToken(VirtualEndLoc, SM, LangOpts);
std::optional<Token> NextToken =
Lexer::findNextToken(VirtualEndLoc, SM, LangOpts);
if (!NextToken)
return std::nullopt;
SourceLocation StartOfNextToken = NextToken->getLocation();

View File

@ -23,7 +23,7 @@ static const llvm::StringRef RenameCaseToSuiteMessage =
"Google Test APIs named with 'case' are deprecated; use equivalent APIs "
"named with 'suite'";
static llvm::Optional<llvm::StringRef>
static std::optional<llvm::StringRef>
getNewMacroName(llvm::StringRef MacroName) {
std::pair<llvm::StringRef, llvm::StringRef> ReplacementMap[] = {
{"TYPED_TEST_CASE", "TYPED_TEST_SUITE"},
@ -98,7 +98,7 @@ private:
std::string Name = PP->getSpelling(MacroNameTok);
llvm::Optional<llvm::StringRef> Replacement = getNewMacroName(Name);
std::optional<llvm::StringRef> Replacement = getNewMacroName(Name);
if (!Replacement)
return;

View File

@ -505,7 +505,8 @@ static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result,
ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
if (!ConstExpr)
return false;
Optional<llvm::APSInt> R = ConstExpr->getIntegerConstantExpr(*Result.Context);
std::optional<llvm::APSInt> R =
ConstExpr->getIntegerConstantExpr(*Result.Context);
if (!R)
return false;
Value = *R;
@ -1309,7 +1310,7 @@ void RedundantExpressionCheck::check(const MatchFinder::MatchResult &Result) {
"left-right-shift-confusion")) {
const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>("shift-const");
assert(ShiftingConst && "Expr* 'ShiftingConst' is nullptr!");
Optional<llvm::APSInt> ShiftingValue =
std::optional<llvm::APSInt> ShiftingValue =
ShiftingConst->getIntegerConstantExpr(*Result.Context);
if (!ShiftingValue)
@ -1317,7 +1318,7 @@ void RedundantExpressionCheck::check(const MatchFinder::MatchResult &Result) {
const auto *AndConst = Result.Nodes.getNodeAs<Expr>("and-const");
assert(AndConst && "Expr* 'AndCont' is nullptr!");
Optional<llvm::APSInt> AndValue =
std::optional<llvm::APSInt> AndValue =
AndConst->getIntegerConstantExpr(*Result.Context);
if (!AndValue)
return;

View File

@ -140,7 +140,7 @@ SourceLocation StaticAssertCheck::getLastParenLoc(const ASTContext *ASTCtx,
const LangOptions &Opts = ASTCtx->getLangOpts();
const SourceManager &SM = ASTCtx->getSourceManager();
llvm::Optional<llvm::MemoryBufferRef> Buffer =
std::optional<llvm::MemoryBufferRef> Buffer =
SM.getBufferOrNone(SM.getFileID(AssertLoc));
if (!Buffer)
return SourceLocation();

View File

@ -22,8 +22,8 @@ static constexpr std::array<StringRef, 5> DeprecatedTypes = {
"::std::ios_base::seek_dir", "::std::ios_base::streamoff",
"::std::ios_base::streampos"};
static llvm::Optional<const char *> getReplacementType(StringRef Type) {
return llvm::StringSwitch<llvm::Optional<const char *>>(Type)
static std::optional<const char *> getReplacementType(StringRef Type) {
return llvm::StringSwitch<std::optional<const char *>>(Type)
.Case("io_state", "iostate")
.Case("open_mode", "openmode")
.Case("seek_dir", "seekdir")

View File

@ -672,7 +672,7 @@ void LoopConvertCheck::doConversion(
CharSourceRange::getTokenRange(ParenRange), Range));
if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) {
if (Optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
Context->getSourceManager().getFileID(Loop->getBeginLoc()),
getReverseHeader()))
FixIts.push_back(*Insertion);

View File

@ -445,7 +445,7 @@ static bool arrayMatchesBoundExpr(ASTContext *Context,
Context->getAsConstantArrayType(ArrayType);
if (!ConstType)
return false;
Optional<llvm::APSInt> ConditionSize =
std::optional<llvm::APSInt> ConditionSize =
ConditionExpr->getIntegerConstantExpr(*Context);
if (!ConditionSize)
return false;

View File

@ -61,7 +61,7 @@ private:
/// \returns \c true if the next token after the given \p MacroLoc is \b not a
/// semicolon.
bool shouldAppendSemi(SourceRange MacroLoc) {
llvm::Optional<Token> Next = Lexer::findNextToken(
std::optional<Token> Next = Lexer::findNextToken(
MacroLoc.getEnd(), PP.getSourceManager(), PP.getLangOpts());
return !(Next && Next->is(tok::semi));
}

View File

@ -345,7 +345,7 @@ void UseEqualsDefaultCheck::check(const MatchFinder::MatchResult &Result) {
*Body, Result.Context->getSourceManager(),
Result.Context->getLangOpts());
// Skipping comments, check for a semicolon after Body->getSourceRange()
Optional<Token> Token = utils::lexer::findNextTokenSkippingComments(
std::optional<Token> Token = utils::lexer::findNextTokenSkippingComments(
UnifiedEnd, Result.Context->getSourceManager(),
Result.Context->getLangOpts());
StringRef Replacement =

View File

@ -178,7 +178,7 @@ static bool isSpecifier(Token T) {
tok::kw_static, tok::kw_friend, tok::kw_virtual);
}
static llvm::Optional<ClassifiedToken>
static std::optional<ClassifiedToken>
classifyToken(const FunctionDecl &F, Preprocessor &PP, Token Tok) {
ClassifiedToken CT;
CT.T = Tok;
@ -218,7 +218,7 @@ classifyToken(const FunctionDecl &F, Preprocessor &PP, Token Tok) {
return CT;
}
llvm::Optional<SmallVector<ClassifiedToken, 8>>
std::optional<SmallVector<ClassifiedToken, 8>>
UseTrailingReturnTypeCheck::classifyTokensBeforeFunctionName(
const FunctionDecl &F, const ASTContext &Ctx, const SourceManager &SM,
const LangOptions &LangOpts) {
@ -252,7 +252,7 @@ UseTrailingReturnTypeCheck::classifyTokensBeforeFunctionName(
T.setKind(Info.getTokenID());
}
if (llvm::Optional<ClassifiedToken> CT = classifyToken(F, *PP, T))
if (std::optional<ClassifiedToken> CT = classifyToken(F, *PP, T))
ClassifiedTokens.push_back(*CT);
else {
diag(F.getLocation(), Message);
@ -294,7 +294,7 @@ SourceRange UseTrailingReturnTypeCheck::findReturnTypeAndCVSourceRange(
return ReturnTypeRange;
// Include qualifiers to the left and right of the return type.
llvm::Optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
std::optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
classifyTokensBeforeFunctionName(F, Ctx, SM, LangOpts);
if (!MaybeTokens)
return {};
@ -346,7 +346,7 @@ void UseTrailingReturnTypeCheck::keepSpecifiers(
// Tokenize return type. If it contains macros which contain a mix of
// qualifiers, specifiers and types, give up.
llvm::Optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
std::optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
classifyTokensBeforeFunctionName(F, Ctx, SM, LangOpts);
if (!MaybeTokens)
return;

View File

@ -45,7 +45,7 @@ private:
SourceLocation findTrailingReturnTypeSourceLocation(
const FunctionDecl &F, const FunctionTypeLoc &FTL, const ASTContext &Ctx,
const SourceManager &SM, const LangOptions &LangOpts);
llvm::Optional<SmallVector<ClassifiedToken, 8>>
std::optional<SmallVector<ClassifiedToken, 8>>
classifyTokensBeforeFunctionName(const FunctionDecl &F, const ASTContext &Ctx,
const SourceManager &SM,
const LangOptions &LangOpts);

View File

@ -45,7 +45,7 @@ private:
enum class IndirectionType : unsigned char { Pointer, Array };
Optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
std::optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
};
} // namespace mpi

View File

@ -46,7 +46,7 @@ private:
ArrayRef<const Expr *> BufferExprs,
ArrayRef<StringRef> MPIDatatypes, const LangOptions &LO);
Optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
std::optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
};
} // namespace mpi

View File

@ -52,7 +52,7 @@ AST_POLYMORPHIC_MATCHER(isObjCManagedLifetime,
QT.getQualifiers().getObjCLifetime() > Qualifiers::OCL_ExplicitNone;
}
static llvm::Optional<FixItHint>
static std::optional<FixItHint>
fixItHintReplacementForOwnershipString(StringRef Text, CharSourceRange Range,
StringRef Ownership) {
size_t Index = Text.find(Ownership);
@ -65,7 +65,7 @@ fixItHintReplacementForOwnershipString(StringRef Text, CharSourceRange Range,
UnsafeUnretainedText);
}
static llvm::Optional<FixItHint>
static std::optional<FixItHint>
fixItHintForVarDecl(const VarDecl *VD, const SourceManager &SM,
const LangOptions &LangOpts) {
assert(VD && "VarDecl parameter must not be null");
@ -85,11 +85,11 @@ fixItHintForVarDecl(const VarDecl *VD, const SourceManager &SM,
}
StringRef VarDeclText = Lexer::getSourceText(Range, SM, LangOpts);
if (llvm::Optional<FixItHint> Hint =
if (std::optional<FixItHint> Hint =
fixItHintReplacementForOwnershipString(VarDeclText, Range, WeakText))
return Hint;
if (llvm::Optional<FixItHint> Hint = fixItHintReplacementForOwnershipString(
if (std::optional<FixItHint> Hint = fixItHintReplacementForOwnershipString(
VarDeclText, Range, StrongText))
return Hint;

View File

@ -22,7 +22,7 @@ namespace performance {
namespace {
llvm::Optional<std::string> makeCharacterLiteral(const StringLiteral *Literal) {
std::optional<std::string> makeCharacterLiteral(const StringLiteral *Literal) {
std::string Result;
{
llvm::raw_string_ostream OS(Result);

View File

@ -82,7 +82,7 @@ bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar,
} else if (!LoopVar.getType().isConstQualified()) {
return false;
}
llvm::Optional<bool> Expensive =
std::optional<bool> Expensive =
utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
if (!Expensive || !*Expensive)
return false;
@ -92,7 +92,7 @@ bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar,
"copy in each iteration; consider making this a reference")
<< utils::fixit::changeVarDeclToReference(LoopVar, Context);
if (!LoopVar.getType().isConstQualified()) {
if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
LoopVar, Context, DeclSpec::TQ::TQ_const))
Diagnostic << *Fix;
}
@ -102,7 +102,7 @@ bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar,
bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
const VarDecl &LoopVar, const CXXForRangeStmt &ForRange,
ASTContext &Context) {
llvm::Optional<bool> Expensive =
std::optional<bool> Expensive =
utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
if (LoopVar.getType().isConstQualified() || !Expensive || !*Expensive)
return false;
@ -123,7 +123,7 @@ bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
"loop variable is copied but only used as const reference; consider "
"making it a const reference");
if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
LoopVar, Context, DeclSpec::TQ::TQ_const))
Diag << *Fix << utils::fixit::changeVarDeclToReference(LoopVar, Context);

View File

@ -36,14 +36,14 @@ void recordFixes(const VarDecl &Var, ASTContext &Context,
DiagnosticBuilder &Diagnostic) {
Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
if (!Var.getType().isLocalConstQualified()) {
if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
Var, Context, DeclSpec::TQ::TQ_const))
Diagnostic << *Fix;
}
}
llvm::Optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
SourceManager &SM) {
std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
SourceManager &SM) {
bool Invalid;
const char *TextAfter = SM.getCharacterData(Loc, &Invalid);
if (Invalid) {
@ -59,7 +59,7 @@ void recordRemoval(const DeclStmt &Stmt, ASTContext &Context,
// Attempt to remove trailing comments as well.
auto Tok = utils::lexer::findNextTokenSkippingComments(Stmt.getEndLoc(), SM,
Context.getLangOpts());
llvm::Optional<SourceLocation> PastNewLine =
std::optional<SourceLocation> PastNewLine =
firstLocAfterNewLine(Stmt.getEndLoc(), SM);
if (Tok && PastNewLine) {
auto BeforeFirstTokenAfterComment = Tok->getLocation().getLocWithOffset(-1);

View File

@ -151,7 +151,7 @@ void UnnecessaryValueParamCheck::check(const MatchFinder::MatchResult &Result) {
// whether it is const or not as constness can differ between definition and
// declaration.
if (!CurrentParam.getType().getCanonicalType().isConstQualified()) {
if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
CurrentParam, *Result.Context, DeclSpec::TQ::TQ_const))
Diag << *Fix;
}

View File

@ -25,7 +25,7 @@ namespace readability {
// return type. Returns `std::nullopt` when the return type is not
// `const`-qualified or `const` does not appear in `Def`'s source, like when the
// type is an alias or a macro.
static llvm::Optional<Token>
static std::optional<Token>
findConstToRemove(const FunctionDecl *Def,
const MatchFinder::MatchResult &Result) {
if (!Def->getReturnType().isLocalConstQualified())
@ -83,7 +83,7 @@ struct CheckResult {
static CheckResult checkDef(const clang::FunctionDecl *Def,
const MatchFinder::MatchResult &MatchResult) {
CheckResult Result;
llvm::Optional<Token> Tok = findConstToRemove(Def, MatchResult);
std::optional<Token> Tok = findConstToRemove(Def, MatchResult);
if (!Tok)
return Result;
@ -96,7 +96,7 @@ static CheckResult checkDef(const clang::FunctionDecl *Def,
// single warning at the definition.
for (const FunctionDecl *Decl = Def->getPreviousDecl(); Decl != nullptr;
Decl = Decl->getPreviousDecl()) {
if (llvm::Optional<Token> T = findConstToRemove(Decl, MatchResult))
if (std::optional<Token> T = findConstToRemove(Decl, MatchResult))
Result.Hints.push_back(FixItHint::CreateRemoval(
CharSourceRange::getCharRange(T->getLocation(), T->getEndLoc())));
else

View File

@ -219,7 +219,7 @@ class FunctionASTVisitor final
// Used to efficiently know the last type of the binary sequence operator
// that was encountered. It would make sense for the function call to start
// the new sequence, thus it is a stack.
using OBO = Optional<BinaryOperator::Opcode>;
using OBO = std::optional<BinaryOperator::Opcode>;
std::stack<OBO, SmallVector<OBO, 4>> BinaryOperatorsStack;
public:
@ -332,7 +332,8 @@ public:
// We might encounter a function call, which starts a new sequence, thus
// we need to save the current previous binary operator.
const Optional<BinaryOperator::Opcode> BinOpCopy(CurrentBinaryOperator);
const std::optional<BinaryOperator::Opcode> BinOpCopy(
CurrentBinaryOperator);
// Record the operator that we are currently processing and traverse it.
CurrentBinaryOperator = Op->getOpcode();

View File

@ -229,7 +229,7 @@ static StringRef const HungarainNotationUserDefinedTypes[] = {
// clang-format on
IdentifierNamingCheck::NamingStyle::NamingStyle(
llvm::Optional<IdentifierNamingCheck::CaseType> Case,
std::optional<IdentifierNamingCheck::CaseType> Case,
const std::string &Prefix, const std::string &Suffix,
const std::string &IgnoredRegexpStr, HungarianPrefixType HPType)
: Case(Case), Prefix(Prefix), Suffix(Suffix),
@ -250,7 +250,7 @@ IdentifierNamingCheck::FileStyle IdentifierNamingCheck::getFileStyleFromOptions(
HungarianNotation.loadDefaultConfig(HNOption);
HungarianNotation.loadFileConfig(Options, HNOption);
SmallVector<llvm::Optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
SmallVector<std::optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
Styles.resize(SK_Count);
SmallString<64> StyleString;
for (unsigned I = 0; I < SK_Count; ++I) {
@ -802,7 +802,7 @@ void IdentifierNamingCheck::HungarianNotation::loadDefaultConfig(
void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
RenamerClangTidyCheck::storeOptions(Opts);
SmallString<64> StyleString;
ArrayRef<llvm::Optional<NamingStyle>> Styles = MainFileStyle->getStyles();
ArrayRef<std::optional<NamingStyle>> Styles = MainFileStyle->getStyles();
for (size_t I = 0; I < SK_Count; ++I) {
if (!Styles[I])
continue;
@ -1068,7 +1068,7 @@ std::string IdentifierNamingCheck::fixupWithStyle(
StyleKind IdentifierNamingCheck::findStyleKind(
const NamedDecl *D,
ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
bool IgnoreMainLikeFunctions) const {
assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
"Decl must be an explicit identifier with a name.");
@ -1353,11 +1353,11 @@ StyleKind IdentifierNamingCheck::findStyleKind(
return SK_Invalid;
}
llvm::Optional<RenamerClangTidyCheck::FailureInfo>
std::optional<RenamerClangTidyCheck::FailureInfo>
IdentifierNamingCheck::getFailureInfo(
StringRef Type, StringRef Name, const NamedDecl *ND,
SourceLocation Location,
ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
const IdentifierNamingCheck::HungarianNotationOption &HNOption,
StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const {
if (SK == SK_Invalid || !NamingStyles[SK])
@ -1389,7 +1389,7 @@ IdentifierNamingCheck::getFailureInfo(
std::move(Fixup)};
}
llvm::Optional<RenamerClangTidyCheck::FailureInfo>
std::optional<RenamerClangTidyCheck::FailureInfo>
IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
const SourceManager &SM) const {
SourceLocation Loc = Decl->getLocation();
@ -1405,7 +1405,7 @@ IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
SM, IgnoreFailedSplit);
}
llvm::Optional<RenamerClangTidyCheck::FailureInfo>
std::optional<RenamerClangTidyCheck::FailureInfo>
IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &SM) const {
SourceLocation Loc = MacroNameTok.getLocation();

View File

@ -58,7 +58,7 @@ public:
struct HungarianNotationOption {
HungarianNotationOption() : HPType(HungarianPrefixType::HPT_Off) {}
llvm::Optional<CaseType> Case;
std::optional<CaseType> Case;
HungarianPrefixType HPType;
llvm::StringMap<std::string> General;
llvm::StringMap<std::string> CString;
@ -70,14 +70,14 @@ public:
struct NamingStyle {
NamingStyle() = default;
NamingStyle(llvm::Optional<CaseType> Case, const std::string &Prefix,
NamingStyle(std::optional<CaseType> Case, const std::string &Prefix,
const std::string &Suffix, const std::string &IgnoredRegexpStr,
HungarianPrefixType HPType);
NamingStyle(const NamingStyle &O) = delete;
NamingStyle &operator=(NamingStyle &&O) = default;
NamingStyle(NamingStyle &&O) = default;
llvm::Optional<CaseType> Case;
std::optional<CaseType> Case;
std::string Prefix;
std::string Suffix;
// Store both compiled and non-compiled forms so original value can be
@ -121,12 +121,12 @@ public:
struct FileStyle {
FileStyle() : IsActive(false), IgnoreMainLikeFunctions(false) {}
FileStyle(SmallVectorImpl<Optional<NamingStyle>> &&Styles,
FileStyle(SmallVectorImpl<std::optional<NamingStyle>> &&Styles,
HungarianNotationOption HNOption, bool IgnoreMainLike)
: Styles(std::move(Styles)), HNOption(std::move(HNOption)),
IsActive(true), IgnoreMainLikeFunctions(IgnoreMainLike) {}
ArrayRef<Optional<NamingStyle>> getStyles() const {
ArrayRef<std::optional<NamingStyle>> getStyles() const {
assert(IsActive);
return Styles;
}
@ -140,7 +140,7 @@ public:
bool isIgnoringMainLikeFunction() const { return IgnoreMainLikeFunctions; }
private:
SmallVector<Optional<NamingStyle>, 0> Styles;
SmallVector<std::optional<NamingStyle>, 0> Styles;
HungarianNotationOption HNOption;
bool IsActive;
bool IgnoreMainLikeFunctions;
@ -169,13 +169,13 @@ public:
StyleKind findStyleKind(
const NamedDecl *D,
ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
bool IgnoreMainLikeFunctions) const;
llvm::Optional<RenamerClangTidyCheck::FailureInfo> getFailureInfo(
std::optional<RenamerClangTidyCheck::FailureInfo> getFailureInfo(
StringRef Type, StringRef Name, const NamedDecl *ND,
SourceLocation Location,
ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
const IdentifierNamingCheck::HungarianNotationOption &HNOption,
StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const;
@ -183,10 +183,10 @@ public:
bool IncludeMainLike) const;
private:
llvm::Optional<FailureInfo>
std::optional<FailureInfo>
getDeclFailureInfo(const NamedDecl *Decl,
const SourceManager &SM) const override;
llvm::Optional<FailureInfo>
std::optional<FailureInfo>
getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &SM) const override;
DiagInfo getDiagInfo(const NamingCheckId &ID,

View File

@ -106,7 +106,7 @@ static bool typeIsMemberPointer(const Type *T) {
/// // [ ][ ] [ ] - The ranges here are inclusive
/// \endcode
/// \todo Generalize this function to take other declarations than \c VarDecl.
static Optional<std::vector<SourceRange>>
static std::optional<std::vector<SourceRange>>
declRanges(const DeclStmt *DS, const SourceManager &SM,
const LangOptions &LangOpts) {
std::size_t DeclCount = std::distance(DS->decl_begin(), DS->decl_end());
@ -201,7 +201,7 @@ declRanges(const DeclStmt *DS, const SourceManager &SM,
return Slices;
}
static Optional<std::vector<StringRef>>
static std::optional<std::vector<StringRef>>
collectSourceRanges(llvm::ArrayRef<SourceRange> Ranges, const SourceManager &SM,
const LangOptions &LangOpts) {
std::vector<StringRef> Snippets;
@ -252,12 +252,12 @@ void IsolateDeclarationCheck::check(const MatchFinder::MatchResult &Result) {
diag(WholeDecl->getBeginLoc(),
"multiple declarations in a single statement reduces readability");
Optional<std::vector<SourceRange>> PotentialRanges =
std::optional<std::vector<SourceRange>> PotentialRanges =
declRanges(WholeDecl, *Result.SourceManager, getLangOpts());
if (!PotentialRanges)
return;
Optional<std::vector<StringRef>> PotentialSnippets = collectSourceRanges(
std::optional<std::vector<StringRef>> PotentialSnippets = collectSourceRanges(
*PotentialRanges, *Result.SourceManager, getLangOpts());
if (!PotentialSnippets)

View File

@ -46,7 +46,7 @@ static bool locationsInSameFile(const SourceManager &Sources,
Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
}
static llvm::Optional<std::string>
static std::optional<std::string>
getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources,
const LangOptions &LangOpts) {
// Loc should be at the begin of the namespace decl (usually, `namespace`
@ -56,7 +56,7 @@ getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources,
// the opening brace can result from attributes.
std::string Result;
int Nesting = 0;
while (llvm::Optional<Token> T = utils::lexer::findNextTokenSkippingComments(
while (std::optional<Token> T = utils::lexer::findNextTokenSkippingComments(
Loc, Sources, LangOpts)) {
Loc = T->getLocation();
if (T->is(tok::l_brace))
@ -111,7 +111,7 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) {
return;
}
llvm::Optional<std::string> NamespaceNameAsWritten =
std::optional<std::string> NamespaceNameAsWritten =
getNamespaceNameAsWritten(LBraceLoc, Sources, getLangOpts());
if (!NamespaceNameAsWritten)
return;

View File

@ -29,8 +29,8 @@ AST_MATCHER_P(QualType, hasUnqualifiedType,
enum class Qualifier { Const, Volatile, Restrict };
llvm::Optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
const MatchFinder::MatchResult &Result) {
std::optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
const MatchFinder::MatchResult &Result) {
// Since either of the locs can be in a macro, use `makeFileCharRange` to be
// sure that we have a consistent `CharSourceRange`, located entirely in the
// source file.
@ -60,7 +60,7 @@ llvm::Optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
*Result.SourceManager);
}
llvm::Optional<SourceRange>
std::optional<SourceRange>
getTypeSpecifierLocation(const VarDecl *Var,
const MatchFinder::MatchResult &Result) {
SourceRange TypeSpecifier(
@ -75,8 +75,8 @@ getTypeSpecifierLocation(const VarDecl *Var,
return TypeSpecifier;
}
llvm::Optional<SourceRange> mergeReplacementRange(SourceRange &TypeSpecifier,
const Token &ConstToken) {
std::optional<SourceRange> mergeReplacementRange(SourceRange &TypeSpecifier,
const Token &ConstToken) {
if (TypeSpecifier.getBegin().getLocWithOffset(-1) == ConstToken.getEndLoc()) {
TypeSpecifier.setBegin(ConstToken.getLocation());
return std::nullopt;
@ -162,7 +162,7 @@ void QualifiedAutoCheck::registerMatchers(MatchFinder *Finder) {
void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *Var = Result.Nodes.getNodeAs<VarDecl>("auto")) {
SourceRange TypeSpecifier;
if (llvm::Optional<SourceRange> TypeSpec =
if (std::optional<SourceRange> TypeSpec =
getTypeSpecifierLocation(Var, Result)) {
TypeSpecifier = *TypeSpec;
} else
@ -171,10 +171,10 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
llvm::SmallVector<SourceRange, 4> RemoveQualifiersRange;
auto CheckQualifier = [&](bool IsPresent, Qualifier Qual) {
if (IsPresent) {
llvm::Optional<Token> Token = findQualToken(Var, Qual, Result);
std::optional<Token> Token = findQualToken(Var, Qual, Result);
if (!Token || Token->getLocation().isMacroID())
return true; // Disregard this VarDecl.
if (llvm::Optional<SourceRange> Result =
if (std::optional<SourceRange> Result =
mergeReplacementRange(TypeSpecifier, *Token))
RemoveQualifiersRange.push_back(*Result);
}
@ -235,25 +235,24 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
// explicitly.
if (Var->getType().isLocalConstQualified()) {
llvm::Optional<Token> Token =
findQualToken(Var, Qualifier::Const, Result);
std::optional<Token> Token = findQualToken(Var, Qualifier::Const, Result);
if (!Token || Token->getLocation().isMacroID())
return;
}
if (Var->getType().isLocalVolatileQualified()) {
llvm::Optional<Token> Token =
std::optional<Token> Token =
findQualToken(Var, Qualifier::Volatile, Result);
if (!Token || Token->getLocation().isMacroID())
return;
}
if (Var->getType().isLocalRestrictQualified()) {
llvm::Optional<Token> Token =
std::optional<Token> Token =
findQualToken(Var, Qualifier::Restrict, Result);
if (!Token || Token->getLocation().isMacroID())
return;
}
if (llvm::Optional<SourceRange> TypeSpec =
if (std::optional<SourceRange> TypeSpec =
getTypeSpecifierLocation(Var, Result)) {
if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() ||
TypeSpec->getEnd().isMacroID())
@ -275,7 +274,7 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
// Const isn't wrapped in the auto type, so must be declared explicitly.
return;
if (llvm::Optional<SourceRange> TypeSpec =
if (std::optional<SourceRange> TypeSpec =
getTypeSpecifierLocation(Var, Result)) {
if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() ||
TypeSpec->getEnd().isMacroID())

View File

@ -41,7 +41,7 @@ getConstructExpr(const CXXCtorInitializer &CtorInit) {
return dyn_cast<CXXConstructExpr>(InitExpr);
}
static llvm::Optional<SourceRange>
static std::optional<SourceRange>
getConstructExprArgRange(const CXXConstructExpr &Construct) {
SourceLocation B, E;
for (const Expr *Arg : Construct.arguments()) {
@ -155,7 +155,7 @@ void RedundantStringInitCheck::check(const MatchFinder::MatchResult &Result) {
const CXXConstructExpr *Construct = getConstructExpr(*CtorInit);
if (!Construct)
return;
if (llvm::Optional<SourceRange> RemovalRange =
if (std::optional<SourceRange> RemovalRange =
getConstructExprArgRange(*Construct))
diag(CtorInit->getMemberLocation(), "redundant string initialization")
<< FixItHint::CreateRemoval(*RemovalRange);

View File

@ -298,7 +298,7 @@ public:
}
// Extracts a bool if an expression is (true|false|!true|!false);
static Optional<bool> getAsBoolLiteral(const Expr *E, bool FilterMacro) {
static std::optional<bool> getAsBoolLiteral(const Expr *E, bool FilterMacro) {
if (const auto *Bool = dyn_cast<CXXBoolLiteralExpr>(E)) {
if (FilterMacro && Bool->getBeginLoc().isMacroID())
return std::nullopt;
@ -308,7 +308,7 @@ public:
if (FilterMacro && UnaryOp->getBeginLoc().isMacroID())
return std::nullopt;
if (UnaryOp->getOpcode() == UO_LNot)
if (Optional<bool> Res = getAsBoolLiteral(
if (std::optional<bool> Res = getAsBoolLiteral(
UnaryOp->getSubExpr()->IgnoreImplicit(), FilterMacro))
return !*Res;
}
@ -330,7 +330,7 @@ public:
const auto *RS = dyn_cast<ReturnStmt>(S);
if (!RS || !RS->getRetValue())
return {};
if (Optional<bool> Ret =
if (std::optional<bool> Ret =
getAsBoolLiteral(RS->getRetValue()->IgnoreImplicit(), false)) {
return {RS->getRetValue(), *Ret};
}
@ -365,7 +365,7 @@ public:
* if (false) ThenStmt(); else ElseStmt() -> ElseStmt();
*/
Expr *Cond = If->getCond()->IgnoreImplicit();
if (Optional<bool> Bool = getAsBoolLiteral(Cond, true)) {
if (std::optional<bool> Bool = getAsBoolLiteral(Cond, true)) {
if (*Bool)
Check->replaceWithThenStatement(Context, If, Cond);
else
@ -400,7 +400,7 @@ public:
const auto *BO = dyn_cast<BinaryOperator>(S);
if (!BO || BO->getOpcode() != BO_Assign)
return {};
Optional<bool> RightasBool =
std::optional<bool> RightasBool =
getAsBoolLiteral(BO->getRHS()->IgnoreImplicit(), false);
if (!RightasBool)
return {};
@ -439,9 +439,9 @@ public:
* Condition ? true : false; -> Condition
* Condition ? false : true; -> !Condition;
*/
if (Optional<bool> Then =
if (std::optional<bool> Then =
getAsBoolLiteral(Cond->getTrueExpr()->IgnoreImplicit(), false)) {
if (Optional<bool> Else =
if (std::optional<bool> Else =
getAsBoolLiteral(Cond->getFalseExpr()->IgnoreImplicit(), false)) {
if (*Then != *Else)
Check->replaceWithCondition(Context, Cond, *Else);
@ -785,16 +785,16 @@ static BinaryOperatorKind getDemorganFlippedOperator(BinaryOperatorKind BO) {
static bool flipDemorganSide(SmallVectorImpl<FixItHint> &Fixes,
const ASTContext &Ctx, const Expr *E,
Optional<BinaryOperatorKind> OuterBO);
std::optional<BinaryOperatorKind> OuterBO);
/// Inverts \p BinOp, Removing \p Parens if they exist and are safe to remove.
/// returns \c true if there is any issue building the Fixes, \c false
/// otherwise.
static bool flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
const ASTContext &Ctx,
const BinaryOperator *BinOp,
Optional<BinaryOperatorKind> OuterBO,
const ParenExpr *Parens = nullptr) {
static bool
flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
const ASTContext &Ctx, const BinaryOperator *BinOp,
std::optional<BinaryOperatorKind> OuterBO,
const ParenExpr *Parens = nullptr) {
switch (BinOp->getOpcode()) {
case BO_LAnd:
case BO_LOr: {
@ -871,7 +871,7 @@ static bool flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
static bool flipDemorganSide(SmallVectorImpl<FixItHint> &Fixes,
const ASTContext &Ctx, const Expr *E,
Optional<BinaryOperatorKind> OuterBO) {
std::optional<BinaryOperatorKind> OuterBO) {
if (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->getOpcode() == UO_LNot) {
// if we have a not operator, '!a', just remove the '!'.
if (cast<UnaryOperator>(E)->getOperatorLoc().isMacroID())

View File

@ -582,8 +582,8 @@ bool SuspiciousCallArgumentCheck::isHeuristicEnabled(Heuristic H) const {
return llvm::is_contained(AppliedHeuristics, H);
}
Optional<int8_t> SuspiciousCallArgumentCheck::getBound(Heuristic H,
BoundKind BK) const {
std::optional<int8_t>
SuspiciousCallArgumentCheck::getBound(Heuristic H, BoundKind BK) const {
auto Idx = static_cast<std::size_t>(H);
assert(Idx < HeuristicCount);
@ -783,7 +783,7 @@ bool SuspiciousCallArgumentCheck::areNamesSimilar(StringRef Arg,
StringRef Param, Heuristic H,
BoundKind BK) const {
int8_t Threshold = -1;
if (Optional<int8_t> GotBound = getBound(H, BK))
if (std::optional<int8_t> GotBound = getBound(H, BK))
Threshold = *GotBound;
switch (H) {

View File

@ -72,7 +72,7 @@ private:
llvm::StringMap<std::string> AbbreviationDictionary;
bool isHeuristicEnabled(Heuristic H) const;
Optional<int8_t> getBound(Heuristic H, BoundKind BK) const;
std::optional<int8_t> getBound(Heuristic H, BoundKind BK) const;
// Runtime information of the currently analyzed function call.
SmallVector<QualType, SmallVectorSize> ArgTypes;

View File

@ -61,11 +61,11 @@ constexpr llvm::StringLiteral FloatingLiteralCheck::Suffixes;
struct NewSuffix {
SourceRange LiteralLocation;
StringRef OldSuffix;
llvm::Optional<FixItHint> FixIt;
std::optional<FixItHint> FixIt;
};
llvm::Optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc,
const SourceManager &SM) {
std::optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc,
const SourceManager &SM) {
// Do nothing if the provided location is invalid.
if (Loc.isInvalid())
return std::nullopt;
@ -76,17 +76,17 @@ llvm::Optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc,
return SpellingLoc;
}
llvm::Optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc,
const SourceManager &SM) {
llvm::Optional<SourceLocation> Begin =
std::optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc,
const SourceManager &SM) {
std::optional<SourceLocation> Begin =
getMacroAwareLocation(Loc.getBegin(), SM);
llvm::Optional<SourceLocation> End = getMacroAwareLocation(Loc.getEnd(), SM);
std::optional<SourceLocation> End = getMacroAwareLocation(Loc.getEnd(), SM);
if (!Begin || !End)
return std::nullopt;
return SourceRange(*Begin, *End);
}
llvm::Optional<std::string>
std::optional<std::string>
getNewSuffix(llvm::StringRef OldSuffix,
const std::vector<StringRef> &NewSuffixes) {
// If there is no config, just uppercase the entirety of the suffix.
@ -105,7 +105,7 @@ getNewSuffix(llvm::StringRef OldSuffix,
}
template <typename LiteralType>
llvm::Optional<NewSuffix>
std::optional<NewSuffix>
shouldReplaceLiteralSuffix(const Expr &Literal,
const std::vector<StringRef> &NewSuffixes,
const SourceManager &SM, const LangOptions &LO) {
@ -121,7 +121,7 @@ shouldReplaceLiteralSuffix(const Expr &Literal,
utils::rangeCanBeFixed(ReplacementDsc.LiteralLocation, &SM);
// The literal may have macro expansion, we need the final expanded src range.
llvm::Optional<SourceRange> Range =
std::optional<SourceRange> Range =
getMacroAwareSourceRange(ReplacementDsc.LiteralLocation, SM);
if (!Range)
return std::nullopt;
@ -172,7 +172,7 @@ shouldReplaceLiteralSuffix(const Expr &Literal,
"We still should have some chars left.");
// And get the replacement suffix.
llvm::Optional<std::string> NewSuffix =
std::optional<std::string> NewSuffix =
getNewSuffix(ReplacementDsc.OldSuffix, NewSuffixes);
if (!NewSuffix || ReplacementDsc.OldSuffix == *NewSuffix)
return std::nullopt; // The suffix was already the way it should be.

View File

@ -189,7 +189,7 @@ StmtToBlockMap::StmtToBlockMap(const CFG *TheCFG, ASTContext *TheContext)
: Context(TheContext) {
for (const auto *B : *TheCFG) {
for (const auto &Elem : *B) {
if (Optional<CFGStmt> S = Elem.getAs<CFGStmt>())
if (std::optional<CFGStmt> S = Elem.getAs<CFGStmt>())
Map[S->getStmt()] = B;
}
}

View File

@ -54,7 +54,7 @@ bool parseFileExtensions(StringRef AllFileExtensions,
return true;
}
llvm::Optional<StringRef>
std::optional<StringRef>
getFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions) {
StringRef Extension = llvm::sys::path::extension(FileName);
if (Extension.empty())

View File

@ -55,7 +55,7 @@ bool parseFileExtensions(StringRef AllFileExtensions,
/// Decides whether a file has a header file extension.
/// Returns the file extension, if included in the provided set.
llvm::Optional<StringRef>
std::optional<StringRef>
getFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions);
/// Decides whether a file has one of the specified file extensions.

View File

@ -42,7 +42,7 @@ static bool locDangerous(SourceLocation S) {
return S.isInvalid() || S.isMacroID();
}
static Optional<SourceLocation>
static std::optional<SourceLocation>
skipLParensBackwards(SourceLocation Start, const ASTContext &Context) {
if (locDangerous(Start))
return std::nullopt;
@ -63,8 +63,8 @@ skipLParensBackwards(SourceLocation Start, const ASTContext &Context) {
return Start;
}
static Optional<FixItHint> fixIfNotDangerous(SourceLocation Loc,
StringRef Text) {
static std::optional<FixItHint> fixIfNotDangerous(SourceLocation Loc,
StringRef Text) {
if (locDangerous(Loc))
return std::nullopt;
return FixItHint::CreateInsertion(Loc, Text);
@ -79,17 +79,17 @@ static std::string buildQualifier(DeclSpec::TQ Qualifier,
return (llvm::Twine(DeclSpec::getSpecifierName(Qualifier)) + " ").str();
}
static Optional<FixItHint> changeValue(const VarDecl &Var,
DeclSpec::TQ Qualifier,
QualifierTarget QualTarget,
QualifierPolicy QualPolicy,
const ASTContext &Context) {
static std::optional<FixItHint> changeValue(const VarDecl &Var,
DeclSpec::TQ Qualifier,
QualifierTarget QualTarget,
QualifierPolicy QualPolicy,
const ASTContext &Context) {
switch (QualPolicy) {
case QualifierPolicy::Left:
return fixIfNotDangerous(Var.getTypeSpecStartLoc(),
buildQualifier(Qualifier));
case QualifierPolicy::Right:
Optional<SourceLocation> IgnoredParens =
std::optional<SourceLocation> IgnoredParens =
skipLParensBackwards(Var.getLocation(), Context);
if (IgnoredParens)
@ -99,20 +99,20 @@ static Optional<FixItHint> changeValue(const VarDecl &Var,
llvm_unreachable("Unknown QualifierPolicy enum");
}
static Optional<FixItHint> changePointerItself(const VarDecl &Var,
DeclSpec::TQ Qualifier,
const ASTContext &Context) {
static std::optional<FixItHint> changePointerItself(const VarDecl &Var,
DeclSpec::TQ Qualifier,
const ASTContext &Context) {
if (locDangerous(Var.getLocation()))
return std::nullopt;
Optional<SourceLocation> IgnoredParens =
std::optional<SourceLocation> IgnoredParens =
skipLParensBackwards(Var.getLocation(), Context);
if (IgnoredParens)
return fixIfNotDangerous(*IgnoredParens, buildQualifier(Qualifier));
return std::nullopt;
}
static Optional<FixItHint>
static std::optional<FixItHint>
changePointer(const VarDecl &Var, DeclSpec::TQ Qualifier, const Type *Pointee,
QualifierTarget QualTarget, QualifierPolicy QualPolicy,
const ASTContext &Context) {
@ -139,7 +139,7 @@ changePointer(const VarDecl &Var, DeclSpec::TQ Qualifier, const Type *Pointee,
if (locDangerous(BeforeStar))
return std::nullopt;
Optional<SourceLocation> IgnoredParens =
std::optional<SourceLocation> IgnoredParens =
skipLParensBackwards(BeforeStar, Context);
if (IgnoredParens)
@ -163,7 +163,7 @@ changePointer(const VarDecl &Var, DeclSpec::TQ Qualifier, const Type *Pointee,
return std::nullopt;
}
static Optional<FixItHint>
static std::optional<FixItHint>
changeReferencee(const VarDecl &Var, DeclSpec::TQ Qualifier, QualType Pointee,
QualifierTarget QualTarget, QualifierPolicy QualPolicy,
const ASTContext &Context) {
@ -174,7 +174,7 @@ changeReferencee(const VarDecl &Var, DeclSpec::TQ Qualifier, QualType Pointee,
SourceLocation BeforeRef = lexer::findPreviousAnyTokenKind(
Var.getLocation(), Context.getSourceManager(), Context.getLangOpts(),
tok::amp, tok::ampamp);
Optional<SourceLocation> IgnoredParens =
std::optional<SourceLocation> IgnoredParens =
skipLParensBackwards(BeforeRef, Context);
if (IgnoredParens)
return fixIfNotDangerous(*IgnoredParens, buildQualifier(Qualifier, true));
@ -182,11 +182,11 @@ changeReferencee(const VarDecl &Var, DeclSpec::TQ Qualifier, QualType Pointee,
return std::nullopt;
}
Optional<FixItHint> addQualifierToVarDecl(const VarDecl &Var,
const ASTContext &Context,
DeclSpec::TQ Qualifier,
QualifierTarget QualTarget,
QualifierPolicy QualPolicy) {
std::optional<FixItHint> addQualifierToVarDecl(const VarDecl &Var,
const ASTContext &Context,
DeclSpec::TQ Qualifier,
QualifierTarget QualTarget,
QualifierPolicy QualPolicy) {
assert((QualPolicy == QualifierPolicy::Left ||
QualPolicy == QualifierPolicy::Right) &&
"Unexpected Insertion Policy");

View File

@ -42,7 +42,7 @@ enum class QualifierTarget {
/// \brief Creates fix to qualify ``VarDecl`` with the specified \c Qualifier.
/// Requires that `Var` is isolated in written code like in `int foo = 42;`.
Optional<FixItHint>
std::optional<FixItHint>
addQualifierToVarDecl(const VarDecl &Var, const ASTContext &Context,
DeclSpec::TQ Qualifier,
QualifierTarget CT = QualifierTarget::Pointee,

View File

@ -68,7 +68,7 @@ IncludeSorter &IncludeInserter::getOrCreate(FileID FileID) {
return *Entry;
}
llvm::Optional<FixItHint>
std::optional<FixItHint>
IncludeInserter::createIncludeInsertion(FileID FileID, llvm::StringRef Header) {
bool IsAngled = Header.consume_front("<");
if (IsAngled != Header.consume_back(">"))
@ -83,7 +83,7 @@ IncludeInserter::createIncludeInsertion(FileID FileID, llvm::StringRef Header) {
return getOrCreate(FileID).createIncludeInsertion(Header, IsAngled);
}
llvm::Optional<FixItHint>
std::optional<FixItHint>
IncludeInserter::createMainFileIncludeInsertion(StringRef Header) {
assert(SourceMgr && "SourceMgr shouldn't be null; did you remember to call "
"registerPreprocessor()?");

View File

@ -72,15 +72,15 @@ public:
/// inclusion directive, otherwise uses quotes.
/// Returns ``std::nullopt`` on error or if the inclusion directive already
/// exists.
llvm::Optional<FixItHint> createIncludeInsertion(FileID FileID,
llvm::StringRef Header);
std::optional<FixItHint> createIncludeInsertion(FileID FileID,
llvm::StringRef Header);
/// Creates a \p Header inclusion directive fixit in the main file.
/// When \p Header is enclosed in angle brackets, uses angle brackets in the
/// inclusion directive, otherwise uses quotes.
/// Returns ``std::nullopt`` on error or if the inclusion directive already
/// exists.
llvm::Optional<FixItHint>
std::optional<FixItHint>
createMainFileIncludeInsertion(llvm::StringRef Header);
IncludeSorter::IncludeStyle getStyle() const { return Style; }

View File

@ -150,8 +150,8 @@ void IncludeSorter::addInclude(StringRef FileName, bool IsAngled,
IncludeBucket[Kind].push_back(FileName.str());
}
Optional<FixItHint> IncludeSorter::createIncludeInsertion(StringRef FileName,
bool IsAngled) {
std::optional<FixItHint>
IncludeSorter::createIncludeInsertion(StringRef FileName, bool IsAngled) {
std::string IncludeStmt;
if (Style == IncludeStyle::IS_Google_ObjC) {
IncludeStmt = IsAngled

View File

@ -48,7 +48,8 @@ public:
/// Creates a quoted inclusion directive in the right sort order. Returns
/// std::nullopt on error or if header inclusion directive for header already
/// exists.
Optional<FixItHint> createIncludeInsertion(StringRef FileName, bool IsAngled);
std::optional<FixItHint> createIncludeInsertion(StringRef FileName,
bool IsAngled);
private:
typedef SmallVector<SourceRange, 1> SourceRangeVector;

View File

@ -78,10 +78,10 @@ SourceLocation findNextTerminator(SourceLocation Start, const SourceManager &SM,
return findNextAnyTokenKind(Start, SM, LangOpts, tok::comma, tok::semi);
}
Optional<Token> findNextTokenSkippingComments(SourceLocation Start,
const SourceManager &SM,
const LangOptions &LangOpts) {
Optional<Token> CurrentToken;
std::optional<Token>
findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM,
const LangOptions &LangOpts) {
std::optional<Token> CurrentToken;
do {
CurrentToken = Lexer::findNextToken(Start, SM, LangOpts);
} while (CurrentToken && CurrentToken->is(tok::comment));
@ -98,7 +98,7 @@ bool rangeContainsExpansionsOrDirectives(SourceRange Range,
if (Loc.isMacroID())
return true;
llvm::Optional<Token> Tok = Lexer::findNextToken(Loc, SM, LangOpts);
std::optional<Token> Tok = Lexer::findNextToken(Loc, SM, LangOpts);
if (!Tok)
return true;
@ -112,10 +112,10 @@ bool rangeContainsExpansionsOrDirectives(SourceRange Range,
return false;
}
llvm::Optional<Token> getQualifyingToken(tok::TokenKind TK,
CharSourceRange Range,
const ASTContext &Context,
const SourceManager &SM) {
std::optional<Token> getQualifyingToken(tok::TokenKind TK,
CharSourceRange Range,
const ASTContext &Context,
const SourceManager &SM) {
assert((TK == tok::kw_const || TK == tok::kw_volatile ||
TK == tok::kw_restrict) &&
"TK is not a qualifier keyword");
@ -123,8 +123,8 @@ llvm::Optional<Token> getQualifyingToken(tok::TokenKind TK,
StringRef File = SM.getBufferData(LocInfo.first);
Lexer RawLexer(SM.getLocForStartOfFile(LocInfo.first), Context.getLangOpts(),
File.begin(), File.data() + LocInfo.second, File.end());
llvm::Optional<Token> LastMatchBeforeTemplate;
llvm::Optional<Token> LastMatchAfterTemplate;
std::optional<Token> LastMatchBeforeTemplate;
std::optional<Token> LastMatchAfterTemplate;
bool SawTemplate = false;
Token Tok;
while (!RawLexer.LexFromRawLexer(Tok) &&
@ -172,7 +172,7 @@ static SourceLocation getSemicolonAfterStmtEndLoc(const SourceLocation &EndLoc,
// F ( foo() ; )
// ^ EndLoc ^ SpellingLoc ^ next token of SpellingLoc
const SourceLocation SpellingLoc = SM.getSpellingLoc(EndLoc);
Optional<Token> NextTok =
std::optional<Token> NextTok =
findNextTokenSkippingComments(SpellingLoc, SM, LangOpts);
// Was the next token found successfully?
@ -188,7 +188,8 @@ static SourceLocation getSemicolonAfterStmtEndLoc(const SourceLocation &EndLoc,
// ^ EndLoc ^ SpellingLoc ) ^ next token of EndLoc
}
Optional<Token> NextTok = findNextTokenSkippingComments(EndLoc, SM, LangOpts);
std::optional<Token> NextTok =
findNextTokenSkippingComments(EndLoc, SM, LangOpts);
// Testing for semicolon again avoids some issues with macros.
if (NextTok && NextTok->is(tok::TokenKind::semi))

View File

@ -68,7 +68,8 @@ SourceLocation findNextAnyTokenKind(SourceLocation Start,
const LangOptions &LangOpts, TokenKind TK,
TokenKinds... TKs) {
while (true) {
Optional<Token> CurrentToken = Lexer::findNextToken(Start, SM, LangOpts);
std::optional<Token> CurrentToken =
Lexer::findNextToken(Start, SM, LangOpts);
if (!CurrentToken)
return SourceLocation();
@ -87,9 +88,9 @@ SourceLocation findNextAnyTokenKind(SourceLocation Start,
}
// Finds next token that's not a comment.
Optional<Token> findNextTokenSkippingComments(SourceLocation Start,
const SourceManager &SM,
const LangOptions &LangOpts);
std::optional<Token> findNextTokenSkippingComments(SourceLocation Start,
const SourceManager &SM,
const LangOptions &LangOpts);
/// Re-lex the provide \p Range and return \c false if either a macro spans
/// multiple tokens, a pre-processor directive or failure to retrieve the
@ -103,10 +104,10 @@ bool rangeContainsExpansionsOrDirectives(SourceRange Range,
/// must be valid with respect to ``SM``. Returns ``std::nullopt`` if no
/// qualifying tokens are found.
/// \note: doesn't support member function qualifiers.
llvm::Optional<Token> getQualifyingToken(tok::TokenKind TK,
CharSourceRange Range,
const ASTContext &Context,
const SourceManager &SM);
std::optional<Token> getQualifyingToken(tok::TokenKind TK,
CharSourceRange Range,
const ASTContext &Context,
const SourceManager &SM);
/// Stmt->getEndLoc does not always behave the same way depending on Token type.
/// See implementation for exceptions.

View File

@ -24,7 +24,7 @@ AST_MATCHER(BinaryOperator, isRelationalOperator) {
AST_MATCHER(BinaryOperator, isEqualityOperator) { return Node.isEqualityOp(); }
AST_MATCHER(QualType, isExpensiveToCopy) {
llvm::Optional<bool> IsExpensive =
std::optional<bool> IsExpensive =
utils::type_traits::isExpensiveToCopy(Node, Finder->getASTContext());
return IsExpensive && *IsExpensive;
}

View File

@ -27,7 +27,7 @@ AST_MATCHER_P(NamespaceAliasDecl, hasTargetNamespace,
return innerMatcher.matches(*Node.getNamespace(), Finder, Builder);
}
Optional<FixItHint>
std::optional<FixItHint>
NamespaceAliaser::createAlias(ASTContext &Context, const Stmt &Statement,
StringRef Namespace,
const std::vector<std::string> &Abbreviations) {

View File

@ -29,7 +29,7 @@ public:
// Adds a namespace alias for \p Namespace valid near \p
// Statement. Picks the first available name from \p Abbreviations.
// Returns ``std::nullopt`` if an alias already exists or there is an error.
llvm::Optional<FixItHint>
std::optional<FixItHint>
createAlias(ASTContext &Context, const Stmt &Statement,
llvm::StringRef Namespace,
const std::vector<std::string> &Abbreviations);

View File

@ -446,7 +446,7 @@ void RenamerClangTidyCheck::check(const MatchFinder::MatchResult &Result) {
if (isa<ClassTemplateSpecializationDecl>(Decl))
return;
Optional<FailureInfo> MaybeFailure =
std::optional<FailureInfo> MaybeFailure =
getDeclFailureInfo(Decl, *Result.SourceManager);
if (!MaybeFailure)
return;
@ -477,7 +477,7 @@ void RenamerClangTidyCheck::check(const MatchFinder::MatchResult &Result) {
void RenamerClangTidyCheck::checkMacro(SourceManager &SourceMgr,
const Token &MacroNameTok,
const MacroInfo *MI) {
Optional<FailureInfo> MaybeFailure =
std::optional<FailureInfo> MaybeFailure =
getMacroFailureInfo(MacroNameTok, SourceMgr);
if (!MaybeFailure)
return;

View File

@ -126,13 +126,13 @@ protected:
/// Overridden by derived classes, returns information about if and how a Decl
/// failed the check. A 'std::nullopt' result means the Decl did not fail the
/// check.
virtual llvm::Optional<FailureInfo>
virtual std::optional<FailureInfo>
getDeclFailureInfo(const NamedDecl *Decl, const SourceManager &SM) const = 0;
/// Overridden by derived classes, returns information about if and how a
/// macro failed the check. A 'std::nullopt' result means the macro did not
/// fail the check.
virtual llvm::Optional<FailureInfo>
virtual std::optional<FailureInfo>
getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &SM) const = 0;

View File

@ -68,12 +68,12 @@ TransformerClangTidyCheck::TransformerClangTidyCheck(StringRef Name,
// we would be accessing `getLangOpts` and `Options` before the underlying
// `ClangTidyCheck` instance was properly initialized.
TransformerClangTidyCheck::TransformerClangTidyCheck(
std::function<Optional<RewriteRuleWith<std::string>>(const LangOptions &,
const OptionsView &)>
std::function<std::optional<RewriteRuleWith<std::string>>(
const LangOptions &, const OptionsView &)>
MakeRule,
StringRef Name, ClangTidyContext *Context)
: TransformerClangTidyCheck(Name, Context) {
if (Optional<RewriteRuleWith<std::string>> R =
if (std::optional<RewriteRuleWith<std::string>> R =
MakeRule(getLangOpts(), Options))
setRule(std::move(*R));
}

View File

@ -50,7 +50,7 @@ public:
///
/// See \c setRule for constraints on the rule.
TransformerClangTidyCheck(
std::function<Optional<transformer::RewriteRuleWith<std::string>>(
std::function<std::optional<transformer::RewriteRuleWith<std::string>>(
const LangOptions &, const OptionsView &)>
MakeRule,
StringRef Name, ClangTidyContext *Context);

View File

@ -39,8 +39,8 @@ bool hasDeletedCopyConstructor(QualType Type) {
} // namespace
llvm::Optional<bool> isExpensiveToCopy(QualType Type,
const ASTContext &Context) {
std::optional<bool> isExpensiveToCopy(QualType Type,
const ASTContext &Context) {
if (Type->isDependentType() || Type->isIncompleteType())
return std::nullopt;
return !Type.isTriviallyCopyableType(Context) &&

View File

@ -19,8 +19,7 @@ namespace utils {
namespace type_traits {
/// Returns `true` if `Type` is expensive to copy.
llvm::Optional<bool> isExpensiveToCopy(QualType Type,
const ASTContext &Context);
std::optional<bool> isExpensiveToCopy(QualType Type, const ASTContext &Context);
/// Returns `true` if `Type` is trivially default constructible.
bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context);

View File

@ -30,7 +30,7 @@ static StringRef getUnqualifiedName(StringRef QualifiedName) {
UsingInserter::UsingInserter(const SourceManager &SourceMgr)
: SourceMgr(SourceMgr) {}
Optional<FixItHint> UsingInserter::createUsingDeclaration(
std::optional<FixItHint> UsingInserter::createUsingDeclaration(
ASTContext &Context, const Stmt &Statement, StringRef QualifiedName) {
StringRef UnqualifiedName = getUnqualifiedName(QualifiedName);
const FunctionDecl *Function = getSurroundingFunction(Context, Statement);

View File

@ -29,7 +29,7 @@ public:
// Creates a \p using declaration fixit. Returns ``std::nullopt`` on error
// or if the using declaration already exists.
llvm::Optional<FixItHint>
std::optional<FixItHint>
createUsingDeclaration(ASTContext &Context, const Stmt &Statement,
llvm::StringRef QualifiedName);

View File

@ -45,7 +45,7 @@ namespace clang {
namespace clangd {
namespace {
llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>>
std::optional<llvm::ArrayRef<TemplateArgumentLoc>>
getTemplateSpecializationArgLocs(const NamedDecl &ND) {
if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) {
if (const ASTTemplateArgumentListInfo *Args =
@ -267,7 +267,7 @@ std::string printTemplateSpecializationArgs(const NamedDecl &ND) {
std::string TemplateArgs;
llvm::raw_string_ostream OS(TemplateArgs);
PrintingPolicy Policy(ND.getASTContext().getLangOpts());
if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
if (std::optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
getTemplateSpecializationArgLocs(ND)) {
printTemplateArgumentList(OS, *Args, Policy);
} else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) {
@ -564,8 +564,7 @@ public:
};
} // namespace
llvm::Optional<QualType> getDeducedType(ASTContext &ASTCtx,
SourceLocation Loc) {
std::optional<QualType> getDeducedType(ASTContext &ASTCtx, SourceLocation Loc) {
if (!Loc.isValid())
return {};
DeducedTypeVisitor V(Loc);
@ -798,11 +797,11 @@ public:
ArrayRef<const ParmVarDecl *> Tail;
// If the parameters were resolved to another forwarding FunctionDecl, this
// is it.
Optional<FunctionDecl *> PackTarget;
std::optional<FunctionDecl *> PackTarget;
};
// The output of this visitor
Optional<ForwardingInfo> Info;
std::optional<ForwardingInfo> Info;
private:
// inspects the given callee with the given args to check whether it
@ -844,7 +843,7 @@ private:
// Returns the beginning of the expanded pack represented by Parameters
// in the given arguments, if it is there.
llvm::Optional<size_t> findPack(typename CallExpr::arg_range Args) {
std::optional<size_t> findPack(typename CallExpr::arg_range Args) {
// find the argument directly referring to the first parameter
assert(Parameters.size() <= static_cast<size_t>(llvm::size(Args)));
for (auto Begin = Args.begin(), End = Args.end() - Parameters.size() + 1;

View File

@ -152,7 +152,7 @@ QualType declaredType(const TypeDecl *D);
/// Retrieves the deduced type at a given location (auto, decltype).
/// It will return the underlying type.
/// If the type is an undeduced auto, returns the type itself.
llvm::Optional<QualType> getDeducedType(ASTContext &, SourceLocation Loc);
std::optional<QualType> getDeducedType(ASTContext &, SourceLocation Loc);
// Find the abbreviated-function-template `auto` within a type, or returns null.
// Similar to getContainedAutoTypeLoc, but these `auto`s are

View File

@ -245,7 +245,7 @@ public:
// clangd receives the reply from the LSP client.
// Return a call id of the request.
llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
std::optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
int ID;
{
std::lock_guard<std::mutex> Mutex(CallMutex);
@ -516,7 +516,7 @@ void ClangdLSPServer::onInitialize(const InitializeParams &Params,
// rather want to propagate information from LSPServer's context into the
// Server, CDB, etc.
WithContext MainContext(BackgroundContext.clone());
llvm::Optional<WithContextValue> WithOffsetEncoding;
std::optional<WithContextValue> WithOffsetEncoding;
if (Opts.Encoding)
WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding);
Server.emplace(*CDB, TFS, Opts,
@ -908,7 +908,7 @@ flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
const URIForFile &FileURI) {
std::vector<SymbolInformation> Results;
std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
[&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
[&](const DocumentSymbol &S, std::optional<llvm::StringRef> ParentName) {
SymbolInformation SI;
SI.containerName = std::string(ParentName ? "" : *ParentName);
SI.name = S.name;
@ -949,7 +949,7 @@ void ClangdLSPServer::onFoldingRange(
Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
}
static llvm::Optional<Command> asCommand(const CodeAction &Action) {
static std::optional<Command> asCommand(const CodeAction &Action) {
Command Cmd;
if (Action.command && Action.edit)
return std::nullopt; // Not representable. (We never emit these anyway).
@ -1149,7 +1149,7 @@ void ClangdLSPServer::onSwitchSourceHeader(
Server->switchSourceHeader(
Params.uri.file(),
[Reply = std::move(Reply),
Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
Params](llvm::Expected<std::optional<clangd::Path>> Path) mutable {
if (!Path)
return Reply(Path.takeError());
if (*Path)

View File

@ -44,7 +44,7 @@ public:
/// set via LSP (extensions) only.
bool UseDirBasedCDB = true;
/// The offset-encoding to use, or std::nullopt to negotiate it over LSP.
llvm::Optional<OffsetEncoding> Encoding;
std::optional<OffsetEncoding> Encoding;
/// If set, periodically called to release memory.
/// Consider malloc_trim(3)
std::function<void()> MemoryCleanup = nullptr;
@ -292,9 +292,9 @@ private:
// The CDB is created by the "initialize" LSP method.
std::unique_ptr<GlobalCompilationDatabase> BaseCDB;
// CDB is BaseCDB plus any commands overridden via LSP extensions.
llvm::Optional<OverlayCDB> CDB;
std::optional<OverlayCDB> CDB;
// The ClangdServer is created by the "initialize" LSP method.
llvm::Optional<ClangdServer> Server;
std::optional<ClangdServer> Server;
};
} // namespace clangd
} // namespace clang

View File

@ -393,7 +393,7 @@ void ClangdServer::codeComplete(PathRef File, Position Pos,
if (auto Reason = isCancelled())
return CB(llvm::make_error<CancelledError>(Reason));
llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
std::optional<SpeculativeFuzzyFind> SpecFuzzyFind;
if (!IP->Preamble) {
// No speculation in Fallback mode, as it's supposed to be much faster
// without compiling.
@ -471,7 +471,7 @@ void ClangdServer::signatureHelp(PathRef File, Position Pos,
std::move(Action));
}
void ClangdServer::formatFile(PathRef File, llvm::Optional<Range> Rng,
void ClangdServer::formatFile(PathRef File, std::optional<Range> Rng,
Callback<tooling::Replacements> CB) {
auto Code = getDraft(File);
if (!Code)
@ -538,7 +538,7 @@ void ClangdServer::formatOnType(PathRef File, Position Pos,
}
void ClangdServer::prepareRename(PathRef File, Position Pos,
llvm::Optional<std::string> NewName,
std::optional<std::string> NewName,
const RenameOptions &RenameOpts,
Callback<RenameResult> CB) {
auto Action = [Pos, File = File.str(), CB = std::move(CB),
@ -672,7 +672,7 @@ void ClangdServer::applyTweak(PathRef File, Range Sel, StringRef TweakID,
auto Selections = tweakSelection(Sel, *InpAST, FS.get());
if (!Selections)
return CB(Selections.takeError());
llvm::Optional<llvm::Expected<Tweak::Effect>> Effect;
std::optional<llvm::Expected<Tweak::Effect>> Effect;
// Try each selection, take the first one that prepare()s.
// If they all fail, Effect will hold get the last error.
for (const auto &Selection : *Selections) {
@ -714,7 +714,7 @@ void ClangdServer::locateSymbolAt(PathRef File, Position Pos,
}
void ClangdServer::switchSourceHeader(
PathRef Path, Callback<llvm::Optional<clangd::Path>> CB) {
PathRef Path, Callback<std::optional<clangd::Path>> CB) {
// We want to return the result as fast as possible, strategy is:
// 1) use the file-only heuristic, it requires some IO but it is much
// faster than building AST, but it only works when .h/.cc files are in
@ -1029,7 +1029,7 @@ llvm::StringMap<TUScheduler::FileStats> ClangdServer::fileStats() const {
}
[[nodiscard]] bool
ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
ClangdServer::blockUntilIdleForTest(std::optional<double> TimeoutSeconds) {
// Order is important here: we don't want to block on A and then B,
// if B might schedule work on A.
@ -1056,8 +1056,8 @@ ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
// Then on the last iteration, verify they're idle without waiting.
//
// There's a small chance they're juggling work and we didn't catch them :-(
for (llvm::Optional<double> Timeout :
{TimeoutSeconds, TimeoutSeconds, llvm::Optional<double>(0)}) {
for (std::optional<double> Timeout :
{TimeoutSeconds, TimeoutSeconds, std::optional<double>(0)}) {
if (!CDB.blockUntilIdle(timeoutSeconds(Timeout)))
return false;
if (BackgroundIdx && !BackgroundIdx->blockUntilIdleForTest(Timeout))

View File

@ -137,13 +137,13 @@ public:
/// Clangd's workspace root. Relevant for "workspace" operations not bound
/// to a particular file.
/// FIXME: If not set, should use the current working directory.
llvm::Optional<std::string> WorkspaceRoot;
std::optional<std::string> WorkspaceRoot;
/// The resource directory is used to find internal headers, overriding
/// defaults and -resource-dir compiler flag).
/// If None, ClangdServer calls CompilerInvocation::GetResourcePath() to
/// obtain the standard resource directory.
llvm::Optional<std::string> ResourceDir = std::nullopt;
std::optional<std::string> ResourceDir = std::nullopt;
/// Time to wait after a new file version before computing diagnostics.
DebouncePolicy UpdateDebounce = DebouncePolicy{
@ -241,7 +241,7 @@ public:
/// Switch to a corresponding source file when given a header file, and vice
/// versa.
void switchSourceHeader(PathRef Path,
Callback<llvm::Optional<clangd::Path>> CB);
Callback<std::optional<clangd::Path>> CB);
/// Get document highlights for a given position.
void findDocumentHighlights(PathRef File, Position Pos,
@ -304,7 +304,7 @@ public:
/// Run formatting for the \p File with content \p Code.
/// If \p Rng is non-null, formats only that region.
void formatFile(PathRef File, llvm::Optional<Range> Rng,
void formatFile(PathRef File, std::optional<Range> Rng,
Callback<tooling::Replacements> CB);
/// Run formatting after \p TriggerText was typed at \p Pos in \p File with
@ -316,7 +316,7 @@ public:
///
/// If NewName is provided, it performs a name validation.
void prepareRename(PathRef File, Position Pos,
llvm::Optional<std::string> NewName,
std::optional<std::string> NewName,
const RenameOptions &RenameOpts,
Callback<RenameResult> CB);
@ -398,7 +398,7 @@ public:
// FIXME: various subcomponents each get the full timeout, so it's more of
// an order of magnitude than a hard deadline.
[[nodiscard]] bool
blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10);
blockUntilIdleForTest(std::optional<double> TimeoutSeconds = 10);
/// Builds a nested representation of memory used by components.
void profile(MemoryTree &MT) const;
@ -436,13 +436,13 @@ private:
bool PreambleParseForwardingFunctions = false;
// GUARDED_BY(CachedCompletionFuzzyFindRequestMutex)
llvm::StringMap<llvm::Optional<FuzzyFindRequest>>
llvm::StringMap<std::optional<FuzzyFindRequest>>
CachedCompletionFuzzyFindRequestByFile;
mutable std::mutex CachedCompletionFuzzyFindRequestMutex;
llvm::Optional<std::string> WorkspaceRoot;
llvm::Optional<AsyncTaskRunner> IndexTasks; // for stdlib indexing.
llvm::Optional<TUScheduler> WorkScheduler;
std::optional<std::string> WorkspaceRoot;
std::optional<AsyncTaskRunner> IndexTasks; // for stdlib indexing.
std::optional<TUScheduler> WorkScheduler;
// Invalidation policy used for actions that we assume are "transient".
TUScheduler::ASTActionInvalidation Transient;

View File

@ -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())
@ -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.
@ -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;
};
@ -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.
@ -1834,7 +1834,7 @@ private:
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) ||
@ -1949,7 +1949,7 @@ private:
}
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)
@ -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();

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