From: Kazu Hirata Date: Sun, 8 Jan 2023 04:19:42 +0000 (-0800) Subject: [clang-tools-extra] Use std::optional instead of llvm::Optional (NFC) X-Git-Tag: upstream/17.0.6~21805 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=f71ffd3b735b4d6ae3c12be1806cdd6205b3b378;p=platform%2Fupstream%2Fllvm.git [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 --- diff --git a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp index 43ecfd8f0ccc..d055bf369de4 100644 --- a/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp +++ b/clang-tools-extra/clang-apply-replacements/lib/Tooling/ApplyReplacements.cpp @@ -156,7 +156,7 @@ groupReplacements(const TUReplacements &TUs, const TUDiagnostics &TUDs, auto AddToGroup = [&](const tooling::Replacement &R, const tooling::TranslationUnitDiagnostics *SourceTU, - const llvm::Optional BuildDir) { + const std::optional 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. diff --git a/clang-tools-extra/clang-doc/HTMLGenerator.cpp b/clang-tools-extra/clang-doc/HTMLGenerator.cpp index 589a3232c90c..b61780ca4d97 100644 --- a/clang-tools-extra/clang-doc/HTMLGenerator.cpp +++ b/clang-tools-extra/clang-doc/HTMLGenerator.cpp @@ -309,7 +309,7 @@ static std::unique_ptr genLink(const Twine &Text, const Twine &Link) { static std::unique_ptr genReference(const Reference &Type, StringRef CurrentDirectory, - llvm::Optional JumpToSection = std::nullopt) { + std::optional JumpToSection = std::nullopt) { if (Type.Path.empty()) { if (!JumpToSection) return std::make_unique(Type.Name); @@ -438,7 +438,7 @@ genReferencesBlock(const std::vector &References, static std::unique_ptr writeFileDefinition(const Location &L, - llvm::Optional RepositoryUrl = std::nullopt) { + std::optional RepositoryUrl = std::nullopt) { if (!L.IsFileInRootDir || !RepositoryUrl) return std::make_unique( HTMLTag::TAG_P, "Defined at line " + std::to_string(L.LineNumber) + diff --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp index 2cee43845aaa..f07e9c95d107 100644 --- a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp +++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.cpp @@ -21,7 +21,7 @@ namespace clang { namespace find_all_symbols { -llvm::Optional +std::optional FindAllMacros::CreateMacroSymbol(const Token &MacroNameTok, const MacroInfo *info) { std::string FilePath = diff --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h index 99a7f5deccdc..1f13f3ddd15e 100644 --- a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h +++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllMacros.h @@ -45,8 +45,8 @@ public: void EndOfMainFile() override; private: - llvm::Optional CreateMacroSymbol(const Token &MacroNameTok, - const MacroInfo *MD); + std::optional 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); diff --git a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp index 8608ba74ce9f..e067414f7d17 100644 --- a/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp +++ b/clang-tools-extra/clang-include-fixer/find-all-symbols/FindAllSymbols.cpp @@ -70,7 +70,7 @@ std::vector GetContexts(const NamedDecl *ND) { return Contexts; } -llvm::Optional +std::optional CreateSymbolInfo(const NamedDecl *ND, const SourceManager &SM, const HeaderMapCollector *Collector) { SymbolInfo::SymbolKind Type; diff --git a/clang-tools-extra/clang-query/Query.cpp b/clang-tools-extra/clang-query/Query.cpp index d1db851c1297..c436d6fa9498 100644 --- a/clang-tools-extra/clang-query/Query.cpp +++ b/clang-tools-extra/clang-query/Query.cpp @@ -184,7 +184,7 @@ bool MatchQuery::run(llvm::raw_ostream &OS, QuerySession &QS) const { std::vector Matches; DynTypedMatcher MaybeBoundMatcher = Matcher; if (QS.BindRoot) { - llvm::Optional M = Matcher.tryBind("root"); + std::optional M = Matcher.tryBind("root"); if (M) MaybeBoundMatcher = *M; } diff --git a/clang-tools-extra/clang-query/QueryParser.cpp b/clang-tools-extra/clang-query/QueryParser.cpp index 77621d252aed..41933625a4fa 100644 --- a/clang-tools-extra/clang-query/QueryParser.cpp +++ b/clang-tools-extra/clang-query/QueryParser.cpp @@ -276,7 +276,7 @@ QueryRef QueryParser::doParse() { Diagnostics Diag; auto MatcherSource = Line.ltrim(); auto OrigMatcherSource = MatcherSource; - Optional Matcher = Parser::parseMatcherExpression( + std::optional Matcher = Parser::parseMatcherExpression( MatcherSource, nullptr, &QS.NamedValues, &Diag); if (!Matcher) { return makeInvalidQueryFromDiagnostics(Diag); diff --git a/clang-tools-extra/clang-query/tool/ClangQuery.cpp b/clang-tools-extra/clang-query/tool/ClangQuery.cpp index 6ba2b1a4412d..da7ac2701448 100644 --- a/clang-tools-extra/clang-query/tool/ClangQuery.cpp +++ b/clang-tools-extra/clang-query/tool/ClangQuery.cpp @@ -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 Line = LE.readLine()) { + while (std::optional Line = LE.readLine()) { QueryRef Q = QueryParser::parse(*Line, QS); Q->run(llvm::outs(), QS); llvm::outs().flush(); diff --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp index 8f90becf8ab2..498140e5f13a 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.cpp @@ -52,7 +52,7 @@ ClangTidyCheck::OptionsView::OptionsView( : NamePrefix((CheckName + ".").str()), CheckOptions(CheckOptions), Context(Context) {} -llvm::Optional +std::optional 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 +std::optional 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 getAsBool(StringRef Value, - const llvm::Twine &LookupName) { +static std::optional getAsBool(StringRef Value, + const llvm::Twine &LookupName) { if (std::optional Parsed = llvm::yaml::parseBool(Value)) return *Parsed; @@ -104,9 +104,9 @@ static Optional getAsBool(StringRef Value, } template <> -llvm::Optional +std::optional ClangTidyCheck::OptionsView::get(StringRef LocalName) const { - if (llvm::Optional ValueOr = get(LocalName)) { + if (std::optional ValueOr = get(LocalName)) { if (auto Result = getAsBool(*ValueOr, NamePrefix + LocalName)) return Result; diagnoseBadBooleanOption(NamePrefix + LocalName, *ValueOr); @@ -115,7 +115,7 @@ ClangTidyCheck::OptionsView::get(StringRef LocalName) const { } template <> -llvm::Optional +std::optional ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const { auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName, Context->getOptionsCollector()); @@ -146,7 +146,7 @@ void ClangTidyCheck::OptionsView::store( store(Options, LocalName, Value ? StringRef("true") : StringRef("false")); } -llvm::Optional ClangTidyCheck::OptionsView::getEnumInt( +std::optional ClangTidyCheck::OptionsView::getEnumInt( StringRef LocalName, ArrayRef Mapping, bool CheckGlobal, bool IgnoreCase) const { if (!CheckGlobal && Context->getOptionsCollector()) diff --git a/clang-tools-extra/clang-tidy/ClangTidyCheck.h b/clang-tools-extra/clang-tidy/ClangTidyCheck.h index f2486eab5dfa..796b354ec2fa 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyCheck.h +++ b/clang-tools-extra/clang-tidy/ClangTidyCheck.h @@ -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 get(StringRef LocalName) const; + std::optional 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 getLocalOrGlobal(StringRef LocalName) const; + std::optional 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 - std::enable_if_t::value, llvm::Optional> + std::enable_if_t::value, std::optional> get(StringRef LocalName) const { - if (llvm::Optional Value = get(LocalName)) { + if (std::optional 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 - std::enable_if_t::value, llvm::Optional> + std::enable_if_t::value, std::optional> getLocalOrGlobal(StringRef LocalName) const { - llvm::Optional ValueOr = get(LocalName); + std::optional 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 - std::enable_if_t::value, llvm::Optional> + std::enable_if_t::value, std::optional> get(StringRef LocalName, bool IgnoreCase = false) const { - if (llvm::Optional ValueOr = + if (std::optional ValueOr = getEnumInt(LocalName, typeEraseMapping(), false, IgnoreCase)) return static_cast(*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 - std::enable_if_t::value, llvm::Optional> + std::enable_if_t::value, std::optional> getLocalOrGlobal(StringRef LocalName, bool IgnoreCase = false) const { - if (llvm::Optional ValueOr = + if (std::optional ValueOr = getEnumInt(LocalName, typeEraseMapping(), true, IgnoreCase)) return static_cast(*ValueOr); return std::nullopt; @@ -379,9 +379,9 @@ public: private: using NameAndValue = std::pair; - llvm::Optional getEnumInt(StringRef LocalName, - ArrayRef Mapping, - bool CheckGlobal, bool IgnoreCase) const; + std::optional getEnumInt(StringRef LocalName, + ArrayRef Mapping, + bool CheckGlobal, bool IgnoreCase) const; template std::enable_if_t::value, std::vector> @@ -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 +std::optional ClangTidyCheck::OptionsView::get(StringRef LocalName) const; /// Read a named option from the ``Context`` and parse it as a bool. @@ -446,7 +446,7 @@ ClangTidyCheck::OptionsView::get(StringRef LocalName) const; /// If the corresponding key can't be parsed as a bool, emit a /// diagnostic and return \p Default. template <> -llvm::Optional +std::optional ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const; /// Stores an option with the check-local name \p LocalName with diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp index 05ca2573dc4e..558190e5e13b 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp @@ -256,7 +256,7 @@ void ClangTidyContext::setProfileStoragePrefix(StringRef Prefix) { ProfilePrefix = std::string(Prefix); } -llvm::Optional +std::optional ClangTidyContext::getProfileStorageParams() const { if (ProfilePrefix.empty()) return std::nullopt; diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h index 475f38d334ca..ac5e896bcb85 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h @@ -170,7 +170,7 @@ public: /// Control storage of profile date. void setProfileStoragePrefix(StringRef ProfilePrefix); - llvm::Optional + std::optional getProfileStorageParams() const; /// Should be called when starting to process new translation unit. diff --git a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp index cf790f9f579a..43001a37f2f8 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp @@ -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 Result; + std::optional Result; auto Iter = CachedOptions.find(CurrentPath); if (Iter != CachedOptions.end()) @@ -360,7 +360,7 @@ FileOptionsProvider::getRawOptions(StringRef FileName) { return RawOptions; } -llvm::Optional +std::optional FileOptionsBaseProvider::tryReadConfigFile(StringRef Directory) { assert(!Directory.empty()); diff --git a/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp b/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp index 0cfdda3b5ded..32465a4dc0ba 100644 --- a/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp +++ b/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp @@ -40,7 +40,7 @@ public: return; // FIXME: Why is this happening? We might be losing contents here. - llvm::Optional Data = ContentCache.getBufferDataIfLoaded(); + std::optional Data = ContentCache.getBufferDataIfLoaded(); if (!Data) return; diff --git a/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp b/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp index 7a822cd55bed..7c9f4a0b121f 100644 --- a/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp +++ b/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp @@ -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 strToNoLintType(StringRef Str) { - auto Type = llvm::StringSwitch>(Str) +static std::optional strToNoLintType(StringRef Str) { + auto Type = llvm::StringSwitch>(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 &Checks) + NoLintToken(NoLintType Type, size_t Pos, + const std::optional &Checks) : Type(Type), Pos(Pos), ChecksGlob(std::make_unique( Checks.value_or("*"), /*KeepNegativeGlobs=*/false)) { @@ -97,13 +98,13 @@ public: size_t Pos; // If this NOLINT specifies checks, return the checks. - Optional checks() const { return Checks; } + std::optional checks() const { return Checks; } // Whether this NOLINT applies to the provided check. bool suppresses(StringRef Check) const { return ChecksGlob->contains(Check); } private: - Optional Checks; + std::optional Checks; std::unique_ptr ChecksGlob; }; @@ -128,13 +129,13 @@ static SmallVector getNoLints(StringRef Buffer) { ++Pos; // Is this a recognized NOLINT type? - const Optional NoLintType = + const std::optional NoLintType = strToNoLintType(Buffer.slice(NoLintPos, Pos)); if (!NoLintType) continue; // Get checks, if specified. - Optional Checks; + std::optional 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 NoLintBlocks, } // Get the file contents as a string. -static Optional getBuffer(const SourceManager &SrcMgr, FileID File, - bool AllowIO) { +static std::optional 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 . - Optional FileName = SrcMgr.getNonBuiltinFilenameForID(File); + std::optional FileName = SrcMgr.getNonBuiltinFilenameForID(File); if (!FileName) return false; // Get file contents. - Optional Buffer = getBuffer(SrcMgr, File, AllowIO); + std::optional Buffer = getBuffer(SrcMgr, File, AllowIO); if (!Buffer) return false; diff --git a/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp index 585b7c1310e2..edf6a174ef52 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp @@ -39,7 +39,7 @@ void DurationAdditionCheck::check(const MatchFinder::MatchResult &Result) { if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid()) return; - llvm::Optional Scale = getScaleForTimeInverse( + std::optional Scale = getScaleForTimeInverse( Result.Nodes.getNodeAs("function_decl")->getName()); if (!Scale) return; diff --git a/clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp index 39c7ba4fc9b4..859aad7a579d 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp @@ -31,7 +31,7 @@ void DurationComparisonCheck::registerMatchers(MatchFinder *Finder) { void DurationComparisonCheck::check(const MatchFinder::MatchResult &Result) { const auto *Binop = Result.Nodes.getNodeAs("binop"); - llvm::Optional Scale = getScaleForDurationInverse( + std::optional Scale = getScaleForDurationInverse( Result.Nodes.getNodeAs("function_decl")->getName()); if (!Scale) return; diff --git a/clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp index 3a83e6707efc..328f6f13b80b 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationConversionCastCheck.cpp @@ -45,7 +45,7 @@ void DurationConversionCastCheck::check( const auto *Arg = Result.Nodes.getNodeAs("arg"); StringRef ConversionFuncName = FuncDecl->getName(); - llvm::Optional Scale = + std::optional Scale = getScaleForDurationInverse(ConversionFuncName); if (!Scale) return; diff --git a/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp index 09512347acca..fcb4a8550a6a 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationFactoryFloatCheck.cpp @@ -55,7 +55,7 @@ void DurationFactoryFloatCheck::check(const MatchFinder::MatchResult &Result) { if (Arg->getBeginLoc().isMacroID()) return; - llvm::Optional SimpleArg = stripFloatCast(Result, *Arg); + std::optional SimpleArg = stripFloatCast(Result, *Arg); if (!SimpleArg) SimpleArg = stripFloatLiteralFraction(Result, *Arg); diff --git a/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp index b33f1e364a66..24b3f56d2b45 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationFactoryScaleCheck.cpp @@ -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 +static std::optional getScaleForFactory(llvm::StringRef FactoryName) { - return llvm::StringSwitch>(FactoryName) + return llvm::StringSwitch>(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> +static std::optional> 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 getNewScale(DurationScale OldScale, - double Multiplier) { +static std::optional getNewScale(DurationScale OldScale, + double Multiplier) { while (Multiplier != 1.0) { - llvm::Optional> Result = + std::optional> Result = getNewScaleSingleStep(OldScale, Multiplier); if (!Result) break; @@ -155,14 +155,14 @@ void DurationFactoryScaleCheck::check(const MatchFinder::MatchResult &Result) { } const auto *CallDecl = Result.Nodes.getNodeAs("call_decl"); - llvm::Optional MaybeScale = + std::optional MaybeScale = getScaleForFactory(CallDecl->getName()); if (!MaybeScale) return; DurationScale Scale = *MaybeScale; const Expr *Remainder; - llvm::Optional NewScale; + std::optional 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(DivBinOp->getRHS()); - llvm::Optional NewScale = + std::optional NewScale = getNewScale(Scale, 1.0 / FloatLit->getValueAsApproximateDouble()); if (NewScale) { const Expr *Remainder = DivBinOp->getLHS(); diff --git a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp index c2325c11e2ad..d96093fdd8d2 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.cpp @@ -27,7 +27,7 @@ struct DurationScale2IndexFunctor { }; /// Returns an integer if the fractional part of a `FloatingLiteral` is `0`. -static llvm::Optional +static std::optional 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 +static std::optional rewriteInverseDurationCall(const MatchFinder::MatchResult &Result, DurationScale Scale, const Expr &Node) { const std::pair &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 +static std::optional 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::optional stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result, const Expr &Node) { if (const Expr *MaybeCastArg = selectFirst( @@ -205,12 +205,12 @@ stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result, return std::nullopt; } -llvm::Optional +std::optional stripFloatLiteralFraction(const MatchFinder::MatchResult &Result, const Expr &Node) { if (const auto *LitFloat = llvm::dyn_cast(&Node)) // Attempt to simplify a `Duration` factory call with a literal argument. - if (llvm::Optional IntValue = truncateIfIntegral(*LitFloat)) + if (std::optional 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 MaybeArg = stripFloatCast(Result, Node)) + if (std::optional MaybeArg = stripFloatCast(Result, Node)) return *MaybeArg; // Check for floats without fractional components. - if (llvm::Optional MaybeArg = + if (std::optional 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 getScaleForDurationInverse(llvm::StringRef Name) { +std::optional getScaleForDurationInverse(llvm::StringRef Name) { static const llvm::StringMap ScaleMap( {{"ToDoubleHours", DurationScale::Hours}, {"ToInt64Hours", DurationScale::Hours}, @@ -253,7 +253,7 @@ llvm::Optional getScaleForDurationInverse(llvm::StringRef Name) { return ScaleIter->second; } -llvm::Optional getScaleForTimeInverse(llvm::StringRef Name) { +std::optional getScaleForTimeInverse(llvm::StringRef Name) { static const llvm::StringMap 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 MaybeRewrite = + if (std::optional 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 MaybeRewrite = + if (std::optional MaybeRewrite = rewriteInverseTimeCall(Result, Scale, RootNode)) return *MaybeRewrite; diff --git a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.h b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.h index a23dfaf9bcef..c73418886a67 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationRewriter.h +++ b/clang-tools-extra/clang-tidy/abseil/DurationRewriter.h @@ -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::optional 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::optional 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 getScaleForDurationInverse(llvm::StringRef Name); +std::optional 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 getScaleForTimeInverse(llvm::StringRef Name); +std::optional 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 diff --git a/clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp b/clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp index 4d12fd337ace..21425b4f6fa7 100644 --- a/clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/DurationSubtractionCheck.cpp @@ -38,7 +38,7 @@ void DurationSubtractionCheck::check(const MatchFinder::MatchResult &Result) { if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid()) return; - llvm::Optional Scale = + std::optional Scale = getScaleForDurationInverse(FuncDecl->getName()); if (!Scale) return; diff --git a/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp b/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp index 36e670ea8c36..02d96dbd402a 100644 --- a/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/FasterStrsplitDelimiterCheck.cpp @@ -22,8 +22,8 @@ namespace { AST_MATCHER(StringLiteral, lengthIsOne) { return Node.getLength() == 1; } -llvm::Optional makeCharacterLiteral(const StringLiteral *Literal, - const ASTContext &Context) { +std::optional 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 Replacement = + std::optional Replacement = makeCharacterLiteral(Literal, *Result.Context); if (!Replacement) return; diff --git a/clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp b/clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp index ddbde758684f..fa6fcd877b79 100644 --- a/clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/TimeComparisonCheck.cpp @@ -32,7 +32,7 @@ void TimeComparisonCheck::registerMatchers(MatchFinder *Finder) { void TimeComparisonCheck::check(const MatchFinder::MatchResult &Result) { const auto *Binop = Result.Nodes.getNodeAs("binop"); - llvm::Optional Scale = getScaleForTimeInverse( + std::optional Scale = getScaleForTimeInverse( Result.Nodes.getNodeAs("function_decl")->getName()); if (!Scale) return; diff --git a/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp b/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp index 9f2fba454cbd..7e8a94e0ecb4 100644 --- a/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp +++ b/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.cpp @@ -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 Scale = getScaleForTimeInverse(TimeInverse); + std::optional 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 Scale = getScaleForTimeInverse(InverseName); + std::optional Scale = getScaleForTimeInverse(InverseName); if (!Scale) return; diff --git a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp index 2676540ab2c5..5b6da9a52481 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.cpp @@ -35,7 +35,7 @@ void BadSignalToKillThreadCheck::check(const MatchFinder::MatchResult &Result) { KeyValue.first->hasMacroDefinition(); }; const auto TryExpandAsInteger = - [](Preprocessor::macro_iterator It) -> Optional { + [](Preprocessor::macro_iterator It) -> std::optional { if (It == PP->macro_end()) return std::nullopt; const MacroInfo *MI = PP->getMacroInfo(It->first); diff --git a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h index 3a5919d5121a..f3f7f88c3c0e 100644 --- a/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h +++ b/clang-tools-extra/clang-tidy/bugprone/BadSignalToKillThreadCheck.h @@ -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 SigtermValue; + std::optional SigtermValue; }; } // namespace bugprone diff --git a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp index 23244dceefda..2c525ec1e5a5 100644 --- a/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp @@ -953,7 +953,7 @@ static inline bool isDerivedToBase(const CXXRecordDecl *Derived, Base->isCompleteDefinition() && Derived->isDerivedFrom(Base); } -static Optional +static std::optional 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 operator()() const { + std::optional operator()() const { if (FlaggedConversions.empty()) { LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Empty.\n"); return {}; @@ -1138,7 +1138,7 @@ public: return FlaggedConversions.front(); } - Optional BestConversion; + std::optional 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 +static std::optional 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 + if (std::optional SelectedConversion = ConversionSet()) { QualType RecordType{RD->getTypeForDecl(), 0}; @@ -1243,7 +1243,7 @@ tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD, return {}; } -static Optional +static std::optional 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 + if (std::optional 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 AfterFirstStdConv = + std::optional 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 ConversionOperatorResult = + std::optional 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 ConvCtorResult = + std::optional ConvCtorResult = tryConvertingConstructors(Check, LType, RRD); if (ConvCtorResult) { LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found " @@ -1676,7 +1676,7 @@ public: if (!CalledFn) continue; - llvm::Optional TargetIdx; + std::optional TargetIdx; unsigned NumFnParams = CalledFn->getNumParams(); for (unsigned Idx = 0; Idx < NumFnParams; ++Idx) if (CalledFn->getParamDecl(Idx) == PassedToParam) diff --git a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp index 601949bfb16a..e09092d842d4 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.cpp @@ -60,7 +60,7 @@ void ImplicitWideningOfMultiplicationResultCheck::storeOptions( Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle()); } -llvm::Optional +std::optional ImplicitWideningOfMultiplicationResultCheck::includeStddefHeader( SourceLocation File) { return IncludeInserter.createIncludeInsertion( diff --git a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h index 74152efa4736..ed68bb6cea76 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h +++ b/clang-tools-extra/clang-tidy/bugprone/ImplicitWideningOfMultiplicationResultCheck.h @@ -26,7 +26,7 @@ class ImplicitWideningOfMultiplicationResultCheck : public ClangTidyCheck { bool ShouldUseCXXStaticCast; bool ShouldUseCXXHeader; - llvm::Optional includeStddefHeader(SourceLocation File); + std::optional includeStddefHeader(SourceLocation File); void handleImplicitCastExpr(const ImplicitCastExpr *ICE); void handlePointerOffsetting(const Expr *E); diff --git a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp index ce58f1e50f0e..35f12d25e958 100644 --- a/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp @@ -676,15 +676,15 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) { //===--------------------------------------------------------------------===// struct CallContext { - CallContext(StringRef Name, Optional DestinationPos, - Optional SourcePos, unsigned LengthPos, + CallContext(StringRef Name, std::optional DestinationPos, + std::optional SourcePos, unsigned LengthPos, bool WithIncrease) : Name(Name), DestinationPos(DestinationPos), SourcePos(SourcePos), LengthPos(LengthPos), WithIncrease(WithIncrease){}; StringRef Name; - Optional DestinationPos; - Optional SourcePos; + std::optional DestinationPos; + std::optional SourcePos; unsigned LengthPos; bool WithIncrease; }; @@ -797,7 +797,7 @@ void NotNullTerminatedResultCheck::check( return; if (WantToUseSafeFunctions && PP->isMacroDefined("__STDC_LIB_EXT1__")) { - Optional AreSafeFunctionsWanted; + std::optional AreSafeFunctionsWanted; Preprocessor::macro_iterator It = PP->macro_begin(); while (It != PP->macro_end() && !AreSafeFunctionsWanted) { diff --git a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp index 560e9a157b46..c6409c0fc2da 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.cpp @@ -69,7 +69,7 @@ static bool hasReservedDoubleUnderscore(StringRef Name, return Name.startswith("__"); } -static Optional +static std::optional 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 getUnderscoreCapitalFixup(StringRef Name) { +static std::optional 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 +static std::optional 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 +static std::optional getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace, const LangOptions &LangOpts, bool Invert, ArrayRef AllowedIdentifiers) { @@ -121,7 +121,7 @@ getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace, using FailureInfo = RenamerClangTidyCheck::FailureInfo; if (!Invert) { - Optional Info; + std::optional 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 +std::optional 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 +std::optional ReservedIdentifierCheck::getMacroFailureInfo(const Token &MacroNameTok, const SourceManager &) const { return getFailureInfoImpl(MacroNameTok.getIdentifierInfo()->getName(), true, diff --git a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h index 99c1dbe3363e..f7a8c4ccbe35 100644 --- a/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h +++ b/clang-tools-extra/clang-tidy/bugprone/ReservedIdentifierCheck.h @@ -41,10 +41,10 @@ public: void storeOptions(ClangTidyOptions::OptionMap &Opts) override; private: - llvm::Optional + std::optional getDeclFailureInfo(const NamedDecl *Decl, const SourceManager &SM) const override; - llvm::Optional + std::optional getMacroFailureInfo(const Token &MacroNameTok, const SourceManager &SM) const override; DiagInfo getDiagInfo(const NamingCheckId &ID, diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp index 177882777f07..f3d2e3d7d1ff 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousIncludeCheck.cpp @@ -81,7 +81,7 @@ void SuspiciousIncludePPCallbacks::InclusionDirective( SourceLocation DiagLoc = FilenameRange.getBegin().getLocWithOffset(1); - const Optional IFE = + const std::optional IFE = utils::getFileExtension(FileName, Check.ImplementationFileExtensions); if (!IFE) return; diff --git a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp index a1d04dc966ad..57d0ff62b4c1 100644 --- a/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemoryComparisonCheck.cpp @@ -17,8 +17,8 @@ namespace clang { namespace tidy { namespace bugprone { -static llvm::Optional tryEvaluateSizeExpr(const Expr *SizeExpr, - const ASTContext &Ctx) { +static std::optional 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 ComparedBits = tryEvaluateSizeExpr(SizeExpr, Ctx); + std::optional ComparedBits = tryEvaluateSizeExpr(SizeExpr, Ctx); for (unsigned int ArgIndex = 0; ArgIndex < 2; ++ArgIndex) { const Expr *ArgExpr = CE->getArg(ArgIndex); diff --git a/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp index 89d39d289816..c8976e4d07d5 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.cpp @@ -36,7 +36,7 @@ using llvm::Optional; static constexpr llvm::StringLiteral FuncID("fun"); -static Optional> +static std::optional> 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 Diagnostics; - Expected>>> + Expected>>> BlockToOutputState = dataflow::runDataflowAnalysis( *Context, Analysis, Env, [&ASTCtx, &Diagnoser, &Diagnostics]( @@ -97,7 +97,7 @@ void UncheckedOptionalAccessCheck::check( if (FuncDecl->isTemplated()) return; - if (Optional> Errors = + if (std::optional> Errors = analyzeFunction(*FuncDecl, *Result.Context, ModelOptions)) for (const SourceLocation &Loc : *Errors) diag(Loc, "unchecked access to optional value"); diff --git a/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h b/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h index 052d6c6d5a6c..4e76e5992204 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h +++ b/clang-tools-extra/clang-tidy/bugprone/UncheckedOptionalAccessCheck.h @@ -19,7 +19,8 @@ namespace tidy { namespace bugprone { /// Warns when the code is unwrapping a `std::optional`, `absl::optional`, -/// or `base::Optional` object without assuring that it contains a value. +/// or `base::std::optional` 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 diff --git a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp index 6c4fa9c55609..f8a861723231 100644 --- a/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp @@ -260,7 +260,7 @@ void UseAfterMoveFinder::getDeclRefs( llvm::SmallPtrSetImpl *DeclRefs) { DeclRefs->clear(); for (const auto &Elem : *Block) { - Optional S = Elem.getAs(); + std::optional S = Elem.getAs(); if (!S) continue; @@ -356,7 +356,7 @@ void UseAfterMoveFinder::getReinits( Stmts->clear(); DeclRefs->clear(); for (const auto &Elem : *Block) { - Optional S = Elem.getAs(); + std::optional S = Elem.getAs(); if (!S) continue; diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp index d75990823ce5..75cc360d3b78 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/InitVariablesCheck.cpp @@ -80,7 +80,7 @@ void InitVariablesCheck::check(const MatchFinder::MatchResult &Result) { return; QualType TypePtr = MatchedDecl->getType(); - llvm::Optional InitializationString; + std::optional InitializationString; bool AddMathInclude = false; if (TypePtr->isEnumeralType()) diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp index 6692baca99d5..8c7ae7326a91 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsConstantArrayIndexCheck.cpp @@ -71,7 +71,7 @@ void ProBoundsConstantArrayIndexCheck::check( if (IndexExpr->isValueDependent()) return; // We check in the specialization. - Optional Index = + std::optional Index = IndexExpr->getIntegerConstantExpr(*Result.Context); if (!Index) { SourceRange BaseRange; diff --git a/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp b/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp index 234ddd4ae936..98b48bd6fb1c 100644 --- a/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp +++ b/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp @@ -48,7 +48,7 @@ void VirtualClassDestructorCheck::registerMatchers(MatchFinder *Finder) { this); } -static Optional +static std::optional 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 NextToken = Lexer::findNextToken(VirtualEndLoc, SM, LangOpts); + std::optional NextToken = + Lexer::findNextToken(VirtualEndLoc, SM, LangOpts); if (!NextToken) return std::nullopt; SourceLocation StartOfNextToken = NextToken->getLocation(); diff --git a/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp b/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp index 1055d26e534c..36e1b3f92a15 100644 --- a/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp +++ b/clang-tools-extra/clang-tidy/google/UpgradeGoogletestCaseCheck.cpp @@ -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 +static std::optional getNewMacroName(llvm::StringRef MacroName) { std::pair ReplacementMap[] = { {"TYPED_TEST_CASE", "TYPED_TEST_SUITE"}, @@ -98,7 +98,7 @@ private: std::string Name = PP->getSpelling(MacroNameTok); - llvm::Optional Replacement = getNewMacroName(Name); + std::optional Replacement = getNewMacroName(Name); if (!Replacement) return; diff --git a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp index 7c3811ceb4da..40f5b134a37f 100644 --- a/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp @@ -505,7 +505,8 @@ static bool retrieveIntegerConstantExpr(const MatchFinder::MatchResult &Result, ConstExpr = Result.Nodes.getNodeAs(CstId); if (!ConstExpr) return false; - Optional R = ConstExpr->getIntegerConstantExpr(*Result.Context); + std::optional 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("shift-const"); assert(ShiftingConst && "Expr* 'ShiftingConst' is nullptr!"); - Optional ShiftingValue = + std::optional ShiftingValue = ShiftingConst->getIntegerConstantExpr(*Result.Context); if (!ShiftingValue) @@ -1317,7 +1318,7 @@ void RedundantExpressionCheck::check(const MatchFinder::MatchResult &Result) { const auto *AndConst = Result.Nodes.getNodeAs("and-const"); assert(AndConst && "Expr* 'AndCont' is nullptr!"); - Optional AndValue = + std::optional AndValue = AndConst->getIntegerConstantExpr(*Result.Context); if (!AndValue) return; diff --git a/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp b/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp index eaa7022321f9..6203e19edce3 100644 --- a/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp @@ -140,7 +140,7 @@ SourceLocation StaticAssertCheck::getLastParenLoc(const ASTContext *ASTCtx, const LangOptions &Opts = ASTCtx->getLangOpts(); const SourceManager &SM = ASTCtx->getSourceManager(); - llvm::Optional Buffer = + std::optional Buffer = SM.getBufferOrNone(SM.getFileID(AssertLoc)); if (!Buffer) return SourceLocation(); diff --git a/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp b/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp index 900077ee87b8..1d818c576dc2 100644 --- a/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.cpp @@ -22,8 +22,8 @@ static constexpr std::array DeprecatedTypes = { "::std::ios_base::seek_dir", "::std::ios_base::streamoff", "::std::ios_base::streampos"}; -static llvm::Optional getReplacementType(StringRef Type) { - return llvm::StringSwitch>(Type) +static std::optional getReplacementType(StringRef Type) { + return llvm::StringSwitch>(Type) .Case("io_state", "iostate") .Case("open_mode", "openmode") .Case("seek_dir", "seekdir") diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp index 2db958ce8e69..51de77ba4dd5 100644 --- a/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp @@ -672,7 +672,7 @@ void LoopConvertCheck::doConversion( CharSourceRange::getTokenRange(ParenRange), Range)); if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) { - if (Optional Insertion = Inserter.createIncludeInsertion( + if (std::optional Insertion = Inserter.createIncludeInsertion( Context->getSourceManager().getFileID(Loop->getBeginLoc()), getReverseHeader())) FixIts.push_back(*Insertion); diff --git a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp index 7253b1daf6ae..0cad244bd038 100644 --- a/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp +++ b/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp @@ -445,7 +445,7 @@ static bool arrayMatchesBoundExpr(ASTContext *Context, Context->getAsConstantArrayType(ArrayType); if (!ConstType) return false; - Optional ConditionSize = + std::optional ConditionSize = ConditionExpr->getIntegerConstantExpr(*Context); if (!ConditionSize) return false; diff --git a/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp b/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp index fd96cb2ede97..6c35e24177a3 100644 --- a/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ReplaceDisallowCopyAndAssignMacroCheck.cpp @@ -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 Next = Lexer::findNextToken( + std::optional Next = Lexer::findNextToken( MacroLoc.getEnd(), PP.getSourceManager(), PP.getLangOpts()); return !(Next && Next->is(tok::semi)); } diff --git a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp index adf070866893..aac7c8866e1e 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp @@ -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 = utils::lexer::findNextTokenSkippingComments( + std::optional Token = utils::lexer::findNextTokenSkippingComments( UnifiedEnd, Result.Context->getSourceManager(), Result.Context->getLangOpts()); StringRef Replacement = diff --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp index 6023fddb75ad..070ba9a5451c 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp @@ -178,7 +178,7 @@ static bool isSpecifier(Token T) { tok::kw_static, tok::kw_friend, tok::kw_virtual); } -static llvm::Optional +static std::optional 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> +std::optional> 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 CT = classifyToken(F, *PP, T)) + if (std::optional 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> MaybeTokens = + std::optional> 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> MaybeTokens = + std::optional> MaybeTokens = classifyTokensBeforeFunctionName(F, Ctx, SM, LangOpts); if (!MaybeTokens) return; diff --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h index fa9dd407233d..e28e0be7f45a 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h +++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h @@ -45,7 +45,7 @@ private: SourceLocation findTrailingReturnTypeSourceLocation( const FunctionDecl &F, const FunctionTypeLoc &FTL, const ASTContext &Ctx, const SourceManager &SM, const LangOptions &LangOpts); - llvm::Optional> + std::optional> classifyTokensBeforeFunctionName(const FunctionDecl &F, const ASTContext &Ctx, const SourceManager &SM, const LangOptions &LangOpts); diff --git a/clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h b/clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h index 676654c2c271..6c3323150e5c 100644 --- a/clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h +++ b/clang-tools-extra/clang-tidy/mpi/BufferDerefCheck.h @@ -45,7 +45,7 @@ private: enum class IndirectionType : unsigned char { Pointer, Array }; - Optional FuncClassifier; + std::optional FuncClassifier; }; } // namespace mpi diff --git a/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h b/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h index 261fec40160b..d27e27837b3b 100644 --- a/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h +++ b/clang-tools-extra/clang-tidy/mpi/TypeMismatchCheck.h @@ -46,7 +46,7 @@ private: ArrayRef BufferExprs, ArrayRef MPIDatatypes, const LangOptions &LO); - Optional FuncClassifier; + std::optional FuncClassifier; }; } // namespace mpi diff --git a/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp b/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp index 5127eaa55795..cd979a61cfd0 100644 --- a/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp +++ b/clang-tools-extra/clang-tidy/objc/NSInvocationArgumentLifetimeCheck.cpp @@ -52,7 +52,7 @@ AST_POLYMORPHIC_MATCHER(isObjCManagedLifetime, QT.getQualifiers().getObjCLifetime() > Qualifiers::OCL_ExplicitNone; } -static llvm::Optional +static std::optional 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 +static std::optional 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 Hint = + if (std::optional Hint = fixItHintReplacementForOwnershipString(VarDeclText, Range, WeakText)) return Hint; - if (llvm::Optional Hint = fixItHintReplacementForOwnershipString( + if (std::optional Hint = fixItHintReplacementForOwnershipString( VarDeclText, Range, StrongText)) return Hint; diff --git a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp index 190524720949..427e9f0792f2 100644 --- a/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp +++ b/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.cpp @@ -22,7 +22,7 @@ namespace performance { namespace { -llvm::Optional makeCharacterLiteral(const StringLiteral *Literal) { +std::optional makeCharacterLiteral(const StringLiteral *Literal) { std::string Result; { llvm::raw_string_ostream OS(Result); diff --git a/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp b/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp index d2899852bf13..8ffbd9f3fd6b 100644 --- a/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp +++ b/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp @@ -82,7 +82,7 @@ bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl &LoopVar, } else if (!LoopVar.getType().isConstQualified()) { return false; } - llvm::Optional Expensive = + std::optional 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 Fix = utils::fixit::addQualifierToVarDecl( + if (std::optional 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 Expensive = + std::optional 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 Fix = utils::fixit::addQualifierToVarDecl( + if (std::optional Fix = utils::fixit::addQualifierToVarDecl( LoopVar, Context, DeclSpec::TQ::TQ_const)) Diag << *Fix << utils::fixit::changeVarDeclToReference(LoopVar, Context); diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp index 249c00265da9..7cdd4d3fb001 100644 --- a/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp +++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp @@ -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 Fix = utils::fixit::addQualifierToVarDecl( + if (std::optional Fix = utils::fixit::addQualifierToVarDecl( Var, Context, DeclSpec::TQ::TQ_const)) Diagnostic << *Fix; } } -llvm::Optional firstLocAfterNewLine(SourceLocation Loc, - SourceManager &SM) { +std::optional 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 PastNewLine = + std::optional PastNewLine = firstLocAfterNewLine(Stmt.getEndLoc(), SM); if (Tok && PastNewLine) { auto BeforeFirstTokenAfterComment = Tok->getLocation().getLocWithOffset(-1); diff --git a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp index c3f742e06d09..6afe8fe555bf 100644 --- a/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp +++ b/clang-tools-extra/clang-tidy/performance/UnnecessaryValueParamCheck.cpp @@ -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 Fix = utils::fixit::addQualifierToVarDecl( + if (std::optional Fix = utils::fixit::addQualifierToVarDecl( CurrentParam, *Result.Context, DeclSpec::TQ::TQ_const)) Diag << *Fix; } diff --git a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp index e1ad21aaa3ab..4196ef8f2d92 100644 --- a/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.cpp @@ -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 +static std::optional 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 Tok = findConstToRemove(Def, MatchResult); + std::optional 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 T = findConstToRemove(Decl, MatchResult)) + if (std::optional T = findConstToRemove(Decl, MatchResult)) Result.Hints.push_back(FixItHint::CreateRemoval( CharSourceRange::getCharRange(T->getLocation(), T->getEndLoc()))); else diff --git a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp index 416952cda806..6da558e6f24b 100644 --- a/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/FunctionCognitiveComplexityCheck.cpp @@ -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; + using OBO = std::optional; std::stack> 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 BinOpCopy(CurrentBinaryOperator); + const std::optional BinOpCopy( + CurrentBinaryOperator); // Record the operator that we are currently processing and traverse it. CurrentBinaryOperator = Op->getOpcode(); diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp index 6aaa46d1c787..7f9004ae26d4 100644 --- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp @@ -229,7 +229,7 @@ static StringRef const HungarainNotationUserDefinedTypes[] = { // clang-format on IdentifierNamingCheck::NamingStyle::NamingStyle( - llvm::Optional Case, + std::optional 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, 0> Styles; + SmallVector, 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> Styles = MainFileStyle->getStyles(); + ArrayRef> 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> NamingStyles, + ArrayRef> 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 +std::optional IdentifierNamingCheck::getFailureInfo( StringRef Type, StringRef Name, const NamedDecl *ND, SourceLocation Location, - ArrayRef> NamingStyles, + ArrayRef> 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 +std::optional 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 +std::optional IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok, const SourceManager &SM) const { SourceLocation Loc = MacroNameTok.getLocation(); diff --git a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h index a3ff2d55fa77..5b9087c856cf 100644 --- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h +++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.h @@ -58,7 +58,7 @@ public: struct HungarianNotationOption { HungarianNotationOption() : HPType(HungarianPrefixType::HPT_Off) {} - llvm::Optional Case; + std::optional Case; HungarianPrefixType HPType; llvm::StringMap General; llvm::StringMap CString; @@ -70,14 +70,14 @@ public: struct NamingStyle { NamingStyle() = default; - NamingStyle(llvm::Optional Case, const std::string &Prefix, + NamingStyle(std::optional 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 Case; + std::optional 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> &&Styles, + FileStyle(SmallVectorImpl> &&Styles, HungarianNotationOption HNOption, bool IgnoreMainLike) : Styles(std::move(Styles)), HNOption(std::move(HNOption)), IsActive(true), IgnoreMainLikeFunctions(IgnoreMainLike) {} - ArrayRef> getStyles() const { + ArrayRef> getStyles() const { assert(IsActive); return Styles; } @@ -140,7 +140,7 @@ public: bool isIgnoringMainLikeFunction() const { return IgnoreMainLikeFunctions; } private: - SmallVector, 0> Styles; + SmallVector, 0> Styles; HungarianNotationOption HNOption; bool IsActive; bool IgnoreMainLikeFunctions; @@ -169,13 +169,13 @@ public: StyleKind findStyleKind( const NamedDecl *D, - ArrayRef> NamingStyles, + ArrayRef> NamingStyles, bool IgnoreMainLikeFunctions) const; - llvm::Optional getFailureInfo( + std::optional getFailureInfo( StringRef Type, StringRef Name, const NamedDecl *ND, SourceLocation Location, - ArrayRef> NamingStyles, + ArrayRef> NamingStyles, const IdentifierNamingCheck::HungarianNotationOption &HNOption, StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const; @@ -183,10 +183,10 @@ public: bool IncludeMainLike) const; private: - llvm::Optional + std::optional getDeclFailureInfo(const NamedDecl *Decl, const SourceManager &SM) const override; - llvm::Optional + std::optional getMacroFailureInfo(const Token &MacroNameTok, const SourceManager &SM) const override; DiagInfo getDiagInfo(const NamingCheckId &ID, diff --git a/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp b/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp index bc3d40db1c6d..1a4c6ff83b6a 100644 --- a/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/IsolateDeclarationCheck.cpp @@ -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> +static std::optional> 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> +static std::optional> collectSourceRanges(llvm::ArrayRef Ranges, const SourceManager &SM, const LangOptions &LangOpts) { std::vector Snippets; @@ -252,12 +252,12 @@ void IsolateDeclarationCheck::check(const MatchFinder::MatchResult &Result) { diag(WholeDecl->getBeginLoc(), "multiple declarations in a single statement reduces readability"); - Optional> PotentialRanges = + std::optional> PotentialRanges = declRanges(WholeDecl, *Result.SourceManager, getLangOpts()); if (!PotentialRanges) return; - Optional> PotentialSnippets = collectSourceRanges( + std::optional> PotentialSnippets = collectSourceRanges( *PotentialRanges, *Result.SourceManager, getLangOpts()); if (!PotentialSnippets) diff --git a/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp b/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp index c53565c26040..270a527ba762 100644 --- a/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp @@ -46,7 +46,7 @@ static bool locationsInSameFile(const SourceManager &Sources, Sources.getFileID(Loc1) == Sources.getFileID(Loc2); } -static llvm::Optional +static std::optional 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 T = utils::lexer::findNextTokenSkippingComments( + while (std::optional 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 NamespaceNameAsWritten = + std::optional NamespaceNameAsWritten = getNamespaceNameAsWritten(LBraceLoc, Sources, getLangOpts()); if (!NamespaceNameAsWritten) return; diff --git a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp index c2ec9312bd70..630eff00e048 100644 --- a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp @@ -29,8 +29,8 @@ AST_MATCHER_P(QualType, hasUnqualifiedType, enum class Qualifier { Const, Volatile, Restrict }; -llvm::Optional findQualToken(const VarDecl *Decl, Qualifier Qual, - const MatchFinder::MatchResult &Result) { +std::optional 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 findQualToken(const VarDecl *Decl, Qualifier Qual, *Result.SourceManager); } -llvm::Optional +std::optional getTypeSpecifierLocation(const VarDecl *Var, const MatchFinder::MatchResult &Result) { SourceRange TypeSpecifier( @@ -75,8 +75,8 @@ getTypeSpecifierLocation(const VarDecl *Var, return TypeSpecifier; } -llvm::Optional mergeReplacementRange(SourceRange &TypeSpecifier, - const Token &ConstToken) { +std::optional 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("auto")) { SourceRange TypeSpecifier; - if (llvm::Optional TypeSpec = + if (std::optional TypeSpec = getTypeSpecifierLocation(Var, Result)) { TypeSpecifier = *TypeSpec; } else @@ -171,10 +171,10 @@ void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) { llvm::SmallVector RemoveQualifiersRange; auto CheckQualifier = [&](bool IsPresent, Qualifier Qual) { if (IsPresent) { - llvm::Optional Token = findQualToken(Var, Qual, Result); + std::optional Token = findQualToken(Var, Qual, Result); if (!Token || Token->getLocation().isMacroID()) return true; // Disregard this VarDecl. - if (llvm::Optional Result = + if (std::optional 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 = - findQualToken(Var, Qualifier::Const, Result); + std::optional Token = findQualToken(Var, Qualifier::Const, Result); if (!Token || Token->getLocation().isMacroID()) return; } if (Var->getType().isLocalVolatileQualified()) { - llvm::Optional Token = + std::optional Token = findQualToken(Var, Qualifier::Volatile, Result); if (!Token || Token->getLocation().isMacroID()) return; } if (Var->getType().isLocalRestrictQualified()) { - llvm::Optional Token = + std::optional Token = findQualToken(Var, Qualifier::Restrict, Result); if (!Token || Token->getLocation().isMacroID()) return; } - if (llvm::Optional TypeSpec = + if (std::optional 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 TypeSpec = + if (std::optional TypeSpec = getTypeSpecifierLocation(Var, Result)) { if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() || TypeSpec->getEnd().isMacroID()) diff --git a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp index de250bbc6ce9..3e020377f16e 100644 --- a/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/RedundantStringInitCheck.cpp @@ -41,7 +41,7 @@ getConstructExpr(const CXXCtorInitializer &CtorInit) { return dyn_cast(InitExpr); } -static llvm::Optional +static std::optional 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 RemovalRange = + if (std::optional RemovalRange = getConstructExprArgRange(*Construct)) diag(CtorInit->getMemberLocation(), "redundant string initialization") << FixItHint::CreateRemoval(*RemovalRange); diff --git a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp index 5e96a4917b07..18a3bf6aa639 100644 --- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp @@ -298,7 +298,7 @@ public: } // Extracts a bool if an expression is (true|false|!true|!false); - static Optional getAsBoolLiteral(const Expr *E, bool FilterMacro) { + static std::optional getAsBoolLiteral(const Expr *E, bool FilterMacro) { if (const auto *Bool = dyn_cast(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 Res = getAsBoolLiteral( + if (std::optional Res = getAsBoolLiteral( UnaryOp->getSubExpr()->IgnoreImplicit(), FilterMacro)) return !*Res; } @@ -330,7 +330,7 @@ public: const auto *RS = dyn_cast(S); if (!RS || !RS->getRetValue()) return {}; - if (Optional Ret = + if (std::optional 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 = getAsBoolLiteral(Cond, true)) { + if (std::optional Bool = getAsBoolLiteral(Cond, true)) { if (*Bool) Check->replaceWithThenStatement(Context, If, Cond); else @@ -400,7 +400,7 @@ public: const auto *BO = dyn_cast(S); if (!BO || BO->getOpcode() != BO_Assign) return {}; - Optional RightasBool = + std::optional RightasBool = getAsBoolLiteral(BO->getRHS()->IgnoreImplicit(), false); if (!RightasBool) return {}; @@ -439,9 +439,9 @@ public: * Condition ? true : false; -> Condition * Condition ? false : true; -> !Condition; */ - if (Optional Then = + if (std::optional Then = getAsBoolLiteral(Cond->getTrueExpr()->IgnoreImplicit(), false)) { - if (Optional Else = + if (std::optional 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 &Fixes, const ASTContext &Ctx, const Expr *E, - Optional OuterBO); + std::optional 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 &Fixes, - const ASTContext &Ctx, - const BinaryOperator *BinOp, - Optional OuterBO, - const ParenExpr *Parens = nullptr) { +static bool +flipDemorganBinaryOperator(SmallVectorImpl &Fixes, + const ASTContext &Ctx, const BinaryOperator *BinOp, + std::optional OuterBO, + const ParenExpr *Parens = nullptr) { switch (BinOp->getOpcode()) { case BO_LAnd: case BO_LOr: { @@ -871,7 +871,7 @@ static bool flipDemorganBinaryOperator(SmallVectorImpl &Fixes, static bool flipDemorganSide(SmallVectorImpl &Fixes, const ASTContext &Ctx, const Expr *E, - Optional OuterBO) { + std::optional OuterBO) { if (isa(E) && cast(E)->getOpcode() == UO_LNot) { // if we have a not operator, '!a', just remove the '!'. if (cast(E)->getOperatorLoc().isMacroID()) diff --git a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp index 8272a550249d..3972dc3d4d48 100644 --- a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.cpp @@ -582,8 +582,8 @@ bool SuspiciousCallArgumentCheck::isHeuristicEnabled(Heuristic H) const { return llvm::is_contained(AppliedHeuristics, H); } -Optional SuspiciousCallArgumentCheck::getBound(Heuristic H, - BoundKind BK) const { +std::optional +SuspiciousCallArgumentCheck::getBound(Heuristic H, BoundKind BK) const { auto Idx = static_cast(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 GotBound = getBound(H, BK)) + if (std::optional GotBound = getBound(H, BK)) Threshold = *GotBound; switch (H) { diff --git a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h index 698d9cf52c1c..ec48b8c439ef 100644 --- a/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h +++ b/clang-tools-extra/clang-tidy/readability/SuspiciousCallArgumentCheck.h @@ -72,7 +72,7 @@ private: llvm::StringMap AbbreviationDictionary; bool isHeuristicEnabled(Heuristic H) const; - Optional getBound(Heuristic H, BoundKind BK) const; + std::optional getBound(Heuristic H, BoundKind BK) const; // Runtime information of the currently analyzed function call. SmallVector ArgTypes; diff --git a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp index e6fe75799c32..b40c841dd794 100644 --- a/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/UppercaseLiteralSuffixCheck.cpp @@ -61,11 +61,11 @@ constexpr llvm::StringLiteral FloatingLiteralCheck::Suffixes; struct NewSuffix { SourceRange LiteralLocation; StringRef OldSuffix; - llvm::Optional FixIt; + std::optional FixIt; }; -llvm::Optional getMacroAwareLocation(SourceLocation Loc, - const SourceManager &SM) { +std::optional 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 getMacroAwareLocation(SourceLocation Loc, return SpellingLoc; } -llvm::Optional getMacroAwareSourceRange(SourceRange Loc, - const SourceManager &SM) { - llvm::Optional Begin = +std::optional getMacroAwareSourceRange(SourceRange Loc, + const SourceManager &SM) { + std::optional Begin = getMacroAwareLocation(Loc.getBegin(), SM); - llvm::Optional End = getMacroAwareLocation(Loc.getEnd(), SM); + std::optional End = getMacroAwareLocation(Loc.getEnd(), SM); if (!Begin || !End) return std::nullopt; return SourceRange(*Begin, *End); } -llvm::Optional +std::optional getNewSuffix(llvm::StringRef OldSuffix, const std::vector &NewSuffixes) { // If there is no config, just uppercase the entirety of the suffix. @@ -105,7 +105,7 @@ getNewSuffix(llvm::StringRef OldSuffix, } template -llvm::Optional +std::optional shouldReplaceLiteralSuffix(const Expr &Literal, const std::vector &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 Range = + std::optional 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 NewSuffix = + std::optional NewSuffix = getNewSuffix(ReplacementDsc.OldSuffix, NewSuffixes); if (!NewSuffix || ReplacementDsc.OldSuffix == *NewSuffix) return std::nullopt; // The suffix was already the way it should be. diff --git a/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp b/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp index 3ca854dba67f..ae10be607a2f 100644 --- a/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp +++ b/clang-tools-extra/clang-tidy/utils/ExprSequence.cpp @@ -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 S = Elem.getAs()) + if (std::optional S = Elem.getAs()) Map[S->getStmt()] = B; } } diff --git a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp index 6b1fe062fdd7..4e01409d4976 100644 --- a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.cpp @@ -54,7 +54,7 @@ bool parseFileExtensions(StringRef AllFileExtensions, return true; } -llvm::Optional +std::optional getFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions) { StringRef Extension = llvm::sys::path::extension(FileName); if (Extension.empty()) diff --git a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h index a79cf9a45a12..ed1c05ed2bba 100644 --- a/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h +++ b/clang-tools-extra/clang-tidy/utils/FileExtensionsUtils.h @@ -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 +std::optional getFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions); /// Decides whether a file has one of the specified file extensions. diff --git a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp index 2e96f29ffb45..62ba13772323 100644 --- a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp @@ -42,7 +42,7 @@ static bool locDangerous(SourceLocation S) { return S.isInvalid() || S.isMacroID(); } -static Optional +static std::optional 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 fixIfNotDangerous(SourceLocation Loc, - StringRef Text) { +static std::optional 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 changeValue(const VarDecl &Var, - DeclSpec::TQ Qualifier, - QualifierTarget QualTarget, - QualifierPolicy QualPolicy, - const ASTContext &Context) { +static std::optional 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 IgnoredParens = + std::optional IgnoredParens = skipLParensBackwards(Var.getLocation(), Context); if (IgnoredParens) @@ -99,20 +99,20 @@ static Optional changeValue(const VarDecl &Var, llvm_unreachable("Unknown QualifierPolicy enum"); } -static Optional changePointerItself(const VarDecl &Var, - DeclSpec::TQ Qualifier, - const ASTContext &Context) { +static std::optional changePointerItself(const VarDecl &Var, + DeclSpec::TQ Qualifier, + const ASTContext &Context) { if (locDangerous(Var.getLocation())) return std::nullopt; - Optional IgnoredParens = + std::optional IgnoredParens = skipLParensBackwards(Var.getLocation(), Context); if (IgnoredParens) return fixIfNotDangerous(*IgnoredParens, buildQualifier(Qualifier)); return std::nullopt; } -static Optional +static std::optional 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 IgnoredParens = + std::optional 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 +static std::optional 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 IgnoredParens = + std::optional 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 addQualifierToVarDecl(const VarDecl &Var, - const ASTContext &Context, - DeclSpec::TQ Qualifier, - QualifierTarget QualTarget, - QualifierPolicy QualPolicy) { +std::optional addQualifierToVarDecl(const VarDecl &Var, + const ASTContext &Context, + DeclSpec::TQ Qualifier, + QualifierTarget QualTarget, + QualifierPolicy QualPolicy) { assert((QualPolicy == QualifierPolicy::Left || QualPolicy == QualifierPolicy::Right) && "Unexpected Insertion Policy"); diff --git a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.h b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.h index ec2ed50d9c7d..3ce07195c5a0 100644 --- a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.h +++ b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.h @@ -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 +std::optional addQualifierToVarDecl(const VarDecl &Var, const ASTContext &Context, DeclSpec::TQ Qualifier, QualifierTarget CT = QualifierTarget::Pointee, diff --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp index ced2a73aa768..58afc47fc69e 100644 --- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp +++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.cpp @@ -68,7 +68,7 @@ IncludeSorter &IncludeInserter::getOrCreate(FileID FileID) { return *Entry; } -llvm::Optional +std::optional 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 +std::optional IncludeInserter::createMainFileIncludeInsertion(StringRef Header) { assert(SourceMgr && "SourceMgr shouldn't be null; did you remember to call " "registerPreprocessor()?"); diff --git a/clang-tools-extra/clang-tidy/utils/IncludeInserter.h b/clang-tools-extra/clang-tidy/utils/IncludeInserter.h index 0f4ba11acb05..75e6ddf5948b 100644 --- a/clang-tools-extra/clang-tidy/utils/IncludeInserter.h +++ b/clang-tools-extra/clang-tidy/utils/IncludeInserter.h @@ -72,15 +72,15 @@ public: /// inclusion directive, otherwise uses quotes. /// Returns ``std::nullopt`` on error or if the inclusion directive already /// exists. - llvm::Optional createIncludeInsertion(FileID FileID, - llvm::StringRef Header); + std::optional 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 + std::optional createMainFileIncludeInsertion(llvm::StringRef Header); IncludeSorter::IncludeStyle getStyle() const { return Style; } diff --git a/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp b/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp index 5b25d10d031a..dbb3b38b5aa4 100644 --- a/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp +++ b/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp @@ -150,8 +150,8 @@ void IncludeSorter::addInclude(StringRef FileName, bool IsAngled, IncludeBucket[Kind].push_back(FileName.str()); } -Optional IncludeSorter::createIncludeInsertion(StringRef FileName, - bool IsAngled) { +std::optional +IncludeSorter::createIncludeInsertion(StringRef FileName, bool IsAngled) { std::string IncludeStmt; if (Style == IncludeStyle::IS_Google_ObjC) { IncludeStmt = IsAngled diff --git a/clang-tools-extra/clang-tidy/utils/IncludeSorter.h b/clang-tools-extra/clang-tidy/utils/IncludeSorter.h index 21fe5e48219c..3ee924e4de84 100644 --- a/clang-tools-extra/clang-tidy/utils/IncludeSorter.h +++ b/clang-tools-extra/clang-tidy/utils/IncludeSorter.h @@ -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 createIncludeInsertion(StringRef FileName, bool IsAngled); + std::optional createIncludeInsertion(StringRef FileName, + bool IsAngled); private: typedef SmallVector SourceRangeVector; diff --git a/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp b/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp index 8bdbc1d19b9a..413ca683ee70 100644 --- a/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp +++ b/clang-tools-extra/clang-tidy/utils/LexerUtils.cpp @@ -78,10 +78,10 @@ SourceLocation findNextTerminator(SourceLocation Start, const SourceManager &SM, return findNextAnyTokenKind(Start, SM, LangOpts, tok::comma, tok::semi); } -Optional findNextTokenSkippingComments(SourceLocation Start, - const SourceManager &SM, - const LangOptions &LangOpts) { - Optional CurrentToken; +std::optional +findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM, + const LangOptions &LangOpts) { + std::optional 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 Tok = Lexer::findNextToken(Loc, SM, LangOpts); + std::optional Tok = Lexer::findNextToken(Loc, SM, LangOpts); if (!Tok) return true; @@ -112,10 +112,10 @@ bool rangeContainsExpansionsOrDirectives(SourceRange Range, return false; } -llvm::Optional getQualifyingToken(tok::TokenKind TK, - CharSourceRange Range, - const ASTContext &Context, - const SourceManager &SM) { +std::optional 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 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 LastMatchBeforeTemplate; - llvm::Optional LastMatchAfterTemplate; + std::optional LastMatchBeforeTemplate; + std::optional 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 NextTok = + std::optional 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 NextTok = findNextTokenSkippingComments(EndLoc, SM, LangOpts); + std::optional NextTok = + findNextTokenSkippingComments(EndLoc, SM, LangOpts); // Testing for semicolon again avoids some issues with macros. if (NextTok && NextTok->is(tok::TokenKind::semi)) diff --git a/clang-tools-extra/clang-tidy/utils/LexerUtils.h b/clang-tools-extra/clang-tidy/utils/LexerUtils.h index f67e0cb96ea9..7af487dd0d74 100644 --- a/clang-tools-extra/clang-tidy/utils/LexerUtils.h +++ b/clang-tools-extra/clang-tidy/utils/LexerUtils.h @@ -68,7 +68,8 @@ SourceLocation findNextAnyTokenKind(SourceLocation Start, const LangOptions &LangOpts, TokenKind TK, TokenKinds... TKs) { while (true) { - Optional CurrentToken = Lexer::findNextToken(Start, SM, LangOpts); + std::optional 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 findNextTokenSkippingComments(SourceLocation Start, - const SourceManager &SM, - const LangOptions &LangOpts); +std::optional 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 getQualifyingToken(tok::TokenKind TK, - CharSourceRange Range, - const ASTContext &Context, - const SourceManager &SM); +std::optional 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. diff --git a/clang-tools-extra/clang-tidy/utils/Matchers.h b/clang-tools-extra/clang-tidy/utils/Matchers.h index 5a0e4599abf9..28c9389da716 100644 --- a/clang-tools-extra/clang-tidy/utils/Matchers.h +++ b/clang-tools-extra/clang-tidy/utils/Matchers.h @@ -24,7 +24,7 @@ AST_MATCHER(BinaryOperator, isRelationalOperator) { AST_MATCHER(BinaryOperator, isEqualityOperator) { return Node.isEqualityOp(); } AST_MATCHER(QualType, isExpensiveToCopy) { - llvm::Optional IsExpensive = + std::optional IsExpensive = utils::type_traits::isExpensiveToCopy(Node, Finder->getASTContext()); return IsExpensive && *IsExpensive; } diff --git a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp index 71a06f8e8e66..93561232fe7a 100644 --- a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp +++ b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp @@ -27,7 +27,7 @@ AST_MATCHER_P(NamespaceAliasDecl, hasTargetNamespace, return innerMatcher.matches(*Node.getNamespace(), Finder, Builder); } -Optional +std::optional NamespaceAliaser::createAlias(ASTContext &Context, const Stmt &Statement, StringRef Namespace, const std::vector &Abbreviations) { diff --git a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h index 934ce1341dc9..f655cfb9946c 100644 --- a/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h +++ b/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.h @@ -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 + std::optional createAlias(ASTContext &Context, const Stmt &Statement, llvm::StringRef Namespace, const std::vector &Abbreviations); diff --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp index 80a500592333..e3c22c357ec7 100644 --- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.cpp @@ -446,7 +446,7 @@ void RenamerClangTidyCheck::check(const MatchFinder::MatchResult &Result) { if (isa(Decl)) return; - Optional MaybeFailure = + std::optional 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 MaybeFailure = + std::optional MaybeFailure = getMacroFailureInfo(MacroNameTok, SourceMgr); if (!MaybeFailure) return; diff --git a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h index 2f3b79e73a1c..9b9f3a3c3e7f 100644 --- a/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h +++ b/clang-tools-extra/clang-tidy/utils/RenamerClangTidyCheck.h @@ -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 + virtual std::optional 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 + virtual std::optional getMacroFailureInfo(const Token &MacroNameTok, const SourceManager &SM) const = 0; diff --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp index b5e4b2b74a32..f69be2f6dcbd 100644 --- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp +++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp @@ -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>(const LangOptions &, - const OptionsView &)> + std::function>( + const LangOptions &, const OptionsView &)> MakeRule, StringRef Name, ClangTidyContext *Context) : TransformerClangTidyCheck(Name, Context) { - if (Optional> R = + if (std::optional> R = MakeRule(getLangOpts(), Options)) setRule(std::move(*R)); } diff --git a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h index 8ba15297cd95..f0868f689f08 100644 --- a/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h +++ b/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h @@ -50,7 +50,7 @@ public: /// /// See \c setRule for constraints on the rule. TransformerClangTidyCheck( - std::function>( + std::function>( const LangOptions &, const OptionsView &)> MakeRule, StringRef Name, ClangTidyContext *Context); diff --git a/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp b/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp index 70a6ca17769f..0dbbd5279368 100644 --- a/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp +++ b/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp @@ -39,8 +39,8 @@ bool hasDeletedCopyConstructor(QualType Type) { } // namespace -llvm::Optional isExpensiveToCopy(QualType Type, - const ASTContext &Context) { +std::optional isExpensiveToCopy(QualType Type, + const ASTContext &Context) { if (Type->isDependentType() || Type->isIncompleteType()) return std::nullopt; return !Type.isTriviallyCopyableType(Context) && diff --git a/clang-tools-extra/clang-tidy/utils/TypeTraits.h b/clang-tools-extra/clang-tidy/utils/TypeTraits.h index 37db6ef24e8e..52751393ac6d 100644 --- a/clang-tools-extra/clang-tidy/utils/TypeTraits.h +++ b/clang-tools-extra/clang-tidy/utils/TypeTraits.h @@ -19,8 +19,7 @@ namespace utils { namespace type_traits { /// Returns `true` if `Type` is expensive to copy. -llvm::Optional isExpensiveToCopy(QualType Type, - const ASTContext &Context); +std::optional isExpensiveToCopy(QualType Type, const ASTContext &Context); /// Returns `true` if `Type` is trivially default constructible. bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context); diff --git a/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp b/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp index 2a10d99c0dba..22bef9af47a8 100644 --- a/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp +++ b/clang-tools-extra/clang-tidy/utils/UsingInserter.cpp @@ -30,7 +30,7 @@ static StringRef getUnqualifiedName(StringRef QualifiedName) { UsingInserter::UsingInserter(const SourceManager &SourceMgr) : SourceMgr(SourceMgr) {} -Optional UsingInserter::createUsingDeclaration( +std::optional UsingInserter::createUsingDeclaration( ASTContext &Context, const Stmt &Statement, StringRef QualifiedName) { StringRef UnqualifiedName = getUnqualifiedName(QualifiedName); const FunctionDecl *Function = getSurroundingFunction(Context, Statement); diff --git a/clang-tools-extra/clang-tidy/utils/UsingInserter.h b/clang-tools-extra/clang-tidy/utils/UsingInserter.h index b23025bd5a78..809833a637b6 100644 --- a/clang-tools-extra/clang-tidy/utils/UsingInserter.h +++ b/clang-tools-extra/clang-tidy/utils/UsingInserter.h @@ -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 + std::optional createUsingDeclaration(ASTContext &Context, const Stmt &Statement, llvm::StringRef QualifiedName); diff --git a/clang-tools-extra/clangd/AST.cpp b/clang-tools-extra/clangd/AST.cpp index d33960a0f5cf..9576d74187bc 100644 --- a/clang-tools-extra/clangd/AST.cpp +++ b/clang-tools-extra/clangd/AST.cpp @@ -45,7 +45,7 @@ namespace clang { namespace clangd { namespace { -llvm::Optional> +std::optional> getTemplateSpecializationArgLocs(const NamedDecl &ND) { if (auto *Func = llvm::dyn_cast(&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> Args = + if (std::optional> Args = getTemplateSpecializationArgLocs(ND)) { printTemplateArgumentList(OS, *Args, Policy); } else if (auto *Cls = llvm::dyn_cast(&ND)) { @@ -564,8 +564,7 @@ public: }; } // namespace -llvm::Optional getDeducedType(ASTContext &ASTCtx, - SourceLocation Loc) { +std::optional getDeducedType(ASTContext &ASTCtx, SourceLocation Loc) { if (!Loc.isValid()) return {}; DeducedTypeVisitor V(Loc); @@ -798,11 +797,11 @@ public: ArrayRef Tail; // If the parameters were resolved to another forwarding FunctionDecl, this // is it. - Optional PackTarget; + std::optional PackTarget; }; // The output of this visitor - Optional Info; + std::optional 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 findPack(typename CallExpr::arg_range Args) { + std::optional findPack(typename CallExpr::arg_range Args) { // find the argument directly referring to the first parameter assert(Parameters.size() <= static_cast(llvm::size(Args))); for (auto Begin = Args.begin(), End = Args.end() - Parameters.size() + 1; diff --git a/clang-tools-extra/clangd/AST.h b/clang-tools-extra/clangd/AST.h index fbbee899d0ed..bdc0862e9634 100644 --- a/clang-tools-extra/clangd/AST.h +++ b/clang-tools-extra/clangd/AST.h @@ -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 getDeducedType(ASTContext &, SourceLocation Loc); +std::optional getDeducedType(ASTContext &, SourceLocation Loc); // Find the abbreviated-function-template `auto` within a type, or returns null. // Similar to getContainedAutoTypeLoc, but these `auto`s are diff --git a/clang-tools-extra/clangd/ClangdLSPServer.cpp b/clang-tools-extra/clangd/ClangdLSPServer.cpp index 7d7517679f9d..53d5a7825e46 100644 --- a/clang-tools-extra/clangd/ClangdLSPServer.cpp +++ b/clang-tools-extra/clangd/ClangdLSPServer.cpp @@ -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 Reply) { - llvm::Optional>> OldestCB; + std::optional>> OldestCB; int ID; { std::lock_guard 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 WithOffsetEncoding; + std::optional WithOffsetEncoding; if (Opts.Encoding) WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding); Server.emplace(*CDB, TFS, Opts, @@ -908,7 +908,7 @@ flattenSymbolHierarchy(llvm::ArrayRef Symbols, const URIForFile &FileURI) { std::vector Results; std::function Process = - [&](const DocumentSymbol &S, llvm::Optional ParentName) { + [&](const DocumentSymbol &S, std::optional 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 asCommand(const CodeAction &Action) { +static std::optional 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> Path) mutable { + Params](llvm::Expected> Path) mutable { if (!Path) return Reply(Path.takeError()); if (*Path) diff --git a/clang-tools-extra/clangd/ClangdLSPServer.h b/clang-tools-extra/clangd/ClangdLSPServer.h index 1b1f4ad848fa..3659fd89d2e7 100644 --- a/clang-tools-extra/clangd/ClangdLSPServer.h +++ b/clang-tools-extra/clangd/ClangdLSPServer.h @@ -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 Encoding; + std::optional Encoding; /// If set, periodically called to release memory. /// Consider malloc_trim(3) std::function MemoryCleanup = nullptr; @@ -292,9 +292,9 @@ private: // The CDB is created by the "initialize" LSP method. std::unique_ptr BaseCDB; // CDB is BaseCDB plus any commands overridden via LSP extensions. - llvm::Optional CDB; + std::optional CDB; // The ClangdServer is created by the "initialize" LSP method. - llvm::Optional Server; + std::optional Server; }; } // namespace clangd } // namespace clang diff --git a/clang-tools-extra/clangd/ClangdServer.cpp b/clang-tools-extra/clangd/ClangdServer.cpp index 5a9b2edbffec..74ad3c9847be 100644 --- a/clang-tools-extra/clangd/ClangdServer.cpp +++ b/clang-tools-extra/clangd/ClangdServer.cpp @@ -393,7 +393,7 @@ void ClangdServer::codeComplete(PathRef File, Position Pos, if (auto Reason = isCancelled()) return CB(llvm::make_error(Reason)); - llvm::Optional SpecFuzzyFind; + std::optional 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 Rng, +void ClangdServer::formatFile(PathRef File, std::optional Rng, Callback 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 NewName, + std::optional NewName, const RenameOptions &RenameOpts, Callback 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> Effect; + std::optional> 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> CB) { + PathRef Path, Callback> 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 ClangdServer::fileStats() const { } [[nodiscard]] bool -ClangdServer::blockUntilIdleForTest(llvm::Optional TimeoutSeconds) { +ClangdServer::blockUntilIdleForTest(std::optional 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 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 Timeout : - {TimeoutSeconds, TimeoutSeconds, llvm::Optional(0)}) { + for (std::optional Timeout : + {TimeoutSeconds, TimeoutSeconds, std::optional(0)}) { if (!CDB.blockUntilIdle(timeoutSeconds(Timeout))) return false; if (BackgroundIdx && !BackgroundIdx->blockUntilIdleForTest(Timeout)) diff --git a/clang-tools-extra/clangd/ClangdServer.h b/clang-tools-extra/clangd/ClangdServer.h index 097fed134464..40b9183f067d 100644 --- a/clang-tools-extra/clangd/ClangdServer.h +++ b/clang-tools-extra/clangd/ClangdServer.h @@ -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 WorkspaceRoot; + std::optional 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 ResourceDir = std::nullopt; + std::optional 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> CB); + Callback> 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 Rng, + void formatFile(PathRef File, std::optional Rng, Callback 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 NewName, + std::optional NewName, const RenameOptions &RenameOpts, Callback 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 TimeoutSeconds = 10); + blockUntilIdleForTest(std::optional 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::StringMap> CachedCompletionFuzzyFindRequestByFile; mutable std::mutex CachedCompletionFuzzyFindRequestMutex; - llvm::Optional WorkspaceRoot; - llvm::Optional IndexTasks; // for stdlib indexing. - llvm::Optional WorkScheduler; + std::optional WorkspaceRoot; + std::optional IndexTasks; // for stdlib indexing. + std::optional WorkScheduler; // Invalidation policy used for actions that we assume are "transient". TUScheduler::ASTActionInvalidation Transient; diff --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp index 42e6ef2bc231..b6d7da1b360e 100644 --- a/clang-tools-extra/clangd/CodeComplete.cpp +++ b/clang-tools-extra/clangd/CodeComplete.cpp @@ -265,7 +265,7 @@ struct CompletionCandidate { } // The best header to include if include insertion is allowed. - llvm::Optional + std::optional headerToInsertIfAllowed(const CodeCompleteOptions &Opts) const { if (Opts.InsertIncludes == CodeCompleteOptions::NeverInsert || RankedIncludeHeaders.empty()) @@ -647,7 +647,7 @@ struct SpecifiedScope { std::vector 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 UnresolvedQualifier; + std::optional 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 Patch; + const std::optional 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 Filter; // Initialized once Sema runs. + std::optional Filter; // Initialized once Sema runs. Range ReplacedRange; std::vector QueryScopes; // Initialized once Sema runs. // Initialized once QueryScopes is initialized, if there are scopes. - llvm::Optional ScopeProximity; - llvm::Optional PreferredType; // Initialized once Sema runs. + std::optional ScopeProximity; + std::optional 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 Inserter; // Available during runWithSema. - llvm::Optional FileProximity; // Initialized once Sema runs. + std::optional Inserter; // Available during runWithSema. + std::optional 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 SpecReq; + std::optional 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 fuzzyScore(const CompletionCandidate &C) { + std::optional 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 Builder; + std::optional 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 +std::optional maybeFunctionArgumentCommentStart(llvm::StringRef Content) { while (!Content.empty() && isAsciiIdentifierContinue(Content.back())) Content = Content.drop_back(); diff --git a/clang-tools-extra/clangd/CodeComplete.h b/clang-tools-extra/clangd/CodeComplete.h index e88e9b3734b2..4f7fcd7f3f8b 100644 --- a/clang-tools-extra/clangd/CodeComplete.h +++ b/clang-tools-extra/clangd/CodeComplete.h @@ -57,7 +57,7 @@ struct CodeCompleteOptions { /// If none, the implementation may choose an appropriate behavior. /// (In practice, ClangdLSPServer enables bundling if the client claims /// to supports signature help). - llvm::Optional BundleOverloads; + std::optional BundleOverloads; /// Limit the number of results returned (0 means no limit). /// If more results are available, we set CompletionList.isIncomplete. @@ -175,7 +175,7 @@ struct CodeCompletion { // Type to be displayed for this completion. std::string ReturnType; // The parsed documentation comment. - llvm::Optional Documentation; + std::optional Documentation; CompletionItemKind Kind = CompletionItemKind::Missing; // This completion item may represent several symbols that can be inserted in // the same way, such as function overloads. In this case BundleSize > 1, and @@ -194,7 +194,7 @@ struct CodeCompletion { // Empty for non-symbol completions, or when not known. std::string Header; // Present if Header should be inserted to use this item. - llvm::Optional Insertion; + std::optional Insertion; }; // All possible include headers ranked by preference. By default, the first // include is used. @@ -247,7 +247,7 @@ struct CodeCompleteResult { // Example: foo.pb^ -> foo.push_back() // ~~ // Typically matches the textEdit.range of Completions, but not guaranteed to. - llvm::Optional CompletionRange; + std::optional CompletionRange; // Usually the source will be parsed with a real C++ parser. // But heuristics may be used instead if e.g. the preamble is not ready. bool RanParser = true; @@ -260,10 +260,10 @@ raw_ostream &operator<<(raw_ostream &, const CodeCompleteResult &); struct SpeculativeFuzzyFind { /// A cached request from past code completions. /// Set by caller of `codeComplete()`. - llvm::Optional CachedReq; + std::optional CachedReq; /// The actual request used by `codeComplete()`. /// Set by `codeComplete()`. This can be used by callers to update cache. - llvm::Optional NewReq; + std::optional NewReq; /// The result is consumed by `codeComplete()` if speculation succeeded. /// NOTE: the destructor will wait for the async call to finish. std::future> Result; diff --git a/clang-tools-extra/clangd/CompileCommands.cpp b/clang-tools-extra/clangd/CompileCommands.cpp index 6669103a62dc..3b7e25789cea 100644 --- a/clang-tools-extra/clangd/CompileCommands.cpp +++ b/clang-tools-extra/clangd/CompileCommands.cpp @@ -38,7 +38,7 @@ namespace { // Query apple's `xcrun` launcher, which is the source of truth for "how should" // clang be invoked on this system. -llvm::Optional queryXcrun(llvm::ArrayRef Argv) { +std::optional queryXcrun(llvm::ArrayRef Argv) { auto Xcrun = llvm::sys::findProgramByName("xcrun"); if (!Xcrun) { log("Couldn't find xcrun. Hopefully you have a non-apple toolchain..."); @@ -118,7 +118,7 @@ std::string detectClangPath() { // On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang. // The effect of this is to set -isysroot correctly. We do the same. -llvm::Optional detectSysroot() { +std::optional detectSysroot() { #ifndef __APPLE__ return std::nullopt; #endif @@ -141,7 +141,7 @@ std::string detectStandardResourceDir() { // Where possible it should be an absolute path with sensible directory, but // with the original basename. static std::string resolveDriver(llvm::StringRef Driver, bool FollowSymlink, - llvm::Optional ClangPath) { + std::optional ClangPath) { auto SiblingOf = [&](llvm::StringRef AbsPath) { llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath); llvm::sys::path::append(Result, llvm::sys::path::filename(Driver)); @@ -256,7 +256,7 @@ void CommandMangler::operator()(tooling::CompileCommand &Command, // In practice only the extension of the file matters, so do this only when // it differs. llvm::StringRef FileExtension = llvm::sys::path::extension(File); - llvm::Optional TransferFrom; + std::optional TransferFrom; auto SawInput = [&](llvm::StringRef Input) { if (llvm::sys::path::extension(Input) != FileExtension) TransferFrom.emplace(Input); diff --git a/clang-tools-extra/clangd/CompileCommands.h b/clang-tools-extra/clangd/CompileCommands.h index 561d9ea2f9ed..eb318d18baf6 100644 --- a/clang-tools-extra/clangd/CompileCommands.h +++ b/clang-tools-extra/clangd/CompileCommands.h @@ -28,11 +28,11 @@ namespace clangd { // - injecting -isysroot flags on mac as the system clang does struct CommandMangler { // Absolute path to clang. - llvm::Optional ClangPath; + std::optional ClangPath; // Directory containing builtin headers. - llvm::Optional ResourceDir; + std::optional ResourceDir; // Root for searching for standard library (passed to -isysroot). - llvm::Optional Sysroot; + std::optional Sysroot; SystemIncludeExtractorFn SystemIncludeExtractor; // A command-mangler that doesn't know anything about the system. diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp b/clang-tools-extra/clangd/ConfigCompile.cpp index e1a511d0a082..f0cf9370fc3f 100644 --- a/clang-tools-extra/clangd/ConfigCompile.cpp +++ b/clang-tools-extra/clangd/ConfigCompile.cpp @@ -103,7 +103,7 @@ struct FragmentCompiler { std::string FragmentDirectory; bool Trusted = false; - llvm::Optional + std::optional compileRegex(const Located &Text, llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags) { std::string Anchored = "^(" + *Text + ")$"; @@ -142,7 +142,7 @@ struct FragmentCompiler { FragmentCompiler &Outer; llvm::StringRef EnumName; const Located &Input; - llvm::Optional Result; + std::optional Result; llvm::SmallVector ValidValues; public: @@ -158,7 +158,7 @@ struct FragmentCompiler { return *this; } - llvm::Optional value() { + std::optional value() { if (!Result) Outer.diag( Warning, @@ -173,7 +173,7 @@ struct FragmentCompiler { // Attempt to parse a specified string into an enum. // Yields std::nullopt and produces a diagnostic on failure. // - // Optional Value = compileEnum("Foo", Frag.Foo) + // std::optional Value = compileEnum("Foo", Frag.Foo) // .map("Foo", Enum::Foo) // .map("Bar", Enum::Bar) // .value(); @@ -291,7 +291,7 @@ struct FragmentCompiler { } if (F.CompilationDatabase) { - llvm::Optional Spec; + std::optional Spec; if (**F.CompilationDatabase == "Ancestors") { Spec.emplace(); Spec->Policy = Config::CDBSearchSpec::Ancestors; diff --git a/clang-tools-extra/clangd/Diagnostics.cpp b/clang-tools-extra/clangd/Diagnostics.cpp index 6c8cf5c52217..326df0a5e203 100644 --- a/clang-tools-extra/clangd/Diagnostics.cpp +++ b/clang-tools-extra/clangd/Diagnostics.cpp @@ -907,9 +907,9 @@ llvm::StringRef normalizeSuppressedCode(llvm::StringRef Code) { return Code; } -llvm::Optional getDiagnosticDocURI(Diag::DiagSource Source, - unsigned ID, - llvm::StringRef Name) { +std::optional getDiagnosticDocURI(Diag::DiagSource Source, + unsigned ID, + llvm::StringRef Name) { switch (Source) { case Diag::Unknown: break; diff --git a/clang-tools-extra/clangd/Diagnostics.h b/clang-tools-extra/clangd/Diagnostics.h index b1a1f0170d34..ca6b92f26dbb 100644 --- a/clang-tools-extra/clangd/Diagnostics.h +++ b/clang-tools-extra/clangd/Diagnostics.h @@ -62,7 +62,7 @@ struct DiagBase { // May be relative, absolute or even artificially constructed. std::string File; // Absolute path to containing file, if available. - llvm::Optional AbsFile; + std::optional AbsFile; clangd::Range Range; DiagnosticsEngine::Level Severity = DiagnosticsEngine::Note; @@ -128,8 +128,8 @@ CodeAction toCodeAction(const Fix &D, const URIForFile &File); int getSeverity(DiagnosticsEngine::Level L); /// Returns a URI providing more information about a particular diagnostic. -llvm::Optional getDiagnosticDocURI(Diag::DiagSource, unsigned ID, - llvm::StringRef Name); +std::optional getDiagnosticDocURI(Diag::DiagSource, unsigned ID, + llvm::StringRef Name); /// StoreDiags collects the diagnostics that can later be reported by /// clangd. It groups all notes for a diagnostic into a single Diag @@ -171,9 +171,9 @@ private: LevelAdjuster Adjuster = nullptr; DiagCallback DiagCB = nullptr; std::vector Output; - llvm::Optional LangOpts; - llvm::Optional LastDiag; - llvm::Optional LastDiagLoc; // Valid only when LastDiag is set. + std::optional LangOpts; + std::optional LastDiag; + std::optional LastDiagLoc; // Valid only when LastDiag is set. bool LastDiagOriginallyError = false; // Valid only when LastDiag is set. SourceManager *OrigSrcMgr = nullptr; diff --git a/clang-tools-extra/clangd/DraftStore.cpp b/clang-tools-extra/clangd/DraftStore.cpp index 7df70e69bdf3..66e45b0c04ce 100644 --- a/clang-tools-extra/clangd/DraftStore.cpp +++ b/clang-tools-extra/clangd/DraftStore.cpp @@ -16,7 +16,7 @@ namespace clang { namespace clangd { -llvm::Optional DraftStore::getDraft(PathRef File) const { +std::optional DraftStore::getDraft(PathRef File) const { std::lock_guard Lock(Mutex); auto It = Drafts.find(File); diff --git a/clang-tools-extra/clangd/DraftStore.h b/clang-tools-extra/clangd/DraftStore.h index a19fe55890b1..0d5204215f8c 100644 --- a/clang-tools-extra/clangd/DraftStore.h +++ b/clang-tools-extra/clangd/DraftStore.h @@ -34,7 +34,7 @@ public: /// \return Contents of the stored document. /// For untracked files, a std::nullopt is returned. - llvm::Optional getDraft(PathRef File) const; + std::optional getDraft(PathRef File) const; /// \return List of names of the drafts in this store. std::vector getActiveFiles() const; diff --git a/clang-tools-extra/clangd/DumpAST.cpp b/clang-tools-extra/clangd/DumpAST.cpp index 438733d44f13..2bf75e65a9ef 100644 --- a/clang-tools-extra/clangd/DumpAST.cpp +++ b/clang-tools-extra/clangd/DumpAST.cpp @@ -88,7 +88,7 @@ class DumpVisitor : public RecursiveASTVisitor { // Range: most nodes have getSourceRange(), with a couple of exceptions. // We only return it if it's valid at both ends and there are no macros. - template llvm::Optional getRange(const T &Node) { + template std::optional getRange(const T &Node) { SourceRange SR = getSourceRange(Node); auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(SR)); if (!Spelled) diff --git a/clang-tools-extra/clangd/ExpectedTypes.cpp b/clang-tools-extra/clangd/ExpectedTypes.cpp index 563612aa745c..deea8a50111e 100644 --- a/clang-tools-extra/clangd/ExpectedTypes.cpp +++ b/clang-tools-extra/clangd/ExpectedTypes.cpp @@ -40,8 +40,7 @@ static const Type *toEquivClass(ASTContext &Ctx, QualType T) { return T.getTypePtr(); } -static llvm::Optional -typeOfCompletion(const CodeCompletionResult &R) { +static std::optional typeOfCompletion(const CodeCompletionResult &R) { const NamedDecl *D = R.Declaration; // Templates do not have a type on their own, look at the templated decl. if (auto *Template = dyn_cast_or_null(D)) @@ -63,7 +62,7 @@ typeOfCompletion(const CodeCompletionResult &R) { } } // namespace -llvm::Optional OpaqueType::encode(ASTContext &Ctx, QualType T) { +std::optional OpaqueType::encode(ASTContext &Ctx, QualType T) { if (T.isNull()) return std::nullopt; const Type *C = toEquivClass(Ctx, T); @@ -77,12 +76,11 @@ llvm::Optional OpaqueType::encode(ASTContext &Ctx, QualType T) { OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {} -llvm::Optional OpaqueType::fromType(ASTContext &Ctx, - QualType Type) { +std::optional OpaqueType::fromType(ASTContext &Ctx, QualType Type) { return encode(Ctx, Type); } -llvm::Optional +std::optional OpaqueType::fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R) { auto T = typeOfCompletion(R); diff --git a/clang-tools-extra/clangd/ExpectedTypes.h b/clang-tools-extra/clangd/ExpectedTypes.h index 6cfd0936def6..8182e7684416 100644 --- a/clang-tools-extra/clangd/ExpectedTypes.h +++ b/clang-tools-extra/clangd/ExpectedTypes.h @@ -35,11 +35,11 @@ namespace clangd { class OpaqueType { public: /// Create a type from a code completion result. - static llvm::Optional + static std::optional fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R); /// Construct an instance from a clang::QualType. This is usually a /// PreferredType from a clang's completion context. - static llvm::Optional fromType(ASTContext &Ctx, QualType Type); + static std::optional fromType(ASTContext &Ctx, QualType Type); /// Get the raw byte representation of the type. You can only rely on the /// types being equal iff their raw representation is the same. The particular @@ -55,7 +55,7 @@ public: } private: - static llvm::Optional encode(ASTContext &Ctx, QualType Type); + static std::optional encode(ASTContext &Ctx, QualType Type); explicit OpaqueType(std::string Data); std::string Data; diff --git a/clang-tools-extra/clangd/FS.cpp b/clang-tools-extra/clangd/FS.cpp index 587b9212188c..3622d35d9d52 100644 --- a/clang-tools-extra/clangd/FS.cpp +++ b/clang-tools-extra/clangd/FS.cpp @@ -36,7 +36,7 @@ void PreambleFileStatusCache::update(const llvm::vfs::FileSystem &FS, StatCache.insert({PathStore, std::move(S)}); } -llvm::Optional +std::optional PreambleFileStatusCache::lookup(llvm::StringRef File) const { // Canonicalize to match the cached form. // Lookup tends to be first by absolute path, so no need to make absolute. diff --git a/clang-tools-extra/clangd/FS.h b/clang-tools-extra/clangd/FS.h index 96b04dc7c9e5..16a0a4997fb0 100644 --- a/clang-tools-extra/clangd/FS.h +++ b/clang-tools-extra/clangd/FS.h @@ -45,7 +45,7 @@ public: void update(const llvm::vfs::FileSystem &FS, llvm::vfs::Status S); /// \p Path is a path stored in preamble. - llvm::Optional lookup(llvm::StringRef Path) const; + std::optional lookup(llvm::StringRef Path) const; /// Returns a VFS that collects file status. /// Only cache stats for files that exist because diff --git a/clang-tools-extra/clangd/FeatureModule.h b/clang-tools-extra/clangd/FeatureModule.h index eb4232f26b06..7b6883507be3 100644 --- a/clang-tools-extra/clangd/FeatureModule.h +++ b/clang-tools-extra/clangd/FeatureModule.h @@ -138,7 +138,7 @@ protected: using OutgoingMethod = llvm::unique_function)>; private: - llvm::Optional Fac; + std::optional Fac; }; /// A FeatureModuleSet is a collection of feature modules installed in clangd. diff --git a/clang-tools-extra/clangd/FindSymbols.cpp b/clang-tools-extra/clangd/FindSymbols.cpp index 682ca79a746d..6e6dbb208fba 100644 --- a/clang-tools-extra/clangd/FindSymbols.cpp +++ b/clang-tools-extra/clangd/FindSymbols.cpp @@ -220,7 +220,7 @@ std::string getSymbolDetail(ASTContext &Ctx, const NamedDecl &ND) { return std::move(OS.str()); } -llvm::Optional declToSym(ASTContext &Ctx, const NamedDecl &ND) { +std::optional declToSym(ASTContext &Ctx, const NamedDecl &ND) { auto &SM = Ctx.getSourceManager(); SourceLocation BeginLoc = SM.getSpellingLoc(SM.getFileLoc(ND.getBeginLoc())); diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp index 37f6173d30e6..9e32fce9ab32 100644 --- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp +++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp @@ -354,7 +354,7 @@ DirectoryBasedGlobalCompilationDatabase:: DirectoryBasedGlobalCompilationDatabase:: ~DirectoryBasedGlobalCompilationDatabase() = default; -llvm::Optional +std::optional DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const { CDBLookupRequest Req; Req.FileName = File; @@ -398,7 +398,7 @@ DirectoryBasedGlobalCompilationDatabase::getDirectoryCaches( return Ret; } -llvm::Optional +std::optional DirectoryBasedGlobalCompilationDatabase::lookupCDB( CDBLookupRequest Request) const { assert(llvm::sys::path::is_absolute(Request.FileName) && @@ -476,7 +476,7 @@ class DirectoryBasedGlobalCompilationDatabase::BroadcastThread { Context Ctx; }; std::deque Queue; - llvm::Optional ActiveTask; + std::optional ActiveTask; std::thread Thread; // Must be last member. // Thread body: this is just the basic queue procesing boilerplate. @@ -725,7 +725,7 @@ bool DirectoryBasedGlobalCompilationDatabase::blockUntilIdle( return Broadcaster->blockUntilIdle(Timeout); } -llvm::Optional +std::optional DirectoryBasedGlobalCompilationDatabase::getProjectInfo(PathRef File) const { CDBLookupRequest Req; Req.FileName = File; @@ -744,9 +744,9 @@ OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base, : DelegatingCDB(Base), Mangler(std::move(Mangler)), FallbackFlags(std::move(FallbackFlags)) {} -llvm::Optional +std::optional OverlayCDB::getCompileCommand(PathRef File) const { - llvm::Optional Cmd; + std::optional Cmd; { std::lock_guard Lock(Mutex); auto It = Commands.find(removeDots(File)); @@ -772,8 +772,8 @@ tooling::CompileCommand OverlayCDB::getFallbackCommand(PathRef File) const { return Cmd; } -void OverlayCDB::setCompileCommand( - PathRef File, llvm::Optional Cmd) { +void OverlayCDB::setCompileCommand(PathRef File, + std::optional Cmd) { // We store a canonical version internally to prevent mismatches between set // and get compile commands. Also it assures clients listening to broadcasts // doesn't receive different names for the same file. @@ -801,14 +801,14 @@ DelegatingCDB::DelegatingCDB(std::unique_ptr Base) BaseOwner = std::move(Base); } -llvm::Optional +std::optional DelegatingCDB::getCompileCommand(PathRef File) const { if (!Base) return std::nullopt; return Base->getCompileCommand(File); } -llvm::Optional DelegatingCDB::getProjectInfo(PathRef File) const { +std::optional DelegatingCDB::getProjectInfo(PathRef File) const { if (!Base) return std::nullopt; return Base->getProjectInfo(File); diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.h b/clang-tools-extra/clangd/GlobalCompilationDatabase.h index 04481fa6ea22..12cf280dfd54 100644 --- a/clang-tools-extra/clangd/GlobalCompilationDatabase.h +++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.h @@ -38,11 +38,11 @@ public: virtual ~GlobalCompilationDatabase() = default; /// If there are any known-good commands for building this file, returns one. - virtual llvm::Optional + virtual std::optional getCompileCommand(PathRef File) const = 0; /// Finds the closest project to \p File. - virtual llvm::Optional getProjectInfo(PathRef File) const { + virtual std::optional getProjectInfo(PathRef File) const { return std::nullopt; } @@ -72,10 +72,10 @@ public: DelegatingCDB(const GlobalCompilationDatabase *Base); DelegatingCDB(std::unique_ptr Base); - llvm::Optional + std::optional getCompileCommand(PathRef File) const override; - llvm::Optional getProjectInfo(PathRef File) const override; + std::optional getProjectInfo(PathRef File) const override; tooling::CompileCommand getFallbackCommand(PathRef File) const override; @@ -116,12 +116,12 @@ public: /// Scans File's parents looking for compilation databases. /// Any extra flags will be added. /// Might trigger OnCommandChanged, if CDB wasn't broadcasted yet. - llvm::Optional + std::optional getCompileCommand(PathRef File) const override; /// Returns the path to first directory containing a compilation database in /// \p File's parents. - llvm::Optional getProjectInfo(PathRef File) const override; + std::optional getProjectInfo(PathRef File) const override; bool blockUntilIdle(Deadline Timeout) const override; @@ -150,7 +150,7 @@ private: std::shared_ptr CDB; ProjectInfo PI; }; - llvm::Optional lookupCDB(CDBLookupRequest Request) const; + std::optional lookupCDB(CDBLookupRequest Request) const; class BroadcastThread; std::unique_ptr Broadcaster; @@ -186,14 +186,14 @@ public: std::vector FallbackFlags = {}, CommandMangler Mangler = nullptr); - llvm::Optional + std::optional getCompileCommand(PathRef File) const override; tooling::CompileCommand getFallbackCommand(PathRef File) const override; /// Sets or clears the compilation command for a particular file. void setCompileCommand(PathRef File, - llvm::Optional CompilationCommand); + std::optional CompilationCommand); private: mutable std::mutex Mutex; diff --git a/clang-tools-extra/clangd/HeaderSourceSwitch.cpp b/clang-tools-extra/clangd/HeaderSourceSwitch.cpp index ded7a43d4ea1..2351858cc629 100644 --- a/clang-tools-extra/clangd/HeaderSourceSwitch.cpp +++ b/clang-tools-extra/clangd/HeaderSourceSwitch.cpp @@ -18,7 +18,7 @@ namespace clang { namespace clangd { -llvm::Optional getCorrespondingHeaderOrSource( +std::optional getCorrespondingHeaderOrSource( PathRef OriginalFile, llvm::IntrusiveRefCntPtr VFS) { llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx", ".c++", ".m", ".mm"}; @@ -64,9 +64,9 @@ llvm::Optional getCorrespondingHeaderOrSource( return std::nullopt; } -llvm::Optional getCorrespondingHeaderOrSource(PathRef OriginalFile, - ParsedAST &AST, - const SymbolIndex *Index) { +std::optional getCorrespondingHeaderOrSource(PathRef OriginalFile, + ParsedAST &AST, + const SymbolIndex *Index) { if (!Index) { // FIXME: use the AST to do the inference. return std::nullopt; diff --git a/clang-tools-extra/clangd/HeaderSourceSwitch.h b/clang-tools-extra/clangd/HeaderSourceSwitch.h index 1cf9da969e24..aa1d73e5807a 100644 --- a/clang-tools-extra/clangd/HeaderSourceSwitch.h +++ b/clang-tools-extra/clangd/HeaderSourceSwitch.h @@ -18,14 +18,14 @@ namespace clangd { /// Given a header file, returns the best matching source file, and vice visa. /// It only uses the filename heuristics to do the inference. -llvm::Optional getCorrespondingHeaderOrSource( +std::optional getCorrespondingHeaderOrSource( PathRef OriginalFile, llvm::IntrusiveRefCntPtr VFS); /// Given a header file, returns the best matching source file, and vice visa. /// The heuristics incorporate with the AST and the index (if provided). -llvm::Optional getCorrespondingHeaderOrSource(PathRef OriginalFile, - ParsedAST &AST, - const SymbolIndex *Index); +std::optional getCorrespondingHeaderOrSource(PathRef OriginalFile, + ParsedAST &AST, + const SymbolIndex *Index); /// Returns all indexable decls that are present in the main file of the AST. /// Exposed for unittests. diff --git a/clang-tools-extra/clangd/Headers.cpp b/clang-tools-extra/clangd/Headers.cpp index fd058e8cfd89..3e5fefb07130 100644 --- a/clang-tools-extra/clangd/Headers.cpp +++ b/clang-tools-extra/clangd/Headers.cpp @@ -235,7 +235,7 @@ void IncludeStructure::collect(const CompilerInstance &CI) { CI.getPreprocessor().addPPCallbacks(std::move(Collector)); } -llvm::Optional +std::optional IncludeStructure::getID(const FileEntry *Entry) const { // HeaderID of the main file is always 0; if (Entry == MainFileEntry) { @@ -315,7 +315,7 @@ bool IncludeInserter::shouldInsertInclude( return !Included(DeclaringHeader) && !Included(InsertedHeader.File); } -llvm::Optional +std::optional IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader, llvm::StringRef IncludingFile) const { assert(InsertedHeader.valid()); @@ -345,10 +345,10 @@ IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader, return Suggested; } -llvm::Optional +std::optional IncludeInserter::insert(llvm::StringRef VerbatimHeader, tooling::IncludeDirective Directive) const { - llvm::Optional Edit; + std::optional Edit; if (auto Insertion = Inserter.insert(VerbatimHeader.trim("\"<>"), VerbatimHeader.startswith("<"), Directive)) diff --git a/clang-tools-extra/clangd/Headers.h b/clang-tools-extra/clangd/Headers.h index 68ccf935fbd4..8a5b885a680e 100644 --- a/clang-tools-extra/clangd/Headers.h +++ b/clang-tools-extra/clangd/Headers.h @@ -72,7 +72,7 @@ struct Inclusion { unsigned HashOffset = 0; // Byte offset from start of file to #. int HashLine = 0; // Line number containing the directive, 0-indexed. SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User; - llvm::Optional HeaderID; + std::optional HeaderID; bool BehindPragmaKeep = false; // Has IWYU pragma: keep right after. }; llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Inclusion &); @@ -143,7 +143,7 @@ public: // file builds. enum class HeaderID : unsigned {}; - llvm::Optional getID(const FileEntry *Entry) const; + std::optional getID(const FileEntry *Entry) const; HeaderID getOrCreateID(FileEntryRef Entry); StringRef getRealPath(HeaderID ID) const { @@ -243,14 +243,14 @@ public: /// /// \return A quoted "path" or to be included, or std::nullopt if it /// couldn't be shortened. - llvm::Optional + std::optional calculateIncludePath(const HeaderFile &InsertedHeader, llvm::StringRef IncludingFile) const; /// Calculates an edit that inserts \p VerbatimHeader into code. If the header /// is already included, this returns std::nullopt. - llvm::Optional insert(llvm::StringRef VerbatimHeader, - tooling::IncludeDirective Directive) const; + std::optional insert(llvm::StringRef VerbatimHeader, + tooling::IncludeDirective Directive) const; private: StringRef FileName; diff --git a/clang-tools-extra/clangd/Hover.cpp b/clang-tools-extra/clangd/Hover.cpp index ca6301999f2c..456b54440b54 100644 --- a/clang-tools-extra/clangd/Hover.cpp +++ b/clang-tools-extra/clangd/Hover.cpp @@ -402,8 +402,8 @@ static llvm::FormattedNumber printHex(const llvm::APSInt &V) { return llvm::format_hex(Bits, 0); } -llvm::Optional printExprValue(const Expr *E, - const ASTContext &Ctx) { +std::optional printExprValue(const Expr *E, + const ASTContext &Ctx) { // InitListExpr has two forms, syntactic and semantic. They are the same thing // (refer to a same AST node) in most cases. // When they are different, RAV returns the syntactic form, and we should feed @@ -451,8 +451,8 @@ llvm::Optional printExprValue(const Expr *E, return Constant.Val.getAsString(Ctx, T); } -llvm::Optional printExprValue(const SelectionTree::Node *N, - const ASTContext &Ctx) { +std::optional printExprValue(const SelectionTree::Node *N, + const ASTContext &Ctx) { for (; N; N = N->Parent) { // Try to evaluate the first evaluatable enclosing expression. if (const Expr *E = N->ASTNode.get()) { @@ -471,7 +471,7 @@ llvm::Optional printExprValue(const SelectionTree::Node *N, return std::nullopt; } -llvm::Optional fieldName(const Expr *E) { +std::optional fieldName(const Expr *E) { const auto *ME = llvm::dyn_cast(E->IgnoreCasts()); if (!ME || !llvm::isa(ME->getBase()->IgnoreCasts())) return std::nullopt; @@ -482,7 +482,7 @@ llvm::Optional fieldName(const Expr *E) { } // If CMD is of the form T foo() { return FieldName; } then returns "FieldName". -llvm::Optional getterVariableName(const CXXMethodDecl *CMD) { +std::optional getterVariableName(const CXXMethodDecl *CMD) { assert(CMD->hasBody()); if (CMD->getNumParams() != 0 || CMD->isVariadic()) return std::nullopt; @@ -501,7 +501,7 @@ llvm::Optional getterVariableName(const CXXMethodDecl *CMD) { // void foo(T arg) { FieldName = std::move(arg); } // R foo(T arg) { FieldName = std::move(arg); return *this; } // then returns "FieldName" -llvm::Optional setterVariableName(const CXXMethodDecl *CMD) { +std::optional setterVariableName(const CXXMethodDecl *CMD) { assert(CMD->hasBody()); if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic()) return std::nullopt; @@ -1283,8 +1283,8 @@ markup::Document HoverInfo::present() const { // If the backtick at `Offset` starts a probable quoted range, return the range // (including the quotes). -llvm::Optional getBacktickQuoteRange(llvm::StringRef Line, - unsigned Offset) { +std::optional getBacktickQuoteRange(llvm::StringRef Line, + unsigned Offset) { assert(Line[Offset] == '`'); // The open-quote is usually preceded by whitespace. diff --git a/clang-tools-extra/clangd/Hover.h b/clang-tools-extra/clangd/Hover.h index a2c4e6094949..e63ff95b400b 100644 --- a/clang-tools-extra/clangd/Hover.h +++ b/clang-tools-extra/clangd/Hover.h @@ -33,7 +33,7 @@ struct HoverInfo { /// Pretty-printed type std::string Type; /// Desugared type - llvm::Optional AKA; + std::optional AKA; }; /// Represents parameters of a function, a template or a macro. @@ -44,11 +44,11 @@ struct HoverInfo { struct Param { /// The printable parameter type, e.g. "int", or "typename" (in /// TemplateParameters), might be std::nullopt for macro parameters. - llvm::Optional Type; + std::optional Type; /// std::nullopt for unnamed parameters. std::optional Name; /// std::nullopt if no default is provided. - llvm::Optional Default; + std::optional Default; }; /// For a variable named Bar, declared in clang::clangd::Foo::getFoo the @@ -61,13 +61,13 @@ struct HoverInfo { /// auto/decltype. /// Contains all of the enclosing namespaces, empty string means global /// namespace. - llvm::Optional NamespaceScope; + std::optional NamespaceScope; /// Remaining named contexts in symbol's qualified name, empty string means /// symbol is not local. std::string LocalScope; /// Name of the symbol, does not contain any "::". std::string Name; - llvm::Optional SymRange; + std::optional SymRange; index::SymbolKind Kind = index::SymbolKind::Unknown; std::string Documentation; /// Source code containing the definition of the symbol. @@ -78,24 +78,24 @@ struct HoverInfo { std::string AccessSpecifier; /// Printable variable type. /// Set only for variables. - llvm::Optional Type; + std::optional Type; /// Set for functions and lambdas. - llvm::Optional ReturnType; + std::optional ReturnType; /// Set for functions, lambdas and macros with parameters. - llvm::Optional> Parameters; + std::optional> Parameters; /// Set for all templates(function, class, variable). - llvm::Optional> TemplateParameters; + std::optional> TemplateParameters; /// Contains the evaluated value of the symbol if available. - llvm::Optional Value; + std::optional Value; /// Contains the byte-size of fields and types where it's interesting. - llvm::Optional Size; + std::optional Size; /// Contains the offset of fields within the enclosing class. - llvm::Optional Offset; + std::optional Offset; /// Contains the padding following a field within the enclosing class. - llvm::Optional Padding; + std::optional Padding; // Set when symbol is inside function call. Contains information extracted // from the callee definition about the argument this is passed as. - llvm::Optional CalleeArgInfo; + std::optional CalleeArgInfo; struct PassType { // How the variable is passed to callee. enum PassMode { Ref, ConstRef, Value }; @@ -106,7 +106,7 @@ struct HoverInfo { bool Converted = false; }; // Set only if CalleeArgInfo is set. - llvm::Optional CallPassType; + std::optional CallPassType; /// Produce a user-readable information. markup::Document present() const; diff --git a/clang-tools-extra/clangd/IncludeCleaner.cpp b/clang-tools-extra/clangd/IncludeCleaner.cpp index daac976a41e7..dbed805142b7 100644 --- a/clang-tools-extra/clangd/IncludeCleaner.cpp +++ b/clang-tools-extra/clangd/IncludeCleaner.cpp @@ -345,7 +345,7 @@ ReferencedLocations findReferencedLocations(ParsedAST &AST) { ReferencedFiles findReferencedFiles( const ReferencedLocations &Locs, const SourceManager &SM, llvm::function_ref HeaderResponsible, - llvm::function_ref(FileID)> UmbrellaHeader) { + llvm::function_ref(FileID)> UmbrellaHeader) { std::vector Sorted{Locs.User.begin(), Locs.User.end()}; llvm::sort(Sorted); // Group by FileID. ReferencedFilesBuilder Builder(SM); @@ -390,7 +390,7 @@ ReferencedFiles findReferencedFiles(const ReferencedLocations &Locs, [&SM, &Includes](FileID ID) { return headerResponsible(ID, SM, Includes); }, - [&SM, &CanonIncludes](FileID ID) -> Optional { + [&SM, &CanonIncludes](FileID ID) -> std::optional { auto Entry = SM.getFileEntryRefForID(ID); if (!Entry) return std::nullopt; diff --git a/clang-tools-extra/clangd/IncludeCleaner.h b/clang-tools-extra/clangd/IncludeCleaner.h index fc3d04da78a8..8d8a5f75b3d3 100644 --- a/clang-tools-extra/clangd/IncludeCleaner.h +++ b/clang-tools-extra/clangd/IncludeCleaner.h @@ -77,7 +77,7 @@ struct ReferencedFiles { ReferencedFiles findReferencedFiles( const ReferencedLocations &Locs, const SourceManager &SM, llvm::function_ref HeaderResponsible, - llvm::function_ref(FileID)> UmbrellaHeader); + llvm::function_ref(FileID)> UmbrellaHeader); ReferencedFiles findReferencedFiles(const ReferencedLocations &Locs, const IncludeStructure &Includes, const CanonicalIncludes &CanonIncludes, diff --git a/clang-tools-extra/clangd/IncludeFixer.cpp b/clang-tools-extra/clangd/IncludeFixer.cpp index 5ab993230709..f6b397747a69 100644 --- a/clang-tools-extra/clangd/IncludeFixer.cpp +++ b/clang-tools-extra/clangd/IncludeFixer.cpp @@ -50,8 +50,8 @@ namespace clang { namespace clangd { namespace { -llvm::Optional getArgStr(const clang::Diagnostic &Info, - unsigned Index) { +std::optional getArgStr(const clang::Diagnostic &Info, + unsigned Index) { switch (Info.getArgKind(Index)) { case DiagnosticsEngine::ak_c_string: return llvm::StringRef(Info.getArgCStr(Index)); @@ -62,7 +62,7 @@ llvm::Optional getArgStr(const clang::Diagnostic &Info, } } -std::vector only(llvm::Optional F) { +std::vector only(std::optional F) { if (F) return {std::move(*F)}; return {}; @@ -248,7 +248,7 @@ std::vector IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel, return {}; } -llvm::Optional IncludeFixer::insertHeader(llvm::StringRef Spelled, +std::optional IncludeFixer::insertHeader(llvm::StringRef Spelled, llvm::StringRef Symbol, tooling::IncludeDirective Directive) const { Fix F; @@ -282,7 +282,7 @@ std::vector IncludeFixer::fixIncompleteType(const Type &T) const { auto ID = getSymbolID(TD); if (!ID) return {}; - llvm::Optional Symbols = lookupCached(ID); + std::optional Symbols = lookupCached(ID); if (!Symbols) return {}; const SymbolSlab &Syms = **Symbols; @@ -347,7 +347,7 @@ std::vector IncludeFixer::fixesForSymbols(const SymbolSlab &Syms) const { // "::X::Y" that is qualified by unresolved name "clangd": // clang::clangd::X::Y // ~ -llvm::Optional qualifiedByUnresolved(const SourceManager &SM, +std::optional qualifiedByUnresolved(const SourceManager &SM, SourceLocation Loc, const LangOptions &LangOpts) { std::string Result; @@ -373,15 +373,15 @@ struct CheapUnresolvedName { // This is the part of what was typed that was resolved, and it's in its // resolved form not its typed form (think `namespace clang { clangd::x }` --> // `clang::clangd::`). - llvm::Optional ResolvedScope; + std::optional ResolvedScope; // Unresolved part of the scope. When the unresolved name is a specifier, we // use the name that comes after it as the alternative name to resolve and use // the specifier as the extra scope in the accessible scopes. - llvm::Optional UnresolvedScope; + std::optional UnresolvedScope; }; -llvm::Optional getSpelledSpecifier(const CXXScopeSpec &SS, +std::optional getSpelledSpecifier(const CXXScopeSpec &SS, const SourceManager &SM) { // Support specifiers written within a single macro argument. if (!SM.isWrittenInSameFile(SS.getBeginLoc(), SS.getEndLoc())) @@ -395,7 +395,7 @@ llvm::Optional getSpelledSpecifier(const CXXScopeSpec &SS, // Extracts unresolved name and scope information around \p Unresolved. // FIXME: try to merge this with the scope-wrangling code in CodeComplete. -llvm::Optional extractUnresolvedNameCheaply( +std::optional extractUnresolvedNameCheaply( const SourceManager &SM, const DeclarationNameInfo &Unresolved, CXXScopeSpec *SS, const LangOptions &LangOpts, bool UnresolvedIsSpecifier) { CheapUnresolvedName Result; @@ -406,7 +406,7 @@ llvm::Optional extractUnresolvedNameCheaply( Result.ResolvedScope = ""; } else if (const auto *NS = Nested->getAsNamespace()) { std::string SpecifiedNS = printNamespaceScope(*NS); - llvm::Optional Spelling = getSpelledSpecifier(*SS, SM); + std::optional Spelling = getSpelledSpecifier(*SS, SM); // Check the specifier spelled in the source. // If the resolved scope doesn't end with the spelled scope, the @@ -491,7 +491,7 @@ collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S, class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource { public: - UnresolvedNameRecorder(llvm::Optional &LastUnresolvedName) + UnresolvedNameRecorder(std::optional &LastUnresolvedName) : LastUnresolvedName(LastUnresolvedName) {} void InitializeSema(Sema &S) override { this->SemaPtr = &S; } @@ -544,7 +544,7 @@ public: private: Sema *SemaPtr = nullptr; - llvm::Optional &LastUnresolvedName; + std::optional &LastUnresolvedName; }; llvm::IntrusiveRefCntPtr @@ -565,13 +565,13 @@ std::vector IncludeFixer::fixUnresolvedName() const { Req.RestrictForCodeCompletion = true; Req.Limit = 100; - if (llvm::Optional Syms = fuzzyFindCached(Req)) + if (std::optional Syms = fuzzyFindCached(Req)) return fixesForSymbols(**Syms); return {}; } -llvm::Optional +std::optional IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const { auto ReqStr = llvm::formatv("{0}", toJSON(Req)).str(); auto I = FuzzyFindCache.find(ReqStr); @@ -594,7 +594,7 @@ IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const { return &E.first->second; } -llvm::Optional +std::optional IncludeFixer::lookupCached(const SymbolID &ID) const { LookupRequest Req; Req.IDs.insert(ID); diff --git a/clang-tools-extra/clangd/IncludeFixer.h b/clang-tools-extra/clangd/IncludeFixer.h index 2a74c23ffa8e..0c51ad9ff9ba 100644 --- a/clang-tools-extra/clangd/IncludeFixer.h +++ b/clang-tools-extra/clangd/IncludeFixer.h @@ -56,10 +56,10 @@ private: /// Generates header insertion fixes for all symbols. Fixes are deduplicated. std::vector fixesForSymbols(const SymbolSlab &Syms) const; - llvm::Optional - insertHeader(llvm::StringRef Name, llvm::StringRef Symbol = "", - tooling::IncludeDirective Directive = - tooling::IncludeDirective::Include) const; + std::optional insertHeader(llvm::StringRef Name, + llvm::StringRef Symbol = "", + tooling::IncludeDirective Directive = + tooling::IncludeDirective::Include) const; struct UnresolvedName { std::string Name; // E.g. "X" in foo::X. @@ -84,7 +84,7 @@ private: // These collect the last unresolved name so that we can associate it with the // diagnostic. - llvm::Optional LastUnresolvedName; + std::optional LastUnresolvedName; // There can be multiple diagnostics that are caused by the same unresolved // name or incomplete type in one parse, especially when code is @@ -93,9 +93,9 @@ private: mutable llvm::StringMap FuzzyFindCache; mutable llvm::DenseMap LookupCache; // Returns std::nullopt if the number of index requests has reached the limit. - llvm::Optional + std::optional fuzzyFindCached(const FuzzyFindRequest &Req) const; - llvm::Optional lookupCached(const SymbolID &ID) const; + std::optional lookupCached(const SymbolID &ID) const; }; } // namespace clangd diff --git a/clang-tools-extra/clangd/InlayHints.cpp b/clang-tools-extra/clangd/InlayHints.cpp index 20a8adcecc73..30c7c05e3c02 100644 --- a/clang-tools-extra/clangd/InlayHints.cpp +++ b/clang-tools-extra/clangd/InlayHints.cpp @@ -648,7 +648,7 @@ private: } // Get the range of the main file that *exactly* corresponds to R. - llvm::Optional getHintRange(SourceRange R) { + std::optional getHintRange(SourceRange R) { const auto &SM = AST.getSourceManager(); auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R)); // TokenBuffer will return null if e.g. R corresponds to only part of a diff --git a/clang-tools-extra/clangd/JSONTransport.cpp b/clang-tools-extra/clangd/JSONTransport.cpp index 50b1833a7575..9dc0df807aa3 100644 --- a/clang-tools-extra/clangd/JSONTransport.cpp +++ b/clang-tools-extra/clangd/JSONTransport.cpp @@ -164,12 +164,12 @@ bool JSONTransport::handleMessage(llvm::json::Value Message, // Message must be an object with "jsonrpc":"2.0". auto *Object = Message.getAsObject(); if (!Object || - Object->getString("jsonrpc") != llvm::Optional("2.0")) { + Object->getString("jsonrpc") != std::optional("2.0")) { elog("Not a JSON-RPC 2.0 message: {0:2}", Message); return false; } // ID may be any JSON value. If absent, this is a notification. - llvm::Optional ID; + std::optional ID; if (auto *I = Object->get("id")) ID = std::move(*I); auto Method = Object->getString("method"); diff --git a/clang-tools-extra/clangd/ParsedAST.cpp b/clang-tools-extra/clangd/ParsedAST.cpp index c2846749a708..cd814c828702 100644 --- a/clang-tools-extra/clangd/ParsedAST.cpp +++ b/clang-tools-extra/clangd/ParsedAST.cpp @@ -339,7 +339,7 @@ void applyWarningOptions(llvm::ArrayRef ExtraArgs, } // namespace -llvm::Optional +std::optional ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs, std::unique_ptr CI, llvm::ArrayRef CompilerInvocationDiags, @@ -376,7 +376,7 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs, [&](const auto &L) { L->sawDiagnostic(D, Diag); }); }); - llvm::Optional Patch; + std::optional Patch; bool PreserveDiags = true; // We might use an ignoring diagnostic consumer if they are going to be // dropped later on to not pay for extra latency by processing them. @@ -465,10 +465,10 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs, // In practice almost all checks work well without modifications. std::vector> CTChecks; ast_matchers::MatchFinder CTFinder; - llvm::Optional CTContext; + std::optional CTContext; // Must outlive FixIncludes. auto BuildDir = VFS->getCurrentWorkingDirectory(); - llvm::Optional FixIncludes; + std::optional FixIncludes; llvm::DenseMap OverriddenSeverity; // No need to run clang-tidy or IncludeFixerif we are not going to surface // diagnostics. @@ -653,7 +653,7 @@ ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs, // CompilerInstance won't run this callback, do it directly. ASTDiags.EndSourceFile(); - llvm::Optional> Diags; + std::optional> Diags; // FIXME: Also skip generation of diagnostics alltogether to speed up ast // builds when we are patching a stale preamble. if (PreserveDiags) { @@ -770,7 +770,7 @@ ParsedAST::ParsedAST(PathRef TUPath, llvm::StringRef Version, syntax::TokenBuffer Tokens, MainFileMacros Macros, std::vector Marks, std::vector LocalTopLevelDecls, - llvm::Optional> Diags, + std::optional> Diags, IncludeStructure Includes, CanonicalIncludes CanonIncludes) : TUPath(TUPath), Version(Version), Preamble(std::move(Preamble)), Clang(std::move(Clang)), Action(std::move(Action)), @@ -783,7 +783,7 @@ ParsedAST::ParsedAST(PathRef TUPath, llvm::StringRef Version, assert(this->Action); } -llvm::Optional ParsedAST::preambleVersion() const { +std::optional ParsedAST::preambleVersion() const { if (!Preamble) return std::nullopt; return llvm::StringRef(Preamble->Version); diff --git a/clang-tools-extra/clangd/ParsedAST.h b/clang-tools-extra/clangd/ParsedAST.h index 8f74c17992d4..f0085d7e3587 100644 --- a/clang-tools-extra/clangd/ParsedAST.h +++ b/clang-tools-extra/clangd/ParsedAST.h @@ -49,7 +49,7 @@ public: /// Attempts to run Clang and store the parsed AST. /// If \p Preamble is non-null it is reused during parsing. /// This function does not check if preamble is valid to reuse. - static llvm::Optional + static std::optional build(llvm::StringRef Filename, const ParseInputs &Inputs, std::unique_ptr CI, llvm::ArrayRef CompilerInvocationDiags, @@ -88,7 +88,7 @@ public: /// (These should be const, but RecursiveASTVisitor requires Decl*). ArrayRef getLocalTopLevelDecls(); - const llvm::Optional> &getDiagnostics() const { + const std::optional> &getDiagnostics() const { return Diags; } @@ -115,7 +115,7 @@ public: /// Returns the version of the ParseInputs used to build Preamble part of this /// AST. Might be std::nullopt if no Preamble is used. - llvm::Optional preambleVersion() const; + std::optional preambleVersion() const; const HeuristicResolver *getHeuristicResolver() const { return Resolver.get(); @@ -128,7 +128,7 @@ private: std::unique_ptr Action, syntax::TokenBuffer Tokens, MainFileMacros Macros, std::vector Marks, std::vector LocalTopLevelDecls, - llvm::Optional> Diags, IncludeStructure Includes, + std::optional> Diags, IncludeStructure Includes, CanonicalIncludes CanonIncludes); Path TUPath; @@ -155,7 +155,7 @@ private: std::vector Marks; // Data, stored after parsing. std::nullopt if AST was built with a stale // preamble. - llvm::Optional> Diags; + std::optional> Diags; // Top-level decls inside the current file. Not that this does not include // top-level decls from the preamble. std::vector LocalTopLevelDecls; diff --git a/clang-tools-extra/clangd/Protocol.h b/clang-tools-extra/clangd/Protocol.h index 9cd1955ba95b..9056ae6cebf0 100644 --- a/clang-tools-extra/clangd/Protocol.h +++ b/clang-tools-extra/clangd/Protocol.h @@ -416,7 +416,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, MarkupKind); struct ClientCapabilities { /// The supported set of SymbolKinds for workspace/symbol. /// workspace.symbol.symbolKind.valueSet - llvm::Optional WorkspaceSymbolKinds; + std::optional WorkspaceSymbolKinds; /// Whether the client accepts diagnostics with codeActions attached inline. /// textDocument.publishDiagnostics.codeActionsInline. @@ -469,7 +469,7 @@ struct ClientCapabilities { /// The supported set of CompletionItemKinds for textDocument/completion. /// textDocument.completion.completionItemKind.valueSet - llvm::Optional CompletionItemKinds; + std::optional CompletionItemKinds; /// The documentation format that should be used for textDocument/completion. /// textDocument.completion.completionItem.documentationFormat @@ -490,7 +490,7 @@ struct ClientCapabilities { bool TheiaSemanticHighlighting = false; /// Supported encodings for LSP character offsets. (clangd extension). - llvm::Optional> offsetEncoding; + std::optional> offsetEncoding; /// The content format that should be used for Hover requests. /// textDocument.hover.contentEncoding @@ -651,14 +651,14 @@ struct WorkDoneProgressReport { /// /// Clients that don't support cancellation or don't support control /// the button's enablement state are allowed to ignore the setting. - llvm::Optional cancellable; + std::optional cancellable; /// Optional, more detailed associated progress message. Contains /// complementary information to the `title`. /// /// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep". /// If unset, the previous progress message (if any) is still valid. - llvm::Optional message; + std::optional message; /// Optional progress percentage to display (value 100 is considered 100%). /// If not provided infinite progress is assumed and clients are allowed @@ -666,7 +666,7 @@ struct WorkDoneProgressReport { /// /// The value should be steadily rising. Clients are free to ignore values /// that are not following this rule. - llvm::Optional percentage; + std::optional percentage; }; llvm::json::Value toJSON(const WorkDoneProgressReport &); // @@ -674,7 +674,7 @@ llvm::json::Value toJSON(const WorkDoneProgressReport &); struct WorkDoneProgressEnd { /// Optional, a final message indicating to for example indicate the outcome /// of the operation. - llvm::Optional message; + std::optional message; }; llvm::json::Value toJSON(const WorkDoneProgressEnd &); @@ -879,7 +879,7 @@ struct Diagnostic { std::string code; /// An optional property to describe the error code. - llvm::Optional codeDescription; + std::optional codeDescription; /// A human-readable string describing the source of this /// diagnostic, e.g. 'typescript' or 'super lint'. @@ -1019,13 +1019,13 @@ struct CodeAction { /// The kind of the code action. /// Used to filter code actions. - llvm::Optional kind; + std::optional kind; const static llvm::StringLiteral QUICKFIX_KIND; const static llvm::StringLiteral REFACTOR_KIND; const static llvm::StringLiteral INFO_KIND; /// The diagnostics that this code action resolves. - llvm::Optional> diagnostics; + std::optional> diagnostics; /// Marks this as a preferred action. Preferred actions are used by the /// `auto fix` command and can be targeted by keybindings. @@ -1035,11 +1035,11 @@ struct CodeAction { bool isPreferred = false; /// The workspace edit this code action performs. - llvm::Optional edit; + std::optional edit; /// A command this code action executes. If a code action provides an edit /// and a command, first the edit is executed and then the command. - llvm::Optional command; + std::optional command; }; llvm::json::Value toJSON(const CodeAction &); @@ -1097,7 +1097,7 @@ struct SymbolInformation { /// This can be used to re-rank results as the user types, using client-side /// fuzzy-matching (that score should be multiplied with this one). /// This is a clangd extension, set only for workspace/symbol responses. - llvm::Optional score; + std::optional score; }; llvm::json::Value toJSON(const SymbolInformation &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolInformation &); @@ -1118,9 +1118,9 @@ struct SymbolDetails { SymbolID ID; - llvm::Optional declarationRange; + std::optional declarationRange; - llvm::Optional definitionRange; + std::optional definitionRange; }; llvm::json::Value toJSON(const SymbolDetails &); llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolDetails &); @@ -1202,7 +1202,7 @@ struct Hover { /// An optional range is a range inside a text document /// that is used to visualize a hover, e.g. by changing the background color. - llvm::Optional range; + std::optional range; }; llvm::json::Value toJSON(const Hover &H); @@ -1261,7 +1261,7 @@ struct CompletionItem { /// /// Note: The range of the edit must be a single line range and it must /// contain the position at which completion has been requested. - llvm::Optional textEdit; + std::optional textEdit; /// An optional array of additional text edits that are applied when selecting /// this completion. Edits must not overlap with the main edit nor with @@ -1312,7 +1312,7 @@ struct ParameterInformation { /// label. /// Offsets are computed by lspLength(), which counts UTF-16 code units by /// default but that can be overriden, see its documentation for details. - llvm::Optional> labelOffsets; + std::optional> labelOffsets; /// The documentation of this parameter. Optional. std::string documentation; @@ -1731,9 +1731,9 @@ llvm::json::Value toJSON(const SemanticTokensEdit &); struct SemanticTokensOrDelta { std::string resultId; /// Set if we computed edits relative to a previous set of tokens. - llvm::Optional> edits; + std::optional> edits; /// Set if we computed a fresh set of tokens. - llvm::Optional> tokens; // encoded as integer array + std::optional> tokens; // encoded as integer array }; llvm::json::Value toJSON(const SemanticTokensOrDelta &); @@ -1870,7 +1870,7 @@ struct ASTNode { std::string arcana; /// The range of the original source file covered by this node. /// May be missing for implicit nodes, or those created by macro expansion. - llvm::Optional range; + std::optional range; /// Nodes nested within this one, such as the operands of a BinaryOperator. std::vector children; }; diff --git a/clang-tools-extra/clangd/Quality.cpp b/clang-tools-extra/clangd/Quality.cpp index 72e3154bdbab..318488f269f8 100644 --- a/clang-tools-extra/clangd/Quality.cpp +++ b/clang-tools-extra/clangd/Quality.cpp @@ -368,7 +368,7 @@ static float scopeProximityScore(unsigned ScopeDistance) { return std::max(0.65, 2.0 * std::pow(0.6, ScopeDistance / 2.0)); } -static llvm::Optional +static std::optional wordMatching(llvm::StringRef Name, const llvm::StringSet<> *ContextWords) { if (ContextWords) for (const auto &Word : ContextWords->keys()) diff --git a/clang-tools-extra/clangd/Quality.h b/clang-tools-extra/clangd/Quality.h index 2a4efe934f58..5fe70454f5cf 100644 --- a/clang-tools-extra/clangd/Quality.h +++ b/clang-tools-extra/clangd/Quality.h @@ -106,7 +106,7 @@ struct SymbolRelevanceSignals { // Scope proximity is only considered (both index and sema) when this is set. ScopeDistance *ScopeProximityMatch = nullptr; - llvm::Optional SymbolScope; + std::optional SymbolScope; // A symbol from sema should be accessible from the current scope. bool SemaSaysInScope = false; diff --git a/clang-tools-extra/clangd/Selection.cpp b/clang-tools-extra/clangd/Selection.cpp index 56836fd85095..f46da8e41f58 100644 --- a/clang-tools-extra/clangd/Selection.cpp +++ b/clang-tools-extra/clangd/Selection.cpp @@ -513,7 +513,7 @@ private: } // Decomposes Loc and returns the offset if the file ID is SelFile. - llvm::Optional offsetInSelFile(SourceLocation Loc) const { + std::optional offsetInSelFile(SourceLocation Loc) const { // Decoding Loc with SM.getDecomposedLoc is relatively expensive. // But SourceLocations for a file are numerically contiguous, so we // can use cheap integer operations instead. @@ -1060,7 +1060,7 @@ bool SelectionTree::createEach(ASTContext &AST, SelectionTree SelectionTree::createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned int Begin, unsigned int End) { - llvm::Optional Result; + std::optional Result; createEach(AST, Tokens, Begin, End, [&](SelectionTree T) { Result = std::move(T); return true; diff --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp b/clang-tools-extra/clangd/SemanticHighlighting.cpp index eaed8870fcbe..db346efe19f3 100644 --- a/clang-tools-extra/clangd/SemanticHighlighting.cpp +++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp @@ -83,10 +83,10 @@ bool isUniqueDefinition(const NamedDecl *Decl) { isa(Decl); } -llvm::Optional kindForType(const Type *TP, - const HeuristicResolver *Resolver); -llvm::Optional -kindForDecl(const NamedDecl *D, const HeuristicResolver *Resolver) { +std::optional kindForType(const Type *TP, + const HeuristicResolver *Resolver); +std::optional kindForDecl(const NamedDecl *D, + const HeuristicResolver *Resolver) { if (auto *USD = dyn_cast(D)) { if (auto *Target = USD->getTargetDecl()) D = Target; @@ -164,8 +164,8 @@ kindForDecl(const NamedDecl *D, const HeuristicResolver *Resolver) { } return std::nullopt; } -llvm::Optional -kindForType(const Type *TP, const HeuristicResolver *Resolver) { +std::optional kindForType(const Type *TP, + const HeuristicResolver *Resolver) { if (!TP) return std::nullopt; if (TP->isBuiltinType()) // Builtins are special, they do not have decls. @@ -332,8 +332,8 @@ unsigned evaluateHighlightPriority(const HighlightingToken &Tok) { // // In particular, heuristically resolved dependent names get their heuristic // kind, plus the dependent modifier. -llvm::Optional resolveConflict(const HighlightingToken &A, - const HighlightingToken &B) { +std::optional resolveConflict(const HighlightingToken &A, + const HighlightingToken &B) { unsigned Priority1 = evaluateHighlightPriority(A); unsigned Priority2 = evaluateHighlightPriority(B); if (Priority1 == Priority2 && A.Kind != B.Kind) @@ -342,13 +342,14 @@ llvm::Optional resolveConflict(const HighlightingToken &A, Result.Modifiers = A.Modifiers | B.Modifiers; return Result; } -llvm::Optional +std::optional resolveConflict(ArrayRef Tokens) { if (Tokens.size() == 1) return Tokens[0]; assert(Tokens.size() >= 2); - Optional Winner = resolveConflict(Tokens[0], Tokens[1]); + std::optional Winner = + resolveConflict(Tokens[0], Tokens[1]); for (size_t I = 2; Winner && I < Tokens.size(); ++I) Winner = resolveConflict(*Winner, Tokens[I]); return Winner; @@ -474,7 +475,7 @@ public: const HeuristicResolver *getResolver() const { return Resolver; } private: - llvm::Optional getRangeForSourceLocation(SourceLocation Loc) { + std::optional getRangeForSourceLocation(SourceLocation Loc) { Loc = getHighlightableSpellingToken(Loc, SourceMgr); if (Loc.isInvalid()) return std::nullopt; @@ -496,7 +497,7 @@ private: HighlightingToken InvalidHighlightingToken; }; -llvm::Optional scopeModifier(const NamedDecl *D) { +std::optional scopeModifier(const NamedDecl *D) { const DeclContext *DC = D->getDeclContext(); // Injected "Foo" within the class "Foo" has file scope, not class scope. if (auto *R = dyn_cast_or_null(D)) @@ -524,7 +525,7 @@ llvm::Optional scopeModifier(const NamedDecl *D) { return HighlightingModifier::GlobalScope; } -llvm::Optional scopeModifier(const Type *T) { +std::optional scopeModifier(const Type *T) { if (!T) return std::nullopt; if (T->isBuiltinType()) @@ -672,7 +673,7 @@ public: return; } - llvm::Optional Location; + std::optional Location; // FIXME Add "unwrapping" for ArraySubscriptExpr, // e.g. highlight `a` in `a[i]` diff --git a/clang-tools-extra/clangd/SemanticSelection.cpp b/clang-tools-extra/clangd/SemanticSelection.cpp index fe01c1577bff..b3f3d2856d7a 100644 --- a/clang-tools-extra/clangd/SemanticSelection.cpp +++ b/clang-tools-extra/clangd/SemanticSelection.cpp @@ -41,8 +41,8 @@ void addIfDistinct(const Range &R, std::vector &Result) { } } -llvm::Optional toFoldingRange(SourceRange SR, - const SourceManager &SM) { +std::optional toFoldingRange(SourceRange SR, + const SourceManager &SM) { const auto Begin = SM.getDecomposedLoc(SR.getBegin()), End = SM.getDecomposedLoc(SR.getEnd()); // Do not produce folding ranges if either range ends is not within the main @@ -58,7 +58,7 @@ llvm::Optional toFoldingRange(SourceRange SR, return Range; } -llvm::Optional +std::optional extractFoldingRange(const syntax::Node *Node, const syntax::TokenBufferTokenManager &TM) { if (const auto *Stmt = dyn_cast(Node)) { diff --git a/clang-tools-extra/clangd/SourceCode.cpp b/clang-tools-extra/clangd/SourceCode.cpp index 90dd37f82f04..b53e9adeef6a 100644 --- a/clang-tools-extra/clangd/SourceCode.cpp +++ b/clang-tools-extra/clangd/SourceCode.cpp @@ -422,9 +422,9 @@ bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM) { return FID == SM.getMainFileID() || FID == SM.getPreambleFileID(); } -llvm::Optional toHalfOpenFileRange(const SourceManager &SM, - const LangOptions &LangOpts, - SourceRange R) { +std::optional toHalfOpenFileRange(const SourceManager &SM, + const LangOptions &LangOpts, + SourceRange R) { SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts); if (!isValidFileRange(SM, R1)) return std::nullopt; @@ -512,8 +512,8 @@ std::vector replacementsToEdits(llvm::StringRef Code, return Edits; } -llvm::Optional getCanonicalPath(const FileEntry *F, - const SourceManager &SourceMgr) { +std::optional getCanonicalPath(const FileEntry *F, + const SourceManager &SourceMgr) { if (!F) return std::nullopt; @@ -570,7 +570,7 @@ FileDigest digest(llvm::StringRef Content) { return Result; } -llvm::Optional digestFile(const SourceManager &SM, FileID FID) { +std::optional digestFile(const SourceManager &SM, FileID FID) { bool Invalid = false; llvm::StringRef Content = SM.getBufferData(FID, &Invalid); if (Invalid) @@ -924,9 +924,9 @@ static bool isLikelyIdentifier(llvm::StringRef Word, llvm::StringRef Before, return false; } -llvm::Optional SpelledWord::touching(SourceLocation SpelledLoc, - const syntax::TokenBuffer &TB, - const LangOptions &LangOpts) { +std::optional SpelledWord::touching(SourceLocation SpelledLoc, + const syntax::TokenBuffer &TB, + const LangOptions &LangOpts) { const auto &SM = TB.sourceManager(); auto Touching = syntax::spelledTokensTouching(SpelledLoc, TB); for (const auto &T : Touching) { @@ -974,8 +974,8 @@ llvm::Optional SpelledWord::touching(SourceLocation SpelledLoc, return Result; } -llvm::Optional locateMacroAt(const syntax::Token &SpelledTok, - Preprocessor &PP) { +std::optional locateMacroAt(const syntax::Token &SpelledTok, + Preprocessor &PP) { if (SpelledTok.kind() != tok::identifier) return std::nullopt; SourceLocation Loc = SpelledTok.location(); @@ -1196,7 +1196,7 @@ EligibleRegion getEligiblePoints(llvm::StringRef Code, } bool isHeaderFile(llvm::StringRef FileName, - llvm::Optional LangOpts) { + std::optional LangOpts) { // Respect the langOpts, for non-file-extension cases, e.g. standard library // files. if (LangOpts && LangOpts->IsHeaderFile) diff --git a/clang-tools-extra/clangd/SourceCode.h b/clang-tools-extra/clangd/SourceCode.h index 69626c2678d5..7527fd944ea9 100644 --- a/clang-tools-extra/clangd/SourceCode.h +++ b/clang-tools-extra/clangd/SourceCode.h @@ -41,7 +41,7 @@ namespace clangd { // of hashing function at every place that needs to store this information. using FileDigest = std::array; FileDigest digest(StringRef Content); -Optional digestFile(const SourceManager &SM, FileID FID); +std::optional digestFile(const SourceManager &SM, FileID FID); // This context variable controls the behavior of functions in this file // that convert between LSP offsets and native clang byte offsets. @@ -111,9 +111,9 @@ bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM); /// User input (e.g. cursor position) is expressed as a file location, so this /// function can be viewed as a way to normalize the ranges used in the clang /// AST so that they are comparable with ranges coming from the user input. -llvm::Optional toHalfOpenFileRange(const SourceManager &Mgr, - const LangOptions &LangOpts, - SourceRange R); +std::optional toHalfOpenFileRange(const SourceManager &Mgr, + const LangOptions &LangOpts, + SourceRange R); /// Returns true iff all of the following conditions hold: /// - start and end locations are valid, @@ -163,8 +163,8 @@ TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, /// This function should be used when paths needs to be used outside the /// component that generate it, so that paths are normalized as much as /// possible. -llvm::Optional getCanonicalPath(const FileEntry *F, - const SourceManager &SourceMgr); +std::optional getCanonicalPath(const FileEntry *F, + const SourceManager &SourceMgr); /// Choose the clang-format style we should apply to a certain file. /// This will usually use FS to look for .clang-format directories. @@ -252,9 +252,9 @@ struct SpelledWord { const syntax::Token *ExpandedToken = nullptr; // Find the unique word that contains SpelledLoc or starts/ends there. - static llvm::Optional touching(SourceLocation SpelledLoc, - const syntax::TokenBuffer &TB, - const LangOptions &LangOpts); + static std::optional touching(SourceLocation SpelledLoc, + const syntax::TokenBuffer &TB, + const LangOptions &LangOpts); }; /// Return true if the \p TokenName is in the list of reversed keywords of the @@ -315,13 +315,13 @@ struct DefinedMacro { }; /// Gets the macro referenced by \p SpelledTok. It must be a spelled token /// aligned to the beginning of an identifier. -llvm::Optional locateMacroAt(const syntax::Token &SpelledTok, - Preprocessor &PP); +std::optional locateMacroAt(const syntax::Token &SpelledTok, + Preprocessor &PP); /// Infers whether this is a header from the FileName and LangOpts (if /// presents). bool isHeaderFile(llvm::StringRef FileName, - llvm::Optional LangOpts = std::nullopt); + std::optional LangOpts = std::nullopt); /// Returns true if the given location is in a generated protobuf file. bool isProtoFile(SourceLocation Loc, const SourceManager &SourceMgr); diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp index d78d56e367c8..c334697e1e23 100644 --- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp +++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp @@ -75,7 +75,7 @@ bool isValidTarget(llvm::StringRef Triple) { return bool(Target); } -llvm::Optional parseDriverOutput(llvm::StringRef Output) { +std::optional parseDriverOutput(llvm::StringRef Output) { DriverInfo Info; const char SIS[] = "#include <...> search starts here:"; const char SIE[] = "End of search list."; @@ -136,7 +136,7 @@ llvm::Optional parseDriverOutput(llvm::StringRef Output) { return std::move(Info); } -llvm::Optional +std::optional extractSystemIncludesAndTarget(llvm::SmallString<128> Driver, llvm::StringRef Lang, llvm::ArrayRef CommandLine, @@ -226,7 +226,7 @@ extractSystemIncludesAndTarget(llvm::SmallString<128> Driver, return std::nullopt; } - llvm::Optional Info = + std::optional Info = parseDriverOutput(BufOrError->get()->getBuffer()); if (!Info) return std::nullopt; @@ -361,7 +361,7 @@ public: private: // Caches includes extracted from a driver. Key is driver:lang. - Memoize>> QueriedDrivers; + Memoize>> QueriedDrivers; llvm::Regex QueryDriverRegex; }; } // namespace diff --git a/clang-tools-extra/clangd/TUScheduler.cpp b/clang-tools-extra/clangd/TUScheduler.cpp index 50802d2c8b37..b50d47af2261 100644 --- a/clang-tools-extra/clangd/TUScheduler.cpp +++ b/clang-tools-extra/clangd/TUScheduler.cpp @@ -137,7 +137,7 @@ class ASTWorker; static clang::clangd::Key FileBeingProcessed; -llvm::Optional TUScheduler::getFileBeingProcessedInContext() { +std::optional TUScheduler::getFileBeingProcessedInContext() { if (auto *File = Context::current().get(FileBeingProcessed)) return llvm::StringRef(*File); return std::nullopt; @@ -184,7 +184,7 @@ public: /// the cache anymore. If nullptr was cached for \p K, this function will /// return a null unique_ptr wrapped into an optional. /// If \p AccessMetric is set records whether there was a hit or miss. - llvm::Optional> + std::optional> take(Key K, const trace::Metric *AccessMetric = nullptr) { // Record metric after unlocking the mutex. std::unique_lock Lock(Mut); @@ -201,7 +201,7 @@ public: // GCC 4.8 fails to compile `return V;`, as it tries to call the copy // constructor of unique_ptr, so we call the move ctor explicitly to avoid // this miscompile. - return llvm::Optional>(std::move(V)); + return std::optional>(std::move(V)); } private: @@ -465,7 +465,7 @@ public: void run() { while (true) { - llvm::Optional Throttle; + std::optional Throttle; { std::unique_lock Lock(Mutex); assert(!CurrentReq && "Already processing a request?"); @@ -476,7 +476,7 @@ public: { Throttle.emplace(FileName, Throttler, ReqCV); - llvm::Optional Tracer; + std::optional Tracer; // If acquire succeeded synchronously, avoid status jitter. if (!Throttle->satisfied()) { Tracer.emplace("PreambleThrottle"); @@ -564,8 +564,8 @@ private: mutable std::mutex Mutex; bool Done = false; /* GUARDED_BY(Mutex) */ - llvm::Optional NextReq; /* GUARDED_BY(Mutex) */ - llvm::Optional CurrentReq; /* GUARDED_BY(Mutex) */ + std::optional NextReq; /* GUARDED_BY(Mutex) */ + std::optional CurrentReq; /* GUARDED_BY(Mutex) */ // Signaled whenever a thread populates NextReq or worker thread builds a // Preamble. mutable std::condition_variable ReqCV; /* GUARDED_BY(Mutex) */ @@ -681,7 +681,7 @@ private: /// Adds a new task to the end of the request queue. void startTask(llvm::StringRef Name, llvm::unique_function Task, - llvm::Optional Update, + std::optional Update, TUScheduler::ASTActionInvalidation); /// Runs a task synchronously. void runTask(llvm::StringRef Name, llvm::function_ref Task); @@ -699,8 +699,8 @@ private: std::string Name; steady_clock::time_point AddTime; Context Ctx; - llvm::Optional QueueCtx; - llvm::Optional Update; + std::optional QueueCtx; + std::optional Update; TUScheduler::ASTActionInvalidation InvalidationPolicy; Canceler Invalidate; }; @@ -734,7 +734,7 @@ private: /// Set to true to signal run() to finish processing. bool Done; /* GUARDED_BY(Mutex) */ std::deque Requests; /* GUARDED_BY(Mutex) */ - llvm::Optional CurrentRequest; /* GUARDED_BY(Mutex) */ + std::optional CurrentRequest; /* GUARDED_BY(Mutex) */ /// Signalled whenever a new request has been scheduled or processing of a /// request has completed. mutable std::condition_variable RequestsCV; @@ -742,7 +742,7 @@ private: /// Latest build preamble for current TU. /// None means no builds yet, null means there was an error while building. /// Only written by ASTWorker's thread. - llvm::Optional> LatestPreamble; + std::optional> LatestPreamble; std::deque PreambleRequests; /* GUARDED_BY(Mutex) */ /// Signaled whenever LatestPreamble changes state or there's a new /// PreambleRequest. @@ -965,7 +965,7 @@ void ASTWorker::runWithAST( auto Task = [=, Action = std::move(Action)]() mutable { if (auto Reason = isCancelled()) return Action(llvm::make_error(Reason)); - llvm::Optional> AST = + std::optional> AST = IdleASTs.take(this, &ASTAccessForRead); if (!AST) { StoreDiags CompilerInvocationDiagConsumer; @@ -977,7 +977,7 @@ void ASTWorker::runWithAST( // FIXME: We might need to build a patched ast once preamble thread starts // running async. Currently getPossiblyStalePreamble below will always // return a compatible preamble as ASTWorker::update blocks. - llvm::Optional NewAST; + std::optional NewAST; if (Invocation) { NewAST = ParsedAST::build(FileName, FileInputs, std::move(Invocation), CompilerInvocationDiagConsumer.take(), @@ -1184,11 +1184,11 @@ void ASTWorker::generateDiagnostics( // We might be able to reuse the last we've built for a read request. // FIXME: It might be better to not reuse this AST. That way queued AST builds // won't be required for diags. - llvm::Optional> AST = + std::optional> AST = IdleASTs.take(this, &ASTAccessForDiag); if (!AST || !InputsAreLatest) { auto RebuildStartTime = DebouncePolicy::clock::now(); - llvm::Optional NewAST = ParsedAST::build( + std::optional NewAST = ParsedAST::build( FileName, Inputs, std::move(Invocation), CIDiags, *LatestPreamble); auto RebuildDuration = DebouncePolicy::clock::now() - RebuildStartTime; ++ASTBuildCount; @@ -1307,7 +1307,7 @@ void ASTWorker::runTask(llvm::StringRef Name, llvm::function_ref Task) { void ASTWorker::startTask(llvm::StringRef Name, llvm::unique_function Task, - llvm::Optional Update, + std::optional Update, TUScheduler::ASTActionInvalidation Invalidation) { if (RunSync) { assert(!Done && "running a task after stop()"); @@ -1338,7 +1338,7 @@ void ASTWorker::startTask(llvm::StringRef Name, } // Trace the time the request spends in the queue, and the requests that // it's going to wait for. - llvm::Optional QueueCtx; + std::optional QueueCtx; if (trace::enabled()) { // Tracers that follow threads and need strict nesting will see a tiny // instantaneous event "we're enqueueing", and sometime later it runs. @@ -1385,8 +1385,8 @@ void ASTWorker::run() { } // Tracing: we have a next request, attribute this sleep to it. - llvm::Optional Ctx; - llvm::Optional Tracer; + std::optional Ctx; + std::optional Tracer; if (!Requests.empty()) { Ctx.emplace(Requests.front().Ctx.clone()); Tracer.emplace("Debounce"); diff --git a/clang-tools-extra/clangd/TUScheduler.h b/clang-tools-extra/clangd/TUScheduler.h index f9582a6f3f42..7e2343c2b8c3 100644 --- a/clang-tools-extra/clangd/TUScheduler.h +++ b/clang-tools-extra/clangd/TUScheduler.h @@ -353,7 +353,7 @@ public: // FIXME: remove this when there is proper index support via build system // integration. // FIXME: move to ClangdServer via createProcessingContext. - static llvm::Optional getFileBeingProcessedInContext(); + static std::optional getFileBeingProcessedInContext(); void profile(MemoryTree &MT) const; @@ -371,8 +371,8 @@ private: std::unique_ptr HeaderIncluders; // None when running tasks synchronously and non-None when running tasks // asynchronously. - llvm::Optional PreambleTasks; - llvm::Optional WorkerThreads; + std::optional PreambleTasks; + std::optional WorkerThreads; // Used to create contexts for operations that are not bound to a particular // file (e.g. index queries). std::string LastActiveFile; diff --git a/clang-tools-extra/clangd/XRefs.cpp b/clang-tools-extra/clangd/XRefs.cpp index da33b722876f..ee677fee07f8 100644 --- a/clang-tools-extra/clangd/XRefs.cpp +++ b/clang-tools-extra/clangd/XRefs.cpp @@ -117,8 +117,8 @@ void logIfOverflow(const SymbolLocation &Loc) { // TUPath is used to resolve the path of URI. // FIXME: figure out a good home for it, and share the implementation with // FindSymbols. -llvm::Optional toLSPLocation(const SymbolLocation &Loc, - llvm::StringRef TUPath) { +std::optional toLSPLocation(const SymbolLocation &Loc, + llvm::StringRef TUPath) { if (!Loc) return std::nullopt; auto Uri = URI::parse(Loc.FileURI); @@ -206,8 +206,8 @@ getDeclAtPosition(ParsedAST &AST, SourceLocation Pos, DeclRelationSet Relations, // Expects Loc to be a SpellingLocation, will bail out otherwise as it can't // figure out a filename. -llvm::Optional makeLocation(const ASTContext &AST, SourceLocation Loc, - llvm::StringRef TUPath) { +std::optional makeLocation(const ASTContext &AST, SourceLocation Loc, + llvm::StringRef TUPath) { const auto &SM = AST.getSourceManager(); const FileEntry *F = SM.getFileEntryForID(SM.getFileID(Loc)); if (!F) @@ -228,9 +228,9 @@ llvm::Optional makeLocation(const ASTContext &AST, SourceLocation Loc, } // Treat #included files as symbols, to enable go-to-definition on them. -llvm::Optional locateFileReferent(const Position &Pos, - ParsedAST &AST, - llvm::StringRef MainFilePath) { +std::optional locateFileReferent(const Position &Pos, + ParsedAST &AST, + llvm::StringRef MainFilePath) { for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) { if (!Inc.Resolved.empty() && Inc.HashLine == Pos.line) { LocatedSymbol File; @@ -247,7 +247,7 @@ llvm::Optional locateFileReferent(const Position &Pos, // Macros are simple: there's no declaration/definition distinction. // As a consequence, there's no need to look them up in the index either. -llvm::Optional +std::optional locateMacroReferent(const syntax::Token &TouchedIdentifier, ParsedAST &AST, llvm::StringRef MainFilePath) { if (auto M = locateMacroAt(TouchedIdentifier, AST.getPreprocessor())) { @@ -1201,8 +1201,8 @@ DocumentHighlight toHighlight(const ReferenceFinder::Reference &Ref, return DH; } -llvm::Optional toHighlight(SourceLocation Loc, - const syntax::TokenBuffer &TB) { +std::optional toHighlight(SourceLocation Loc, + const syntax::TokenBuffer &TB) { Loc = TB.sourceManager().getFileLoc(Loc); if (const auto *Tok = TB.spelledTokenAt(Loc)) { DocumentHighlight Result; @@ -1303,7 +1303,7 @@ void getOverriddenMethods(const CXXMethodDecl *CMD, } } -llvm::Optional +std::optional stringifyContainerForMainFileRef(const Decl *Container) { // FIXME We might also want to display the signature here // When doing so, remember to also add the Signature to index results! @@ -1329,7 +1329,7 @@ ReferencesResult findReferences(ParsedAST &AST, Position Pos, uint32_t Limit, const auto *IdentifierAtCursor = syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens()); - llvm::Optional Macro; + std::optional Macro; if (IdentifierAtCursor) Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor()); if (Macro) { @@ -1607,7 +1607,7 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, } template -static llvm::Optional +static std::optional declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) { ASTContext &Ctx = ND.getASTContext(); auto &SM = Ctx.getSourceManager(); @@ -1649,7 +1649,7 @@ declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) { return HI; } -static llvm::Optional +static std::optional declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) { auto Result = declToHierarchyItem(ND, TUPath); if (Result) { @@ -1663,7 +1663,7 @@ declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) { return Result; } -static llvm::Optional +static std::optional declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) { auto Result = declToHierarchyItem(ND, TUPath); if (!Result) @@ -1676,8 +1676,8 @@ declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) { } template -static llvm::Optional symbolToHierarchyItem(const Symbol &S, - PathRef TUPath) { +static std::optional symbolToHierarchyItem(const Symbol &S, + PathRef TUPath) { auto Loc = symbolToLocation(S, TUPath); if (!Loc) { elog("Failed to convert symbol to hierarchy item: {0}", Loc.takeError()); @@ -1695,7 +1695,7 @@ static llvm::Optional symbolToHierarchyItem(const Symbol &S, return HI; } -static llvm::Optional +static std::optional symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath) { auto Result = symbolToHierarchyItem(S, TUPath); if (Result) { @@ -1705,7 +1705,7 @@ symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath) { return Result; } -static llvm::Optional +static std::optional symbolToCallHierarchyItem(const Symbol &S, PathRef TUPath) { auto Result = symbolToHierarchyItem(S, TUPath); if (!Result) @@ -1723,7 +1723,7 @@ static void fillSubTypes(const SymbolID &ID, Req.Subjects.insert(ID); Req.Predicate = RelationKind::BaseOf; Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) { - if (Optional ChildSym = + if (std::optional ChildSym = symbolToTypeHierarchyItem(Object, TUPath)) { if (Levels > 1) { ChildSym->children.emplace(); @@ -1755,7 +1755,7 @@ static void fillSuperTypes(const CXXRecordDecl &CXXRD, llvm::StringRef TUPath, } for (const CXXRecordDecl *ParentDecl : typeParents(&CXXRD)) { - if (Optional ParentSym = + if (std::optional ParentSym = declToTypeHierarchyItem(*ParentDecl, TUPath)) { fillSuperTypes(*ParentDecl, TUPath, *ParentSym, RPSet); Item.data.parents->emplace_back(ParentSym->data); @@ -2087,7 +2087,7 @@ getTypeHierarchy(ParsedAST &AST, Position Pos, int ResolveLevels, CXXRD = CTSD->getTemplateInstantiationPattern(); } - Optional Result = + std::optional Result = declToTypeHierarchyItem(*CXXRD, AST.tuPath()); if (!Result) continue; diff --git a/clang-tools-extra/clangd/XRefs.h b/clang-tools-extra/clangd/XRefs.h index 8af5106078b4..c4f7952364e0 100644 --- a/clang-tools-extra/clangd/XRefs.h +++ b/clang-tools-extra/clangd/XRefs.h @@ -45,7 +45,7 @@ struct LocatedSymbol { // The canonical or best declaration: where most users find its interface. Location PreferredDeclaration; // Where the symbol is defined, if known. May equal PreferredDeclaration. - llvm::Optional Definition; + std::optional Definition; // SymbolID of the located symbol if available. SymbolID ID; }; diff --git a/clang-tools-extra/clangd/index/Background.cpp b/clang-tools-extra/clangd/index/Background.cpp index f09fb5d29301..117c766eea0d 100644 --- a/clang-tools-extra/clangd/index/Background.cpp +++ b/clang-tools-extra/clangd/index/Background.cpp @@ -124,7 +124,7 @@ BackgroundQueue::Task BackgroundIndex::changedFilesTask( BackgroundQueue::Task T([this, ChangedFiles] { trace::Span Tracer("BackgroundIndexEnqueue"); - llvm::Optional WithProvidedContext; + std::optional WithProvidedContext; if (ContextProvider) WithProvidedContext.emplace(ContextProvider(/*Path=*/"")); @@ -157,7 +157,7 @@ BackgroundQueue::Task BackgroundIndex::indexFileTask(std::string Path) { std::string Tag = filenameWithoutExtension(Path).str(); uint64_t Key = llvm::xxHash64(Path); BackgroundQueue::Task T([this, Path(std::move(Path))] { - llvm::Optional WithProvidedContext; + std::optional WithProvidedContext; if (ContextProvider) WithProvidedContext.emplace(ContextProvider(Path)); auto Cmd = CDB.getCompileCommand(Path); diff --git a/clang-tools-extra/clangd/index/Background.h b/clang-tools-extra/clangd/index/Background.h index 45f679a16617..0d719ffdb957 100644 --- a/clang-tools-extra/clangd/index/Background.h +++ b/clang-tools-extra/clangd/index/Background.h @@ -62,7 +62,7 @@ public: // CDBDirectory is the first directory containing a CDB in parent directories // of a file, or user cache directory if none was found, e.g. stdlib headers. static Factory createDiskBackedStorageFactory( - std::function(PathRef)> GetProjectInfo); + std::function(PathRef)> GetProjectInfo); }; // A priority queue of tasks which can be run on (external) worker threads. @@ -112,7 +112,7 @@ public: // Only affects tasks that run after the call. static void preventThreadStarvationInTests(); [[nodiscard]] bool - blockUntilIdleForTest(llvm::Optional TimeoutSeconds); + blockUntilIdleForTest(std::optional TimeoutSeconds); private: void notifyProgress() const; // Requires lock Mu @@ -174,7 +174,7 @@ public: // Wait until the queue is empty, to allow deterministic testing. [[nodiscard]] bool - blockUntilIdleForTest(llvm::Optional TimeoutSeconds = 10) { + blockUntilIdleForTest(std::optional TimeoutSeconds = 10) { return Queue.blockUntilIdleForTest(TimeoutSeconds); } diff --git a/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp b/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp index c7bbd98a32ce..27c9c91ad633 100644 --- a/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp +++ b/clang-tools-extra/clangd/index/BackgroundIndexStorage.cpp @@ -99,7 +99,7 @@ public: class DiskBackedIndexStorageManager { public: DiskBackedIndexStorageManager( - std::function(PathRef)> GetProjectInfo) + std::function(PathRef)> GetProjectInfo) : IndexStorageMapMu(std::make_unique()), GetProjectInfo(std::move(GetProjectInfo)) { llvm::SmallString<128> FallbackDir; @@ -136,14 +136,14 @@ private: llvm::StringMap> IndexStorageMap; std::unique_ptr IndexStorageMapMu; - std::function(PathRef)> GetProjectInfo; + std::function(PathRef)> GetProjectInfo; }; } // namespace BackgroundIndexStorage::Factory BackgroundIndexStorage::createDiskBackedStorageFactory( - std::function(PathRef)> GetProjectInfo) { + std::function(PathRef)> GetProjectInfo) { return DiskBackedIndexStorageManager(std::move(GetProjectInfo)); } diff --git a/clang-tools-extra/clangd/index/BackgroundQueue.cpp b/clang-tools-extra/clangd/index/BackgroundQueue.cpp index 5fb1511353ee..6023f48ccd3b 100644 --- a/clang-tools-extra/clangd/index/BackgroundQueue.cpp +++ b/clang-tools-extra/clangd/index/BackgroundQueue.cpp @@ -21,7 +21,7 @@ void BackgroundQueue::preventThreadStarvationInTests() { void BackgroundQueue::work(std::function OnIdle) { while (true) { - llvm::Optional Task; + std::optional Task; { std::unique_lock Lock(Mu); CV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); }); @@ -134,7 +134,7 @@ void BackgroundQueue::boost(llvm::StringRef Tag, unsigned NewPriority) { } bool BackgroundQueue::blockUntilIdleForTest( - llvm::Optional TimeoutSeconds) { + std::optional TimeoutSeconds) { std::unique_lock Lock(Mu); return wait(Lock, CV, timeoutSeconds(TimeoutSeconds), [&] { return Queue.empty() && Stat.Active == 0; }); diff --git a/clang-tools-extra/clangd/index/FileIndex.cpp b/clang-tools-extra/clangd/index/FileIndex.cpp index 95bda42a796c..348f15e07317 100644 --- a/clang-tools-extra/clangd/index/FileIndex.cpp +++ b/clang-tools-extra/clangd/index/FileIndex.cpp @@ -189,7 +189,7 @@ std::vector FileShardedIndex::getAllSources() const { return Result; } -llvm::Optional +std::optional FileShardedIndex::getShard(llvm::StringRef Uri) const { auto It = Shards.find(Uri); if (It == Shards.end()) diff --git a/clang-tools-extra/clangd/index/FileIndex.h b/clang-tools-extra/clangd/index/FileIndex.h index 31757d13eb40..34ecbf41e09a 100644 --- a/clang-tools-extra/clangd/index/FileIndex.h +++ b/clang-tools-extra/clangd/index/FileIndex.h @@ -179,7 +179,7 @@ struct FileShardedIndex { /// a copy of all the relevant data. /// Returned index will always have Symbol/Refs/Relation Slabs set, even if /// they are empty. - llvm::Optional getShard(llvm::StringRef Uri) const; + std::optional getShard(llvm::StringRef Uri) const; private: // Contains all the information that belongs to a single file. diff --git a/clang-tools-extra/clangd/index/Index.h b/clang-tools-extra/clangd/index/Index.h index e836d459c2ee..db5c967b6e1a 100644 --- a/clang-tools-extra/clangd/index/Index.h +++ b/clang-tools-extra/clangd/index/Index.h @@ -72,7 +72,7 @@ struct RefsRequest { /// If set, limit the number of refers returned from the index. The index may /// choose to return less than this, e.g. it tries to avoid returning stale /// results. - llvm::Optional Limit; + std::optional Limit; /// If set, populates the container of the reference. /// Index implementations may chose to populate containers no matter what. bool WantContainer = false; @@ -82,7 +82,7 @@ struct RelationsRequest { llvm::DenseSet Subjects; RelationKind Predicate; /// If set, limit the number of relations returned from the index. - llvm::Optional Limit; + std::optional Limit; }; /// Describes what data is covered by an index. diff --git a/clang-tools-extra/clangd/index/IndexAction.cpp b/clang-tools-extra/clangd/index/IndexAction.cpp index d97dc40e03a6..6588f4d51323 100644 --- a/clang-tools-extra/clangd/index/IndexAction.cpp +++ b/clang-tools-extra/clangd/index/IndexAction.cpp @@ -29,7 +29,7 @@ namespace clang { namespace clangd { namespace { -llvm::Optional toURI(OptionalFileEntryRef File) { +std::optional toURI(OptionalFileEntryRef File) { if (!File) return std::nullopt; auto AbsolutePath = File->getFileEntry().tryGetRealPathName(); diff --git a/clang-tools-extra/clangd/index/Serialization.h b/clang-tools-extra/clangd/index/Serialization.h index fceaefed4c0c..b6890d63d2c3 100644 --- a/clang-tools-extra/clangd/index/Serialization.h +++ b/clang-tools-extra/clangd/index/Serialization.h @@ -41,13 +41,13 @@ enum class IndexFileFormat { // Holds the contents of an index file that was read. struct IndexFileIn { - llvm::Optional Symbols; - llvm::Optional Refs; - llvm::Optional Relations; + std::optional Symbols; + std::optional Refs; + std::optional Relations; // Keys are URIs of the source files. - llvm::Optional Sources; + std::optional Sources; // This contains only the Directory and CommandLine. - llvm::Optional Cmd; + std::optional Cmd; }; // Parse an index file. The input must be a RIFF or YAML file. llvm::Expected readIndexFile(llvm::StringRef, SymbolOrigin); diff --git a/clang-tools-extra/clangd/index/StdLib.cpp b/clang-tools-extra/clangd/index/StdLib.cpp index ab9a8ed8cfb3..399bd2ffaff6 100644 --- a/clang-tools-extra/clangd/index/StdLib.cpp +++ b/clang-tools-extra/clangd/index/StdLib.cpp @@ -286,8 +286,8 @@ bool StdLibSet::isBest(const LangOptions &LO) const { Best[langFromOpts(LO)].load(std::memory_order_acquire); } -llvm::Optional StdLibSet::add(const LangOptions &LO, - const HeaderSearch &HS) { +std::optional StdLibSet::add(const LangOptions &LO, + const HeaderSearch &HS) { Lang L = langFromOpts(LO); int OldVersion = Best[L].load(std::memory_order_acquire); int NewVersion = standardFromOpts(LO); diff --git a/clang-tools-extra/clangd/index/StdLib.h b/clang-tools-extra/clangd/index/StdLib.h index 6c170dceba9c..2ed5eae61f85 100644 --- a/clang-tools-extra/clangd/index/StdLib.h +++ b/clang-tools-extra/clangd/index/StdLib.h @@ -67,7 +67,7 @@ public: // Returns the location where the standard library was found. // // This function is threadsafe. - llvm::Optional add(const LangOptions &, const HeaderSearch &); + std::optional add(const LangOptions &, const HeaderSearch &); // Indicates whether a built index should be used. // It should not be used if a newer version has subsequently been added. diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp b/clang-tools-extra/clangd/index/SymbolCollector.cpp index 5f9c8bbb4ee9..822f3cb9b956 100644 --- a/clang-tools-extra/clangd/index/SymbolCollector.cpp +++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp @@ -146,7 +146,7 @@ RefKind toRefKind(index::SymbolRoleSet Roles, bool Spelled = false) { return Result; } -llvm::Optional indexableRelation(const index::SymbolRelation &R) { +std::optional indexableRelation(const index::SymbolRelation &R) { if (R.Roles & static_cast(index::SymbolRole::RelationBaseOf)) return RelationKind::BaseOf; if (R.Roles & static_cast(index::SymbolRole::RelationOverrideOf)) @@ -178,10 +178,10 @@ bool isSpelled(SourceLocation Loc, const NamedDecl &ND) { class SymbolCollector::HeaderFileURICache { struct FrameworkUmbrellaSpelling { // Spelling for the public umbrella header, e.g. - llvm::Optional PublicHeader; + std::optional PublicHeader; // Spelling for the private umbrella header, e.g. // - llvm::Optional PrivateHeader; + std::optional PrivateHeader; }; // Weird double-indirect access to PP, which might not be ready yet when // HeaderFiles is created but will be by the time it's used. @@ -263,7 +263,7 @@ private: bool IsPrivateHeader; }; - llvm::Optional + std::optional splitFrameworkHeaderPath(llvm::StringRef Path) { using namespace llvm::sys; path::reverse_iterator I = path::rbegin(Path); @@ -296,7 +296,7 @@ private: // instead of // which should be used instead of directly // importing the header. - llvm::Optional getFrameworkUmbrellaSpelling( + std::optional getFrameworkUmbrellaSpelling( llvm::StringRef Framework, SrcMgr::CharacteristicKind HeadersDirKind, HeaderSearch &HS, FrameworkHeaderPath &HeaderPath) { auto Res = CacheFrameworkToUmbrellaHeaderSpelling.try_emplace(Framework); @@ -340,7 +340,7 @@ private: // named `Framework`, e.g. `NSObject.h` in framework `Foundation` would // give if the umbrella header exists, otherwise // . - llvm::Optional getFrameworkHeaderIncludeSpelling( + std::optional getFrameworkHeaderIncludeSpelling( const FileEntry *FE, llvm::StringRef Framework, HeaderSearch &HS) { auto Res = CachePathToFrameworkSpelling.try_emplace(FE->getName()); auto *CachedHeaderSpelling = &Res.first->second; @@ -414,7 +414,7 @@ private: }; // Return the symbol location of the token at \p TokLoc. -llvm::Optional +std::optional SymbolCollector::getTokenLocation(SourceLocation TokLoc) { const auto &SM = ASTCtx->getSourceManager(); auto *FE = SM.getFileEntryForID(SM.getFileID(TokLoc)); @@ -941,7 +941,7 @@ const Symbol *SymbolCollector::addDeclaration(const NamedDecl &ND, SymbolID ID, std::string ReturnType = getReturnType(*CCS); S.ReturnType = ReturnType; - llvm::Optional TypeStorage; + std::optional TypeStorage; if (S.Flags & Symbol::IndexedForCodeCompletion) { TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion); if (TypeStorage) diff --git a/clang-tools-extra/clangd/index/SymbolCollector.h b/clang-tools-extra/clangd/index/SymbolCollector.h index 6acce1f3e3c4..265554429a2d 100644 --- a/clang-tools-extra/clangd/index/SymbolCollector.h +++ b/clang-tools-extra/clangd/index/SymbolCollector.h @@ -156,9 +156,9 @@ private: void processRelations(const NamedDecl &ND, const SymbolID &ID, ArrayRef Relations); - llvm::Optional getTokenLocation(SourceLocation TokLoc); + std::optional getTokenLocation(SourceLocation TokLoc); - llvm::Optional getIncludeHeader(const Symbol &S, FileID); + std::optional getIncludeHeader(const Symbol &S, FileID); SymbolID getSymbolIDCached(const Decl *D); SymbolID getSymbolIDCached(const llvm::StringRef MacroName, diff --git a/clang-tools-extra/clangd/index/YAMLSerialization.cpp b/clang-tools-extra/clangd/index/YAMLSerialization.cpp index c51489fd5dc6..2892d8cd8769 100644 --- a/clang-tools-extra/clangd/index/YAMLSerialization.cpp +++ b/clang-tools-extra/clangd/index/YAMLSerialization.cpp @@ -42,11 +42,11 @@ using RefBundle = std::pair>; // This is a pale imitation of std::variant struct VariantEntry { - llvm::Optional Symbol; - llvm::Optional Refs; - llvm::Optional Relation; - llvm::Optional Source; - llvm::Optional Cmd; + std::optional Symbol; + std::optional Refs; + std::optional Relation; + std::optional Source; + std::optional Cmd; }; // A class helps YAML to serialize the 32-bit encoded position (Line&Column), // as YAMLIO can't directly map bitfields. @@ -480,7 +480,7 @@ llvm::Expected readYAML(llvm::StringRef Data, llvm::UniqueStringSaver Strings(Arena); llvm::yaml::Input Yin(Data, &Strings); IncludeGraph Sources; - llvm::Optional Cmd; + std::optional Cmd; while (Yin.setCurrentDocument()) { llvm::yaml::EmptyContext Ctx; VariantEntry Variant; diff --git a/clang-tools-extra/clangd/index/dex/Dex.cpp b/clang-tools-extra/clangd/index/dex/Dex.cpp index 0e94f59187de..8f504fb9b7ea 100644 --- a/clang-tools-extra/clangd/index/dex/Dex.cpp +++ b/clang-tools-extra/clangd/index/dex/Dex.cpp @@ -268,7 +268,7 @@ bool Dex::fuzzyFind(const FuzzyFindRequest &Req, for (const auto &IDAndScore : IDAndScores) { const DocID SymbolDocID = IDAndScore.first; const auto *Sym = Symbols[SymbolDocID]; - const llvm::Optional Score = Filter.match(Sym->Name); + const std::optional Score = Filter.match(Sym->Name); if (!Score) continue; // Combine Fuzzy Matching score, precomputed symbol quality and boosting diff --git a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp index 763382204dc2..392960d6d666 100644 --- a/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp +++ b/clang-tools-extra/clangd/index/dex/dexp/Dexp.cpp @@ -443,6 +443,6 @@ int main(int argc, const char *argv[]) { return runCommand(ExecCommand, *Index) ? 0 : 1; llvm::LineEditor LE("dexp"); - while (llvm::Optional Request = LE.readLine()) + while (std::optional Request = LE.readLine()) runCommand(std::move(*Request), *Index); } diff --git a/clang-tools-extra/clangd/index/remote/server/Server.cpp b/clang-tools-extra/clangd/index/remote/server/Server.cpp index 5d2c82e2c86a..e108d4d0b057 100644 --- a/clang-tools-extra/clangd/index/remote/server/Server.cpp +++ b/clang-tools-extra/clangd/index/remote/server/Server.cpp @@ -504,7 +504,7 @@ int main(int argc, char *argv[]) { auto Logger = makeLogger(LogPrefix.getValue(), llvm::errs()); clang::clangd::LoggingSession LoggingSession(*Logger); - llvm::Optional TracerStream; + std::optional TracerStream; std::unique_ptr Tracer; if (!TraceFile.empty()) { std::error_code EC; @@ -522,7 +522,7 @@ int main(int argc, char *argv[]) { } } - llvm::Optional TracingSession; + std::optional TracingSession; if (Tracer) TracingSession.emplace(*Tracer); diff --git a/clang-tools-extra/clangd/refactor/InsertionPoint.cpp b/clang-tools-extra/clangd/refactor/InsertionPoint.cpp index ff17ddd420b7..7f042c0cacb9 100644 --- a/clang-tools-extra/clangd/refactor/InsertionPoint.cpp +++ b/clang-tools-extra/clangd/refactor/InsertionPoint.cpp @@ -22,8 +22,8 @@ namespace { // Choose the decl to insert before, according to an anchor. // Nullptr means insert at end of DC. // None means no valid place to insert. -llvm::Optional insertionDecl(const DeclContext &DC, - const Anchor &A) { +std::optional insertionDecl(const DeclContext &DC, + const Anchor &A) { bool LastMatched = false; bool ReturnNext = false; for (const auto *D : DC.decls()) { diff --git a/clang-tools-extra/clangd/refactor/Rename.cpp b/clang-tools-extra/clangd/refactor/Rename.cpp index afddab007358..6362768f9b47 100644 --- a/clang-tools-extra/clangd/refactor/Rename.cpp +++ b/clang-tools-extra/clangd/refactor/Rename.cpp @@ -39,8 +39,8 @@ namespace clang { namespace clangd { namespace { -llvm::Optional filePath(const SymbolLocation &Loc, - llvm::StringRef HintFilePath) { +std::optional filePath(const SymbolLocation &Loc, + llvm::StringRef HintFilePath) { if (!Loc) return std::nullopt; auto Path = URI::resolve(Loc.FileURI, HintFilePath); @@ -197,10 +197,10 @@ enum class ReasonToReject { SameName, }; -llvm::Optional renameable(const NamedDecl &RenameDecl, - StringRef MainFilePath, - const SymbolIndex *Index, - const RenameOptions& Opts) { +std::optional renameable(const NamedDecl &RenameDecl, + StringRef MainFilePath, + const SymbolIndex *Index, + const RenameOptions &Opts) { trace::Span Tracer("Renameable"); if (!Opts.RenameVirtual) { if (const auto *S = llvm::dyn_cast(&RenameDecl)) { @@ -501,13 +501,13 @@ static bool mayBeValidIdentifier(llvm::StringRef Ident) { // Check if we can rename the given RenameDecl into NewName. // Return details if the rename would produce a conflict. -llvm::Optional checkName(const NamedDecl &RenameDecl, - llvm::StringRef NewName) { +std::optional checkName(const NamedDecl &RenameDecl, + llvm::StringRef NewName) { trace::Span Tracer("CheckName"); static constexpr trace::Metric InvalidNameMetric( "rename_name_invalid", trace::Metric::Counter, "invalid_kind"); auto &ASTCtx = RenameDecl.getASTContext(); - llvm::Optional Result; + std::optional Result; if (isKeyword(NewName, ASTCtx.getLangOpts())) Result = InvalidName{InvalidName::Keywords, NewName.str()}; else if (!mayBeValidIdentifier(NewName)) @@ -911,7 +911,7 @@ llvm::Expected buildRenameEdit(llvm::StringRef AbsFilePath, // ranges onto candidates in a plausible way (e.g. guess that lines // were inserted). If such a "near miss" is found, the rename is still // possible -llvm::Optional> +std::optional> adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier, std::vector Indexed, const LangOptions &LangOpts) { trace::Span Tracer("AdjustRenameRanges"); @@ -923,8 +923,8 @@ adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier, return getMappedRanges(Indexed, Lexed); } -llvm::Optional> getMappedRanges(ArrayRef Indexed, - ArrayRef Lexed) { +std::optional> getMappedRanges(ArrayRef Indexed, + ArrayRef Lexed) { trace::Span Tracer("GetMappedRanges"); assert(!Indexed.empty()); assert(llvm::is_sorted(Indexed)); diff --git a/clang-tools-extra/clangd/refactor/Rename.h b/clang-tools-extra/clangd/refactor/Rename.h index 6b917d561180..91728ba59e5d 100644 --- a/clang-tools-extra/clangd/refactor/Rename.h +++ b/clang-tools-extra/clangd/refactor/Rename.h @@ -84,7 +84,7 @@ llvm::Expected buildRenameEdit(llvm::StringRef AbsFilePath, /// The API assumes that Indexed contains only named occurrences (each /// occurrence has the same length). /// REQUIRED: Indexed is sorted. -llvm::Optional> +std::optional> adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier, std::vector Indexed, const LangOptions &LangOpts); @@ -94,8 +94,8 @@ adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier, /// Exposed for testing only. /// /// REQUIRED: Indexed and Lexed are sorted. -llvm::Optional> getMappedRanges(ArrayRef Indexed, - ArrayRef Lexed); +std::optional> getMappedRanges(ArrayRef Indexed, + ArrayRef Lexed); /// Evaluates how good the mapped result is. 0 indicates a perfect match. /// /// Exposed for testing only. diff --git a/clang-tools-extra/clangd/refactor/Tweak.h b/clang-tools-extra/clangd/refactor/Tweak.h index f91faf2aedcf..e35d34afc4d1 100644 --- a/clang-tools-extra/clangd/refactor/Tweak.h +++ b/clang-tools-extra/clangd/refactor/Tweak.h @@ -74,7 +74,7 @@ public: struct Effect { /// A message to be displayed to the user. - llvm::Optional ShowMessage; + std::optional ShowMessage; FileEdits ApplyEdits; /// Whether the edits should be formatted before presenting to the client. /// Note that it applies to all files. diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp index 410dec0b9100..4e97b1306217 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/DefineInline.cpp @@ -53,7 +53,7 @@ namespace { // Returns semicolon location for the given FD. Since AST doesn't contain that // information, searches for a semicolon by lexing from end of function decl // while skipping comments. -llvm::Optional getSemicolonForDecl(const FunctionDecl *FD) { +std::optional getSemicolonForDecl(const FunctionDecl *FD) { const SourceManager &SM = FD->getASTContext().getSourceManager(); const LangOptions &LangOpts = FD->getASTContext().getLangOpts(); @@ -349,7 +349,7 @@ const SourceLocation getBeginLoc(const FunctionDecl *FD) { return FD->getBeginLoc(); } -llvm::Optional +std::optional addInlineIfInHeader(const FunctionDecl *FD) { // This includes inline functions and constexpr functions. if (FD->isInlined() || llvm::isa(FD)) diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp index 1e09da9aa20b..782d14ec9e9b 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp @@ -59,8 +59,8 @@ const FunctionDecl *getSelectedFunction(const SelectionTree::Node *SelNode) { return nullptr; } -llvm::Optional getSourceFile(llvm::StringRef FileName, - const Tweak::Selection &Sel) { +std::optional getSourceFile(llvm::StringRef FileName, + const Tweak::Selection &Sel) { assert(Sel.FS); if (auto Source = getCorrespondingHeaderOrSource(FileName, Sel.FS)) return *Source; @@ -70,7 +70,7 @@ llvm::Optional getSourceFile(llvm::StringRef FileName, // Synthesize a DeclContext for TargetNS from CurContext. TargetNS must be empty // for global namespace, and endwith "::" otherwise. // Returns std::nullopt if TargetNS is not a prefix of CurContext. -llvm::Optional +std::optional findContextForNS(llvm::StringRef TargetNS, const DeclContext *CurContext) { assert(TargetNS.empty() || TargetNS.endswith("::")); // Skip any non-namespace contexts, e.g. TagDecls, functions/methods. diff --git a/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp b/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp index 7a89ce7dc3cf..e126e72ef253 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/DumpAST.cpp @@ -56,7 +56,7 @@ private: return N.get() || N.get() || N.get(); } - llvm::Optional Node; + std::optional Node; }; REGISTER_TWEAK(DumpAST) diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp index aabaed045c3d..b87752117e16 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/ExpandAutoType.cpp @@ -114,7 +114,7 @@ bool ExpandAutoType::prepare(const Selection &Inputs) { Expected ExpandAutoType::apply(const Selection& Inputs) { auto &SrcMgr = Inputs.AST->getSourceManager(); - llvm::Optional DeducedType = + std::optional DeducedType = getDeducedType(Inputs.AST->getASTContext(), AutoRange.getBegin()); // if we can't resolve the type, return an error message diff --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp index a259deb0a915..b47d0833868b 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp @@ -265,9 +265,9 @@ const FunctionDecl *findEnclosingFunction(const Node *CommonAnc) { // Zone Range is the union of SourceRanges of all child Nodes in Parent since // all child Nodes are RootStmts -llvm::Optional findZoneRange(const Node *Parent, - const SourceManager &SM, - const LangOptions &LangOpts) { +std::optional findZoneRange(const Node *Parent, + const SourceManager &SM, + const LangOptions &LangOpts) { SourceRange SR; if (auto BeginFileRange = toHalfOpenFileRange( SM, LangOpts, Parent->Children.front()->ASTNode.getSourceRange())) @@ -286,7 +286,7 @@ llvm::Optional findZoneRange(const Node *Parent, // FIXME: check if EnclosingFunction has any attributes as the AST doesn't // always store the source range of the attributes and thus we end up extracting // between the attributes and the EnclosingFunction. -llvm::Optional +std::optional computeEnclosingFuncRange(const FunctionDecl *EnclosingFunction, const SourceManager &SM, const LangOptions &LangOpts) { @@ -311,9 +311,9 @@ bool validSingleChild(const Node *Child, const FunctionDecl *EnclosingFunc) { // FIXME: Check we're not extracting from the initializer/condition of a control // flow structure. -llvm::Optional findExtractionZone(const Node *CommonAnc, - const SourceManager &SM, - const LangOptions &LangOpts) { +std::optional findExtractionZone(const Node *CommonAnc, + const SourceManager &SM, + const LangOptions &LangOpts) { ExtractionZone ExtZone; ExtZone.Parent = getParentOfRootStmts(CommonAnc); if (!ExtZone.Parent || ExtZone.Parent->Children.empty()) @@ -358,7 +358,7 @@ struct NewFunction { std::vector Parameters; SourceRange BodyRange; SourceLocation DefinitionPoint; - llvm::Optional ForwardDeclarationPoint; + std::optional ForwardDeclarationPoint; const CXXRecordDecl *EnclosingClass = nullptr; const NestedNameSpecifier *DefinitionQualifier = nullptr; const DeclContext *SemanticDC = nullptr; diff --git a/clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp b/clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp index dbaf2a5d5c36..c3f53219f224 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/ObjCMemberwiseInitializer.cpp @@ -90,7 +90,7 @@ struct MethodParameter { else // Could be a dynamic property or a property in a header. Assignee = ("self." + Name).str(); } - static llvm::Optional parameterFor(const Decl &D) { + static std::optional parameterFor(const Decl &D) { if (const auto *ID = dyn_cast(&D)) return MethodParameter(*ID); if (const auto *PD = dyn_cast(&D)) diff --git a/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp b/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp index 51d299ee63de..da32e00a0ee0 100644 --- a/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp +++ b/clang-tools-extra/clangd/refactor/tweaks/RemoveUsingNamespace.cpp @@ -73,7 +73,7 @@ private: llvm::Expected removeUsingDirective(ASTContext &Ctx, const UsingDirectiveDecl *D) { auto &SM = Ctx.getSourceManager(); - llvm::Optional NextTok = + std::optional NextTok = Lexer::findNextToken(D->getEndLoc(), SM, Ctx.getLangOpts()); if (!NextTok || NextTok->isNot(tok::semi)) return error("no semicolon after using-directive"); diff --git a/clang-tools-extra/clangd/tool/Check.cpp b/clang-tools-extra/clangd/tool/Check.cpp index 3250571d4bce..b0af90061dd2 100644 --- a/clang-tools-extra/clangd/tool/Check.cpp +++ b/clang-tools-extra/clangd/tool/Check.cpp @@ -126,7 +126,7 @@ class Checker { format::FormatStyle Style; // from buildAST std::shared_ptr Preamble; - llvm::Optional AST; + std::optional AST; FileIndex Index; public: @@ -167,7 +167,7 @@ public: // Prepare inputs and build CompilerInvocation (parsed compile command). bool buildInvocation(const ThreadsafeFS &TFS, - llvm::Optional Contents) { + std::optional Contents) { StoreDiags CaptureInvocationDiags; std::vector CC1Args; Inputs.CompileCommand = Cmd; @@ -438,7 +438,7 @@ bool check(llvm::StringRef File, const ThreadsafeFS &TFS, } llvm::SmallString<0> FakeFile; - llvm::Optional Contents; + std::optional Contents; if (File.empty()) { llvm::sys::path::system_temp_directory(false, FakeFile); llvm::sys::path::append(FakeFile, "test.cc"); diff --git a/clang-tools-extra/clangd/tool/ClangdMain.cpp b/clang-tools-extra/clangd/tool/ClangdMain.cpp index fa6bda1c6d1e..e0682f164c89 100644 --- a/clang-tools-extra/clangd/tool/ClangdMain.cpp +++ b/clang-tools-extra/clangd/tool/ClangdMain.cpp @@ -639,9 +639,9 @@ private: public: FlagsConfigProvider() { - llvm::Optional CDBSearch; - llvm::Optional IndexSpec; - llvm::Optional BGPolicy; + std::optional CDBSearch; + std::optional IndexSpec; + std::optional BGPolicy; // If --compile-commands-dir arg was invoked, check value and override // default path. @@ -784,7 +784,7 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var clang::format::DefaultFallbackStyle = FallbackStyle.c_str(); // Validate command line arguments. - llvm::Optional InputMirrorStream; + std::optional InputMirrorStream; if (!InputMirrorFile.empty()) { std::error_code EC; InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC, @@ -808,7 +808,7 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var // Setup tracing facilities if CLANGD_TRACE is set. In practice enabling a // trace flag in your editor's config is annoying, launching with // `CLANGD_TRACE=trace.json vim` is easier. - llvm::Optional TracerStream; + std::optional TracerStream; std::unique_ptr Tracer; const char *JSONTraceFile = getenv("CLANGD_TRACE"); const char *MetricsCSVFile = getenv("CLANGD_METRICS"); @@ -828,7 +828,7 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var } } - llvm::Optional TracingSession; + std::optional TracingSession; if (Tracer) TracingSession.emplace(*Tracer); diff --git a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp index a9a30eac4368..4c6a238bbb26 100644 --- a/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp +++ b/clang-tools-extra/clangd/unittests/ClangdLSPServerTests.cpp @@ -98,8 +98,8 @@ private: Logger L; LoggingSession LogSession; - llvm::Optional Server; - llvm::Optional ServerThread; + std::optional Server; + std::optional ServerThread; LSPClient Client; }; @@ -262,10 +262,11 @@ TEST_F(LSPTest, ModulesTest) { ElementsAre(llvm::json::Value(2), llvm::json::Value(10))); } -// Creates a Callback that writes its received value into an Optional. +// Creates a Callback that writes its received value into an +// std::optional. template llvm::unique_function)> -capture(llvm::Optional> &Out) { +capture(std::optional> &Out) { Out.reset(); return [&Out](llvm::Expected V) { Out.emplace(std::move(V)); }; } diff --git a/clang-tools-extra/clangd/unittests/ClangdTests.cpp b/clang-tools-extra/clangd/unittests/ClangdTests.cpp index 05630629009c..6e6036ece34a 100644 --- a/clang-tools-extra/clangd/unittests/ClangdTests.cpp +++ b/clang-tools-extra/clangd/unittests/ClangdTests.cpp @@ -1111,7 +1111,7 @@ TEST(ClangdServerTest, FallbackWhenWaitingForCompileCommand) { DelayedCompilationDatabase(Notification &CanReturnCommand) : CanReturnCommand(CanReturnCommand) {} - llvm::Optional + std::optional getCompileCommand(PathRef File) const override { // FIXME: make this timeout and fail instead of waiting forever in case // something goes wrong. diff --git a/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp b/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp index 8d434a2793e2..16dd81a107e2 100644 --- a/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp +++ b/clang-tools-extra/clangd/unittests/ConfigCompileTests.cpp @@ -436,7 +436,7 @@ TEST_F(ConfigCompileTests, ExternalBlockDisablesBackgroundIndex) { TEST_F(ConfigCompileTests, ExternalBlockMountPoint) { auto GetFrag = [](llvm::StringRef Directory, - llvm::Optional MountPoint) { + std::optional MountPoint) { Fragment Frag; Frag.Source.Directory = Directory.str(); Fragment::IndexBlock::ExternalBlock External; diff --git a/clang-tools-extra/clangd/unittests/ConfigTesting.h b/clang-tools-extra/clangd/unittests/ConfigTesting.h index c06a06127673..dc92e1335e11 100644 --- a/clang-tools-extra/clangd/unittests/ConfigTesting.h +++ b/clang-tools-extra/clangd/unittests/ConfigTesting.h @@ -50,7 +50,7 @@ struct CapturedDiags { std::string Message; llvm::SourceMgr::DiagKind Kind; Position Pos; - llvm::Optional Rng; + std::optional Rng; friend void PrintTo(const Diag &D, std::ostream *OS) { *OS << (D.Kind == llvm::SourceMgr::DK_Error ? "error: " : "warning: ") diff --git a/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp b/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp index 839f4c8e57a5..afefa245f03e 100644 --- a/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp +++ b/clang-tools-extra/clangd/unittests/ExpectedTypeTest.cpp @@ -39,7 +39,7 @@ protected: } /// An overload for convenience. - llvm::Optional fromCompletionResult(const NamedDecl *D) { + std::optional fromCompletionResult(const NamedDecl *D) { return OpaqueType::fromCompletionResult( astCtx(), CodeCompletionResult(D, CCP_Declaration)); } @@ -75,7 +75,7 @@ protected: private: // Set after calling build(). - llvm::Optional AST; + std::optional AST; }; TEST_F(ExpectedTypeConversionTest, BasicTypes) { diff --git a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp index 71bcb1234ba8..a2fc52ae6e7a 100644 --- a/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp +++ b/clang-tools-extra/clangd/unittests/GlobalCompilationDatabaseTests.cpp @@ -64,7 +64,7 @@ static tooling::CompileCommand cmd(llvm::StringRef File, llvm::StringRef Arg) { class OverlayCDBTest : public ::testing::Test { class BaseCDB : public GlobalCompilationDatabase { public: - llvm::Optional + std::optional getCompileCommand(llvm::StringRef File) const override { if (File == testPath("foo.cc")) return cmd(File, "-DA=1"); @@ -76,7 +76,7 @@ class OverlayCDBTest : public ::testing::Test { return cmd(File, "-DA=2"); } - llvm::Optional getProjectInfo(PathRef File) const override { + std::optional getProjectInfo(PathRef File) const override { return ProjectInfo{testRoot()}; } }; diff --git a/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp b/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp index f6bc9a6248cf..6e280f5b085a 100644 --- a/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp +++ b/clang-tools-extra/clangd/unittests/HeaderSourceSwitchTests.cpp @@ -31,7 +31,7 @@ TEST(HeaderSourceSwitchTest, FileHeuristic) { FS.Files[FooCpp]; FS.Files[FooH]; FS.Files[Invalid]; - Optional PathResult = + std::optional PathResult = getCorrespondingHeaderOrSource(FooCpp, FS.view(std::nullopt)); EXPECT_TRUE(PathResult.has_value()); ASSERT_EQ(*PathResult, FooH); @@ -142,7 +142,7 @@ TEST(HeaderSourceSwitchTest, FromHeaderToSource) { // Test for switch from .h header to .cc source struct { llvm::StringRef HeaderCode; - llvm::Optional ExpectedSource; + std::optional ExpectedSource; } TestCases[] = { {"// empty, no header found", std::nullopt}, {R"cpp( @@ -211,7 +211,7 @@ TEST(HeaderSourceSwitchTest, FromSourceToHeader) { // Test for switching from .cc source file to .h header. struct { llvm::StringRef SourceCode; - llvm::Optional ExpectedResult; + std::optional ExpectedResult; } TestCases[] = { {"// empty, no header found", std::nullopt}, {R"cpp( diff --git a/clang-tools-extra/clangd/unittests/HeadersTests.cpp b/clang-tools-extra/clangd/unittests/HeadersTests.cpp index b14a14f0528b..4fadb7c04aea 100644 --- a/clang-tools-extra/clangd/unittests/HeadersTests.cpp +++ b/clang-tools-extra/clangd/unittests/HeadersTests.cpp @@ -119,8 +119,8 @@ protected: return Path.value_or(""); } - llvm::Optional insert(llvm::StringRef VerbatimHeader, - tooling::IncludeDirective Directive) { + std::optional insert(llvm::StringRef VerbatimHeader, + tooling::IncludeDirective Directive) { Clang = setupClang(); PreprocessOnlyAction Action; EXPECT_TRUE( diff --git a/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp b/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp index b23c00edc99e..03f787035b36 100644 --- a/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp +++ b/clang-tools-extra/clangd/unittests/LSPBinderTests.cpp @@ -31,10 +31,11 @@ bool fromJSON(const llvm::json::Value &V, Foo &F, llvm::json::Path P) { } llvm::json::Value toJSON(const Foo &F) { return F.X; } -// Creates a Callback that writes its received value into an Optional. +// Creates a Callback that writes its received value into an +// std::optional. template llvm::unique_function)> -capture(llvm::Optional> &Out) { +capture(std::optional> &Out) { Out.reset(); return [&Out](llvm::Expected V) { Out.emplace(std::move(V)); }; } @@ -90,7 +91,7 @@ TEST(LSPBinderTest, IncomingCalls) { UnorderedElementsAre("notify")); ASSERT_THAT(RawHandlers.CommandHandlers.keys(), UnorderedElementsAre("cmdPlusOne")); - llvm::Optional> Reply; + std::optional> Reply; auto &RawPlusOne = RawHandlers.MethodHandlers["plusOne"]; RawPlusOne(1, capture(Reply)); @@ -136,14 +137,14 @@ TEST(LSPBinderTest, OutgoingCalls) { LSPBinder::OutgoingMethod Fail; Fail = Binder.outgoingMethod("fail"); - llvm::Optional> Reply; + std::optional> Reply; Echo(Foo{2}, capture(Reply)); EXPECT_THAT(RawOutgoing.take("echo"), ElementsAre(llvm::json::Value(2))); ASSERT_TRUE(Reply.has_value()); EXPECT_THAT_EXPECTED(*Reply, llvm::HasValue(Foo{2})); // JSON response is integer, can't be parsed as string. - llvm::Optional> WrongTypeReply; + std::optional> WrongTypeReply; WrongSignature(Foo{2}, capture(WrongTypeReply)); EXPECT_THAT(RawOutgoing.take("wrongSignature"), ElementsAre(llvm::json::Value(2))); diff --git a/clang-tools-extra/clangd/unittests/LSPClient.cpp b/clang-tools-extra/clangd/unittests/LSPClient.cpp index 027bf57a8a04..9361c0e29c91 100644 --- a/clang-tools-extra/clangd/unittests/LSPClient.cpp +++ b/clang-tools-extra/clangd/unittests/LSPClient.cpp @@ -199,7 +199,7 @@ void LSPClient::didClose(llvm::StringRef Path) { void LSPClient::sync() { call("sync", nullptr).takeValue(); } -llvm::Optional> +std::optional> LSPClient::diagnostics(llvm::StringRef Path) { sync(); auto Notifications = takeNotifications("textDocument/publishDiagnostics"); diff --git a/clang-tools-extra/clangd/unittests/PreambleTests.cpp b/clang-tools-extra/clangd/unittests/PreambleTests.cpp index eb071e39c41d..1e95b62884f6 100644 --- a/clang-tools-extra/clangd/unittests/PreambleTests.cpp +++ b/clang-tools-extra/clangd/unittests/PreambleTests.cpp @@ -190,8 +190,8 @@ TEST(PreamblePatchTest, PatchesPreambleIncludes) { Field(&Inclusion::Resolved, testPath("a.h"))))); } -llvm::Optional createPatchedAST(llvm::StringRef Baseline, - llvm::StringRef Modified) { +std::optional createPatchedAST(llvm::StringRef Baseline, + llvm::StringRef Modified) { auto BaselinePreamble = TestTU::withCode(Baseline).preamble(); if (!BaselinePreamble) { ADD_FAILURE() << "Failed to build baseline preamble"; diff --git a/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp b/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp index eb5f60c3b935..9d40702ca5cd 100644 --- a/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp +++ b/clang-tools-extra/clangd/unittests/SourceCodeTests.cpp @@ -356,9 +356,9 @@ TEST(SourceCodeTests, CollectWords) { } class SpelledWordsTest : public ::testing::Test { - llvm::Optional AST; + std::optional AST; - llvm::Optional tryWord(const char *Text) { + std::optional tryWord(const char *Text) { llvm::Annotations A(Text); auto TU = TestTU::withCode(A.code()); AST = TU.build(); @@ -663,7 +663,7 @@ TEST(SourceCodeTests, HalfOpenFileRangePathologicalPreprocessor) { const auto &Func = cast(findDecl(AST, "test")); const auto &Body = cast(Func.getBody()); const auto &Loop = cast(*Body->child_begin()); - llvm::Optional Range = toHalfOpenFileRange( + std::optional Range = toHalfOpenFileRange( AST.getSourceManager(), AST.getLangOpts(), Loop->getSourceRange()); ASSERT_TRUE(Range) << "Failed to get file range"; EXPECT_EQ(AST.getSourceManager().getFileOffset(Range->getBegin()), diff --git a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp index 08523edfc558..a2bf1c0baf0b 100644 --- a/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp +++ b/clang-tools-extra/clangd/unittests/SymbolCollectorTests.cpp @@ -132,7 +132,7 @@ protected: std::string HeaderName = "f.h"; std::string FileName = "f.cpp"; TestTU File; - llvm::Optional AST; // Initialized after build. + std::optional AST; // Initialized after build. }; TEST_F(ShouldCollectSymbolTest, ShouldCollectSymbol) { @@ -870,7 +870,7 @@ TEST_F(SymbolCollectorTest, RefContainers) { CollectorOpts.RefFilter = RefKind::All; CollectorOpts.CollectMainFileRefs = true; runSymbolCollector("", Code.code()); - auto FindRefWithRange = [&](Range R) -> Optional { + auto FindRefWithRange = [&](Range R) -> std::optional { for (auto &Entry : Refs) { for (auto &Ref : Entry.second) { if (rangesMatch(Ref.Location, R)) diff --git a/clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp b/clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp index ad76d7dcf554..6c91f3783a62 100644 --- a/clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp +++ b/clang-tools-extra/clangd/unittests/SymbolInfoTests.cpp @@ -377,7 +377,7 @@ TEST(SymbolInfoTests, All) { std::vector Expected; for (const auto &Sym : T.second) { - llvm::Optional Decl, Def; + std::optional Decl, Def; if (Sym.DeclMarker) Decl = Location{URIForFile::canonicalize(testPath(TU.Filename), ""), TestInput.range(Sym.DeclMarker)}; diff --git a/clang-tools-extra/clangd/unittests/SyncAPI.cpp b/clang-tools-extra/clangd/unittests/SyncAPI.cpp index 2c4fde7d1895..d48622eba537 100644 --- a/clang-tools-extra/clangd/unittests/SyncAPI.cpp +++ b/clang-tools-extra/clangd/unittests/SyncAPI.cpp @@ -28,7 +28,7 @@ namespace { /// T Result; /// someAsyncFunc(Param1, Param2, /*Callback=*/capture(Result)); template struct CaptureProxy { - CaptureProxy(llvm::Optional &Target) : Target(&Target) { assert(!Target); } + CaptureProxy(std::optional &Target) : Target(&Target) { assert(!Target); } CaptureProxy(const CaptureProxy &) = delete; CaptureProxy &operator=(const CaptureProxy &) = delete; @@ -55,7 +55,7 @@ template struct CaptureProxy { } private: - llvm::Optional *Target; + std::optional *Target; // Using shared_ptr to workaround compilation errors with MSVC. // MSVC only allows default-constructible and copyable objects as future<> // arguments. @@ -63,7 +63,7 @@ private: std::future> Future; }; -template CaptureProxy capture(llvm::Optional &Target) { +template CaptureProxy capture(std::optional &Target) { return CaptureProxy(Target); } } // namespace @@ -71,7 +71,7 @@ template CaptureProxy capture(llvm::Optional &Target) { llvm::Expected runCodeComplete(ClangdServer &Server, PathRef File, Position Pos, clangd::CodeCompleteOptions Opts) { - llvm::Optional> Result; + std::optional> Result; Server.codeComplete(File, Pos, Opts, capture(Result)); return std::move(*Result); } @@ -79,21 +79,21 @@ runCodeComplete(ClangdServer &Server, PathRef File, Position Pos, llvm::Expected runSignatureHelp(ClangdServer &Server, PathRef File, Position Pos, MarkupKind DocumentationFormat) { - llvm::Optional> Result; + std::optional> Result; Server.signatureHelp(File, Pos, DocumentationFormat, capture(Result)); return std::move(*Result); } llvm::Expected> runLocateSymbolAt(ClangdServer &Server, PathRef File, Position Pos) { - llvm::Optional>> Result; + std::optional>> Result; Server.locateSymbolAt(File, Pos, capture(Result)); return std::move(*Result); } llvm::Expected> runFindDocumentHighlights(ClangdServer &Server, PathRef File, Position Pos) { - llvm::Optional>> Result; + std::optional>> Result; Server.findDocumentHighlights(File, Pos, capture(Result)); return std::move(*Result); } @@ -101,23 +101,23 @@ runFindDocumentHighlights(ClangdServer &Server, PathRef File, Position Pos) { llvm::Expected runRename(ClangdServer &Server, PathRef File, Position Pos, llvm::StringRef NewName, const RenameOptions &RenameOpts) { - llvm::Optional> Result; + std::optional> Result; Server.rename(File, Pos, NewName, RenameOpts, capture(Result)); return std::move(*Result); } llvm::Expected runPrepareRename(ClangdServer &Server, PathRef File, Position Pos, - llvm::Optional NewName, + std::optional NewName, const RenameOptions &RenameOpts) { - llvm::Optional> Result; + std::optional> Result; Server.prepareRename(File, Pos, NewName, RenameOpts, capture(Result)); return std::move(*Result); } llvm::Expected -runFormatFile(ClangdServer &Server, PathRef File, llvm::Optional Rng) { - llvm::Optional> Result; +runFormatFile(ClangdServer &Server, PathRef File, std::optional Rng) { + std::optional> Result; Server.formatFile(File, Rng, capture(Result)); return std::move(*Result); } @@ -146,14 +146,14 @@ RefSlab getRefs(const SymbolIndex &Index, SymbolID ID) { llvm::Expected> runSemanticRanges(ClangdServer &Server, PathRef File, const std::vector &Pos) { - llvm::Optional>> Result; + std::optional>> Result; Server.semanticRanges(File, Pos, capture(Result)); return std::move(*Result); } -llvm::Expected> +llvm::Expected> runSwitchHeaderSource(ClangdServer &Server, PathRef File) { - llvm::Optional>> Result; + std::optional>> Result; Server.switchSourceHeader(File, capture(Result)); return std::move(*Result); } diff --git a/clang-tools-extra/clangd/unittests/SyncAPI.h b/clang-tools-extra/clangd/unittests/SyncAPI.h index 6b4e3fc608e9..cf3de4f742e8 100644 --- a/clang-tools-extra/clangd/unittests/SyncAPI.h +++ b/clang-tools-extra/clangd/unittests/SyncAPI.h @@ -49,11 +49,11 @@ llvm::Expected runRename(ClangdServer &Server, PathRef File, llvm::Expected runPrepareRename(ClangdServer &Server, PathRef File, Position Pos, - llvm::Optional NewName, + std::optional NewName, const clangd::RenameOptions &RenameOpts); llvm::Expected -runFormatFile(ClangdServer &Server, PathRef File, llvm::Optional); +runFormatFile(ClangdServer &Server, PathRef File, std::optional); SymbolSlab runFuzzyFind(const SymbolIndex &Index, StringRef Query); SymbolSlab runFuzzyFind(const SymbolIndex &Index, const FuzzyFindRequest &Req); @@ -63,7 +63,7 @@ llvm::Expected> runSemanticRanges(ClangdServer &Server, PathRef File, const std::vector &Pos); -llvm::Expected> +llvm::Expected> runSwitchHeaderSource(ClangdServer &Server, PathRef File); llvm::Error runCustomAction(ClangdServer &Server, PathRef File, diff --git a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp index c7e28a0e213a..5b3cab16ddb6 100644 --- a/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp +++ b/clang-tools-extra/clangd/unittests/TUSchedulerTests.cpp @@ -1204,7 +1204,7 @@ TEST_F(TUSchedulerTests, IncluderCache) { OK = testPath("ok.h"), NotIncluded = testPath("not_included.h"); struct NoHeadersCDB : public GlobalCompilationDatabase { - llvm::Optional + std::optional getCompileCommand(PathRef File) const override { if (File == NoCmd || File == NotIncluded || FailAll) return std::nullopt; @@ -1387,7 +1387,7 @@ TEST_F(TUSchedulerTests, PreambleThrottle) { std::vector Releases; llvm::DenseMap Callbacks; // If set, the notification is signalled after acquiring the specified ID. - llvm::Optional> Notify; + std::optional> Notify; RequestID acquire(llvm::StringRef Filename, Callback CB) override { RequestID ID; diff --git a/clang-tools-extra/clangd/unittests/TestFS.cpp b/clang-tools-extra/clangd/unittests/TestFS.cpp index be26a6ccf25f..1b313f78586a 100644 --- a/clang-tools-extra/clangd/unittests/TestFS.cpp +++ b/clang-tools-extra/clangd/unittests/TestFS.cpp @@ -52,12 +52,12 @@ MockCompilationDatabase::MockCompilationDatabase(llvm::StringRef Directory, // -ffreestanding avoids implicit stdc-predef.h. } -llvm::Optional +std::optional MockCompilationDatabase::getProjectInfo(PathRef File) const { return ProjectInfo{std::string(Directory)}; } -llvm::Optional +std::optional MockCompilationDatabase::getCompileCommand(PathRef File) const { if (ExtraClangFlags.empty()) return std::nullopt; diff --git a/clang-tools-extra/clangd/unittests/TestFS.h b/clang-tools-extra/clangd/unittests/TestFS.h index 3e4ac3bab1c9..a7a521c76d37 100644 --- a/clang-tools-extra/clangd/unittests/TestFS.h +++ b/clang-tools-extra/clangd/unittests/TestFS.h @@ -61,10 +61,10 @@ public: MockCompilationDatabase(StringRef Directory = StringRef(), StringRef RelPathPrefix = StringRef()); - llvm::Optional + std::optional getCompileCommand(PathRef File) const override; - llvm::Optional getProjectInfo(PathRef File) const override; + std::optional getProjectInfo(PathRef File) const override; std::vector ExtraClangFlags; diff --git a/clang-tools-extra/clangd/unittests/TestWorkspace.cpp b/clang-tools-extra/clangd/unittests/TestWorkspace.cpp index 662eef63d25a..40c08fc5357d 100644 --- a/clang-tools-extra/clangd/unittests/TestWorkspace.cpp +++ b/clang-tools-extra/clangd/unittests/TestWorkspace.cpp @@ -32,7 +32,7 @@ std::unique_ptr TestWorkspace::index() { return Index; } -Optional TestWorkspace::openFile(llvm::StringRef Filename) { +std::optional TestWorkspace::openFile(llvm::StringRef Filename) { auto It = Inputs.find(Filename); if (It == Inputs.end()) { ADD_FAILURE() << "Accessing non-existing file: " << Filename; diff --git a/clang-tools-extra/clangd/unittests/TestWorkspace.h b/clang-tools-extra/clangd/unittests/TestWorkspace.h index bc6aee1c58d1..a5e688d8a7d7 100644 --- a/clang-tools-extra/clangd/unittests/TestWorkspace.h +++ b/clang-tools-extra/clangd/unittests/TestWorkspace.h @@ -39,7 +39,7 @@ public: std::unique_ptr index(); - Optional openFile(llvm::StringRef Filename); + std::optional openFile(llvm::StringRef Filename); private: struct SourceFile { diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/clang-tools-extra/clangd/unittests/XRefsTests.cpp index ae19656f6f9a..3bbcde267d3e 100644 --- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp +++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp @@ -272,7 +272,7 @@ TEST(HighlightsTest, ControlFlow) { } MATCHER_P3(sym, Name, Decl, DefOrNone, "") { - llvm::Optional Def = DefOrNone; + std::optional Def = DefOrNone; if (Name != arg.Name) { *result_listener << "Name is " << arg.Name; return false; @@ -1003,8 +1003,8 @@ TEST(LocateSymbol, All) { )objc"}; for (const char *Test : Tests) { Annotations T(Test); - llvm::Optional WantDecl; - llvm::Optional WantDef; + std::optional WantDecl; + std::optional WantDef; if (!T.ranges().empty()) WantDecl = WantDef = T.range(); if (!T.ranges("decl").empty()) @@ -1026,7 +1026,7 @@ TEST(LocateSymbol, All) { ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test; EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test; EXPECT_TRUE(Results[0].ID) << Test; - llvm::Optional GotDef; + std::optional GotDef; if (Results[0].Definition) GotDef = Results[0].Definition->range; EXPECT_EQ(WantDef, GotDef) << Test; @@ -1061,7 +1061,7 @@ TEST(LocateSymbol, AllMulti) { // N starts at 0. struct ExpectedRanges { Range WantDecl; - llvm::Optional WantDef; + std::optional WantDef; }; const char *Tests[] = { R"objc( @@ -1128,7 +1128,7 @@ TEST(LocateSymbol, AllMulti) { for (size_t Idx = 0; Idx < Ranges.size(); Idx++) { EXPECT_EQ(Results[Idx].PreferredDeclaration.range, Ranges[Idx].WantDecl) << "($decl" << Idx << ")" << Test; - llvm::Optional GotDef; + std::optional GotDef; if (Results[Idx].Definition) GotDef = Results[Idx].Definition->range; EXPECT_EQ(GotDef, Ranges[Idx].WantDef) << "($def" << Idx << ")" << Test; @@ -1159,8 +1159,8 @@ TEST(LocateSymbol, Warnings) { for (const char *Test : Tests) { Annotations T(Test); - llvm::Optional WantDecl; - llvm::Optional WantDef; + std::optional WantDecl; + std::optional WantDef; if (!T.ranges().empty()) WantDecl = WantDef = T.range(); if (!T.ranges("decl").empty()) @@ -1179,7 +1179,7 @@ TEST(LocateSymbol, Warnings) { } else { ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test; EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test; - llvm::Optional GotDef; + std::optional GotDef; if (Results[0].Definition) GotDef = Results[0].Definition->range; EXPECT_EQ(WantDef, GotDef) << Test; @@ -1233,7 +1233,7 @@ TEST(LocateSymbol, Textual) { for (const char *Test : Tests) { Annotations T(Test); - llvm::Optional WantDecl; + std::optional WantDecl; if (!T.ranges().empty()) WantDecl = T.range(); @@ -1731,7 +1731,7 @@ TEST(LocateSymbol, NearbyIdentifier) { Annotations T(Test); auto AST = TestTU::withCode(T.code()).build(); const auto &SM = AST.getSourceManager(); - llvm::Optional Nearby; + std::optional Nearby; auto Word = SpelledWord::touching(cantFail(sourceLocationInMainFile(SM, T.point())), AST.getTokens(), AST.getLangOpts()); @@ -2379,7 +2379,7 @@ TEST(FindReferences, NeedsIndexForMacro) { TEST(FindReferences, NoQueryForLocalSymbols) { struct RecordingIndex : public MemIndex { - mutable Optional> RefIDs; + mutable std::optional> RefIDs; bool refs(const RefsRequest &Req, llvm::function_ref) const override { RefIDs = Req.IDs; diff --git a/clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp b/clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp index 133b83ba93fd..840cad623d77 100644 --- a/clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp +++ b/clang-tools-extra/clangd/unittests/support/FileCacheTests.cpp @@ -41,7 +41,7 @@ public: std::string Result; read( FS, FreshTime, - [&](llvm::Optional Data) { + [&](std::optional Data) { GotParse = true; Value = Data.value_or("").str(); }, diff --git a/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp b/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp index 12836d0926e2..ee93436d708d 100644 --- a/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp +++ b/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp @@ -61,10 +61,10 @@ llvm::Annotations::Range rangeOrPoint(const llvm::Annotations &A) { // Prepare and apply the specified tweak based on the selection in Input. // Returns std::nullopt if and only if prepare() failed. -llvm::Optional> +std::optional> applyTweak(ParsedAST &AST, llvm::Annotations::Range Range, StringRef TweakID, const SymbolIndex *Index, llvm::vfs::FileSystem *FS) { - llvm::Optional> Result; + std::optional> Result; SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Range.Begin, Range.End, [&](SelectionTree ST) { Tweak::Selection S(Index, AST, Range.Begin, diff --git a/clang-tools-extra/clangd/xpc/XPCTransport.cpp b/clang-tools-extra/clangd/xpc/XPCTransport.cpp index dac8e29efae1..8f5b787f8f71 100644 --- a/clang-tools-extra/clangd/xpc/XPCTransport.cpp +++ b/clang-tools-extra/clangd/xpc/XPCTransport.cpp @@ -107,12 +107,13 @@ private: bool XPCTransport::handleMessage(json::Value Message, MessageHandler &Handler) { // Message must be an object with "jsonrpc":"2.0". auto *Object = Message.getAsObject(); - if (!Object || Object->getString("jsonrpc") != Optional("2.0")) { + if (!Object || + Object->getString("jsonrpc") != std::optional("2.0")) { elog("Not a JSON-RPC 2.0 message: {0:2}", Message); return false; } // ID may be any JSON value. If absent, this is a notification. - Optional ID; + std::optional ID; if (auto *I = Object->get("id")) ID = std::move(*I); auto Method = Object->getString("method"); diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst index 6e9a4e02e6d0..256cb6d05e25 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst @@ -8,7 +8,7 @@ results. Therefore, it may be more resource intensive (RAM, CPU) than the average clang-tidy check. This check identifies unsafe accesses to values contained in -``std::optional``, ``absl::optional``, or ``base::Optional`` +``std::optional``, ``absl::optional``, or ``base::std::optional`` objects. Below we will refer to all these types collectively as ``optional``. diff --git a/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h b/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h index e8f4240b8fa3..aeca616414c2 100644 --- a/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h +++ b/clang-tools-extra/pseudo/include/clang-pseudo/DirectiveTree.h @@ -83,7 +83,7 @@ struct DirectiveTree { /// None indicates no branch was taken (e.g. #if 0 ... #endif). /// The initial tree from `parse()` has no branches marked as taken. /// See `chooseConditionalBranches()`. - llvm::Optional Taken; + std::optional Taken; }; /// Some piece of the file. {One of Code, Directive, Conditional}. diff --git a/clang-tools-extra/pseudo/lib/DirectiveTree.cpp b/clang-tools-extra/pseudo/lib/DirectiveTree.cpp index 4e866815e63b..9e853e46edc2 100644 --- a/clang-tools-extra/pseudo/lib/DirectiveTree.cpp +++ b/clang-tools-extra/pseudo/lib/DirectiveTree.cpp @@ -48,7 +48,7 @@ private: // If we reach an End or Else directive that ends Tree, returns it. // If TopLevel is true, then we do not expect End and always return // std::nullopt. - llvm::Optional parse(DirectiveTree *Tree, + std::optional parse(DirectiveTree *Tree, bool TopLevel) { auto StartsDirective = [&, AllowDirectiveAt((const Token *)nullptr)]() mutable { @@ -286,7 +286,7 @@ public: private: // Return true if the directive starts an always-taken conditional branch, // false if the branch is never taken, and std::nullopt otherwise. - llvm::Optional isTakenWhenReached(const DirectiveTree::Directive &Dir) { + std::optional isTakenWhenReached(const DirectiveTree::Directive &Dir) { switch (Dir.Kind) { case clang::tok::pp_if: case clang::tok::pp_elif: @@ -304,7 +304,7 @@ private: // Does the condition consist of exactly one token? if (&Value >= Tokens.end() || &Value.nextNC() < Tokens.end()) return std::nullopt; - return llvm::StringSwitch>(Value.text()) + return llvm::StringSwitch>(Value.text()) .Cases("true", "1", true) .Cases("false", "0", false) .Default(std::nullopt); diff --git a/clang-tools-extra/pseudo/lib/Forest.cpp b/clang-tools-extra/pseudo/lib/Forest.cpp index e6b2d2ec0f90..6162e02dab49 100644 --- a/clang-tools-extra/pseudo/lib/Forest.cpp +++ b/clang-tools-extra/pseudo/lib/Forest.cpp @@ -94,11 +94,10 @@ std::string ForestNode::dumpRecursive(const Grammar &G, llvm::DenseMap ReferenceIds; std::string Result; constexpr Token::Index KEnd = std::numeric_limits::max(); - std::function, + std::function, LineDecoration &LineDec)> Dump = [&](const ForestNode *P, Token::Index End, - llvm::Optional ElidedParent, - LineDecoration LineDec) { + std::optional ElidedParent, LineDecoration LineDec) { bool SharedNode = VisitCounts.find(P)->getSecond() > 1; llvm::ArrayRef Children; auto EndOfElement = [&](size_t ChildIndex) { diff --git a/clang-tools-extra/pseudo/lib/GLR.cpp b/clang-tools-extra/pseudo/lib/GLR.cpp index a4169dd96f4a..35a81810de63 100644 --- a/clang-tools-extra/pseudo/lib/GLR.cpp +++ b/clang-tools-extra/pseudo/lib/GLR.cpp @@ -134,7 +134,7 @@ void glrRecover(llvm::ArrayRef OldHeads, }); // We may find multiple winners, but they will have the same range. - llvm::Optional RecoveryRange; + std::optional RecoveryRange; std::vector BestOptions; for (const PlaceholderRecovery &Option : Options) { // If this starts further left than options we've already found, then @@ -564,7 +564,7 @@ private: if (!Sequences.empty() || Heads->size() != NextPopHead + 1) return false; const GSS::Node *Head = Heads->back(); - llvm::Optional RID; + std::optional RID; for (RuleID R : Lang.Table.getReduceRules(Head->State)) { if (RID.has_value()) return false; diff --git a/clang-tools-extra/pseudo/tool/ClangPseudo.cpp b/clang-tools-extra/pseudo/tool/ClangPseudo.cpp index c22ea171c96c..6a64760749ce 100644 --- a/clang-tools-extra/pseudo/tool/ClangPseudo.cpp +++ b/clang-tools-extra/pseudo/tool/ClangPseudo.cpp @@ -108,9 +108,9 @@ int main(int argc, char *argv[]) { clang::LangOptions LangOpts = clang::pseudo::genericLangOpts(); std::string SourceText; - llvm::Optional RawStream; - llvm::Optional PreprocessedStream; - llvm::Optional ParseableStream; + std::optional RawStream; + std::optional PreprocessedStream; + std::optional ParseableStream; if (Source.getNumOccurrences()) { SourceText = readOrDie(Source); RawStream = clang::pseudo::lex(SourceText, LangOpts); @@ -119,7 +119,7 @@ int main(int argc, char *argv[]) { auto DirectiveStructure = clang::pseudo::DirectiveTree::parse(*RawStream); clang::pseudo::chooseConditionalBranches(DirectiveStructure, *RawStream); - llvm::Optional Preprocessed; + std::optional Preprocessed; if (StripDirectives) { Preprocessed = DirectiveStructure.stripDirectives(*Stream); Stream = &*Preprocessed; @@ -151,7 +151,7 @@ int main(int argc, char *argv[]) { if (ParseableStream) { clang::pseudo::ForestArena Arena; clang::pseudo::GSS GSS; - llvm::Optional StartSymID = + std::optional StartSymID = Lang.G.findNonterminal(StartSymbol); if (!StartSymID) { llvm::errs() << llvm::formatv( diff --git a/clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp b/clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp index 437d9b4df8fe..dfae25f3f26e 100644 --- a/clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/AddConstTest.cpp @@ -27,7 +27,7 @@ public: void check(const MatchFinder::MatchResult &Result) override { const auto *D = Result.Nodes.getNodeAs("var"); using utils::fixit::addQualifierToVarDecl; - Optional Fix = addQualifierToVarDecl( + std::optional Fix = addQualifierToVarDecl( *D, *Result.Context, DeclSpec::TQ::TQ_const, CT, CP); auto Diag = diag(D->getBeginLoc(), "doing const transformation"); if (Fix) diff --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp index d861e86284b3..36b7d1b8065c 100644 --- a/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyOptionsTest.cpp @@ -168,7 +168,7 @@ public: std::string Message; llvm::SourceMgr::DiagKind Kind; size_t Pos; - Optional Range; + std::optional Range; friend void PrintTo(const Diag &D, std::ostream *OS) { *OS << (D.Kind == llvm::SourceMgr::DK_Error ? "error: " : "warning: ") diff --git a/clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp b/clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp index 964f5f74a2bf..278d435c01ab 100644 --- a/clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/LLVMModuleTest.cpp @@ -15,7 +15,7 @@ namespace test { template static std::string runCheck(StringRef Code, const Twine &Filename, - Optional ExpectedWarning, + std::optional ExpectedWarning, std::map PathsToContent = std::map()) { std::vector Errors; @@ -30,15 +30,16 @@ static std::string runCheck(StringRef Code, const Twine &Filename, return Result; } -static std::string runHeaderGuardCheck(StringRef Code, const Twine &Filename, - Optional ExpectedWarning) { +static std::string +runHeaderGuardCheck(StringRef Code, const Twine &Filename, + std::optional ExpectedWarning) { return runCheck(Code, Filename, std::move(ExpectedWarning)); } static std::string runIncludeOrderCheck(StringRef Code, const Twine &Filename, - Optional ExpectedWarning, + std::optional ExpectedWarning, llvm::ArrayRef Includes) { std::map PathsToContent; for (auto Include : Includes) @@ -56,7 +57,7 @@ struct WithEndifComment : public LLVMHeaderGuardCheck { static std::string runHeaderGuardCheckWithEndif(StringRef Code, const Twine &Filename, - Optional ExpectedWarning) { + std::optional ExpectedWarning) { return runCheck(Code, Filename, std::move(ExpectedWarning)); } } // namespace diff --git a/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp b/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp index 873259414b74..42d40d32bfa5 100644 --- a/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/TransformerClangTidyCheckTest.cpp @@ -211,7 +211,7 @@ TEST(TransformerClangTidyCheckTest, TwoMatchesInMacroExpansion) { } // A trivial rewrite-rule generator that requires Objective-C code. -Optional> +std::optional> needsObjC(const LangOptions &LangOpts, const ClangTidyCheck::OptionsView &Options) { if (!LangOpts.ObjC) @@ -237,7 +237,7 @@ TEST(TransformerClangTidyCheckTest, DisableByLang) { } // A trivial rewrite rule generator that checks config options. -Optional> +std::optional> noSkip(const LangOptions &LangOpts, const ClangTidyCheck::OptionsView &Options) { if (Options.get("Skip", "false") == "true")