auto AddToGroup = [&](const tooling::Replacement &R,
const tooling::TranslationUnitDiagnostics *SourceTU,
- const llvm::Optional<std::string> BuildDir) {
+ const std::optional<std::string> BuildDir) {
// Use the file manager to deduplicate paths. FileEntries are
// automatically canonicalized. Since relative paths can come from different
// build directories, make them absolute immediately.
static std::unique_ptr<HTMLNode>
genReference(const Reference &Type, StringRef CurrentDirectory,
- llvm::Optional<StringRef> JumpToSection = std::nullopt) {
+ std::optional<StringRef> JumpToSection = std::nullopt) {
if (Type.Path.empty()) {
if (!JumpToSection)
return std::make_unique<TextNode>(Type.Name);
static std::unique_ptr<TagNode>
writeFileDefinition(const Location &L,
- llvm::Optional<StringRef> RepositoryUrl = std::nullopt) {
+ std::optional<StringRef> RepositoryUrl = std::nullopt) {
if (!L.IsFileInRootDir || !RepositoryUrl)
return std::make_unique<TagNode>(
HTMLTag::TAG_P, "Defined at line " + std::to_string(L.LineNumber) +
namespace clang {
namespace find_all_symbols {
-llvm::Optional<SymbolInfo>
+std::optional<SymbolInfo>
FindAllMacros::CreateMacroSymbol(const Token &MacroNameTok,
const MacroInfo *info) {
std::string FilePath =
void EndOfMainFile() override;
private:
- llvm::Optional<SymbolInfo> CreateMacroSymbol(const Token &MacroNameTok,
- const MacroInfo *MD);
+ std::optional<SymbolInfo> CreateMacroSymbol(const Token &MacroNameTok,
+ const MacroInfo *MD);
// Not a callback, just a common path for all usage types.
void MacroUsed(const Token &Name, const MacroDefinition &MD);
return Contexts;
}
-llvm::Optional<SymbolInfo>
+std::optional<SymbolInfo>
CreateSymbolInfo(const NamedDecl *ND, const SourceManager &SM,
const HeaderMapCollector *Collector) {
SymbolInfo::SymbolKind Type;
std::vector<BoundNodes> Matches;
DynTypedMatcher MaybeBoundMatcher = Matcher;
if (QS.BindRoot) {
- llvm::Optional<DynTypedMatcher> M = Matcher.tryBind("root");
+ std::optional<DynTypedMatcher> M = Matcher.tryBind("root");
if (M)
MaybeBoundMatcher = *M;
}
Diagnostics Diag;
auto MatcherSource = Line.ltrim();
auto OrigMatcherSource = MatcherSource;
- Optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
+ std::optional<DynTypedMatcher> Matcher = Parser::parseMatcherExpression(
MatcherSource, nullptr, &QS.NamedValues, &Diag);
if (!Matcher) {
return makeInvalidQueryFromDiagnostics(Diag);
LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
return QueryParser::complete(Line, Pos, QS);
});
- while (llvm::Optional<std::string> Line = LE.readLine()) {
+ while (std::optional<std::string> Line = LE.readLine()) {
QueryRef Q = QueryParser::parse(*Line, QS);
Q->run(llvm::outs(), QS);
llvm::outs().flush();
: NamePrefix((CheckName + ".").str()), CheckOptions(CheckOptions),
Context(Context) {}
-llvm::Optional<StringRef>
+std::optional<StringRef>
ClangTidyCheck::OptionsView::get(StringRef LocalName) const {
if (Context->getOptionsCollector())
Context->getOptionsCollector()->insert((NamePrefix + LocalName).str());
return IterGlobal;
}
-llvm::Optional<StringRef>
+std::optional<StringRef>
ClangTidyCheck::OptionsView::getLocalOrGlobal(StringRef LocalName) const {
auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName,
Context->getOptionsCollector());
return std::nullopt;
}
-static Optional<bool> getAsBool(StringRef Value,
- const llvm::Twine &LookupName) {
+static std::optional<bool> getAsBool(StringRef Value,
+ const llvm::Twine &LookupName) {
if (std::optional<bool> Parsed = llvm::yaml::parseBool(Value))
return *Parsed;
}
template <>
-llvm::Optional<bool>
+std::optional<bool>
ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const {
- if (llvm::Optional<StringRef> ValueOr = get(LocalName)) {
+ if (std::optional<StringRef> ValueOr = get(LocalName)) {
if (auto Result = getAsBool(*ValueOr, NamePrefix + LocalName))
return Result;
diagnoseBadBooleanOption(NamePrefix + LocalName, *ValueOr);
}
template <>
-llvm::Optional<bool>
+std::optional<bool>
ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const {
auto Iter = findPriorityOption(CheckOptions, NamePrefix, LocalName,
Context->getOptionsCollector());
store(Options, LocalName, Value ? StringRef("true") : StringRef("false"));
}
-llvm::Optional<int64_t> ClangTidyCheck::OptionsView::getEnumInt(
+std::optional<int64_t> ClangTidyCheck::OptionsView::getEnumInt(
StringRef LocalName, ArrayRef<NameAndValue> Mapping, bool CheckGlobal,
bool IgnoreCase) const {
if (!CheckGlobal && Context->getOptionsCollector())
/// Reads the option with the check-local name \p LocalName from the
/// ``CheckOptions``. If the corresponding key is not present, return
/// ``std::nullopt``.
- llvm::Optional<StringRef> get(StringRef LocalName) const;
+ std::optional<StringRef> get(StringRef LocalName) const;
/// Read a named option from the ``Context``.
///
/// global ``CheckOptions``. Gets local option first. If local is not
/// present, falls back to get global option. If global option is not
/// present either, return ``std::nullopt``.
- llvm::Optional<StringRef> getLocalOrGlobal(StringRef LocalName) const;
+ std::optional<StringRef> getLocalOrGlobal(StringRef LocalName) const;
/// Read a named option from the ``Context``.
///
/// If the corresponding key can't be parsed as a ``T``, emit a
/// diagnostic and return ``std::nullopt``.
template <typename T>
- std::enable_if_t<std::is_integral<T>::value, llvm::Optional<T>>
+ std::enable_if_t<std::is_integral<T>::value, std::optional<T>>
get(StringRef LocalName) const {
- if (llvm::Optional<StringRef> Value = get(LocalName)) {
+ if (std::optional<StringRef> Value = get(LocalName)) {
T Result{};
if (!StringRef(*Value).getAsInteger(10, Result))
return Result;
/// If the corresponding key can't be parsed as a ``T``, emit a
/// diagnostic and return ``std::nullopt``.
template <typename T>
- std::enable_if_t<std::is_integral<T>::value, llvm::Optional<T>>
+ std::enable_if_t<std::is_integral<T>::value, std::optional<T>>
getLocalOrGlobal(StringRef LocalName) const {
- llvm::Optional<StringRef> ValueOr = get(LocalName);
+ std::optional<StringRef> ValueOr = get(LocalName);
bool IsGlobal = false;
if (!ValueOr) {
IsGlobal = true;
/// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
/// supply the mapping required to convert between ``T`` and a string.
template <typename T>
- std::enable_if_t<std::is_enum<T>::value, llvm::Optional<T>>
+ std::enable_if_t<std::is_enum<T>::value, std::optional<T>>
get(StringRef LocalName, bool IgnoreCase = false) const {
- if (llvm::Optional<int64_t> ValueOr =
+ if (std::optional<int64_t> ValueOr =
getEnumInt(LocalName, typeEraseMapping<T>(), false, IgnoreCase))
return static_cast<T>(*ValueOr);
return std::nullopt;
/// \ref clang::tidy::OptionEnumMapping must be specialized for ``T`` to
/// supply the mapping required to convert between ``T`` and a string.
template <typename T>
- std::enable_if_t<std::is_enum<T>::value, llvm::Optional<T>>
+ std::enable_if_t<std::is_enum<T>::value, std::optional<T>>
getLocalOrGlobal(StringRef LocalName, bool IgnoreCase = false) const {
- if (llvm::Optional<int64_t> ValueOr =
+ if (std::optional<int64_t> ValueOr =
getEnumInt(LocalName, typeEraseMapping<T>(), true, IgnoreCase))
return static_cast<T>(*ValueOr);
return std::nullopt;
private:
using NameAndValue = std::pair<int64_t, StringRef>;
- llvm::Optional<int64_t> getEnumInt(StringRef LocalName,
- ArrayRef<NameAndValue> Mapping,
- bool CheckGlobal, bool IgnoreCase) const;
+ std::optional<int64_t> getEnumInt(StringRef LocalName,
+ ArrayRef<NameAndValue> Mapping,
+ bool CheckGlobal, bool IgnoreCase) const;
template <typename T>
std::enable_if_t<std::is_enum<T>::value, std::vector<NameAndValue>>
/// If the corresponding key can't be parsed as a bool, emit a
/// diagnostic and return ``std::nullopt``.
template <>
-llvm::Optional<bool>
+std::optional<bool>
ClangTidyCheck::OptionsView::get<bool>(StringRef LocalName) const;
/// Read a named option from the ``Context`` and parse it as a bool.
/// If the corresponding key can't be parsed as a bool, emit a
/// diagnostic and return \p Default.
template <>
-llvm::Optional<bool>
+std::optional<bool>
ClangTidyCheck::OptionsView::getLocalOrGlobal<bool>(StringRef LocalName) const;
/// Stores an option with the check-local name \p LocalName with
ProfilePrefix = std::string(Prefix);
}
-llvm::Optional<ClangTidyProfiling::StorageParams>
+std::optional<ClangTidyProfiling::StorageParams>
ClangTidyContext::getProfileStorageParams() const {
if (ProfilePrefix.empty())
return std::nullopt;
/// Control storage of profile date.
void setProfileStoragePrefix(StringRef ProfilePrefix);
- llvm::Optional<ClangTidyProfiling::StorageParams>
+ std::optional<ClangTidyProfiling::StorageParams>
getProfileStorageParams() const;
/// Should be called when starting to process new translation unit.
StringRef Path = llvm::sys::path::parent_path(AbsolutePath);
for (StringRef CurrentPath = Path; !CurrentPath.empty();
CurrentPath = llvm::sys::path::parent_path(CurrentPath)) {
- llvm::Optional<OptionsSource> Result;
+ std::optional<OptionsSource> Result;
auto Iter = CachedOptions.find(CurrentPath);
if (Iter != CachedOptions.end())
return RawOptions;
}
-llvm::Optional<OptionsSource>
+std::optional<OptionsSource>
FileOptionsBaseProvider::tryReadConfigFile(StringRef Directory) {
assert(!Directory.empty());
return;
// FIXME: Why is this happening? We might be losing contents here.
- llvm::Optional<StringRef> Data = ContentCache.getBufferDataIfLoaded();
+ std::optional<StringRef> Data = ContentCache.getBufferDataIfLoaded();
if (!Data)
return;
// Convert a string like "NOLINTNEXTLINE" to its enum `Type::NoLintNextLine`.
// Return `std::nullopt` if the string is unrecognized.
-static Optional<NoLintType> strToNoLintType(StringRef Str) {
- auto Type = llvm::StringSwitch<Optional<NoLintType>>(Str)
+static std::optional<NoLintType> strToNoLintType(StringRef Str) {
+ auto Type = llvm::StringSwitch<std::optional<NoLintType>>(Str)
.Case("NOLINT", NoLintType::NoLint)
.Case("NOLINTNEXTLINE", NoLintType::NoLintNextLine)
.Case("NOLINTBEGIN", NoLintType::NoLintBegin)
// to NOLINT(*).
// - An empty string means nothing is suppressed - equivalent to NOLINT().
// - Negative globs ignored (which would effectively disable the suppression).
- NoLintToken(NoLintType Type, size_t Pos, const Optional<std::string> &Checks)
+ NoLintToken(NoLintType Type, size_t Pos,
+ const std::optional<std::string> &Checks)
: Type(Type), Pos(Pos), ChecksGlob(std::make_unique<CachedGlobList>(
Checks.value_or("*"),
/*KeepNegativeGlobs=*/false)) {
size_t Pos;
// If this NOLINT specifies checks, return the checks.
- Optional<std::string> checks() const { return Checks; }
+ std::optional<std::string> checks() const { return Checks; }
// Whether this NOLINT applies to the provided check.
bool suppresses(StringRef Check) const { return ChecksGlob->contains(Check); }
private:
- Optional<std::string> Checks;
+ std::optional<std::string> Checks;
std::unique_ptr<CachedGlobList> ChecksGlob;
};
++Pos;
// Is this a recognized NOLINT type?
- const Optional<NoLintType> NoLintType =
+ const std::optional<NoLintType> NoLintType =
strToNoLintType(Buffer.slice(NoLintPos, Pos));
if (!NoLintType)
continue;
// Get checks, if specified.
- Optional<std::string> Checks;
+ std::optional<std::string> Checks;
if (Pos < Buffer.size() && Buffer[Pos] == '(') {
size_t ClosingBracket = Buffer.find_first_of("\n)", ++Pos);
if (ClosingBracket != StringRef::npos && Buffer[ClosingBracket] == ')') {
}
// Get the file contents as a string.
-static Optional<StringRef> getBuffer(const SourceManager &SrcMgr, FileID File,
- bool AllowIO) {
+static std::optional<StringRef> getBuffer(const SourceManager &SrcMgr,
+ FileID File, bool AllowIO) {
return AllowIO ? SrcMgr.getBufferDataOrNone(File)
: SrcMgr.getBufferDataIfLoaded(File);
}
// We will only see NOLINTs in user-authored sources. No point reading the
// file if it is a <built-in>.
- Optional<StringRef> FileName = SrcMgr.getNonBuiltinFilenameForID(File);
+ std::optional<StringRef> FileName = SrcMgr.getNonBuiltinFilenameForID(File);
if (!FileName)
return false;
// Get file contents.
- Optional<StringRef> Buffer = getBuffer(SrcMgr, File, AllowIO);
+ std::optional<StringRef> Buffer = getBuffer(SrcMgr, File, AllowIO);
if (!Buffer)
return false;
if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
return;
- llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(
+ std::optional<DurationScale> Scale = getScaleForTimeInverse(
Result.Nodes.getNodeAs<clang::FunctionDecl>("function_decl")->getName());
if (!Scale)
return;
void DurationComparisonCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
- llvm::Optional<DurationScale> Scale = getScaleForDurationInverse(
+ std::optional<DurationScale> Scale = getScaleForDurationInverse(
Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
if (!Scale)
return;
const auto *Arg = Result.Nodes.getNodeAs<Expr>("arg");
StringRef ConversionFuncName = FuncDecl->getName();
- llvm::Optional<DurationScale> Scale =
+ std::optional<DurationScale> Scale =
getScaleForDurationInverse(ConversionFuncName);
if (!Scale)
return;
if (Arg->getBeginLoc().isMacroID())
return;
- llvm::Optional<std::string> SimpleArg = stripFloatCast(Result, *Arg);
+ std::optional<std::string> SimpleArg = stripFloatCast(Result, *Arg);
if (!SimpleArg)
SimpleArg = stripFloatLiteralFraction(Result, *Arg);
// Given the name of a duration factory function, return the appropriate
// `DurationScale` for that factory. If no factory can be found for
// `FactoryName`, return `std::nullopt`.
-static llvm::Optional<DurationScale>
+static std::optional<DurationScale>
getScaleForFactory(llvm::StringRef FactoryName) {
- return llvm::StringSwitch<llvm::Optional<DurationScale>>(FactoryName)
+ return llvm::StringSwitch<std::optional<DurationScale>>(FactoryName)
.Case("Nanoseconds", DurationScale::Nanoseconds)
.Case("Microseconds", DurationScale::Microseconds)
.Case("Milliseconds", DurationScale::Milliseconds)
// Given the scale of a duration and a `Multiplier`, determine if `Multiplier`
// would produce a new scale. If so, return a tuple containing the new scale
// and a suitable Multiplier for that scale, otherwise `std::nullopt`.
-static llvm::Optional<std::tuple<DurationScale, double>>
+static std::optional<std::tuple<DurationScale, double>>
getNewScaleSingleStep(DurationScale OldScale, double Multiplier) {
switch (OldScale) {
case DurationScale::Hours:
// Given the scale of a duration and a `Multiplier`, determine if `Multiplier`
// would produce a new scale. If so, return it, otherwise `std::nullopt`.
-static llvm::Optional<DurationScale> getNewScale(DurationScale OldScale,
- double Multiplier) {
+static std::optional<DurationScale> getNewScale(DurationScale OldScale,
+ double Multiplier) {
while (Multiplier != 1.0) {
- llvm::Optional<std::tuple<DurationScale, double>> Result =
+ std::optional<std::tuple<DurationScale, double>> Result =
getNewScaleSingleStep(OldScale, Multiplier);
if (!Result)
break;
}
const auto *CallDecl = Result.Nodes.getNodeAs<FunctionDecl>("call_decl");
- llvm::Optional<DurationScale> MaybeScale =
+ std::optional<DurationScale> MaybeScale =
getScaleForFactory(CallDecl->getName());
if (!MaybeScale)
return;
DurationScale Scale = *MaybeScale;
const Expr *Remainder;
- llvm::Optional<DurationScale> NewScale;
+ std::optional<DurationScale> NewScale;
// We next handle the cases of multiplication and division.
if (const auto *MultBinOp =
// For division, we only check the RHS.
const auto *FloatLit = llvm::cast<FloatingLiteral>(DivBinOp->getRHS());
- llvm::Optional<DurationScale> NewScale =
+ std::optional<DurationScale> NewScale =
getNewScale(Scale, 1.0 / FloatLit->getValueAsApproximateDouble());
if (NewScale) {
const Expr *Remainder = DivBinOp->getLHS();
};
/// Returns an integer if the fractional part of a `FloatingLiteral` is `0`.
-static llvm::Optional<llvm::APSInt>
+static std::optional<llvm::APSInt>
truncateIfIntegral(const FloatingLiteral &FloatLiteral) {
double Value = FloatLiteral.getValueAsApproximateDouble();
if (std::fmod(Value, 1) == 0) {
/// If `Node` is a call to the inverse of `Scale`, return that inverse's
/// argument, otherwise std::nullopt.
-static llvm::Optional<std::string>
+static std::optional<std::string>
rewriteInverseDurationCall(const MatchFinder::MatchResult &Result,
DurationScale Scale, const Expr &Node) {
const std::pair<llvm::StringRef, llvm::StringRef> &InverseFunctions =
/// If `Node` is a call to the inverse of `Scale`, return that inverse's
/// argument, otherwise std::nullopt.
-static llvm::Optional<std::string>
+static std::optional<std::string>
rewriteInverseTimeCall(const MatchFinder::MatchResult &Result,
DurationScale Scale, const Expr &Node) {
llvm::StringRef InverseFunction = getTimeInverseForScale(Scale);
return false;
}
-llvm::Optional<std::string>
+std::optional<std::string>
stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
const Expr &Node) {
if (const Expr *MaybeCastArg = selectFirst<const Expr>(
return std::nullopt;
}
-llvm::Optional<std::string>
+std::optional<std::string>
stripFloatLiteralFraction(const MatchFinder::MatchResult &Result,
const Expr &Node) {
if (const auto *LitFloat = llvm::dyn_cast<FloatingLiteral>(&Node))
// Attempt to simplify a `Duration` factory call with a literal argument.
- if (llvm::Optional<llvm::APSInt> IntValue = truncateIfIntegral(*LitFloat))
+ if (std::optional<llvm::APSInt> IntValue = truncateIfIntegral(*LitFloat))
return toString(*IntValue, /*radix=*/10);
return std::nullopt;
std::string simplifyDurationFactoryArg(const MatchFinder::MatchResult &Result,
const Expr &Node) {
// Check for an explicit cast to `float` or `double`.
- if (llvm::Optional<std::string> MaybeArg = stripFloatCast(Result, Node))
+ if (std::optional<std::string> MaybeArg = stripFloatCast(Result, Node))
return *MaybeArg;
// Check for floats without fractional components.
- if (llvm::Optional<std::string> MaybeArg =
+ if (std::optional<std::string> MaybeArg =
stripFloatLiteralFraction(Result, Node))
return *MaybeArg;
return tooling::fixit::getText(Node, *Result.Context).str();
}
-llvm::Optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
+std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name) {
static const llvm::StringMap<DurationScale> ScaleMap(
{{"ToDoubleHours", DurationScale::Hours},
{"ToInt64Hours", DurationScale::Hours},
return ScaleIter->second;
}
-llvm::Optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name) {
+std::optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name) {
static const llvm::StringMap<DurationScale> ScaleMap(
{{"ToUnixHours", DurationScale::Hours},
{"ToUnixMinutes", DurationScale::Minutes},
const Expr &RootNode = *Node->IgnoreParenImpCasts();
// First check to see if we can undo a complementary function call.
- if (llvm::Optional<std::string> MaybeRewrite =
+ if (std::optional<std::string> MaybeRewrite =
rewriteInverseDurationCall(Result, Scale, RootNode))
return *MaybeRewrite;
const Expr &RootNode = *Node->IgnoreParenImpCasts();
// First check to see if we can undo a complementary function call.
- if (llvm::Optional<std::string> MaybeRewrite =
+ if (std::optional<std::string> MaybeRewrite =
rewriteInverseTimeCall(Result, Scale, RootNode))
return *MaybeRewrite;
///
/// If `Node` represents an explicit cast to a floating point type, return
/// the textual context of the cast argument, otherwise `std::nullopt`.
-llvm::Optional<std::string>
+std::optional<std::string>
stripFloatCast(const ast_matchers::MatchFinder::MatchResult &Result,
const Expr &Node);
///
/// If `Node` represents a floating point literal with a zero fractional part,
/// return the textual context of the integral part, otherwise `std::nullopt`.
-llvm::Optional<std::string>
+std::optional<std::string>
stripFloatLiteralFraction(const ast_matchers::MatchFinder::MatchResult &Result,
const Expr &Node);
/// Given the name of an inverse Duration function (e.g., `ToDoubleSeconds`),
/// return its `DurationScale`, or `std::nullopt` if a match is not found.
-llvm::Optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name);
+std::optional<DurationScale> getScaleForDurationInverse(llvm::StringRef Name);
/// Given the name of an inverse Time function (e.g., `ToUnixSeconds`),
/// return its `DurationScale`, or `std::nullopt` if a match is not found.
-llvm::Optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name);
+std::optional<DurationScale> getScaleForTimeInverse(llvm::StringRef Name);
/// Given a `Scale` return the fully qualified inverse functions for it.
/// The first returned value is the inverse for `double`, and the second
if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
return;
- llvm::Optional<DurationScale> Scale =
+ std::optional<DurationScale> Scale =
getScaleForDurationInverse(FuncDecl->getName());
if (!Scale)
return;
AST_MATCHER(StringLiteral, lengthIsOne) { return Node.getLength() == 1; }
-llvm::Optional<std::string> makeCharacterLiteral(const StringLiteral *Literal,
- const ASTContext &Context) {
+std::optional<std::string> makeCharacterLiteral(const StringLiteral *Literal,
+ const ASTContext &Context) {
assert(Literal->getLength() == 1 &&
"Only single character string should be matched");
assert(Literal->getCharByteWidth() == 1 &&
if (Literal->getBeginLoc().isMacroID() || Literal->getEndLoc().isMacroID())
return;
- llvm::Optional<std::string> Replacement =
+ std::optional<std::string> Replacement =
makeCharacterLiteral(Literal, *Result.Context);
if (!Replacement)
return;
void TimeComparisonCheck::check(const MatchFinder::MatchResult &Result) {
const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
- llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(
+ std::optional<DurationScale> Scale = getScaleForTimeInverse(
Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
if (!Scale)
return;
for (const char *ScaleName :
{"Hours", "Minutes", "Seconds", "Millis", "Micros", "Nanos"}) {
std::string TimeInverse = (llvm::Twine("ToUnix") + ScaleName).str();
- llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(TimeInverse);
+ std::optional<DurationScale> Scale = getScaleForTimeInverse(TimeInverse);
assert(Scale && "Unknown scale encountered");
auto TimeInverseMatcher = callExpr(callee(
if (insideMacroDefinition(Result, BinOp->getSourceRange()))
return;
- llvm::Optional<DurationScale> Scale = getScaleForTimeInverse(InverseName);
+ std::optional<DurationScale> Scale = getScaleForTimeInverse(InverseName);
if (!Scale)
return;
KeyValue.first->hasMacroDefinition();
};
const auto TryExpandAsInteger =
- [](Preprocessor::macro_iterator It) -> Optional<unsigned> {
+ [](Preprocessor::macro_iterator It) -> std::optional<unsigned> {
if (It == PP->macro_end())
return std::nullopt;
const MacroInfo *MI = PP->getMacroInfo(It->first);
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) override;
- Optional<unsigned> SigtermValue;
+ std::optional<unsigned> SigtermValue;
};
} // namespace bugprone
Base->isCompleteDefinition() && Derived->isDerivedFrom(Base);
}
-static Optional<QualType>
+static std::optional<QualType>
approximateStandardConversionSequence(const TheCheck &Check, QualType From,
QualType To, const ASTContext &Ctx) {
LLVM_DEBUG(llvm::dbgs() << ">>> approximateStdConv for LType:\n";
/// Selects the best conversion function that is applicable from the
/// prepared set of potential conversion functions taken.
- Optional<PreparedConversion> operator()() const {
+ std::optional<PreparedConversion> operator()() const {
if (FlaggedConversions.empty()) {
LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Empty.\n");
return {};
return FlaggedConversions.front();
}
- Optional<PreparedConversion> BestConversion;
+ std::optional<PreparedConversion> BestConversion;
unsigned short HowManyGoodConversions = 0;
for (const auto &Prepared : FlaggedConversions) {
LLVM_DEBUG(llvm::dbgs() << "--- selectUserDefinedConv. Candidate flags: "
} // namespace
-static Optional<ConversionSequence>
+static std::optional<ConversionSequence>
tryConversionOperators(const TheCheck &Check, const CXXRecordDecl *RD,
QualType ToType) {
if (!RD || !RD->isCompleteDefinition())
ConversionSet.addConversion(Con, Con->getConversionType(), ToType);
}
- if (Optional<UserDefinedConversionSelector::PreparedConversion>
+ if (std::optional<UserDefinedConversionSelector::PreparedConversion>
SelectedConversion = ConversionSet()) {
QualType RecordType{RD->getTypeForDecl(), 0};
return {};
}
-static Optional<ConversionSequence>
+static std::optional<ConversionSequence>
tryConvertingConstructors(const TheCheck &Check, QualType FromType,
const CXXRecordDecl *RD) {
if (!RD || !RD->isCompleteDefinition())
ConversionSet.addConversion(Con, FromType, Con->getParamDecl(0)->getType());
}
- if (Optional<UserDefinedConversionSelector::PreparedConversion>
+ if (std::optional<UserDefinedConversionSelector::PreparedConversion>
SelectedConversion = ConversionSet()) {
QualType RecordType{RD->getTypeForDecl(), 0};
ConversionSequence ImplicitSeq{LType, RType};
QualType WorkType = LType;
- Optional<QualType> AfterFirstStdConv =
+ std::optional<QualType> AfterFirstStdConv =
approximateStandardConversionSequence(Check, LType, RType, Ctx);
if (AfterFirstStdConv) {
LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Standard "
bool FoundConversionOperator = false, FoundConvertingCtor = false;
if (const auto *LRD = WorkType->getAsCXXRecordDecl()) {
- Optional<ConversionSequence> ConversionOperatorResult =
+ std::optional<ConversionSequence> ConversionOperatorResult =
tryConversionOperators(Check, LRD, RType);
if (ConversionOperatorResult) {
LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found "
// Use the original "LType" here, and not WorkType, because the
// conversion to the converting constructors' parameters will be
// modelled in the recursive call.
- Optional<ConversionSequence> ConvCtorResult =
+ std::optional<ConversionSequence> ConvCtorResult =
tryConvertingConstructors(Check, LType, RRD);
if (ConvCtorResult) {
LLVM_DEBUG(llvm::dbgs() << "--- approximateImplicitConversion. Found "
if (!CalledFn)
continue;
- llvm::Optional<unsigned> TargetIdx;
+ std::optional<unsigned> TargetIdx;
unsigned NumFnParams = CalledFn->getNumParams();
for (unsigned Idx = 0; Idx < NumFnParams; ++Idx)
if (CalledFn->getParamDecl(Idx) == PassedToParam)
Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
}
-llvm::Optional<FixItHint>
+std::optional<FixItHint>
ImplicitWideningOfMultiplicationResultCheck::includeStddefHeader(
SourceLocation File) {
return IncludeInserter.createIncludeInsertion(
bool ShouldUseCXXStaticCast;
bool ShouldUseCXXHeader;
- llvm::Optional<FixItHint> includeStddefHeader(SourceLocation File);
+ std::optional<FixItHint> includeStddefHeader(SourceLocation File);
void handleImplicitCastExpr(const ImplicitCastExpr *ICE);
void handlePointerOffsetting(const Expr *E);
//===--------------------------------------------------------------------===//
struct CallContext {
- CallContext(StringRef Name, Optional<unsigned> DestinationPos,
- Optional<unsigned> SourcePos, unsigned LengthPos,
+ CallContext(StringRef Name, std::optional<unsigned> DestinationPos,
+ std::optional<unsigned> SourcePos, unsigned LengthPos,
bool WithIncrease)
: Name(Name), DestinationPos(DestinationPos), SourcePos(SourcePos),
LengthPos(LengthPos), WithIncrease(WithIncrease){};
StringRef Name;
- Optional<unsigned> DestinationPos;
- Optional<unsigned> SourcePos;
+ std::optional<unsigned> DestinationPos;
+ std::optional<unsigned> SourcePos;
unsigned LengthPos;
bool WithIncrease;
};
return;
if (WantToUseSafeFunctions && PP->isMacroDefined("__STDC_LIB_EXT1__")) {
- Optional<bool> AreSafeFunctionsWanted;
+ std::optional<bool> AreSafeFunctionsWanted;
Preprocessor::macro_iterator It = PP->macro_begin();
while (It != PP->macro_end() && !AreSafeFunctionsWanted) {
return Name.startswith("__");
}
-static Optional<std::string>
+static std::optional<std::string>
getDoubleUnderscoreFixup(StringRef Name, const LangOptions &LangOpts) {
if (hasReservedDoubleUnderscore(Name, LangOpts))
return collapseConsecutive(Name, '_');
return Name.size() >= 2 && Name[0] == '_' && std::isupper(Name[1]);
}
-static Optional<std::string> getUnderscoreCapitalFixup(StringRef Name) {
+static std::optional<std::string> getUnderscoreCapitalFixup(StringRef Name) {
if (startsWithUnderscoreCapital(Name))
return std::string(Name.drop_front(1));
return std::nullopt;
return IsInGlobalNamespace && Name.size() >= 1 && Name[0] == '_';
}
-static Optional<std::string>
+static std::optional<std::string>
getUnderscoreGlobalNamespaceFixup(StringRef Name, bool IsInGlobalNamespace) {
if (startsWithUnderscoreInGlobalNamespace(Name, IsInGlobalNamespace))
return std::string(Name.drop_front(1));
return Name;
}
-static Optional<RenamerClangTidyCheck::FailureInfo>
+static std::optional<RenamerClangTidyCheck::FailureInfo>
getFailureInfoImpl(StringRef Name, bool IsInGlobalNamespace,
const LangOptions &LangOpts, bool Invert,
ArrayRef<StringRef> AllowedIdentifiers) {
using FailureInfo = RenamerClangTidyCheck::FailureInfo;
if (!Invert) {
- Optional<FailureInfo> Info;
+ std::optional<FailureInfo> Info;
auto AppendFailure = [&](StringRef Kind, std::string &&Fixup) {
if (!Info) {
Info = FailureInfo{std::string(Kind), std::move(Fixup)};
return std::nullopt;
}
-Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
ReservedIdentifierCheck::getDeclFailureInfo(const NamedDecl *Decl,
const SourceManager &) const {
assert(Decl && Decl->getIdentifier() && !Decl->getName().empty() &&
getLangOpts(), Invert, AllowedIdentifiers);
}
-Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
ReservedIdentifierCheck::getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &) const {
return getFailureInfoImpl(MacroNameTok.getIdentifierInfo()->getName(), true,
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
private:
- llvm::Optional<FailureInfo>
+ std::optional<FailureInfo>
getDeclFailureInfo(const NamedDecl *Decl,
const SourceManager &SM) const override;
- llvm::Optional<FailureInfo>
+ std::optional<FailureInfo>
getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &SM) const override;
DiagInfo getDiagInfo(const NamingCheckId &ID,
SourceLocation DiagLoc = FilenameRange.getBegin().getLocWithOffset(1);
- const Optional<StringRef> IFE =
+ const std::optional<StringRef> IFE =
utils::getFileExtension(FileName, Check.ImplementationFileExtensions);
if (!IFE)
return;
namespace tidy {
namespace bugprone {
-static llvm::Optional<uint64_t> tryEvaluateSizeExpr(const Expr *SizeExpr,
- const ASTContext &Ctx) {
+static std::optional<uint64_t> tryEvaluateSizeExpr(const Expr *SizeExpr,
+ const ASTContext &Ctx) {
Expr::EvalResult Result;
if (SizeExpr->EvaluateAsRValue(Result, Ctx))
return Ctx.toBits(
const Expr *SizeExpr = CE->getArg(2);
assert(SizeExpr != nullptr && "Third argument of memcmp is mandatory.");
- llvm::Optional<uint64_t> ComparedBits = tryEvaluateSizeExpr(SizeExpr, Ctx);
+ std::optional<uint64_t> ComparedBits = tryEvaluateSizeExpr(SizeExpr, Ctx);
for (unsigned int ArgIndex = 0; ArgIndex < 2; ++ArgIndex) {
const Expr *ArgExpr = CE->getArg(ArgIndex);
static constexpr llvm::StringLiteral FuncID("fun");
-static Optional<std::vector<SourceLocation>>
+static std::optional<std::vector<SourceLocation>>
analyzeFunction(const FunctionDecl &FuncDecl, ASTContext &ASTCtx,
UncheckedOptionalAccessModelOptions ModelOptions) {
using dataflow::ControlFlowContext;
UncheckedOptionalAccessModel Analysis(ASTCtx);
UncheckedOptionalAccessDiagnoser Diagnoser(ModelOptions);
std::vector<SourceLocation> Diagnostics;
- Expected<std::vector<
- Optional<DataflowAnalysisState<UncheckedOptionalAccessModel::Lattice>>>>
+ Expected<std::vector<std::optional<
+ DataflowAnalysisState<UncheckedOptionalAccessModel::Lattice>>>>
BlockToOutputState = dataflow::runDataflowAnalysis(
*Context, Analysis, Env,
[&ASTCtx, &Diagnoser, &Diagnostics](
if (FuncDecl->isTemplated())
return;
- if (Optional<std::vector<SourceLocation>> Errors =
+ if (std::optional<std::vector<SourceLocation>> Errors =
analyzeFunction(*FuncDecl, *Result.Context, ModelOptions))
for (const SourceLocation &Loc : *Errors)
diag(Loc, "unchecked access to optional value");
namespace bugprone {
/// Warns when the code is unwrapping a `std::optional<T>`, `absl::optional<T>`,
-/// or `base::Optional<T>` object without assuring that it contains a value.
+/// or `base::std::optional<T>` object without assuring that it contains a
+/// value.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/unchecked-optional-access.html
llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
DeclRefs->clear();
for (const auto &Elem : *Block) {
- Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
+ std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
if (!S)
continue;
Stmts->clear();
DeclRefs->clear();
for (const auto &Elem : *Block) {
- Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
+ std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
if (!S)
continue;
return;
QualType TypePtr = MatchedDecl->getType();
- llvm::Optional<const char *> InitializationString;
+ std::optional<const char *> InitializationString;
bool AddMathInclude = false;
if (TypePtr->isEnumeralType())
if (IndexExpr->isValueDependent())
return; // We check in the specialization.
- Optional<llvm::APSInt> Index =
+ std::optional<llvm::APSInt> Index =
IndexExpr->getIntegerConstantExpr(*Result.Context);
if (!Index) {
SourceRange BaseRange;
this);
}
-static Optional<CharSourceRange>
+static std::optional<CharSourceRange>
getVirtualKeywordRange(const CXXDestructorDecl &Destructor,
const SourceManager &SM, const LangOptions &LangOpts) {
if (Destructor.getLocation().isMacroID())
/// Range ends with \c StartOfNextToken so that any whitespace after \c
/// virtual is included.
- Optional<Token> NextToken = Lexer::findNextToken(VirtualEndLoc, SM, LangOpts);
+ std::optional<Token> NextToken =
+ Lexer::findNextToken(VirtualEndLoc, SM, LangOpts);
if (!NextToken)
return std::nullopt;
SourceLocation StartOfNextToken = NextToken->getLocation();
"Google Test APIs named with 'case' are deprecated; use equivalent APIs "
"named with 'suite'";
-static llvm::Optional<llvm::StringRef>
+static std::optional<llvm::StringRef>
getNewMacroName(llvm::StringRef MacroName) {
std::pair<llvm::StringRef, llvm::StringRef> ReplacementMap[] = {
{"TYPED_TEST_CASE", "TYPED_TEST_SUITE"},
std::string Name = PP->getSpelling(MacroNameTok);
- llvm::Optional<llvm::StringRef> Replacement = getNewMacroName(Name);
+ std::optional<llvm::StringRef> Replacement = getNewMacroName(Name);
if (!Replacement)
return;
ConstExpr = Result.Nodes.getNodeAs<Expr>(CstId);
if (!ConstExpr)
return false;
- Optional<llvm::APSInt> R = ConstExpr->getIntegerConstantExpr(*Result.Context);
+ std::optional<llvm::APSInt> R =
+ ConstExpr->getIntegerConstantExpr(*Result.Context);
if (!R)
return false;
Value = *R;
"left-right-shift-confusion")) {
const auto *ShiftingConst = Result.Nodes.getNodeAs<Expr>("shift-const");
assert(ShiftingConst && "Expr* 'ShiftingConst' is nullptr!");
- Optional<llvm::APSInt> ShiftingValue =
+ std::optional<llvm::APSInt> ShiftingValue =
ShiftingConst->getIntegerConstantExpr(*Result.Context);
if (!ShiftingValue)
const auto *AndConst = Result.Nodes.getNodeAs<Expr>("and-const");
assert(AndConst && "Expr* 'AndCont' is nullptr!");
- Optional<llvm::APSInt> AndValue =
+ std::optional<llvm::APSInt> AndValue =
AndConst->getIntegerConstantExpr(*Result.Context);
if (!AndValue)
return;
const LangOptions &Opts = ASTCtx->getLangOpts();
const SourceManager &SM = ASTCtx->getSourceManager();
- llvm::Optional<llvm::MemoryBufferRef> Buffer =
+ std::optional<llvm::MemoryBufferRef> Buffer =
SM.getBufferOrNone(SM.getFileID(AssertLoc));
if (!Buffer)
return SourceLocation();
"::std::ios_base::seek_dir", "::std::ios_base::streamoff",
"::std::ios_base::streampos"};
-static llvm::Optional<const char *> getReplacementType(StringRef Type) {
- return llvm::StringSwitch<llvm::Optional<const char *>>(Type)
+static std::optional<const char *> getReplacementType(StringRef Type) {
+ return llvm::StringSwitch<std::optional<const char *>>(Type)
.Case("io_state", "iostate")
.Case("open_mode", "openmode")
.Case("seek_dir", "seekdir")
CharSourceRange::getTokenRange(ParenRange), Range));
if (Descriptor.NeedsReverseCall && !getReverseHeader().empty()) {
- if (Optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
+ if (std::optional<FixItHint> Insertion = Inserter.createIncludeInsertion(
Context->getSourceManager().getFileID(Loop->getBeginLoc()),
getReverseHeader()))
FixIts.push_back(*Insertion);
Context->getAsConstantArrayType(ArrayType);
if (!ConstType)
return false;
- Optional<llvm::APSInt> ConditionSize =
+ std::optional<llvm::APSInt> ConditionSize =
ConditionExpr->getIntegerConstantExpr(*Context);
if (!ConditionSize)
return false;
/// \returns \c true if the next token after the given \p MacroLoc is \b not a
/// semicolon.
bool shouldAppendSemi(SourceRange MacroLoc) {
- llvm::Optional<Token> Next = Lexer::findNextToken(
+ std::optional<Token> Next = Lexer::findNextToken(
MacroLoc.getEnd(), PP.getSourceManager(), PP.getLangOpts());
return !(Next && Next->is(tok::semi));
}
*Body, Result.Context->getSourceManager(),
Result.Context->getLangOpts());
// Skipping comments, check for a semicolon after Body->getSourceRange()
- Optional<Token> Token = utils::lexer::findNextTokenSkippingComments(
+ std::optional<Token> Token = utils::lexer::findNextTokenSkippingComments(
UnifiedEnd, Result.Context->getSourceManager(),
Result.Context->getLangOpts());
StringRef Replacement =
tok::kw_static, tok::kw_friend, tok::kw_virtual);
}
-static llvm::Optional<ClassifiedToken>
+static std::optional<ClassifiedToken>
classifyToken(const FunctionDecl &F, Preprocessor &PP, Token Tok) {
ClassifiedToken CT;
CT.T = Tok;
return CT;
}
-llvm::Optional<SmallVector<ClassifiedToken, 8>>
+std::optional<SmallVector<ClassifiedToken, 8>>
UseTrailingReturnTypeCheck::classifyTokensBeforeFunctionName(
const FunctionDecl &F, const ASTContext &Ctx, const SourceManager &SM,
const LangOptions &LangOpts) {
T.setKind(Info.getTokenID());
}
- if (llvm::Optional<ClassifiedToken> CT = classifyToken(F, *PP, T))
+ if (std::optional<ClassifiedToken> CT = classifyToken(F, *PP, T))
ClassifiedTokens.push_back(*CT);
else {
diag(F.getLocation(), Message);
return ReturnTypeRange;
// Include qualifiers to the left and right of the return type.
- llvm::Optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
+ std::optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
classifyTokensBeforeFunctionName(F, Ctx, SM, LangOpts);
if (!MaybeTokens)
return {};
// Tokenize return type. If it contains macros which contain a mix of
// qualifiers, specifiers and types, give up.
- llvm::Optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
+ std::optional<SmallVector<ClassifiedToken, 8>> MaybeTokens =
classifyTokensBeforeFunctionName(F, Ctx, SM, LangOpts);
if (!MaybeTokens)
return;
SourceLocation findTrailingReturnTypeSourceLocation(
const FunctionDecl &F, const FunctionTypeLoc &FTL, const ASTContext &Ctx,
const SourceManager &SM, const LangOptions &LangOpts);
- llvm::Optional<SmallVector<ClassifiedToken, 8>>
+ std::optional<SmallVector<ClassifiedToken, 8>>
classifyTokensBeforeFunctionName(const FunctionDecl &F, const ASTContext &Ctx,
const SourceManager &SM,
const LangOptions &LangOpts);
enum class IndirectionType : unsigned char { Pointer, Array };
- Optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
+ std::optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
};
} // namespace mpi
ArrayRef<const Expr *> BufferExprs,
ArrayRef<StringRef> MPIDatatypes, const LangOptions &LO);
- Optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
+ std::optional<ento::mpi::MPIFunctionClassifier> FuncClassifier;
};
} // namespace mpi
QT.getQualifiers().getObjCLifetime() > Qualifiers::OCL_ExplicitNone;
}
-static llvm::Optional<FixItHint>
+static std::optional<FixItHint>
fixItHintReplacementForOwnershipString(StringRef Text, CharSourceRange Range,
StringRef Ownership) {
size_t Index = Text.find(Ownership);
UnsafeUnretainedText);
}
-static llvm::Optional<FixItHint>
+static std::optional<FixItHint>
fixItHintForVarDecl(const VarDecl *VD, const SourceManager &SM,
const LangOptions &LangOpts) {
assert(VD && "VarDecl parameter must not be null");
}
StringRef VarDeclText = Lexer::getSourceText(Range, SM, LangOpts);
- if (llvm::Optional<FixItHint> Hint =
+ if (std::optional<FixItHint> Hint =
fixItHintReplacementForOwnershipString(VarDeclText, Range, WeakText))
return Hint;
- if (llvm::Optional<FixItHint> Hint = fixItHintReplacementForOwnershipString(
+ if (std::optional<FixItHint> Hint = fixItHintReplacementForOwnershipString(
VarDeclText, Range, StrongText))
return Hint;
namespace {
-llvm::Optional<std::string> makeCharacterLiteral(const StringLiteral *Literal) {
+std::optional<std::string> makeCharacterLiteral(const StringLiteral *Literal) {
std::string Result;
{
llvm::raw_string_ostream OS(Result);
} else if (!LoopVar.getType().isConstQualified()) {
return false;
}
- llvm::Optional<bool> Expensive =
+ std::optional<bool> Expensive =
utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
if (!Expensive || !*Expensive)
return false;
"copy in each iteration; consider making this a reference")
<< utils::fixit::changeVarDeclToReference(LoopVar, Context);
if (!LoopVar.getType().isConstQualified()) {
- if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
+ if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
LoopVar, Context, DeclSpec::TQ::TQ_const))
Diagnostic << *Fix;
}
bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
const VarDecl &LoopVar, const CXXForRangeStmt &ForRange,
ASTContext &Context) {
- llvm::Optional<bool> Expensive =
+ std::optional<bool> Expensive =
utils::type_traits::isExpensiveToCopy(LoopVar.getType(), Context);
if (LoopVar.getType().isConstQualified() || !Expensive || !*Expensive)
return false;
"loop variable is copied but only used as const reference; consider "
"making it a const reference");
- if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
+ if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
LoopVar, Context, DeclSpec::TQ::TQ_const))
Diag << *Fix << utils::fixit::changeVarDeclToReference(LoopVar, Context);
DiagnosticBuilder &Diagnostic) {
Diagnostic << utils::fixit::changeVarDeclToReference(Var, Context);
if (!Var.getType().isLocalConstQualified()) {
- if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
+ if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
Var, Context, DeclSpec::TQ::TQ_const))
Diagnostic << *Fix;
}
}
-llvm::Optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
- SourceManager &SM) {
+std::optional<SourceLocation> firstLocAfterNewLine(SourceLocation Loc,
+ SourceManager &SM) {
bool Invalid;
const char *TextAfter = SM.getCharacterData(Loc, &Invalid);
if (Invalid) {
// Attempt to remove trailing comments as well.
auto Tok = utils::lexer::findNextTokenSkippingComments(Stmt.getEndLoc(), SM,
Context.getLangOpts());
- llvm::Optional<SourceLocation> PastNewLine =
+ std::optional<SourceLocation> PastNewLine =
firstLocAfterNewLine(Stmt.getEndLoc(), SM);
if (Tok && PastNewLine) {
auto BeforeFirstTokenAfterComment = Tok->getLocation().getLocWithOffset(-1);
// whether it is const or not as constness can differ between definition and
// declaration.
if (!CurrentParam.getType().getCanonicalType().isConstQualified()) {
- if (llvm::Optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
+ if (std::optional<FixItHint> Fix = utils::fixit::addQualifierToVarDecl(
CurrentParam, *Result.Context, DeclSpec::TQ::TQ_const))
Diag << *Fix;
}
// return type. Returns `std::nullopt` when the return type is not
// `const`-qualified or `const` does not appear in `Def`'s source, like when the
// type is an alias or a macro.
-static llvm::Optional<Token>
+static std::optional<Token>
findConstToRemove(const FunctionDecl *Def,
const MatchFinder::MatchResult &Result) {
if (!Def->getReturnType().isLocalConstQualified())
static CheckResult checkDef(const clang::FunctionDecl *Def,
const MatchFinder::MatchResult &MatchResult) {
CheckResult Result;
- llvm::Optional<Token> Tok = findConstToRemove(Def, MatchResult);
+ std::optional<Token> Tok = findConstToRemove(Def, MatchResult);
if (!Tok)
return Result;
// single warning at the definition.
for (const FunctionDecl *Decl = Def->getPreviousDecl(); Decl != nullptr;
Decl = Decl->getPreviousDecl()) {
- if (llvm::Optional<Token> T = findConstToRemove(Decl, MatchResult))
+ if (std::optional<Token> T = findConstToRemove(Decl, MatchResult))
Result.Hints.push_back(FixItHint::CreateRemoval(
CharSourceRange::getCharRange(T->getLocation(), T->getEndLoc())));
else
// Used to efficiently know the last type of the binary sequence operator
// that was encountered. It would make sense for the function call to start
// the new sequence, thus it is a stack.
- using OBO = Optional<BinaryOperator::Opcode>;
+ using OBO = std::optional<BinaryOperator::Opcode>;
std::stack<OBO, SmallVector<OBO, 4>> BinaryOperatorsStack;
public:
// We might encounter a function call, which starts a new sequence, thus
// we need to save the current previous binary operator.
- const Optional<BinaryOperator::Opcode> BinOpCopy(CurrentBinaryOperator);
+ const std::optional<BinaryOperator::Opcode> BinOpCopy(
+ CurrentBinaryOperator);
// Record the operator that we are currently processing and traverse it.
CurrentBinaryOperator = Op->getOpcode();
// clang-format on
IdentifierNamingCheck::NamingStyle::NamingStyle(
- llvm::Optional<IdentifierNamingCheck::CaseType> Case,
+ std::optional<IdentifierNamingCheck::CaseType> Case,
const std::string &Prefix, const std::string &Suffix,
const std::string &IgnoredRegexpStr, HungarianPrefixType HPType)
: Case(Case), Prefix(Prefix), Suffix(Suffix),
HungarianNotation.loadDefaultConfig(HNOption);
HungarianNotation.loadFileConfig(Options, HNOption);
- SmallVector<llvm::Optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
+ SmallVector<std::optional<IdentifierNamingCheck::NamingStyle>, 0> Styles;
Styles.resize(SK_Count);
SmallString<64> StyleString;
for (unsigned I = 0; I < SK_Count; ++I) {
void IdentifierNamingCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
RenamerClangTidyCheck::storeOptions(Opts);
SmallString<64> StyleString;
- ArrayRef<llvm::Optional<NamingStyle>> Styles = MainFileStyle->getStyles();
+ ArrayRef<std::optional<NamingStyle>> Styles = MainFileStyle->getStyles();
for (size_t I = 0; I < SK_Count; ++I) {
if (!Styles[I])
continue;
StyleKind IdentifierNamingCheck::findStyleKind(
const NamedDecl *D,
- ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
+ ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
bool IgnoreMainLikeFunctions) const {
assert(D && D->getIdentifier() && !D->getName().empty() && !D->isImplicit() &&
"Decl must be an explicit identifier with a name.");
return SK_Invalid;
}
-llvm::Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
IdentifierNamingCheck::getFailureInfo(
StringRef Type, StringRef Name, const NamedDecl *ND,
SourceLocation Location,
- ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
+ ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
const IdentifierNamingCheck::HungarianNotationOption &HNOption,
StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const {
if (SK == SK_Invalid || !NamingStyles[SK])
std::move(Fixup)};
}
-llvm::Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
IdentifierNamingCheck::getDeclFailureInfo(const NamedDecl *Decl,
const SourceManager &SM) const {
SourceLocation Loc = Decl->getLocation();
SM, IgnoreFailedSplit);
}
-llvm::Optional<RenamerClangTidyCheck::FailureInfo>
+std::optional<RenamerClangTidyCheck::FailureInfo>
IdentifierNamingCheck::getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &SM) const {
SourceLocation Loc = MacroNameTok.getLocation();
struct HungarianNotationOption {
HungarianNotationOption() : HPType(HungarianPrefixType::HPT_Off) {}
- llvm::Optional<CaseType> Case;
+ std::optional<CaseType> Case;
HungarianPrefixType HPType;
llvm::StringMap<std::string> General;
llvm::StringMap<std::string> CString;
struct NamingStyle {
NamingStyle() = default;
- NamingStyle(llvm::Optional<CaseType> Case, const std::string &Prefix,
+ NamingStyle(std::optional<CaseType> Case, const std::string &Prefix,
const std::string &Suffix, const std::string &IgnoredRegexpStr,
HungarianPrefixType HPType);
NamingStyle(const NamingStyle &O) = delete;
NamingStyle &operator=(NamingStyle &&O) = default;
NamingStyle(NamingStyle &&O) = default;
- llvm::Optional<CaseType> Case;
+ std::optional<CaseType> Case;
std::string Prefix;
std::string Suffix;
// Store both compiled and non-compiled forms so original value can be
struct FileStyle {
FileStyle() : IsActive(false), IgnoreMainLikeFunctions(false) {}
- FileStyle(SmallVectorImpl<Optional<NamingStyle>> &&Styles,
+ FileStyle(SmallVectorImpl<std::optional<NamingStyle>> &&Styles,
HungarianNotationOption HNOption, bool IgnoreMainLike)
: Styles(std::move(Styles)), HNOption(std::move(HNOption)),
IsActive(true), IgnoreMainLikeFunctions(IgnoreMainLike) {}
- ArrayRef<Optional<NamingStyle>> getStyles() const {
+ ArrayRef<std::optional<NamingStyle>> getStyles() const {
assert(IsActive);
return Styles;
}
bool isIgnoringMainLikeFunction() const { return IgnoreMainLikeFunctions; }
private:
- SmallVector<Optional<NamingStyle>, 0> Styles;
+ SmallVector<std::optional<NamingStyle>, 0> Styles;
HungarianNotationOption HNOption;
bool IsActive;
bool IgnoreMainLikeFunctions;
StyleKind findStyleKind(
const NamedDecl *D,
- ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
+ ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
bool IgnoreMainLikeFunctions) const;
- llvm::Optional<RenamerClangTidyCheck::FailureInfo> getFailureInfo(
+ std::optional<RenamerClangTidyCheck::FailureInfo> getFailureInfo(
StringRef Type, StringRef Name, const NamedDecl *ND,
SourceLocation Location,
- ArrayRef<llvm::Optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
+ ArrayRef<std::optional<IdentifierNamingCheck::NamingStyle>> NamingStyles,
const IdentifierNamingCheck::HungarianNotationOption &HNOption,
StyleKind SK, const SourceManager &SM, bool IgnoreFailedSplit) const;
bool IncludeMainLike) const;
private:
- llvm::Optional<FailureInfo>
+ std::optional<FailureInfo>
getDeclFailureInfo(const NamedDecl *Decl,
const SourceManager &SM) const override;
- llvm::Optional<FailureInfo>
+ std::optional<FailureInfo>
getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &SM) const override;
DiagInfo getDiagInfo(const NamingCheckId &ID,
/// // [ ][ ] [ ] - The ranges here are inclusive
/// \endcode
/// \todo Generalize this function to take other declarations than \c VarDecl.
-static Optional<std::vector<SourceRange>>
+static std::optional<std::vector<SourceRange>>
declRanges(const DeclStmt *DS, const SourceManager &SM,
const LangOptions &LangOpts) {
std::size_t DeclCount = std::distance(DS->decl_begin(), DS->decl_end());
return Slices;
}
-static Optional<std::vector<StringRef>>
+static std::optional<std::vector<StringRef>>
collectSourceRanges(llvm::ArrayRef<SourceRange> Ranges, const SourceManager &SM,
const LangOptions &LangOpts) {
std::vector<StringRef> Snippets;
diag(WholeDecl->getBeginLoc(),
"multiple declarations in a single statement reduces readability");
- Optional<std::vector<SourceRange>> PotentialRanges =
+ std::optional<std::vector<SourceRange>> PotentialRanges =
declRanges(WholeDecl, *Result.SourceManager, getLangOpts());
if (!PotentialRanges)
return;
- Optional<std::vector<StringRef>> PotentialSnippets = collectSourceRanges(
+ std::optional<std::vector<StringRef>> PotentialSnippets = collectSourceRanges(
*PotentialRanges, *Result.SourceManager, getLangOpts());
if (!PotentialSnippets)
Sources.getFileID(Loc1) == Sources.getFileID(Loc2);
}
-static llvm::Optional<std::string>
+static std::optional<std::string>
getNamespaceNameAsWritten(SourceLocation &Loc, const SourceManager &Sources,
const LangOptions &LangOpts) {
// Loc should be at the begin of the namespace decl (usually, `namespace`
// the opening brace can result from attributes.
std::string Result;
int Nesting = 0;
- while (llvm::Optional<Token> T = utils::lexer::findNextTokenSkippingComments(
+ while (std::optional<Token> T = utils::lexer::findNextTokenSkippingComments(
Loc, Sources, LangOpts)) {
Loc = T->getLocation();
if (T->is(tok::l_brace))
return;
}
- llvm::Optional<std::string> NamespaceNameAsWritten =
+ std::optional<std::string> NamespaceNameAsWritten =
getNamespaceNameAsWritten(LBraceLoc, Sources, getLangOpts());
if (!NamespaceNameAsWritten)
return;
enum class Qualifier { Const, Volatile, Restrict };
-llvm::Optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
- const MatchFinder::MatchResult &Result) {
+std::optional<Token> findQualToken(const VarDecl *Decl, Qualifier Qual,
+ const MatchFinder::MatchResult &Result) {
// Since either of the locs can be in a macro, use `makeFileCharRange` to be
// sure that we have a consistent `CharSourceRange`, located entirely in the
// source file.
*Result.SourceManager);
}
-llvm::Optional<SourceRange>
+std::optional<SourceRange>
getTypeSpecifierLocation(const VarDecl *Var,
const MatchFinder::MatchResult &Result) {
SourceRange TypeSpecifier(
return TypeSpecifier;
}
-llvm::Optional<SourceRange> mergeReplacementRange(SourceRange &TypeSpecifier,
- const Token &ConstToken) {
+std::optional<SourceRange> mergeReplacementRange(SourceRange &TypeSpecifier,
+ const Token &ConstToken) {
if (TypeSpecifier.getBegin().getLocWithOffset(-1) == ConstToken.getEndLoc()) {
TypeSpecifier.setBegin(ConstToken.getLocation());
return std::nullopt;
void QualifiedAutoCheck::check(const MatchFinder::MatchResult &Result) {
if (const auto *Var = Result.Nodes.getNodeAs<VarDecl>("auto")) {
SourceRange TypeSpecifier;
- if (llvm::Optional<SourceRange> TypeSpec =
+ if (std::optional<SourceRange> TypeSpec =
getTypeSpecifierLocation(Var, Result)) {
TypeSpecifier = *TypeSpec;
} else
llvm::SmallVector<SourceRange, 4> RemoveQualifiersRange;
auto CheckQualifier = [&](bool IsPresent, Qualifier Qual) {
if (IsPresent) {
- llvm::Optional<Token> Token = findQualToken(Var, Qual, Result);
+ std::optional<Token> Token = findQualToken(Var, Qual, Result);
if (!Token || Token->getLocation().isMacroID())
return true; // Disregard this VarDecl.
- if (llvm::Optional<SourceRange> Result =
+ if (std::optional<SourceRange> Result =
mergeReplacementRange(TypeSpecifier, *Token))
RemoveQualifiersRange.push_back(*Result);
}
// explicitly.
if (Var->getType().isLocalConstQualified()) {
- llvm::Optional<Token> Token =
- findQualToken(Var, Qualifier::Const, Result);
+ std::optional<Token> Token = findQualToken(Var, Qualifier::Const, Result);
if (!Token || Token->getLocation().isMacroID())
return;
}
if (Var->getType().isLocalVolatileQualified()) {
- llvm::Optional<Token> Token =
+ std::optional<Token> Token =
findQualToken(Var, Qualifier::Volatile, Result);
if (!Token || Token->getLocation().isMacroID())
return;
}
if (Var->getType().isLocalRestrictQualified()) {
- llvm::Optional<Token> Token =
+ std::optional<Token> Token =
findQualToken(Var, Qualifier::Restrict, Result);
if (!Token || Token->getLocation().isMacroID())
return;
}
- if (llvm::Optional<SourceRange> TypeSpec =
+ if (std::optional<SourceRange> TypeSpec =
getTypeSpecifierLocation(Var, Result)) {
if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() ||
TypeSpec->getEnd().isMacroID())
// Const isn't wrapped in the auto type, so must be declared explicitly.
return;
- if (llvm::Optional<SourceRange> TypeSpec =
+ if (std::optional<SourceRange> TypeSpec =
getTypeSpecifierLocation(Var, Result)) {
if (TypeSpec->isInvalid() || TypeSpec->getBegin().isMacroID() ||
TypeSpec->getEnd().isMacroID())
return dyn_cast<CXXConstructExpr>(InitExpr);
}
-static llvm::Optional<SourceRange>
+static std::optional<SourceRange>
getConstructExprArgRange(const CXXConstructExpr &Construct) {
SourceLocation B, E;
for (const Expr *Arg : Construct.arguments()) {
const CXXConstructExpr *Construct = getConstructExpr(*CtorInit);
if (!Construct)
return;
- if (llvm::Optional<SourceRange> RemovalRange =
+ if (std::optional<SourceRange> RemovalRange =
getConstructExprArgRange(*Construct))
diag(CtorInit->getMemberLocation(), "redundant string initialization")
<< FixItHint::CreateRemoval(*RemovalRange);
}
// Extracts a bool if an expression is (true|false|!true|!false);
- static Optional<bool> getAsBoolLiteral(const Expr *E, bool FilterMacro) {
+ static std::optional<bool> getAsBoolLiteral(const Expr *E, bool FilterMacro) {
if (const auto *Bool = dyn_cast<CXXBoolLiteralExpr>(E)) {
if (FilterMacro && Bool->getBeginLoc().isMacroID())
return std::nullopt;
if (FilterMacro && UnaryOp->getBeginLoc().isMacroID())
return std::nullopt;
if (UnaryOp->getOpcode() == UO_LNot)
- if (Optional<bool> Res = getAsBoolLiteral(
+ if (std::optional<bool> Res = getAsBoolLiteral(
UnaryOp->getSubExpr()->IgnoreImplicit(), FilterMacro))
return !*Res;
}
const auto *RS = dyn_cast<ReturnStmt>(S);
if (!RS || !RS->getRetValue())
return {};
- if (Optional<bool> Ret =
+ if (std::optional<bool> Ret =
getAsBoolLiteral(RS->getRetValue()->IgnoreImplicit(), false)) {
return {RS->getRetValue(), *Ret};
}
* if (false) ThenStmt(); else ElseStmt() -> ElseStmt();
*/
Expr *Cond = If->getCond()->IgnoreImplicit();
- if (Optional<bool> Bool = getAsBoolLiteral(Cond, true)) {
+ if (std::optional<bool> Bool = getAsBoolLiteral(Cond, true)) {
if (*Bool)
Check->replaceWithThenStatement(Context, If, Cond);
else
const auto *BO = dyn_cast<BinaryOperator>(S);
if (!BO || BO->getOpcode() != BO_Assign)
return {};
- Optional<bool> RightasBool =
+ std::optional<bool> RightasBool =
getAsBoolLiteral(BO->getRHS()->IgnoreImplicit(), false);
if (!RightasBool)
return {};
* Condition ? true : false; -> Condition
* Condition ? false : true; -> !Condition;
*/
- if (Optional<bool> Then =
+ if (std::optional<bool> Then =
getAsBoolLiteral(Cond->getTrueExpr()->IgnoreImplicit(), false)) {
- if (Optional<bool> Else =
+ if (std::optional<bool> Else =
getAsBoolLiteral(Cond->getFalseExpr()->IgnoreImplicit(), false)) {
if (*Then != *Else)
Check->replaceWithCondition(Context, Cond, *Else);
static bool flipDemorganSide(SmallVectorImpl<FixItHint> &Fixes,
const ASTContext &Ctx, const Expr *E,
- Optional<BinaryOperatorKind> OuterBO);
+ std::optional<BinaryOperatorKind> OuterBO);
/// Inverts \p BinOp, Removing \p Parens if they exist and are safe to remove.
/// returns \c true if there is any issue building the Fixes, \c false
/// otherwise.
-static bool flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
- const ASTContext &Ctx,
- const BinaryOperator *BinOp,
- Optional<BinaryOperatorKind> OuterBO,
- const ParenExpr *Parens = nullptr) {
+static bool
+flipDemorganBinaryOperator(SmallVectorImpl<FixItHint> &Fixes,
+ const ASTContext &Ctx, const BinaryOperator *BinOp,
+ std::optional<BinaryOperatorKind> OuterBO,
+ const ParenExpr *Parens = nullptr) {
switch (BinOp->getOpcode()) {
case BO_LAnd:
case BO_LOr: {
static bool flipDemorganSide(SmallVectorImpl<FixItHint> &Fixes,
const ASTContext &Ctx, const Expr *E,
- Optional<BinaryOperatorKind> OuterBO) {
+ std::optional<BinaryOperatorKind> OuterBO) {
if (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->getOpcode() == UO_LNot) {
// if we have a not operator, '!a', just remove the '!'.
if (cast<UnaryOperator>(E)->getOperatorLoc().isMacroID())
return llvm::is_contained(AppliedHeuristics, H);
}
-Optional<int8_t> SuspiciousCallArgumentCheck::getBound(Heuristic H,
- BoundKind BK) const {
+std::optional<int8_t>
+SuspiciousCallArgumentCheck::getBound(Heuristic H, BoundKind BK) const {
auto Idx = static_cast<std::size_t>(H);
assert(Idx < HeuristicCount);
StringRef Param, Heuristic H,
BoundKind BK) const {
int8_t Threshold = -1;
- if (Optional<int8_t> GotBound = getBound(H, BK))
+ if (std::optional<int8_t> GotBound = getBound(H, BK))
Threshold = *GotBound;
switch (H) {
llvm::StringMap<std::string> AbbreviationDictionary;
bool isHeuristicEnabled(Heuristic H) const;
- Optional<int8_t> getBound(Heuristic H, BoundKind BK) const;
+ std::optional<int8_t> getBound(Heuristic H, BoundKind BK) const;
// Runtime information of the currently analyzed function call.
SmallVector<QualType, SmallVectorSize> ArgTypes;
struct NewSuffix {
SourceRange LiteralLocation;
StringRef OldSuffix;
- llvm::Optional<FixItHint> FixIt;
+ std::optional<FixItHint> FixIt;
};
-llvm::Optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc,
- const SourceManager &SM) {
+std::optional<SourceLocation> getMacroAwareLocation(SourceLocation Loc,
+ const SourceManager &SM) {
// Do nothing if the provided location is invalid.
if (Loc.isInvalid())
return std::nullopt;
return SpellingLoc;
}
-llvm::Optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc,
- const SourceManager &SM) {
- llvm::Optional<SourceLocation> Begin =
+std::optional<SourceRange> getMacroAwareSourceRange(SourceRange Loc,
+ const SourceManager &SM) {
+ std::optional<SourceLocation> Begin =
getMacroAwareLocation(Loc.getBegin(), SM);
- llvm::Optional<SourceLocation> End = getMacroAwareLocation(Loc.getEnd(), SM);
+ std::optional<SourceLocation> End = getMacroAwareLocation(Loc.getEnd(), SM);
if (!Begin || !End)
return std::nullopt;
return SourceRange(*Begin, *End);
}
-llvm::Optional<std::string>
+std::optional<std::string>
getNewSuffix(llvm::StringRef OldSuffix,
const std::vector<StringRef> &NewSuffixes) {
// If there is no config, just uppercase the entirety of the suffix.
}
template <typename LiteralType>
-llvm::Optional<NewSuffix>
+std::optional<NewSuffix>
shouldReplaceLiteralSuffix(const Expr &Literal,
const std::vector<StringRef> &NewSuffixes,
const SourceManager &SM, const LangOptions &LO) {
utils::rangeCanBeFixed(ReplacementDsc.LiteralLocation, &SM);
// The literal may have macro expansion, we need the final expanded src range.
- llvm::Optional<SourceRange> Range =
+ std::optional<SourceRange> Range =
getMacroAwareSourceRange(ReplacementDsc.LiteralLocation, SM);
if (!Range)
return std::nullopt;
"We still should have some chars left.");
// And get the replacement suffix.
- llvm::Optional<std::string> NewSuffix =
+ std::optional<std::string> NewSuffix =
getNewSuffix(ReplacementDsc.OldSuffix, NewSuffixes);
if (!NewSuffix || ReplacementDsc.OldSuffix == *NewSuffix)
return std::nullopt; // The suffix was already the way it should be.
: Context(TheContext) {
for (const auto *B : *TheCFG) {
for (const auto &Elem : *B) {
- if (Optional<CFGStmt> S = Elem.getAs<CFGStmt>())
+ if (std::optional<CFGStmt> S = Elem.getAs<CFGStmt>())
Map[S->getStmt()] = B;
}
}
return true;
}
-llvm::Optional<StringRef>
+std::optional<StringRef>
getFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions) {
StringRef Extension = llvm::sys::path::extension(FileName);
if (Extension.empty())
/// Decides whether a file has a header file extension.
/// Returns the file extension, if included in the provided set.
-llvm::Optional<StringRef>
+std::optional<StringRef>
getFileExtension(StringRef FileName, const FileExtensionsSet &FileExtensions);
/// Decides whether a file has one of the specified file extensions.
return S.isInvalid() || S.isMacroID();
}
-static Optional<SourceLocation>
+static std::optional<SourceLocation>
skipLParensBackwards(SourceLocation Start, const ASTContext &Context) {
if (locDangerous(Start))
return std::nullopt;
return Start;
}
-static Optional<FixItHint> fixIfNotDangerous(SourceLocation Loc,
- StringRef Text) {
+static std::optional<FixItHint> fixIfNotDangerous(SourceLocation Loc,
+ StringRef Text) {
if (locDangerous(Loc))
return std::nullopt;
return FixItHint::CreateInsertion(Loc, Text);
return (llvm::Twine(DeclSpec::getSpecifierName(Qualifier)) + " ").str();
}
-static Optional<FixItHint> changeValue(const VarDecl &Var,
- DeclSpec::TQ Qualifier,
- QualifierTarget QualTarget,
- QualifierPolicy QualPolicy,
- const ASTContext &Context) {
+static std::optional<FixItHint> changeValue(const VarDecl &Var,
+ DeclSpec::TQ Qualifier,
+ QualifierTarget QualTarget,
+ QualifierPolicy QualPolicy,
+ const ASTContext &Context) {
switch (QualPolicy) {
case QualifierPolicy::Left:
return fixIfNotDangerous(Var.getTypeSpecStartLoc(),
buildQualifier(Qualifier));
case QualifierPolicy::Right:
- Optional<SourceLocation> IgnoredParens =
+ std::optional<SourceLocation> IgnoredParens =
skipLParensBackwards(Var.getLocation(), Context);
if (IgnoredParens)
llvm_unreachable("Unknown QualifierPolicy enum");
}
-static Optional<FixItHint> changePointerItself(const VarDecl &Var,
- DeclSpec::TQ Qualifier,
- const ASTContext &Context) {
+static std::optional<FixItHint> changePointerItself(const VarDecl &Var,
+ DeclSpec::TQ Qualifier,
+ const ASTContext &Context) {
if (locDangerous(Var.getLocation()))
return std::nullopt;
- Optional<SourceLocation> IgnoredParens =
+ std::optional<SourceLocation> IgnoredParens =
skipLParensBackwards(Var.getLocation(), Context);
if (IgnoredParens)
return fixIfNotDangerous(*IgnoredParens, buildQualifier(Qualifier));
return std::nullopt;
}
-static Optional<FixItHint>
+static std::optional<FixItHint>
changePointer(const VarDecl &Var, DeclSpec::TQ Qualifier, const Type *Pointee,
QualifierTarget QualTarget, QualifierPolicy QualPolicy,
const ASTContext &Context) {
if (locDangerous(BeforeStar))
return std::nullopt;
- Optional<SourceLocation> IgnoredParens =
+ std::optional<SourceLocation> IgnoredParens =
skipLParensBackwards(BeforeStar, Context);
if (IgnoredParens)
return std::nullopt;
}
-static Optional<FixItHint>
+static std::optional<FixItHint>
changeReferencee(const VarDecl &Var, DeclSpec::TQ Qualifier, QualType Pointee,
QualifierTarget QualTarget, QualifierPolicy QualPolicy,
const ASTContext &Context) {
SourceLocation BeforeRef = lexer::findPreviousAnyTokenKind(
Var.getLocation(), Context.getSourceManager(), Context.getLangOpts(),
tok::amp, tok::ampamp);
- Optional<SourceLocation> IgnoredParens =
+ std::optional<SourceLocation> IgnoredParens =
skipLParensBackwards(BeforeRef, Context);
if (IgnoredParens)
return fixIfNotDangerous(*IgnoredParens, buildQualifier(Qualifier, true));
return std::nullopt;
}
-Optional<FixItHint> addQualifierToVarDecl(const VarDecl &Var,
- const ASTContext &Context,
- DeclSpec::TQ Qualifier,
- QualifierTarget QualTarget,
- QualifierPolicy QualPolicy) {
+std::optional<FixItHint> addQualifierToVarDecl(const VarDecl &Var,
+ const ASTContext &Context,
+ DeclSpec::TQ Qualifier,
+ QualifierTarget QualTarget,
+ QualifierPolicy QualPolicy) {
assert((QualPolicy == QualifierPolicy::Left ||
QualPolicy == QualifierPolicy::Right) &&
"Unexpected Insertion Policy");
/// \brief Creates fix to qualify ``VarDecl`` with the specified \c Qualifier.
/// Requires that `Var` is isolated in written code like in `int foo = 42;`.
-Optional<FixItHint>
+std::optional<FixItHint>
addQualifierToVarDecl(const VarDecl &Var, const ASTContext &Context,
DeclSpec::TQ Qualifier,
QualifierTarget CT = QualifierTarget::Pointee,
return *Entry;
}
-llvm::Optional<FixItHint>
+std::optional<FixItHint>
IncludeInserter::createIncludeInsertion(FileID FileID, llvm::StringRef Header) {
bool IsAngled = Header.consume_front("<");
if (IsAngled != Header.consume_back(">"))
return getOrCreate(FileID).createIncludeInsertion(Header, IsAngled);
}
-llvm::Optional<FixItHint>
+std::optional<FixItHint>
IncludeInserter::createMainFileIncludeInsertion(StringRef Header) {
assert(SourceMgr && "SourceMgr shouldn't be null; did you remember to call "
"registerPreprocessor()?");
/// inclusion directive, otherwise uses quotes.
/// Returns ``std::nullopt`` on error or if the inclusion directive already
/// exists.
- llvm::Optional<FixItHint> createIncludeInsertion(FileID FileID,
- llvm::StringRef Header);
+ std::optional<FixItHint> createIncludeInsertion(FileID FileID,
+ llvm::StringRef Header);
/// Creates a \p Header inclusion directive fixit in the main file.
/// When \p Header is enclosed in angle brackets, uses angle brackets in the
/// inclusion directive, otherwise uses quotes.
/// Returns ``std::nullopt`` on error or if the inclusion directive already
/// exists.
- llvm::Optional<FixItHint>
+ std::optional<FixItHint>
createMainFileIncludeInsertion(llvm::StringRef Header);
IncludeSorter::IncludeStyle getStyle() const { return Style; }
IncludeBucket[Kind].push_back(FileName.str());
}
-Optional<FixItHint> IncludeSorter::createIncludeInsertion(StringRef FileName,
- bool IsAngled) {
+std::optional<FixItHint>
+IncludeSorter::createIncludeInsertion(StringRef FileName, bool IsAngled) {
std::string IncludeStmt;
if (Style == IncludeStyle::IS_Google_ObjC) {
IncludeStmt = IsAngled
/// Creates a quoted inclusion directive in the right sort order. Returns
/// std::nullopt on error or if header inclusion directive for header already
/// exists.
- Optional<FixItHint> createIncludeInsertion(StringRef FileName, bool IsAngled);
+ std::optional<FixItHint> createIncludeInsertion(StringRef FileName,
+ bool IsAngled);
private:
typedef SmallVector<SourceRange, 1> SourceRangeVector;
return findNextAnyTokenKind(Start, SM, LangOpts, tok::comma, tok::semi);
}
-Optional<Token> findNextTokenSkippingComments(SourceLocation Start,
- const SourceManager &SM,
- const LangOptions &LangOpts) {
- Optional<Token> CurrentToken;
+std::optional<Token>
+findNextTokenSkippingComments(SourceLocation Start, const SourceManager &SM,
+ const LangOptions &LangOpts) {
+ std::optional<Token> CurrentToken;
do {
CurrentToken = Lexer::findNextToken(Start, SM, LangOpts);
} while (CurrentToken && CurrentToken->is(tok::comment));
if (Loc.isMacroID())
return true;
- llvm::Optional<Token> Tok = Lexer::findNextToken(Loc, SM, LangOpts);
+ std::optional<Token> Tok = Lexer::findNextToken(Loc, SM, LangOpts);
if (!Tok)
return true;
return false;
}
-llvm::Optional<Token> getQualifyingToken(tok::TokenKind TK,
- CharSourceRange Range,
- const ASTContext &Context,
- const SourceManager &SM) {
+std::optional<Token> getQualifyingToken(tok::TokenKind TK,
+ CharSourceRange Range,
+ const ASTContext &Context,
+ const SourceManager &SM) {
assert((TK == tok::kw_const || TK == tok::kw_volatile ||
TK == tok::kw_restrict) &&
"TK is not a qualifier keyword");
StringRef File = SM.getBufferData(LocInfo.first);
Lexer RawLexer(SM.getLocForStartOfFile(LocInfo.first), Context.getLangOpts(),
File.begin(), File.data() + LocInfo.second, File.end());
- llvm::Optional<Token> LastMatchBeforeTemplate;
- llvm::Optional<Token> LastMatchAfterTemplate;
+ std::optional<Token> LastMatchBeforeTemplate;
+ std::optional<Token> LastMatchAfterTemplate;
bool SawTemplate = false;
Token Tok;
while (!RawLexer.LexFromRawLexer(Tok) &&
// F ( foo() ; )
// ^ EndLoc ^ SpellingLoc ^ next token of SpellingLoc
const SourceLocation SpellingLoc = SM.getSpellingLoc(EndLoc);
- Optional<Token> NextTok =
+ std::optional<Token> NextTok =
findNextTokenSkippingComments(SpellingLoc, SM, LangOpts);
// Was the next token found successfully?
// ^ EndLoc ^ SpellingLoc ) ^ next token of EndLoc
}
- Optional<Token> NextTok = findNextTokenSkippingComments(EndLoc, SM, LangOpts);
+ std::optional<Token> NextTok =
+ findNextTokenSkippingComments(EndLoc, SM, LangOpts);
// Testing for semicolon again avoids some issues with macros.
if (NextTok && NextTok->is(tok::TokenKind::semi))
const LangOptions &LangOpts, TokenKind TK,
TokenKinds... TKs) {
while (true) {
- Optional<Token> CurrentToken = Lexer::findNextToken(Start, SM, LangOpts);
+ std::optional<Token> CurrentToken =
+ Lexer::findNextToken(Start, SM, LangOpts);
if (!CurrentToken)
return SourceLocation();
}
// Finds next token that's not a comment.
-Optional<Token> findNextTokenSkippingComments(SourceLocation Start,
- const SourceManager &SM,
- const LangOptions &LangOpts);
+std::optional<Token> findNextTokenSkippingComments(SourceLocation Start,
+ const SourceManager &SM,
+ const LangOptions &LangOpts);
/// Re-lex the provide \p Range and return \c false if either a macro spans
/// multiple tokens, a pre-processor directive or failure to retrieve the
/// must be valid with respect to ``SM``. Returns ``std::nullopt`` if no
/// qualifying tokens are found.
/// \note: doesn't support member function qualifiers.
-llvm::Optional<Token> getQualifyingToken(tok::TokenKind TK,
- CharSourceRange Range,
- const ASTContext &Context,
- const SourceManager &SM);
+std::optional<Token> getQualifyingToken(tok::TokenKind TK,
+ CharSourceRange Range,
+ const ASTContext &Context,
+ const SourceManager &SM);
/// Stmt->getEndLoc does not always behave the same way depending on Token type.
/// See implementation for exceptions.
AST_MATCHER(BinaryOperator, isEqualityOperator) { return Node.isEqualityOp(); }
AST_MATCHER(QualType, isExpensiveToCopy) {
- llvm::Optional<bool> IsExpensive =
+ std::optional<bool> IsExpensive =
utils::type_traits::isExpensiveToCopy(Node, Finder->getASTContext());
return IsExpensive && *IsExpensive;
}
return innerMatcher.matches(*Node.getNamespace(), Finder, Builder);
}
-Optional<FixItHint>
+std::optional<FixItHint>
NamespaceAliaser::createAlias(ASTContext &Context, const Stmt &Statement,
StringRef Namespace,
const std::vector<std::string> &Abbreviations) {
// Adds a namespace alias for \p Namespace valid near \p
// Statement. Picks the first available name from \p Abbreviations.
// Returns ``std::nullopt`` if an alias already exists or there is an error.
- llvm::Optional<FixItHint>
+ std::optional<FixItHint>
createAlias(ASTContext &Context, const Stmt &Statement,
llvm::StringRef Namespace,
const std::vector<std::string> &Abbreviations);
if (isa<ClassTemplateSpecializationDecl>(Decl))
return;
- Optional<FailureInfo> MaybeFailure =
+ std::optional<FailureInfo> MaybeFailure =
getDeclFailureInfo(Decl, *Result.SourceManager);
if (!MaybeFailure)
return;
void RenamerClangTidyCheck::checkMacro(SourceManager &SourceMgr,
const Token &MacroNameTok,
const MacroInfo *MI) {
- Optional<FailureInfo> MaybeFailure =
+ std::optional<FailureInfo> MaybeFailure =
getMacroFailureInfo(MacroNameTok, SourceMgr);
if (!MaybeFailure)
return;
/// Overridden by derived classes, returns information about if and how a Decl
/// failed the check. A 'std::nullopt' result means the Decl did not fail the
/// check.
- virtual llvm::Optional<FailureInfo>
+ virtual std::optional<FailureInfo>
getDeclFailureInfo(const NamedDecl *Decl, const SourceManager &SM) const = 0;
/// Overridden by derived classes, returns information about if and how a
/// macro failed the check. A 'std::nullopt' result means the macro did not
/// fail the check.
- virtual llvm::Optional<FailureInfo>
+ virtual std::optional<FailureInfo>
getMacroFailureInfo(const Token &MacroNameTok,
const SourceManager &SM) const = 0;
// we would be accessing `getLangOpts` and `Options` before the underlying
// `ClangTidyCheck` instance was properly initialized.
TransformerClangTidyCheck::TransformerClangTidyCheck(
- std::function<Optional<RewriteRuleWith<std::string>>(const LangOptions &,
- const OptionsView &)>
+ std::function<std::optional<RewriteRuleWith<std::string>>(
+ const LangOptions &, const OptionsView &)>
MakeRule,
StringRef Name, ClangTidyContext *Context)
: TransformerClangTidyCheck(Name, Context) {
- if (Optional<RewriteRuleWith<std::string>> R =
+ if (std::optional<RewriteRuleWith<std::string>> R =
MakeRule(getLangOpts(), Options))
setRule(std::move(*R));
}
///
/// See \c setRule for constraints on the rule.
TransformerClangTidyCheck(
- std::function<Optional<transformer::RewriteRuleWith<std::string>>(
+ std::function<std::optional<transformer::RewriteRuleWith<std::string>>(
const LangOptions &, const OptionsView &)>
MakeRule,
StringRef Name, ClangTidyContext *Context);
} // namespace
-llvm::Optional<bool> isExpensiveToCopy(QualType Type,
- const ASTContext &Context) {
+std::optional<bool> isExpensiveToCopy(QualType Type,
+ const ASTContext &Context) {
if (Type->isDependentType() || Type->isIncompleteType())
return std::nullopt;
return !Type.isTriviallyCopyableType(Context) &&
namespace type_traits {
/// Returns `true` if `Type` is expensive to copy.
-llvm::Optional<bool> isExpensiveToCopy(QualType Type,
- const ASTContext &Context);
+std::optional<bool> isExpensiveToCopy(QualType Type, const ASTContext &Context);
/// Returns `true` if `Type` is trivially default constructible.
bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context);
UsingInserter::UsingInserter(const SourceManager &SourceMgr)
: SourceMgr(SourceMgr) {}
-Optional<FixItHint> UsingInserter::createUsingDeclaration(
+std::optional<FixItHint> UsingInserter::createUsingDeclaration(
ASTContext &Context, const Stmt &Statement, StringRef QualifiedName) {
StringRef UnqualifiedName = getUnqualifiedName(QualifiedName);
const FunctionDecl *Function = getSurroundingFunction(Context, Statement);
// Creates a \p using declaration fixit. Returns ``std::nullopt`` on error
// or if the using declaration already exists.
- llvm::Optional<FixItHint>
+ std::optional<FixItHint>
createUsingDeclaration(ASTContext &Context, const Stmt &Statement,
llvm::StringRef QualifiedName);
namespace clangd {
namespace {
-llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>>
+std::optional<llvm::ArrayRef<TemplateArgumentLoc>>
getTemplateSpecializationArgLocs(const NamedDecl &ND) {
if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) {
if (const ASTTemplateArgumentListInfo *Args =
std::string TemplateArgs;
llvm::raw_string_ostream OS(TemplateArgs);
PrintingPolicy Policy(ND.getASTContext().getLangOpts());
- if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
+ if (std::optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
getTemplateSpecializationArgLocs(ND)) {
printTemplateArgumentList(OS, *Args, Policy);
} else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) {
};
} // namespace
-llvm::Optional<QualType> getDeducedType(ASTContext &ASTCtx,
- SourceLocation Loc) {
+std::optional<QualType> getDeducedType(ASTContext &ASTCtx, SourceLocation Loc) {
if (!Loc.isValid())
return {};
DeducedTypeVisitor V(Loc);
ArrayRef<const ParmVarDecl *> Tail;
// If the parameters were resolved to another forwarding FunctionDecl, this
// is it.
- Optional<FunctionDecl *> PackTarget;
+ std::optional<FunctionDecl *> PackTarget;
};
// The output of this visitor
- Optional<ForwardingInfo> Info;
+ std::optional<ForwardingInfo> Info;
private:
// inspects the given callee with the given args to check whether it
// Returns the beginning of the expanded pack represented by Parameters
// in the given arguments, if it is there.
- llvm::Optional<size_t> findPack(typename CallExpr::arg_range Args) {
+ std::optional<size_t> findPack(typename CallExpr::arg_range Args) {
// find the argument directly referring to the first parameter
assert(Parameters.size() <= static_cast<size_t>(llvm::size(Args)));
for (auto Begin = Args.begin(), End = Args.end() - Parameters.size() + 1;
/// Retrieves the deduced type at a given location (auto, decltype).
/// It will return the underlying type.
/// If the type is an undeduced auto, returns the type itself.
-llvm::Optional<QualType> getDeducedType(ASTContext &, SourceLocation Loc);
+std::optional<QualType> getDeducedType(ASTContext &, SourceLocation Loc);
// Find the abbreviated-function-template `auto` within a type, or returns null.
// Similar to getContainedAutoTypeLoc, but these `auto`s are
// clangd receives the reply from the LSP client.
// Return a call id of the request.
llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
- llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
+ std::optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
int ID;
{
std::lock_guard<std::mutex> Mutex(CallMutex);
// rather want to propagate information from LSPServer's context into the
// Server, CDB, etc.
WithContext MainContext(BackgroundContext.clone());
- llvm::Optional<WithContextValue> WithOffsetEncoding;
+ std::optional<WithContextValue> WithOffsetEncoding;
if (Opts.Encoding)
WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding);
Server.emplace(*CDB, TFS, Opts,
const URIForFile &FileURI) {
std::vector<SymbolInformation> Results;
std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
- [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
+ [&](const DocumentSymbol &S, std::optional<llvm::StringRef> ParentName) {
SymbolInformation SI;
SI.containerName = std::string(ParentName ? "" : *ParentName);
SI.name = S.name;
Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
}
-static llvm::Optional<Command> asCommand(const CodeAction &Action) {
+static std::optional<Command> asCommand(const CodeAction &Action) {
Command Cmd;
if (Action.command && Action.edit)
return std::nullopt; // Not representable. (We never emit these anyway).
Server->switchSourceHeader(
Params.uri.file(),
[Reply = std::move(Reply),
- Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
+ Params](llvm::Expected<std::optional<clangd::Path>> Path) mutable {
if (!Path)
return Reply(Path.takeError());
if (*Path)
/// set via LSP (extensions) only.
bool UseDirBasedCDB = true;
/// The offset-encoding to use, or std::nullopt to negotiate it over LSP.
- llvm::Optional<OffsetEncoding> Encoding;
+ std::optional<OffsetEncoding> Encoding;
/// If set, periodically called to release memory.
/// Consider malloc_trim(3)
std::function<void()> MemoryCleanup = nullptr;
// The CDB is created by the "initialize" LSP method.
std::unique_ptr<GlobalCompilationDatabase> BaseCDB;
// CDB is BaseCDB plus any commands overridden via LSP extensions.
- llvm::Optional<OverlayCDB> CDB;
+ std::optional<OverlayCDB> CDB;
// The ClangdServer is created by the "initialize" LSP method.
- llvm::Optional<ClangdServer> Server;
+ std::optional<ClangdServer> Server;
};
} // namespace clangd
} // namespace clang
if (auto Reason = isCancelled())
return CB(llvm::make_error<CancelledError>(Reason));
- llvm::Optional<SpeculativeFuzzyFind> SpecFuzzyFind;
+ std::optional<SpeculativeFuzzyFind> SpecFuzzyFind;
if (!IP->Preamble) {
// No speculation in Fallback mode, as it's supposed to be much faster
// without compiling.
std::move(Action));
}
-void ClangdServer::formatFile(PathRef File, llvm::Optional<Range> Rng,
+void ClangdServer::formatFile(PathRef File, std::optional<Range> Rng,
Callback<tooling::Replacements> CB) {
auto Code = getDraft(File);
if (!Code)
}
void ClangdServer::prepareRename(PathRef File, Position Pos,
- llvm::Optional<std::string> NewName,
+ std::optional<std::string> NewName,
const RenameOptions &RenameOpts,
Callback<RenameResult> CB) {
auto Action = [Pos, File = File.str(), CB = std::move(CB),
auto Selections = tweakSelection(Sel, *InpAST, FS.get());
if (!Selections)
return CB(Selections.takeError());
- llvm::Optional<llvm::Expected<Tweak::Effect>> Effect;
+ std::optional<llvm::Expected<Tweak::Effect>> Effect;
// Try each selection, take the first one that prepare()s.
// If they all fail, Effect will hold get the last error.
for (const auto &Selection : *Selections) {
}
void ClangdServer::switchSourceHeader(
- PathRef Path, Callback<llvm::Optional<clangd::Path>> CB) {
+ PathRef Path, Callback<std::optional<clangd::Path>> CB) {
// We want to return the result as fast as possible, strategy is:
// 1) use the file-only heuristic, it requires some IO but it is much
// faster than building AST, but it only works when .h/.cc files are in
}
[[nodiscard]] bool
-ClangdServer::blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds) {
+ClangdServer::blockUntilIdleForTest(std::optional<double> TimeoutSeconds) {
// Order is important here: we don't want to block on A and then B,
// if B might schedule work on A.
// Then on the last iteration, verify they're idle without waiting.
//
// There's a small chance they're juggling work and we didn't catch them :-(
- for (llvm::Optional<double> Timeout :
- {TimeoutSeconds, TimeoutSeconds, llvm::Optional<double>(0)}) {
+ for (std::optional<double> Timeout :
+ {TimeoutSeconds, TimeoutSeconds, std::optional<double>(0)}) {
if (!CDB.blockUntilIdle(timeoutSeconds(Timeout)))
return false;
if (BackgroundIdx && !BackgroundIdx->blockUntilIdleForTest(Timeout))
/// Clangd's workspace root. Relevant for "workspace" operations not bound
/// to a particular file.
/// FIXME: If not set, should use the current working directory.
- llvm::Optional<std::string> WorkspaceRoot;
+ std::optional<std::string> WorkspaceRoot;
/// The resource directory is used to find internal headers, overriding
/// defaults and -resource-dir compiler flag).
/// If None, ClangdServer calls CompilerInvocation::GetResourcePath() to
/// obtain the standard resource directory.
- llvm::Optional<std::string> ResourceDir = std::nullopt;
+ std::optional<std::string> ResourceDir = std::nullopt;
/// Time to wait after a new file version before computing diagnostics.
DebouncePolicy UpdateDebounce = DebouncePolicy{
/// Switch to a corresponding source file when given a header file, and vice
/// versa.
void switchSourceHeader(PathRef Path,
- Callback<llvm::Optional<clangd::Path>> CB);
+ Callback<std::optional<clangd::Path>> CB);
/// Get document highlights for a given position.
void findDocumentHighlights(PathRef File, Position Pos,
/// Run formatting for the \p File with content \p Code.
/// If \p Rng is non-null, formats only that region.
- void formatFile(PathRef File, llvm::Optional<Range> Rng,
+ void formatFile(PathRef File, std::optional<Range> Rng,
Callback<tooling::Replacements> CB);
/// Run formatting after \p TriggerText was typed at \p Pos in \p File with
///
/// If NewName is provided, it performs a name validation.
void prepareRename(PathRef File, Position Pos,
- llvm::Optional<std::string> NewName,
+ std::optional<std::string> NewName,
const RenameOptions &RenameOpts,
Callback<RenameResult> CB);
// FIXME: various subcomponents each get the full timeout, so it's more of
// an order of magnitude than a hard deadline.
[[nodiscard]] bool
- blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10);
+ blockUntilIdleForTest(std::optional<double> TimeoutSeconds = 10);
/// Builds a nested representation of memory used by components.
void profile(MemoryTree &MT) const;
bool PreambleParseForwardingFunctions = false;
// GUARDED_BY(CachedCompletionFuzzyFindRequestMutex)
- llvm::StringMap<llvm::Optional<FuzzyFindRequest>>
+ llvm::StringMap<std::optional<FuzzyFindRequest>>
CachedCompletionFuzzyFindRequestByFile;
mutable std::mutex CachedCompletionFuzzyFindRequestMutex;
- llvm::Optional<std::string> WorkspaceRoot;
- llvm::Optional<AsyncTaskRunner> IndexTasks; // for stdlib indexing.
- llvm::Optional<TUScheduler> WorkScheduler;
+ std::optional<std::string> WorkspaceRoot;
+ std::optional<AsyncTaskRunner> IndexTasks; // for stdlib indexing.
+ std::optional<TUScheduler> WorkScheduler;
// Invalidation policy used for actions that we assume are "transient".
TUScheduler::ASTActionInvalidation Transient;
}
// The best header to include if include insertion is allowed.
- llvm::Optional<llvm::StringRef>
+ std::optional<llvm::StringRef>
headerToInsertIfAllowed(const CodeCompleteOptions &Opts) const {
if (Opts.InsertIncludes == CodeCompleteOptions::NeverInsert ||
RankedIncludeHeaders.empty())
std::vector<std::string> AccessibleScopes;
// The full scope qualifier as typed by the user (without the leading "::").
// Set if the qualifier is not fully resolved by Sema.
- llvm::Optional<std::string> UnresolvedQualifier;
+ std::optional<std::string> UnresolvedQualifier;
// Construct scopes being queried in indexes. The results are deduplicated.
// This method format the scopes to match the index request representation.
PathRef FileName;
size_t Offset;
const PreambleData &Preamble;
- const llvm::Optional<PreamblePatch> Patch;
+ const std::optional<PreamblePatch> Patch;
const ParseInputs &ParseInput;
};
int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
bool Incomplete = false; // Would more be available with a higher limit?
CompletionPrefix HeuristicPrefix;
- llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
+ std::optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Range ReplacedRange;
std::vector<std::string> QueryScopes; // Initialized once Sema runs.
// Initialized once QueryScopes is initialized, if there are scopes.
- llvm::Optional<ScopeDistance> ScopeProximity;
- llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
+ std::optional<ScopeDistance> ScopeProximity;
+ std::optional<OpaqueType> PreferredType; // Initialized once Sema runs.
// Whether to query symbols from any scope. Initialized once Sema runs.
bool AllScopes = false;
llvm::StringSet<> ContextWords;
// Include-insertion and proximity scoring rely on the include structure.
// This is available after Sema has run.
- llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
- llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
+ std::optional<IncludeInserter> Inserter; // Available during runWithSema.
+ std::optional<URIDistance> FileProximity; // Initialized once Sema runs.
/// Speculative request based on the cached request and the filter text before
/// the cursor.
/// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
/// set and contains a cached request.
- llvm::Optional<FuzzyFindRequest> SpecReq;
+ std::optional<FuzzyFindRequest> SpecReq;
public:
// A CodeCompleteFlow object is only useful for calling run() exactly once.
return std::move(Top).items();
}
- llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) {
+ std::optional<float> fuzzyScore(const CompletionCandidate &C) {
// Macros can be very spammy, so we only support prefix completion.
if (((C.SemaResult &&
C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
}
CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
- llvm::Optional<CodeCompletionBuilder> Builder;
+ std::optional<CodeCompletionBuilder> Builder;
for (const auto &Item : Bundle) {
CodeCompletionString *SemaCCS =
Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
// If Offset is inside what looks like argument comment (e.g.
// "/*^" or "/* foo^"), returns new offset pointing to the start of the /*
// (place where semaCodeComplete should run).
-llvm::Optional<unsigned>
+std::optional<unsigned>
maybeFunctionArgumentCommentStart(llvm::StringRef Content) {
while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
Content = Content.drop_back();
/// If none, the implementation may choose an appropriate behavior.
/// (In practice, ClangdLSPServer enables bundling if the client claims
/// to supports signature help).
- llvm::Optional<bool> BundleOverloads;
+ std::optional<bool> BundleOverloads;
/// Limit the number of results returned (0 means no limit).
/// If more results are available, we set CompletionList.isIncomplete.
// Type to be displayed for this completion.
std::string ReturnType;
// The parsed documentation comment.
- llvm::Optional<markup::Document> Documentation;
+ std::optional<markup::Document> Documentation;
CompletionItemKind Kind = CompletionItemKind::Missing;
// This completion item may represent several symbols that can be inserted in
// the same way, such as function overloads. In this case BundleSize > 1, and
// Empty for non-symbol completions, or when not known.
std::string Header;
// Present if Header should be inserted to use this item.
- llvm::Optional<TextEdit> Insertion;
+ std::optional<TextEdit> Insertion;
};
// All possible include headers ranked by preference. By default, the first
// include is used.
// Example: foo.pb^ -> foo.push_back()
// ~~
// Typically matches the textEdit.range of Completions, but not guaranteed to.
- llvm::Optional<Range> CompletionRange;
+ std::optional<Range> CompletionRange;
// Usually the source will be parsed with a real C++ parser.
// But heuristics may be used instead if e.g. the preamble is not ready.
bool RanParser = true;
struct SpeculativeFuzzyFind {
/// A cached request from past code completions.
/// Set by caller of `codeComplete()`.
- llvm::Optional<FuzzyFindRequest> CachedReq;
+ std::optional<FuzzyFindRequest> CachedReq;
/// The actual request used by `codeComplete()`.
/// Set by `codeComplete()`. This can be used by callers to update cache.
- llvm::Optional<FuzzyFindRequest> NewReq;
+ std::optional<FuzzyFindRequest> NewReq;
/// The result is consumed by `codeComplete()` if speculation succeeded.
/// NOTE: the destructor will wait for the async call to finish.
std::future<std::pair<bool /*Incomplete*/, SymbolSlab>> Result;
// Query apple's `xcrun` launcher, which is the source of truth for "how should"
// clang be invoked on this system.
-llvm::Optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
+std::optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
auto Xcrun = llvm::sys::findProgramByName("xcrun");
if (!Xcrun) {
log("Couldn't find xcrun. Hopefully you have a non-apple toolchain...");
// On mac, /usr/bin/clang sets SDKROOT and then invokes the real clang.
// The effect of this is to set -isysroot correctly. We do the same.
-llvm::Optional<std::string> detectSysroot() {
+std::optional<std::string> detectSysroot() {
#ifndef __APPLE__
return std::nullopt;
#endif
// Where possible it should be an absolute path with sensible directory, but
// with the original basename.
static std::string resolveDriver(llvm::StringRef Driver, bool FollowSymlink,
- llvm::Optional<std::string> ClangPath) {
+ std::optional<std::string> ClangPath) {
auto SiblingOf = [&](llvm::StringRef AbsPath) {
llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
llvm::sys::path::append(Result, llvm::sys::path::filename(Driver));
// In practice only the extension of the file matters, so do this only when
// it differs.
llvm::StringRef FileExtension = llvm::sys::path::extension(File);
- llvm::Optional<std::string> TransferFrom;
+ std::optional<std::string> TransferFrom;
auto SawInput = [&](llvm::StringRef Input) {
if (llvm::sys::path::extension(Input) != FileExtension)
TransferFrom.emplace(Input);
// - injecting -isysroot flags on mac as the system clang does
struct CommandMangler {
// Absolute path to clang.
- llvm::Optional<std::string> ClangPath;
+ std::optional<std::string> ClangPath;
// Directory containing builtin headers.
- llvm::Optional<std::string> ResourceDir;
+ std::optional<std::string> ResourceDir;
// Root for searching for standard library (passed to -isysroot).
- llvm::Optional<std::string> Sysroot;
+ std::optional<std::string> Sysroot;
SystemIncludeExtractorFn SystemIncludeExtractor;
// A command-mangler that doesn't know anything about the system.
std::string FragmentDirectory;
bool Trusted = false;
- llvm::Optional<llvm::Regex>
+ std::optional<llvm::Regex>
compileRegex(const Located<std::string> &Text,
llvm::Regex::RegexFlags Flags = llvm::Regex::NoFlags) {
std::string Anchored = "^(" + *Text + ")$";
FragmentCompiler &Outer;
llvm::StringRef EnumName;
const Located<std::string> &Input;
- llvm::Optional<T> Result;
+ std::optional<T> Result;
llvm::SmallVector<llvm::StringLiteral> ValidValues;
public:
return *this;
}
- llvm::Optional<T> value() {
+ std::optional<T> value() {
if (!Result)
Outer.diag(
Warning,
// Attempt to parse a specified string into an enum.
// Yields std::nullopt and produces a diagnostic on failure.
//
- // Optional<T> Value = compileEnum<En>("Foo", Frag.Foo)
+ // std::optional<T> Value = compileEnum<En>("Foo", Frag.Foo)
// .map("Foo", Enum::Foo)
// .map("Bar", Enum::Bar)
// .value();
}
if (F.CompilationDatabase) {
- llvm::Optional<Config::CDBSearchSpec> Spec;
+ std::optional<Config::CDBSearchSpec> Spec;
if (**F.CompilationDatabase == "Ancestors") {
Spec.emplace();
Spec->Policy = Config::CDBSearchSpec::Ancestors;
return Code;
}
-llvm::Optional<std::string> getDiagnosticDocURI(Diag::DiagSource Source,
- unsigned ID,
- llvm::StringRef Name) {
+std::optional<std::string> getDiagnosticDocURI(Diag::DiagSource Source,
+ unsigned ID,
+ llvm::StringRef Name) {
switch (Source) {
case Diag::Unknown:
break;
// May be relative, absolute or even artificially constructed.
std::string File;
// Absolute path to containing file, if available.
- llvm::Optional<std::string> AbsFile;
+ std::optional<std::string> AbsFile;
clangd::Range Range;
DiagnosticsEngine::Level Severity = DiagnosticsEngine::Note;
int getSeverity(DiagnosticsEngine::Level L);
/// Returns a URI providing more information about a particular diagnostic.
-llvm::Optional<std::string> getDiagnosticDocURI(Diag::DiagSource, unsigned ID,
- llvm::StringRef Name);
+std::optional<std::string> getDiagnosticDocURI(Diag::DiagSource, unsigned ID,
+ llvm::StringRef Name);
/// StoreDiags collects the diagnostics that can later be reported by
/// clangd. It groups all notes for a diagnostic into a single Diag
LevelAdjuster Adjuster = nullptr;
DiagCallback DiagCB = nullptr;
std::vector<Diag> Output;
- llvm::Optional<LangOptions> LangOpts;
- llvm::Optional<Diag> LastDiag;
- llvm::Optional<FullSourceLoc> LastDiagLoc; // Valid only when LastDiag is set.
+ std::optional<LangOptions> LangOpts;
+ std::optional<Diag> LastDiag;
+ std::optional<FullSourceLoc> LastDiagLoc; // Valid only when LastDiag is set.
bool LastDiagOriginallyError = false; // Valid only when LastDiag is set.
SourceManager *OrigSrcMgr = nullptr;
namespace clang {
namespace clangd {
-llvm::Optional<DraftStore::Draft> DraftStore::getDraft(PathRef File) const {
+std::optional<DraftStore::Draft> DraftStore::getDraft(PathRef File) const {
std::lock_guard<std::mutex> Lock(Mutex);
auto It = Drafts.find(File);
/// \return Contents of the stored document.
/// For untracked files, a std::nullopt is returned.
- llvm::Optional<Draft> getDraft(PathRef File) const;
+ std::optional<Draft> getDraft(PathRef File) const;
/// \return List of names of the drafts in this store.
std::vector<Path> getActiveFiles() const;
// Range: most nodes have getSourceRange(), with a couple of exceptions.
// We only return it if it's valid at both ends and there are no macros.
- template <typename T> llvm::Optional<Range> getRange(const T &Node) {
+ template <typename T> std::optional<Range> getRange(const T &Node) {
SourceRange SR = getSourceRange(Node);
auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(SR));
if (!Spelled)
return T.getTypePtr();
}
-static llvm::Optional<QualType>
-typeOfCompletion(const CodeCompletionResult &R) {
+static std::optional<QualType> typeOfCompletion(const CodeCompletionResult &R) {
const NamedDecl *D = R.Declaration;
// Templates do not have a type on their own, look at the templated decl.
if (auto *Template = dyn_cast_or_null<TemplateDecl>(D))
}
} // namespace
-llvm::Optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
+std::optional<OpaqueType> OpaqueType::encode(ASTContext &Ctx, QualType T) {
if (T.isNull())
return std::nullopt;
const Type *C = toEquivClass(Ctx, T);
OpaqueType::OpaqueType(std::string Data) : Data(std::move(Data)) {}
-llvm::Optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx,
- QualType Type) {
+std::optional<OpaqueType> OpaqueType::fromType(ASTContext &Ctx, QualType Type) {
return encode(Ctx, Type);
}
-llvm::Optional<OpaqueType>
+std::optional<OpaqueType>
OpaqueType::fromCompletionResult(ASTContext &Ctx,
const CodeCompletionResult &R) {
auto T = typeOfCompletion(R);
class OpaqueType {
public:
/// Create a type from a code completion result.
- static llvm::Optional<OpaqueType>
+ static std::optional<OpaqueType>
fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R);
/// Construct an instance from a clang::QualType. This is usually a
/// PreferredType from a clang's completion context.
- static llvm::Optional<OpaqueType> fromType(ASTContext &Ctx, QualType Type);
+ static std::optional<OpaqueType> fromType(ASTContext &Ctx, QualType Type);
/// Get the raw byte representation of the type. You can only rely on the
/// types being equal iff their raw representation is the same. The particular
}
private:
- static llvm::Optional<OpaqueType> encode(ASTContext &Ctx, QualType Type);
+ static std::optional<OpaqueType> encode(ASTContext &Ctx, QualType Type);
explicit OpaqueType(std::string Data);
std::string Data;
StatCache.insert({PathStore, std::move(S)});
}
-llvm::Optional<llvm::vfs::Status>
+std::optional<llvm::vfs::Status>
PreambleFileStatusCache::lookup(llvm::StringRef File) const {
// Canonicalize to match the cached form.
// Lookup tends to be first by absolute path, so no need to make absolute.
void update(const llvm::vfs::FileSystem &FS, llvm::vfs::Status S);
/// \p Path is a path stored in preamble.
- llvm::Optional<llvm::vfs::Status> lookup(llvm::StringRef Path) const;
+ std::optional<llvm::vfs::Status> lookup(llvm::StringRef Path) const;
/// Returns a VFS that collects file status.
/// Only cache stats for files that exist because
using OutgoingMethod = llvm::unique_function<void(const P &, Callback<R>)>;
private:
- llvm::Optional<Facilities> Fac;
+ std::optional<Facilities> Fac;
};
/// A FeatureModuleSet is a collection of feature modules installed in clangd.
return std::move(OS.str());
}
-llvm::Optional<DocumentSymbol> declToSym(ASTContext &Ctx, const NamedDecl &ND) {
+std::optional<DocumentSymbol> declToSym(ASTContext &Ctx, const NamedDecl &ND) {
auto &SM = Ctx.getSourceManager();
SourceLocation BeginLoc = SM.getSpellingLoc(SM.getFileLoc(ND.getBeginLoc()));
DirectoryBasedGlobalCompilationDatabase::
~DirectoryBasedGlobalCompilationDatabase() = default;
-llvm::Optional<tooling::CompileCommand>
+std::optional<tooling::CompileCommand>
DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const {
CDBLookupRequest Req;
Req.FileName = File;
return Ret;
}
-llvm::Optional<DirectoryBasedGlobalCompilationDatabase::CDBLookupResult>
+std::optional<DirectoryBasedGlobalCompilationDatabase::CDBLookupResult>
DirectoryBasedGlobalCompilationDatabase::lookupCDB(
CDBLookupRequest Request) const {
assert(llvm::sys::path::is_absolute(Request.FileName) &&
Context Ctx;
};
std::deque<Task> Queue;
- llvm::Optional<Task> ActiveTask;
+ std::optional<Task> ActiveTask;
std::thread Thread; // Must be last member.
// Thread body: this is just the basic queue procesing boilerplate.
return Broadcaster->blockUntilIdle(Timeout);
}
-llvm::Optional<ProjectInfo>
+std::optional<ProjectInfo>
DirectoryBasedGlobalCompilationDatabase::getProjectInfo(PathRef File) const {
CDBLookupRequest Req;
Req.FileName = File;
: DelegatingCDB(Base), Mangler(std::move(Mangler)),
FallbackFlags(std::move(FallbackFlags)) {}
-llvm::Optional<tooling::CompileCommand>
+std::optional<tooling::CompileCommand>
OverlayCDB::getCompileCommand(PathRef File) const {
- llvm::Optional<tooling::CompileCommand> Cmd;
+ std::optional<tooling::CompileCommand> Cmd;
{
std::lock_guard<std::mutex> Lock(Mutex);
auto It = Commands.find(removeDots(File));
return Cmd;
}
-void OverlayCDB::setCompileCommand(
- PathRef File, llvm::Optional<tooling::CompileCommand> Cmd) {
+void OverlayCDB::setCompileCommand(PathRef File,
+ std::optional<tooling::CompileCommand> Cmd) {
// We store a canonical version internally to prevent mismatches between set
// and get compile commands. Also it assures clients listening to broadcasts
// doesn't receive different names for the same file.
BaseOwner = std::move(Base);
}
-llvm::Optional<tooling::CompileCommand>
+std::optional<tooling::CompileCommand>
DelegatingCDB::getCompileCommand(PathRef File) const {
if (!Base)
return std::nullopt;
return Base->getCompileCommand(File);
}
-llvm::Optional<ProjectInfo> DelegatingCDB::getProjectInfo(PathRef File) const {
+std::optional<ProjectInfo> DelegatingCDB::getProjectInfo(PathRef File) const {
if (!Base)
return std::nullopt;
return Base->getProjectInfo(File);
virtual ~GlobalCompilationDatabase() = default;
/// If there are any known-good commands for building this file, returns one.
- virtual llvm::Optional<tooling::CompileCommand>
+ virtual std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const = 0;
/// Finds the closest project to \p File.
- virtual llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const {
+ virtual std::optional<ProjectInfo> getProjectInfo(PathRef File) const {
return std::nullopt;
}
DelegatingCDB(const GlobalCompilationDatabase *Base);
DelegatingCDB(std::unique_ptr<GlobalCompilationDatabase> Base);
- llvm::Optional<tooling::CompileCommand>
+ std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override;
- llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override;
+ std::optional<ProjectInfo> getProjectInfo(PathRef File) const override;
tooling::CompileCommand getFallbackCommand(PathRef File) const override;
/// Scans File's parents looking for compilation databases.
/// Any extra flags will be added.
/// Might trigger OnCommandChanged, if CDB wasn't broadcasted yet.
- llvm::Optional<tooling::CompileCommand>
+ std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override;
/// Returns the path to first directory containing a compilation database in
/// \p File's parents.
- llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override;
+ std::optional<ProjectInfo> getProjectInfo(PathRef File) const override;
bool blockUntilIdle(Deadline Timeout) const override;
std::shared_ptr<const tooling::CompilationDatabase> CDB;
ProjectInfo PI;
};
- llvm::Optional<CDBLookupResult> lookupCDB(CDBLookupRequest Request) const;
+ std::optional<CDBLookupResult> lookupCDB(CDBLookupRequest Request) const;
class BroadcastThread;
std::unique_ptr<BroadcastThread> Broadcaster;
std::vector<std::string> FallbackFlags = {},
CommandMangler Mangler = nullptr);
- llvm::Optional<tooling::CompileCommand>
+ std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override;
tooling::CompileCommand getFallbackCommand(PathRef File) const override;
/// Sets or clears the compilation command for a particular file.
void
setCompileCommand(PathRef File,
- llvm::Optional<tooling::CompileCommand> CompilationCommand);
+ std::optional<tooling::CompileCommand> CompilationCommand);
private:
mutable std::mutex Mutex;
namespace clang {
namespace clangd {
-llvm::Optional<Path> getCorrespondingHeaderOrSource(
+std::optional<Path> getCorrespondingHeaderOrSource(
PathRef OriginalFile, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
llvm::StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
".c++", ".m", ".mm"};
return std::nullopt;
}
-llvm::Optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
- ParsedAST &AST,
- const SymbolIndex *Index) {
+std::optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
+ ParsedAST &AST,
+ const SymbolIndex *Index) {
if (!Index) {
// FIXME: use the AST to do the inference.
return std::nullopt;
/// Given a header file, returns the best matching source file, and vice visa.
/// It only uses the filename heuristics to do the inference.
-llvm::Optional<Path> getCorrespondingHeaderOrSource(
+std::optional<Path> getCorrespondingHeaderOrSource(
PathRef OriginalFile, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS);
/// Given a header file, returns the best matching source file, and vice visa.
/// The heuristics incorporate with the AST and the index (if provided).
-llvm::Optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
- ParsedAST &AST,
- const SymbolIndex *Index);
+std::optional<Path> getCorrespondingHeaderOrSource(PathRef OriginalFile,
+ ParsedAST &AST,
+ const SymbolIndex *Index);
/// Returns all indexable decls that are present in the main file of the AST.
/// Exposed for unittests.
CI.getPreprocessor().addPPCallbacks(std::move(Collector));
}
-llvm::Optional<IncludeStructure::HeaderID>
+std::optional<IncludeStructure::HeaderID>
IncludeStructure::getID(const FileEntry *Entry) const {
// HeaderID of the main file is always 0;
if (Entry == MainFileEntry) {
return !Included(DeclaringHeader) && !Included(InsertedHeader.File);
}
-llvm::Optional<std::string>
+std::optional<std::string>
IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
llvm::StringRef IncludingFile) const {
assert(InsertedHeader.valid());
return Suggested;
}
-llvm::Optional<TextEdit>
+std::optional<TextEdit>
IncludeInserter::insert(llvm::StringRef VerbatimHeader,
tooling::IncludeDirective Directive) const {
- llvm::Optional<TextEdit> Edit;
+ std::optional<TextEdit> Edit;
if (auto Insertion =
Inserter.insert(VerbatimHeader.trim("\"<>"),
VerbatimHeader.startswith("<"), Directive))
unsigned HashOffset = 0; // Byte offset from start of file to #.
int HashLine = 0; // Line number containing the directive, 0-indexed.
SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
- llvm::Optional<unsigned> HeaderID;
+ std::optional<unsigned> HeaderID;
bool BehindPragmaKeep = false; // Has IWYU pragma: keep right after.
};
llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Inclusion &);
// file builds.
enum class HeaderID : unsigned {};
- llvm::Optional<HeaderID> getID(const FileEntry *Entry) const;
+ std::optional<HeaderID> getID(const FileEntry *Entry) const;
HeaderID getOrCreateID(FileEntryRef Entry);
StringRef getRealPath(HeaderID ID) const {
///
/// \return A quoted "path" or <path> to be included, or std::nullopt if it
/// couldn't be shortened.
- llvm::Optional<std::string>
+ std::optional<std::string>
calculateIncludePath(const HeaderFile &InsertedHeader,
llvm::StringRef IncludingFile) const;
/// Calculates an edit that inserts \p VerbatimHeader into code. If the header
/// is already included, this returns std::nullopt.
- llvm::Optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
- tooling::IncludeDirective Directive) const;
+ std::optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
+ tooling::IncludeDirective Directive) const;
private:
StringRef FileName;
return llvm::format_hex(Bits, 0);
}
-llvm::Optional<std::string> printExprValue(const Expr *E,
- const ASTContext &Ctx) {
+std::optional<std::string> printExprValue(const Expr *E,
+ const ASTContext &Ctx) {
// InitListExpr has two forms, syntactic and semantic. They are the same thing
// (refer to a same AST node) in most cases.
// When they are different, RAV returns the syntactic form, and we should feed
return Constant.Val.getAsString(Ctx, T);
}
-llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
- const ASTContext &Ctx) {
+std::optional<std::string> printExprValue(const SelectionTree::Node *N,
+ const ASTContext &Ctx) {
for (; N; N = N->Parent) {
// Try to evaluate the first evaluatable enclosing expression.
if (const Expr *E = N->ASTNode.get<Expr>()) {
return std::nullopt;
}
-llvm::Optional<StringRef> fieldName(const Expr *E) {
+std::optional<StringRef> fieldName(const Expr *E) {
const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
return std::nullopt;
}
// If CMD is of the form T foo() { return FieldName; } then returns "FieldName".
-llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
+std::optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
assert(CMD->hasBody());
if (CMD->getNumParams() != 0 || CMD->isVariadic())
return std::nullopt;
// void foo(T arg) { FieldName = std::move(arg); }
// R foo(T arg) { FieldName = std::move(arg); return *this; }
// then returns "FieldName"
-llvm::Optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
+std::optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
assert(CMD->hasBody());
if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
return std::nullopt;
// If the backtick at `Offset` starts a probable quoted range, return the range
// (including the quotes).
-llvm::Optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
- unsigned Offset) {
+std::optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
+ unsigned Offset) {
assert(Line[Offset] == '`');
// The open-quote is usually preceded by whitespace.
/// Pretty-printed type
std::string Type;
/// Desugared type
- llvm::Optional<std::string> AKA;
+ std::optional<std::string> AKA;
};
/// Represents parameters of a function, a template or a macro.
struct Param {
/// The printable parameter type, e.g. "int", or "typename" (in
/// TemplateParameters), might be std::nullopt for macro parameters.
- llvm::Optional<PrintedType> Type;
+ std::optional<PrintedType> Type;
/// std::nullopt for unnamed parameters.
std::optional<std::string> Name;
/// std::nullopt if no default is provided.
- llvm::Optional<std::string> Default;
+ std::optional<std::string> Default;
};
/// For a variable named Bar, declared in clang::clangd::Foo::getFoo the
/// auto/decltype.
/// Contains all of the enclosing namespaces, empty string means global
/// namespace.
- llvm::Optional<std::string> NamespaceScope;
+ std::optional<std::string> NamespaceScope;
/// Remaining named contexts in symbol's qualified name, empty string means
/// symbol is not local.
std::string LocalScope;
/// Name of the symbol, does not contain any "::".
std::string Name;
- llvm::Optional<Range> SymRange;
+ std::optional<Range> SymRange;
index::SymbolKind Kind = index::SymbolKind::Unknown;
std::string Documentation;
/// Source code containing the definition of the symbol.
std::string AccessSpecifier;
/// Printable variable type.
/// Set only for variables.
- llvm::Optional<PrintedType> Type;
+ std::optional<PrintedType> Type;
/// Set for functions and lambdas.
- llvm::Optional<PrintedType> ReturnType;
+ std::optional<PrintedType> ReturnType;
/// Set for functions, lambdas and macros with parameters.
- llvm::Optional<std::vector<Param>> Parameters;
+ std::optional<std::vector<Param>> Parameters;
/// Set for all templates(function, class, variable).
- llvm::Optional<std::vector<Param>> TemplateParameters;
+ std::optional<std::vector<Param>> TemplateParameters;
/// Contains the evaluated value of the symbol if available.
- llvm::Optional<std::string> Value;
+ std::optional<std::string> Value;
/// Contains the byte-size of fields and types where it's interesting.
- llvm::Optional<uint64_t> Size;
+ std::optional<uint64_t> Size;
/// Contains the offset of fields within the enclosing class.
- llvm::Optional<uint64_t> Offset;
+ std::optional<uint64_t> Offset;
/// Contains the padding following a field within the enclosing class.
- llvm::Optional<uint64_t> Padding;
+ std::optional<uint64_t> Padding;
// Set when symbol is inside function call. Contains information extracted
// from the callee definition about the argument this is passed as.
- llvm::Optional<Param> CalleeArgInfo;
+ std::optional<Param> CalleeArgInfo;
struct PassType {
// How the variable is passed to callee.
enum PassMode { Ref, ConstRef, Value };
bool Converted = false;
};
// Set only if CalleeArgInfo is set.
- llvm::Optional<PassType> CallPassType;
+ std::optional<PassType> CallPassType;
/// Produce a user-readable information.
markup::Document present() const;
ReferencedFiles findReferencedFiles(
const ReferencedLocations &Locs, const SourceManager &SM,
llvm::function_ref<FileID(FileID)> HeaderResponsible,
- llvm::function_ref<Optional<StringRef>(FileID)> UmbrellaHeader) {
+ llvm::function_ref<std::optional<StringRef>(FileID)> UmbrellaHeader) {
std::vector<SourceLocation> Sorted{Locs.User.begin(), Locs.User.end()};
llvm::sort(Sorted); // Group by FileID.
ReferencedFilesBuilder Builder(SM);
[&SM, &Includes](FileID ID) {
return headerResponsible(ID, SM, Includes);
},
- [&SM, &CanonIncludes](FileID ID) -> Optional<StringRef> {
+ [&SM, &CanonIncludes](FileID ID) -> std::optional<StringRef> {
auto Entry = SM.getFileEntryRefForID(ID);
if (!Entry)
return std::nullopt;
ReferencedFiles findReferencedFiles(
const ReferencedLocations &Locs, const SourceManager &SM,
llvm::function_ref<FileID(FileID)> HeaderResponsible,
- llvm::function_ref<Optional<StringRef>(FileID)> UmbrellaHeader);
+ llvm::function_ref<std::optional<StringRef>(FileID)> UmbrellaHeader);
ReferencedFiles findReferencedFiles(const ReferencedLocations &Locs,
const IncludeStructure &Includes,
const CanonicalIncludes &CanonIncludes,
namespace clangd {
namespace {
-llvm::Optional<llvm::StringRef> getArgStr(const clang::Diagnostic &Info,
- unsigned Index) {
+std::optional<llvm::StringRef> getArgStr(const clang::Diagnostic &Info,
+ unsigned Index) {
switch (Info.getArgKind(Index)) {
case DiagnosticsEngine::ak_c_string:
return llvm::StringRef(Info.getArgCStr(Index));
}
}
-std::vector<Fix> only(llvm::Optional<Fix> F) {
+std::vector<Fix> only(std::optional<Fix> F) {
if (F)
return {std::move(*F)};
return {};
return {};
}
-llvm::Optional<Fix> IncludeFixer::insertHeader(llvm::StringRef Spelled,
+std::optional<Fix> IncludeFixer::insertHeader(llvm::StringRef Spelled,
llvm::StringRef Symbol,
tooling::IncludeDirective Directive) const {
Fix F;
auto ID = getSymbolID(TD);
if (!ID)
return {};
- llvm::Optional<const SymbolSlab *> Symbols = lookupCached(ID);
+ std::optional<const SymbolSlab *> Symbols = lookupCached(ID);
if (!Symbols)
return {};
const SymbolSlab &Syms = **Symbols;
// "::X::Y" that is qualified by unresolved name "clangd":
// clang::clangd::X::Y
// ~
-llvm::Optional<std::string> qualifiedByUnresolved(const SourceManager &SM,
+std::optional<std::string> qualifiedByUnresolved(const SourceManager &SM,
SourceLocation Loc,
const LangOptions &LangOpts) {
std::string Result;
// This is the part of what was typed that was resolved, and it's in its
// resolved form not its typed form (think `namespace clang { clangd::x }` -->
// `clang::clangd::`).
- llvm::Optional<std::string> ResolvedScope;
+ std::optional<std::string> ResolvedScope;
// Unresolved part of the scope. When the unresolved name is a specifier, we
// use the name that comes after it as the alternative name to resolve and use
// the specifier as the extra scope in the accessible scopes.
- llvm::Optional<std::string> UnresolvedScope;
+ std::optional<std::string> UnresolvedScope;
};
-llvm::Optional<std::string> getSpelledSpecifier(const CXXScopeSpec &SS,
+std::optional<std::string> getSpelledSpecifier(const CXXScopeSpec &SS,
const SourceManager &SM) {
// Support specifiers written within a single macro argument.
if (!SM.isWrittenInSameFile(SS.getBeginLoc(), SS.getEndLoc()))
// Extracts unresolved name and scope information around \p Unresolved.
// FIXME: try to merge this with the scope-wrangling code in CodeComplete.
-llvm::Optional<CheapUnresolvedName> extractUnresolvedNameCheaply(
+std::optional<CheapUnresolvedName> extractUnresolvedNameCheaply(
const SourceManager &SM, const DeclarationNameInfo &Unresolved,
CXXScopeSpec *SS, const LangOptions &LangOpts, bool UnresolvedIsSpecifier) {
CheapUnresolvedName Result;
Result.ResolvedScope = "";
} else if (const auto *NS = Nested->getAsNamespace()) {
std::string SpecifiedNS = printNamespaceScope(*NS);
- llvm::Optional<std::string> Spelling = getSpelledSpecifier(*SS, SM);
+ std::optional<std::string> Spelling = getSpelledSpecifier(*SS, SM);
// Check the specifier spelled in the source.
// If the resolved scope doesn't end with the spelled scope, the
class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource {
public:
- UnresolvedNameRecorder(llvm::Optional<UnresolvedName> &LastUnresolvedName)
+ UnresolvedNameRecorder(std::optional<UnresolvedName> &LastUnresolvedName)
: LastUnresolvedName(LastUnresolvedName) {}
void InitializeSema(Sema &S) override { this->SemaPtr = &S; }
private:
Sema *SemaPtr = nullptr;
- llvm::Optional<UnresolvedName> &LastUnresolvedName;
+ std::optional<UnresolvedName> &LastUnresolvedName;
};
llvm::IntrusiveRefCntPtr<ExternalSemaSource>
Req.RestrictForCodeCompletion = true;
Req.Limit = 100;
- if (llvm::Optional<const SymbolSlab *> Syms = fuzzyFindCached(Req))
+ if (std::optional<const SymbolSlab *> Syms = fuzzyFindCached(Req))
return fixesForSymbols(**Syms);
return {};
}
-llvm::Optional<const SymbolSlab *>
+std::optional<const SymbolSlab *>
IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const {
auto ReqStr = llvm::formatv("{0}", toJSON(Req)).str();
auto I = FuzzyFindCache.find(ReqStr);
return &E.first->second;
}
-llvm::Optional<const SymbolSlab *>
+std::optional<const SymbolSlab *>
IncludeFixer::lookupCached(const SymbolID &ID) const {
LookupRequest Req;
Req.IDs.insert(ID);
/// Generates header insertion fixes for all symbols. Fixes are deduplicated.
std::vector<Fix> fixesForSymbols(const SymbolSlab &Syms) const;
- llvm::Optional<Fix>
- insertHeader(llvm::StringRef Name, llvm::StringRef Symbol = "",
- tooling::IncludeDirective Directive =
- tooling::IncludeDirective::Include) const;
+ std::optional<Fix> insertHeader(llvm::StringRef Name,
+ llvm::StringRef Symbol = "",
+ tooling::IncludeDirective Directive =
+ tooling::IncludeDirective::Include) const;
struct UnresolvedName {
std::string Name; // E.g. "X" in foo::X.
// These collect the last unresolved name so that we can associate it with the
// diagnostic.
- llvm::Optional<UnresolvedName> LastUnresolvedName;
+ std::optional<UnresolvedName> LastUnresolvedName;
// There can be multiple diagnostics that are caused by the same unresolved
// name or incomplete type in one parse, especially when code is
mutable llvm::StringMap<SymbolSlab> FuzzyFindCache;
mutable llvm::DenseMap<SymbolID, SymbolSlab> LookupCache;
// Returns std::nullopt if the number of index requests has reached the limit.
- llvm::Optional<const SymbolSlab *>
+ std::optional<const SymbolSlab *>
fuzzyFindCached(const FuzzyFindRequest &Req) const;
- llvm::Optional<const SymbolSlab *> lookupCached(const SymbolID &ID) const;
+ std::optional<const SymbolSlab *> lookupCached(const SymbolID &ID) const;
};
} // namespace clangd
}
// Get the range of the main file that *exactly* corresponds to R.
- llvm::Optional<Range> getHintRange(SourceRange R) {
+ std::optional<Range> getHintRange(SourceRange R) {
const auto &SM = AST.getSourceManager();
auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
// TokenBuffer will return null if e.g. R corresponds to only part of a
// Message must be an object with "jsonrpc":"2.0".
auto *Object = Message.getAsObject();
if (!Object ||
- Object->getString("jsonrpc") != llvm::Optional<llvm::StringRef>("2.0")) {
+ Object->getString("jsonrpc") != std::optional<llvm::StringRef>("2.0")) {
elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
return false;
}
// ID may be any JSON value. If absent, this is a notification.
- llvm::Optional<llvm::json::Value> ID;
+ std::optional<llvm::json::Value> ID;
if (auto *I = Object->get("id"))
ID = std::move(*I);
auto Method = Object->getString("method");
} // namespace
-llvm::Optional<ParsedAST>
+std::optional<ParsedAST>
ParsedAST::build(llvm::StringRef Filename, const ParseInputs &Inputs,
std::unique_ptr<clang::CompilerInvocation> CI,
llvm::ArrayRef<Diag> CompilerInvocationDiags,
[&](const auto &L) { L->sawDiagnostic(D, Diag); });
});
- llvm::Optional<PreamblePatch> Patch;
+ std::optional<PreamblePatch> Patch;
bool PreserveDiags = true;
// We might use an ignoring diagnostic consumer if they are going to be
// dropped later on to not pay for extra latency by processing them.
// In practice almost all checks work well without modifications.
std::vector<std::unique_ptr<tidy::ClangTidyCheck>> CTChecks;
ast_matchers::MatchFinder CTFinder;
- llvm::Optional<tidy::ClangTidyContext> CTContext;
+ std::optional<tidy::ClangTidyContext> CTContext;
// Must outlive FixIncludes.
auto BuildDir = VFS->getCurrentWorkingDirectory();
- llvm::Optional<IncludeFixer> FixIncludes;
+ std::optional<IncludeFixer> FixIncludes;
llvm::DenseMap<diag::kind, DiagnosticsEngine::Level> OverriddenSeverity;
// No need to run clang-tidy or IncludeFixerif we are not going to surface
// diagnostics.
// CompilerInstance won't run this callback, do it directly.
ASTDiags.EndSourceFile();
- llvm::Optional<std::vector<Diag>> Diags;
+ std::optional<std::vector<Diag>> Diags;
// FIXME: Also skip generation of diagnostics alltogether to speed up ast
// builds when we are patching a stale preamble.
if (PreserveDiags) {
syntax::TokenBuffer Tokens, MainFileMacros Macros,
std::vector<PragmaMark> Marks,
std::vector<Decl *> LocalTopLevelDecls,
- llvm::Optional<std::vector<Diag>> Diags,
+ std::optional<std::vector<Diag>> Diags,
IncludeStructure Includes, CanonicalIncludes CanonIncludes)
: TUPath(TUPath), Version(Version), Preamble(std::move(Preamble)),
Clang(std::move(Clang)), Action(std::move(Action)),
assert(this->Action);
}
-llvm::Optional<llvm::StringRef> ParsedAST::preambleVersion() const {
+std::optional<llvm::StringRef> ParsedAST::preambleVersion() const {
if (!Preamble)
return std::nullopt;
return llvm::StringRef(Preamble->Version);
/// Attempts to run Clang and store the parsed AST.
/// If \p Preamble is non-null it is reused during parsing.
/// This function does not check if preamble is valid to reuse.
- static llvm::Optional<ParsedAST>
+ static std::optional<ParsedAST>
build(llvm::StringRef Filename, const ParseInputs &Inputs,
std::unique_ptr<clang::CompilerInvocation> CI,
llvm::ArrayRef<Diag> CompilerInvocationDiags,
/// (These should be const, but RecursiveASTVisitor requires Decl*).
ArrayRef<Decl *> getLocalTopLevelDecls();
- const llvm::Optional<std::vector<Diag>> &getDiagnostics() const {
+ const std::optional<std::vector<Diag>> &getDiagnostics() const {
return Diags;
}
/// Returns the version of the ParseInputs used to build Preamble part of this
/// AST. Might be std::nullopt if no Preamble is used.
- llvm::Optional<llvm::StringRef> preambleVersion() const;
+ std::optional<llvm::StringRef> preambleVersion() const;
const HeuristicResolver *getHeuristicResolver() const {
return Resolver.get();
std::unique_ptr<FrontendAction> Action, syntax::TokenBuffer Tokens,
MainFileMacros Macros, std::vector<PragmaMark> Marks,
std::vector<Decl *> LocalTopLevelDecls,
- llvm::Optional<std::vector<Diag>> Diags, IncludeStructure Includes,
+ std::optional<std::vector<Diag>> Diags, IncludeStructure Includes,
CanonicalIncludes CanonIncludes);
Path TUPath;
std::vector<PragmaMark> Marks;
// Data, stored after parsing. std::nullopt if AST was built with a stale
// preamble.
- llvm::Optional<std::vector<Diag>> Diags;
+ std::optional<std::vector<Diag>> Diags;
// Top-level decls inside the current file. Not that this does not include
// top-level decls from the preamble.
std::vector<Decl *> LocalTopLevelDecls;
struct ClientCapabilities {
/// The supported set of SymbolKinds for workspace/symbol.
/// workspace.symbol.symbolKind.valueSet
- llvm::Optional<SymbolKindBitset> WorkspaceSymbolKinds;
+ std::optional<SymbolKindBitset> WorkspaceSymbolKinds;
/// Whether the client accepts diagnostics with codeActions attached inline.
/// textDocument.publishDiagnostics.codeActionsInline.
/// The supported set of CompletionItemKinds for textDocument/completion.
/// textDocument.completion.completionItemKind.valueSet
- llvm::Optional<CompletionItemKindBitset> CompletionItemKinds;
+ std::optional<CompletionItemKindBitset> CompletionItemKinds;
/// The documentation format that should be used for textDocument/completion.
/// textDocument.completion.completionItem.documentationFormat
bool TheiaSemanticHighlighting = false;
/// Supported encodings for LSP character offsets. (clangd extension).
- llvm::Optional<std::vector<OffsetEncoding>> offsetEncoding;
+ std::optional<std::vector<OffsetEncoding>> offsetEncoding;
/// The content format that should be used for Hover requests.
/// textDocument.hover.contentEncoding
///
/// Clients that don't support cancellation or don't support control
/// the button's enablement state are allowed to ignore the setting.
- llvm::Optional<bool> cancellable;
+ std::optional<bool> cancellable;
/// Optional, more detailed associated progress message. Contains
/// complementary information to the `title`.
///
/// Examples: "3/25 files", "project/src/module2", "node_modules/some_dep".
/// If unset, the previous progress message (if any) is still valid.
- llvm::Optional<std::string> message;
+ std::optional<std::string> message;
/// Optional progress percentage to display (value 100 is considered 100%).
/// If not provided infinite progress is assumed and clients are allowed
///
/// The value should be steadily rising. Clients are free to ignore values
/// that are not following this rule.
- llvm::Optional<unsigned> percentage;
+ std::optional<unsigned> percentage;
};
llvm::json::Value toJSON(const WorkDoneProgressReport &);
//
struct WorkDoneProgressEnd {
/// Optional, a final message indicating to for example indicate the outcome
/// of the operation.
- llvm::Optional<std::string> message;
+ std::optional<std::string> message;
};
llvm::json::Value toJSON(const WorkDoneProgressEnd &);
std::string code;
/// An optional property to describe the error code.
- llvm::Optional<CodeDescription> codeDescription;
+ std::optional<CodeDescription> codeDescription;
/// A human-readable string describing the source of this
/// diagnostic, e.g. 'typescript' or 'super lint'.
/// The kind of the code action.
/// Used to filter code actions.
- llvm::Optional<std::string> kind;
+ std::optional<std::string> kind;
const static llvm::StringLiteral QUICKFIX_KIND;
const static llvm::StringLiteral REFACTOR_KIND;
const static llvm::StringLiteral INFO_KIND;
/// The diagnostics that this code action resolves.
- llvm::Optional<std::vector<Diagnostic>> diagnostics;
+ std::optional<std::vector<Diagnostic>> diagnostics;
/// Marks this as a preferred action. Preferred actions are used by the
/// `auto fix` command and can be targeted by keybindings.
bool isPreferred = false;
/// The workspace edit this code action performs.
- llvm::Optional<WorkspaceEdit> edit;
+ std::optional<WorkspaceEdit> edit;
/// A command this code action executes. If a code action provides an edit
/// and a command, first the edit is executed and then the command.
- llvm::Optional<Command> command;
+ std::optional<Command> command;
};
llvm::json::Value toJSON(const CodeAction &);
/// This can be used to re-rank results as the user types, using client-side
/// fuzzy-matching (that score should be multiplied with this one).
/// This is a clangd extension, set only for workspace/symbol responses.
- llvm::Optional<float> score;
+ std::optional<float> score;
};
llvm::json::Value toJSON(const SymbolInformation &);
llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolInformation &);
SymbolID ID;
- llvm::Optional<Location> declarationRange;
+ std::optional<Location> declarationRange;
- llvm::Optional<Location> definitionRange;
+ std::optional<Location> definitionRange;
};
llvm::json::Value toJSON(const SymbolDetails &);
llvm::raw_ostream &operator<<(llvm::raw_ostream &, const SymbolDetails &);
/// An optional range is a range inside a text document
/// that is used to visualize a hover, e.g. by changing the background color.
- llvm::Optional<Range> range;
+ std::optional<Range> range;
};
llvm::json::Value toJSON(const Hover &H);
///
/// Note: The range of the edit must be a single line range and it must
/// contain the position at which completion has been requested.
- llvm::Optional<TextEdit> textEdit;
+ std::optional<TextEdit> textEdit;
/// An optional array of additional text edits that are applied when selecting
/// this completion. Edits must not overlap with the main edit nor with
/// label.
/// Offsets are computed by lspLength(), which counts UTF-16 code units by
/// default but that can be overriden, see its documentation for details.
- llvm::Optional<std::pair<unsigned, unsigned>> labelOffsets;
+ std::optional<std::pair<unsigned, unsigned>> labelOffsets;
/// The documentation of this parameter. Optional.
std::string documentation;
struct SemanticTokensOrDelta {
std::string resultId;
/// Set if we computed edits relative to a previous set of tokens.
- llvm::Optional<std::vector<SemanticTokensEdit>> edits;
+ std::optional<std::vector<SemanticTokensEdit>> edits;
/// Set if we computed a fresh set of tokens.
- llvm::Optional<std::vector<SemanticToken>> tokens; // encoded as integer array
+ std::optional<std::vector<SemanticToken>> tokens; // encoded as integer array
};
llvm::json::Value toJSON(const SemanticTokensOrDelta &);
std::string arcana;
/// The range of the original source file covered by this node.
/// May be missing for implicit nodes, or those created by macro expansion.
- llvm::Optional<Range> range;
+ std::optional<Range> range;
/// Nodes nested within this one, such as the operands of a BinaryOperator.
std::vector<ASTNode> children;
};
return std::max(0.65, 2.0 * std::pow(0.6, ScopeDistance / 2.0));
}
-static llvm::Optional<llvm::StringRef>
+static std::optional<llvm::StringRef>
wordMatching(llvm::StringRef Name, const llvm::StringSet<> *ContextWords) {
if (ContextWords)
for (const auto &Word : ContextWords->keys())
// Scope proximity is only considered (both index and sema) when this is set.
ScopeDistance *ScopeProximityMatch = nullptr;
- llvm::Optional<llvm::StringRef> SymbolScope;
+ std::optional<llvm::StringRef> SymbolScope;
// A symbol from sema should be accessible from the current scope.
bool SemaSaysInScope = false;
}
// Decomposes Loc and returns the offset if the file ID is SelFile.
- llvm::Optional<unsigned> offsetInSelFile(SourceLocation Loc) const {
+ std::optional<unsigned> offsetInSelFile(SourceLocation Loc) const {
// Decoding Loc with SM.getDecomposedLoc is relatively expensive.
// But SourceLocations for a file are numerically contiguous, so we
// can use cheap integer operations instead.
SelectionTree SelectionTree::createRight(ASTContext &AST,
const syntax::TokenBuffer &Tokens,
unsigned int Begin, unsigned int End) {
- llvm::Optional<SelectionTree> Result;
+ std::optional<SelectionTree> Result;
createEach(AST, Tokens, Begin, End, [&](SelectionTree T) {
Result = std::move(T);
return true;
isa<ObjCImplDecl>(Decl);
}
-llvm::Optional<HighlightingKind> kindForType(const Type *TP,
- const HeuristicResolver *Resolver);
-llvm::Optional<HighlightingKind>
-kindForDecl(const NamedDecl *D, const HeuristicResolver *Resolver) {
+std::optional<HighlightingKind> kindForType(const Type *TP,
+ const HeuristicResolver *Resolver);
+std::optional<HighlightingKind> kindForDecl(const NamedDecl *D,
+ const HeuristicResolver *Resolver) {
if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
if (auto *Target = USD->getTargetDecl())
D = Target;
}
return std::nullopt;
}
-llvm::Optional<HighlightingKind>
-kindForType(const Type *TP, const HeuristicResolver *Resolver) {
+std::optional<HighlightingKind> kindForType(const Type *TP,
+ const HeuristicResolver *Resolver) {
if (!TP)
return std::nullopt;
if (TP->isBuiltinType()) // Builtins are special, they do not have decls.
//
// In particular, heuristically resolved dependent names get their heuristic
// kind, plus the dependent modifier.
-llvm::Optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
- const HighlightingToken &B) {
+std::optional<HighlightingToken> resolveConflict(const HighlightingToken &A,
+ const HighlightingToken &B) {
unsigned Priority1 = evaluateHighlightPriority(A);
unsigned Priority2 = evaluateHighlightPriority(B);
if (Priority1 == Priority2 && A.Kind != B.Kind)
Result.Modifiers = A.Modifiers | B.Modifiers;
return Result;
}
-llvm::Optional<HighlightingToken>
+std::optional<HighlightingToken>
resolveConflict(ArrayRef<HighlightingToken> Tokens) {
if (Tokens.size() == 1)
return Tokens[0];
assert(Tokens.size() >= 2);
- Optional<HighlightingToken> Winner = resolveConflict(Tokens[0], Tokens[1]);
+ std::optional<HighlightingToken> Winner =
+ resolveConflict(Tokens[0], Tokens[1]);
for (size_t I = 2; Winner && I < Tokens.size(); ++I)
Winner = resolveConflict(*Winner, Tokens[I]);
return Winner;
const HeuristicResolver *getResolver() const { return Resolver; }
private:
- llvm::Optional<Range> getRangeForSourceLocation(SourceLocation Loc) {
+ std::optional<Range> getRangeForSourceLocation(SourceLocation Loc) {
Loc = getHighlightableSpellingToken(Loc, SourceMgr);
if (Loc.isInvalid())
return std::nullopt;
HighlightingToken InvalidHighlightingToken;
};
-llvm::Optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
+std::optional<HighlightingModifier> scopeModifier(const NamedDecl *D) {
const DeclContext *DC = D->getDeclContext();
// Injected "Foo" within the class "Foo" has file scope, not class scope.
if (auto *R = dyn_cast_or_null<RecordDecl>(D))
return HighlightingModifier::GlobalScope;
}
-llvm::Optional<HighlightingModifier> scopeModifier(const Type *T) {
+std::optional<HighlightingModifier> scopeModifier(const Type *T) {
if (!T)
return std::nullopt;
if (T->isBuiltinType())
return;
}
- llvm::Optional<SourceLocation> Location;
+ std::optional<SourceLocation> Location;
// FIXME Add "unwrapping" for ArraySubscriptExpr,
// e.g. highlight `a` in `a[i]`
}
}
-llvm::Optional<FoldingRange> toFoldingRange(SourceRange SR,
- const SourceManager &SM) {
+std::optional<FoldingRange> toFoldingRange(SourceRange SR,
+ const SourceManager &SM) {
const auto Begin = SM.getDecomposedLoc(SR.getBegin()),
End = SM.getDecomposedLoc(SR.getEnd());
// Do not produce folding ranges if either range ends is not within the main
return Range;
}
-llvm::Optional<FoldingRange>
+std::optional<FoldingRange>
extractFoldingRange(const syntax::Node *Node,
const syntax::TokenBufferTokenManager &TM) {
if (const auto *Stmt = dyn_cast<syntax::CompoundStatement>(Node)) {
return FID == SM.getMainFileID() || FID == SM.getPreambleFileID();
}
-llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
- const LangOptions &LangOpts,
- SourceRange R) {
+std::optional<SourceRange> toHalfOpenFileRange(const SourceManager &SM,
+ const LangOptions &LangOpts,
+ SourceRange R) {
SourceRange R1 = getTokenFileRange(R.getBegin(), SM, LangOpts);
if (!isValidFileRange(SM, R1))
return std::nullopt;
return Edits;
}
-llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
- const SourceManager &SourceMgr) {
+std::optional<std::string> getCanonicalPath(const FileEntry *F,
+ const SourceManager &SourceMgr) {
if (!F)
return std::nullopt;
return Result;
}
-llvm::Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
+std::optional<FileDigest> digestFile(const SourceManager &SM, FileID FID) {
bool Invalid = false;
llvm::StringRef Content = SM.getBufferData(FID, &Invalid);
if (Invalid)
return false;
}
-llvm::Optional<SpelledWord> SpelledWord::touching(SourceLocation SpelledLoc,
- const syntax::TokenBuffer &TB,
- const LangOptions &LangOpts) {
+std::optional<SpelledWord> SpelledWord::touching(SourceLocation SpelledLoc,
+ const syntax::TokenBuffer &TB,
+ const LangOptions &LangOpts) {
const auto &SM = TB.sourceManager();
auto Touching = syntax::spelledTokensTouching(SpelledLoc, TB);
for (const auto &T : Touching) {
return Result;
}
-llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
- Preprocessor &PP) {
+std::optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
+ Preprocessor &PP) {
if (SpelledTok.kind() != tok::identifier)
return std::nullopt;
SourceLocation Loc = SpelledTok.location();
}
bool isHeaderFile(llvm::StringRef FileName,
- llvm::Optional<LangOptions> LangOpts) {
+ std::optional<LangOptions> LangOpts) {
// Respect the langOpts, for non-file-extension cases, e.g. standard library
// files.
if (LangOpts && LangOpts->IsHeaderFile)
// of hashing function at every place that needs to store this information.
using FileDigest = std::array<uint8_t, 8>;
FileDigest digest(StringRef Content);
-Optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);
+std::optional<FileDigest> digestFile(const SourceManager &SM, FileID FID);
// This context variable controls the behavior of functions in this file
// that convert between LSP offsets and native clang byte offsets.
/// User input (e.g. cursor position) is expressed as a file location, so this
/// function can be viewed as a way to normalize the ranges used in the clang
/// AST so that they are comparable with ranges coming from the user input.
-llvm::Optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
- const LangOptions &LangOpts,
- SourceRange R);
+std::optional<SourceRange> toHalfOpenFileRange(const SourceManager &Mgr,
+ const LangOptions &LangOpts,
+ SourceRange R);
/// Returns true iff all of the following conditions hold:
/// - start and end locations are valid,
/// This function should be used when paths needs to be used outside the
/// component that generate it, so that paths are normalized as much as
/// possible.
-llvm::Optional<std::string> getCanonicalPath(const FileEntry *F,
- const SourceManager &SourceMgr);
+std::optional<std::string> getCanonicalPath(const FileEntry *F,
+ const SourceManager &SourceMgr);
/// Choose the clang-format style we should apply to a certain file.
/// This will usually use FS to look for .clang-format directories.
const syntax::Token *ExpandedToken = nullptr;
// Find the unique word that contains SpelledLoc or starts/ends there.
- static llvm::Optional<SpelledWord> touching(SourceLocation SpelledLoc,
- const syntax::TokenBuffer &TB,
- const LangOptions &LangOpts);
+ static std::optional<SpelledWord> touching(SourceLocation SpelledLoc,
+ const syntax::TokenBuffer &TB,
+ const LangOptions &LangOpts);
};
/// Return true if the \p TokenName is in the list of reversed keywords of the
};
/// Gets the macro referenced by \p SpelledTok. It must be a spelled token
/// aligned to the beginning of an identifier.
-llvm::Optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
- Preprocessor &PP);
+std::optional<DefinedMacro> locateMacroAt(const syntax::Token &SpelledTok,
+ Preprocessor &PP);
/// Infers whether this is a header from the FileName and LangOpts (if
/// presents).
bool isHeaderFile(llvm::StringRef FileName,
- llvm::Optional<LangOptions> LangOpts = std::nullopt);
+ std::optional<LangOptions> LangOpts = std::nullopt);
/// Returns true if the given location is in a generated protobuf file.
bool isProtoFile(SourceLocation Loc, const SourceManager &SourceMgr);
return bool(Target);
}
-llvm::Optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
+std::optional<DriverInfo> parseDriverOutput(llvm::StringRef Output) {
DriverInfo Info;
const char SIS[] = "#include <...> search starts here:";
const char SIE[] = "End of search list.";
return std::move(Info);
}
-llvm::Optional<DriverInfo>
+std::optional<DriverInfo>
extractSystemIncludesAndTarget(llvm::SmallString<128> Driver,
llvm::StringRef Lang,
llvm::ArrayRef<std::string> CommandLine,
return std::nullopt;
}
- llvm::Optional<DriverInfo> Info =
+ std::optional<DriverInfo> Info =
parseDriverOutput(BufOrError->get()->getBuffer());
if (!Info)
return std::nullopt;
private:
// Caches includes extracted from a driver. Key is driver:lang.
- Memoize<llvm::StringMap<llvm::Optional<DriverInfo>>> QueriedDrivers;
+ Memoize<llvm::StringMap<std::optional<DriverInfo>>> QueriedDrivers;
llvm::Regex QueryDriverRegex;
};
} // namespace
static clang::clangd::Key<std::string> FileBeingProcessed;
-llvm::Optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
+std::optional<llvm::StringRef> TUScheduler::getFileBeingProcessedInContext() {
if (auto *File = Context::current().get(FileBeingProcessed))
return llvm::StringRef(*File);
return std::nullopt;
/// the cache anymore. If nullptr was cached for \p K, this function will
/// return a null unique_ptr wrapped into an optional.
/// If \p AccessMetric is set records whether there was a hit or miss.
- llvm::Optional<std::unique_ptr<ParsedAST>>
+ std::optional<std::unique_ptr<ParsedAST>>
take(Key K, const trace::Metric *AccessMetric = nullptr) {
// Record metric after unlocking the mutex.
std::unique_lock<std::mutex> Lock(Mut);
// GCC 4.8 fails to compile `return V;`, as it tries to call the copy
// constructor of unique_ptr, so we call the move ctor explicitly to avoid
// this miscompile.
- return llvm::Optional<std::unique_ptr<ParsedAST>>(std::move(V));
+ return std::optional<std::unique_ptr<ParsedAST>>(std::move(V));
}
private:
void run() {
while (true) {
- llvm::Optional<PreambleThrottlerRequest> Throttle;
+ std::optional<PreambleThrottlerRequest> Throttle;
{
std::unique_lock<std::mutex> Lock(Mutex);
assert(!CurrentReq && "Already processing a request?");
{
Throttle.emplace(FileName, Throttler, ReqCV);
- llvm::Optional<trace::Span> Tracer;
+ std::optional<trace::Span> Tracer;
// If acquire succeeded synchronously, avoid status jitter.
if (!Throttle->satisfied()) {
Tracer.emplace("PreambleThrottle");
mutable std::mutex Mutex;
bool Done = false; /* GUARDED_BY(Mutex) */
- llvm::Optional<Request> NextReq; /* GUARDED_BY(Mutex) */
- llvm::Optional<Request> CurrentReq; /* GUARDED_BY(Mutex) */
+ std::optional<Request> NextReq; /* GUARDED_BY(Mutex) */
+ std::optional<Request> CurrentReq; /* GUARDED_BY(Mutex) */
// Signaled whenever a thread populates NextReq or worker thread builds a
// Preamble.
mutable std::condition_variable ReqCV; /* GUARDED_BY(Mutex) */
/// Adds a new task to the end of the request queue.
void startTask(llvm::StringRef Name, llvm::unique_function<void()> Task,
- llvm::Optional<UpdateType> Update,
+ std::optional<UpdateType> Update,
TUScheduler::ASTActionInvalidation);
/// Runs a task synchronously.
void runTask(llvm::StringRef Name, llvm::function_ref<void()> Task);
std::string Name;
steady_clock::time_point AddTime;
Context Ctx;
- llvm::Optional<Context> QueueCtx;
- llvm::Optional<UpdateType> Update;
+ std::optional<Context> QueueCtx;
+ std::optional<UpdateType> Update;
TUScheduler::ASTActionInvalidation InvalidationPolicy;
Canceler Invalidate;
};
/// Set to true to signal run() to finish processing.
bool Done; /* GUARDED_BY(Mutex) */
std::deque<Request> Requests; /* GUARDED_BY(Mutex) */
- llvm::Optional<Request> CurrentRequest; /* GUARDED_BY(Mutex) */
+ std::optional<Request> CurrentRequest; /* GUARDED_BY(Mutex) */
/// Signalled whenever a new request has been scheduled or processing of a
/// request has completed.
mutable std::condition_variable RequestsCV;
/// Latest build preamble for current TU.
/// None means no builds yet, null means there was an error while building.
/// Only written by ASTWorker's thread.
- llvm::Optional<std::shared_ptr<const PreambleData>> LatestPreamble;
+ std::optional<std::shared_ptr<const PreambleData>> LatestPreamble;
std::deque<Request> PreambleRequests; /* GUARDED_BY(Mutex) */
/// Signaled whenever LatestPreamble changes state or there's a new
/// PreambleRequest.
auto Task = [=, Action = std::move(Action)]() mutable {
if (auto Reason = isCancelled())
return Action(llvm::make_error<CancelledError>(Reason));
- llvm::Optional<std::unique_ptr<ParsedAST>> AST =
+ std::optional<std::unique_ptr<ParsedAST>> AST =
IdleASTs.take(this, &ASTAccessForRead);
if (!AST) {
StoreDiags CompilerInvocationDiagConsumer;
// FIXME: We might need to build a patched ast once preamble thread starts
// running async. Currently getPossiblyStalePreamble below will always
// return a compatible preamble as ASTWorker::update blocks.
- llvm::Optional<ParsedAST> NewAST;
+ std::optional<ParsedAST> NewAST;
if (Invocation) {
NewAST = ParsedAST::build(FileName, FileInputs, std::move(Invocation),
CompilerInvocationDiagConsumer.take(),
// We might be able to reuse the last we've built for a read request.
// FIXME: It might be better to not reuse this AST. That way queued AST builds
// won't be required for diags.
- llvm::Optional<std::unique_ptr<ParsedAST>> AST =
+ std::optional<std::unique_ptr<ParsedAST>> AST =
IdleASTs.take(this, &ASTAccessForDiag);
if (!AST || !InputsAreLatest) {
auto RebuildStartTime = DebouncePolicy::clock::now();
- llvm::Optional<ParsedAST> NewAST = ParsedAST::build(
+ std::optional<ParsedAST> NewAST = ParsedAST::build(
FileName, Inputs, std::move(Invocation), CIDiags, *LatestPreamble);
auto RebuildDuration = DebouncePolicy::clock::now() - RebuildStartTime;
++ASTBuildCount;
void ASTWorker::startTask(llvm::StringRef Name,
llvm::unique_function<void()> Task,
- llvm::Optional<UpdateType> Update,
+ std::optional<UpdateType> Update,
TUScheduler::ASTActionInvalidation Invalidation) {
if (RunSync) {
assert(!Done && "running a task after stop()");
}
// Trace the time the request spends in the queue, and the requests that
// it's going to wait for.
- llvm::Optional<Context> QueueCtx;
+ std::optional<Context> QueueCtx;
if (trace::enabled()) {
// Tracers that follow threads and need strict nesting will see a tiny
// instantaneous event "we're enqueueing", and sometime later it runs.
}
// Tracing: we have a next request, attribute this sleep to it.
- llvm::Optional<WithContext> Ctx;
- llvm::Optional<trace::Span> Tracer;
+ std::optional<WithContext> Ctx;
+ std::optional<trace::Span> Tracer;
if (!Requests.empty()) {
Ctx.emplace(Requests.front().Ctx.clone());
Tracer.emplace("Debounce");
// FIXME: remove this when there is proper index support via build system
// integration.
// FIXME: move to ClangdServer via createProcessingContext.
- static llvm::Optional<llvm::StringRef> getFileBeingProcessedInContext();
+ static std::optional<llvm::StringRef> getFileBeingProcessedInContext();
void profile(MemoryTree &MT) const;
std::unique_ptr<HeaderIncluderCache> HeaderIncluders;
// None when running tasks synchronously and non-None when running tasks
// asynchronously.
- llvm::Optional<AsyncTaskRunner> PreambleTasks;
- llvm::Optional<AsyncTaskRunner> WorkerThreads;
+ std::optional<AsyncTaskRunner> PreambleTasks;
+ std::optional<AsyncTaskRunner> WorkerThreads;
// Used to create contexts for operations that are not bound to a particular
// file (e.g. index queries).
std::string LastActiveFile;
// TUPath is used to resolve the path of URI.
// FIXME: figure out a good home for it, and share the implementation with
// FindSymbols.
-llvm::Optional<Location> toLSPLocation(const SymbolLocation &Loc,
- llvm::StringRef TUPath) {
+std::optional<Location> toLSPLocation(const SymbolLocation &Loc,
+ llvm::StringRef TUPath) {
if (!Loc)
return std::nullopt;
auto Uri = URI::parse(Loc.FileURI);
// Expects Loc to be a SpellingLocation, will bail out otherwise as it can't
// figure out a filename.
-llvm::Optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
- llvm::StringRef TUPath) {
+std::optional<Location> makeLocation(const ASTContext &AST, SourceLocation Loc,
+ llvm::StringRef TUPath) {
const auto &SM = AST.getSourceManager();
const FileEntry *F = SM.getFileEntryForID(SM.getFileID(Loc));
if (!F)
}
// Treat #included files as symbols, to enable go-to-definition on them.
-llvm::Optional<LocatedSymbol> locateFileReferent(const Position &Pos,
- ParsedAST &AST,
- llvm::StringRef MainFilePath) {
+std::optional<LocatedSymbol> locateFileReferent(const Position &Pos,
+ ParsedAST &AST,
+ llvm::StringRef MainFilePath) {
for (auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
if (!Inc.Resolved.empty() && Inc.HashLine == Pos.line) {
LocatedSymbol File;
// Macros are simple: there's no declaration/definition distinction.
// As a consequence, there's no need to look them up in the index either.
-llvm::Optional<LocatedSymbol>
+std::optional<LocatedSymbol>
locateMacroReferent(const syntax::Token &TouchedIdentifier, ParsedAST &AST,
llvm::StringRef MainFilePath) {
if (auto M = locateMacroAt(TouchedIdentifier, AST.getPreprocessor())) {
return DH;
}
-llvm::Optional<DocumentHighlight> toHighlight(SourceLocation Loc,
- const syntax::TokenBuffer &TB) {
+std::optional<DocumentHighlight> toHighlight(SourceLocation Loc,
+ const syntax::TokenBuffer &TB) {
Loc = TB.sourceManager().getFileLoc(Loc);
if (const auto *Tok = TB.spelledTokenAt(Loc)) {
DocumentHighlight Result;
}
}
-llvm::Optional<std::string>
+std::optional<std::string>
stringifyContainerForMainFileRef(const Decl *Container) {
// FIXME We might also want to display the signature here
// When doing so, remember to also add the Signature to index results!
const auto *IdentifierAtCursor =
syntax::spelledIdentifierTouching(*CurLoc, AST.getTokens());
- llvm::Optional<DefinedMacro> Macro;
+ std::optional<DefinedMacro> Macro;
if (IdentifierAtCursor)
Macro = locateMacroAt(*IdentifierAtCursor, AST.getPreprocessor());
if (Macro) {
}
template <typename HierarchyItem>
-static llvm::Optional<HierarchyItem>
+static std::optional<HierarchyItem>
declToHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
ASTContext &Ctx = ND.getASTContext();
auto &SM = Ctx.getSourceManager();
return HI;
}
-static llvm::Optional<TypeHierarchyItem>
+static std::optional<TypeHierarchyItem>
declToTypeHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
auto Result = declToHierarchyItem<TypeHierarchyItem>(ND, TUPath);
if (Result) {
return Result;
}
-static llvm::Optional<CallHierarchyItem>
+static std::optional<CallHierarchyItem>
declToCallHierarchyItem(const NamedDecl &ND, llvm::StringRef TUPath) {
auto Result = declToHierarchyItem<CallHierarchyItem>(ND, TUPath);
if (!Result)
}
template <typename HierarchyItem>
-static llvm::Optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
- PathRef TUPath) {
+static std::optional<HierarchyItem> symbolToHierarchyItem(const Symbol &S,
+ PathRef TUPath) {
auto Loc = symbolToLocation(S, TUPath);
if (!Loc) {
elog("Failed to convert symbol to hierarchy item: {0}", Loc.takeError());
return HI;
}
-static llvm::Optional<TypeHierarchyItem>
+static std::optional<TypeHierarchyItem>
symbolToTypeHierarchyItem(const Symbol &S, PathRef TUPath) {
auto Result = symbolToHierarchyItem<TypeHierarchyItem>(S, TUPath);
if (Result) {
return Result;
}
-static llvm::Optional<CallHierarchyItem>
+static std::optional<CallHierarchyItem>
symbolToCallHierarchyItem(const Symbol &S, PathRef TUPath) {
auto Result = symbolToHierarchyItem<CallHierarchyItem>(S, TUPath);
if (!Result)
Req.Subjects.insert(ID);
Req.Predicate = RelationKind::BaseOf;
Index->relations(Req, [&](const SymbolID &Subject, const Symbol &Object) {
- if (Optional<TypeHierarchyItem> ChildSym =
+ if (std::optional<TypeHierarchyItem> ChildSym =
symbolToTypeHierarchyItem(Object, TUPath)) {
if (Levels > 1) {
ChildSym->children.emplace();
}
for (const CXXRecordDecl *ParentDecl : typeParents(&CXXRD)) {
- if (Optional<TypeHierarchyItem> ParentSym =
+ if (std::optional<TypeHierarchyItem> ParentSym =
declToTypeHierarchyItem(*ParentDecl, TUPath)) {
fillSuperTypes(*ParentDecl, TUPath, *ParentSym, RPSet);
Item.data.parents->emplace_back(ParentSym->data);
CXXRD = CTSD->getTemplateInstantiationPattern();
}
- Optional<TypeHierarchyItem> Result =
+ std::optional<TypeHierarchyItem> Result =
declToTypeHierarchyItem(*CXXRD, AST.tuPath());
if (!Result)
continue;
// The canonical or best declaration: where most users find its interface.
Location PreferredDeclaration;
// Where the symbol is defined, if known. May equal PreferredDeclaration.
- llvm::Optional<Location> Definition;
+ std::optional<Location> Definition;
// SymbolID of the located symbol if available.
SymbolID ID;
};
BackgroundQueue::Task T([this, ChangedFiles] {
trace::Span Tracer("BackgroundIndexEnqueue");
- llvm::Optional<WithContext> WithProvidedContext;
+ std::optional<WithContext> WithProvidedContext;
if (ContextProvider)
WithProvidedContext.emplace(ContextProvider(/*Path=*/""));
std::string Tag = filenameWithoutExtension(Path).str();
uint64_t Key = llvm::xxHash64(Path);
BackgroundQueue::Task T([this, Path(std::move(Path))] {
- llvm::Optional<WithContext> WithProvidedContext;
+ std::optional<WithContext> WithProvidedContext;
if (ContextProvider)
WithProvidedContext.emplace(ContextProvider(Path));
auto Cmd = CDB.getCompileCommand(Path);
// CDBDirectory is the first directory containing a CDB in parent directories
// of a file, or user cache directory if none was found, e.g. stdlib headers.
static Factory createDiskBackedStorageFactory(
- std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo);
+ std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo);
};
// A priority queue of tasks which can be run on (external) worker threads.
// Only affects tasks that run after the call.
static void preventThreadStarvationInTests();
[[nodiscard]] bool
- blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds);
+ blockUntilIdleForTest(std::optional<double> TimeoutSeconds);
private:
void notifyProgress() const; // Requires lock Mu
// Wait until the queue is empty, to allow deterministic testing.
[[nodiscard]] bool
- blockUntilIdleForTest(llvm::Optional<double> TimeoutSeconds = 10) {
+ blockUntilIdleForTest(std::optional<double> TimeoutSeconds = 10) {
return Queue.blockUntilIdleForTest(TimeoutSeconds);
}
class DiskBackedIndexStorageManager {
public:
DiskBackedIndexStorageManager(
- std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo)
+ std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo)
: IndexStorageMapMu(std::make_unique<std::mutex>()),
GetProjectInfo(std::move(GetProjectInfo)) {
llvm::SmallString<128> FallbackDir;
llvm::StringMap<std::unique_ptr<BackgroundIndexStorage>> IndexStorageMap;
std::unique_ptr<std::mutex> IndexStorageMapMu;
- std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo;
+ std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo;
};
} // namespace
BackgroundIndexStorage::Factory
BackgroundIndexStorage::createDiskBackedStorageFactory(
- std::function<llvm::Optional<ProjectInfo>(PathRef)> GetProjectInfo) {
+ std::function<std::optional<ProjectInfo>(PathRef)> GetProjectInfo) {
return DiskBackedIndexStorageManager(std::move(GetProjectInfo));
}
void BackgroundQueue::work(std::function<void()> OnIdle) {
while (true) {
- llvm::Optional<Task> Task;
+ std::optional<Task> Task;
{
std::unique_lock<std::mutex> Lock(Mu);
CV.wait(Lock, [&] { return ShouldStop || !Queue.empty(); });
}
bool BackgroundQueue::blockUntilIdleForTest(
- llvm::Optional<double> TimeoutSeconds) {
+ std::optional<double> TimeoutSeconds) {
std::unique_lock<std::mutex> Lock(Mu);
return wait(Lock, CV, timeoutSeconds(TimeoutSeconds),
[&] { return Queue.empty() && Stat.Active == 0; });
return Result;
}
-llvm::Optional<IndexFileIn>
+std::optional<IndexFileIn>
FileShardedIndex::getShard(llvm::StringRef Uri) const {
auto It = Shards.find(Uri);
if (It == Shards.end())
/// a copy of all the relevant data.
/// Returned index will always have Symbol/Refs/Relation Slabs set, even if
/// they are empty.
- llvm::Optional<IndexFileIn> getShard(llvm::StringRef Uri) const;
+ std::optional<IndexFileIn> getShard(llvm::StringRef Uri) const;
private:
// Contains all the information that belongs to a single file.
/// If set, limit the number of refers returned from the index. The index may
/// choose to return less than this, e.g. it tries to avoid returning stale
/// results.
- llvm::Optional<uint32_t> Limit;
+ std::optional<uint32_t> Limit;
/// If set, populates the container of the reference.
/// Index implementations may chose to populate containers no matter what.
bool WantContainer = false;
llvm::DenseSet<SymbolID> Subjects;
RelationKind Predicate;
/// If set, limit the number of relations returned from the index.
- llvm::Optional<uint32_t> Limit;
+ std::optional<uint32_t> Limit;
};
/// Describes what data is covered by an index.
namespace clangd {
namespace {
-llvm::Optional<std::string> toURI(OptionalFileEntryRef File) {
+std::optional<std::string> toURI(OptionalFileEntryRef File) {
if (!File)
return std::nullopt;
auto AbsolutePath = File->getFileEntry().tryGetRealPathName();
// Holds the contents of an index file that was read.
struct IndexFileIn {
- llvm::Optional<SymbolSlab> Symbols;
- llvm::Optional<RefSlab> Refs;
- llvm::Optional<RelationSlab> Relations;
+ std::optional<SymbolSlab> Symbols;
+ std::optional<RefSlab> Refs;
+ std::optional<RelationSlab> Relations;
// Keys are URIs of the source files.
- llvm::Optional<IncludeGraph> Sources;
+ std::optional<IncludeGraph> Sources;
// This contains only the Directory and CommandLine.
- llvm::Optional<tooling::CompileCommand> Cmd;
+ std::optional<tooling::CompileCommand> Cmd;
};
// Parse an index file. The input must be a RIFF or YAML file.
llvm::Expected<IndexFileIn> readIndexFile(llvm::StringRef, SymbolOrigin);
Best[langFromOpts(LO)].load(std::memory_order_acquire);
}
-llvm::Optional<StdLibLocation> StdLibSet::add(const LangOptions &LO,
- const HeaderSearch &HS) {
+std::optional<StdLibLocation> StdLibSet::add(const LangOptions &LO,
+ const HeaderSearch &HS) {
Lang L = langFromOpts(LO);
int OldVersion = Best[L].load(std::memory_order_acquire);
int NewVersion = standardFromOpts(LO);
// Returns the location where the standard library was found.
//
// This function is threadsafe.
- llvm::Optional<StdLibLocation> add(const LangOptions &, const HeaderSearch &);
+ std::optional<StdLibLocation> add(const LangOptions &, const HeaderSearch &);
// Indicates whether a built index should be used.
// It should not be used if a newer version has subsequently been added.
return Result;
}
-llvm::Optional<RelationKind> indexableRelation(const index::SymbolRelation &R) {
+std::optional<RelationKind> indexableRelation(const index::SymbolRelation &R) {
if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationBaseOf))
return RelationKind::BaseOf;
if (R.Roles & static_cast<unsigned>(index::SymbolRole::RelationOverrideOf))
class SymbolCollector::HeaderFileURICache {
struct FrameworkUmbrellaSpelling {
// Spelling for the public umbrella header, e.g. <Foundation/Foundation.h>
- llvm::Optional<std::string> PublicHeader;
+ std::optional<std::string> PublicHeader;
// Spelling for the private umbrella header, e.g.
// <Foundation/Foundation_Private.h>
- llvm::Optional<std::string> PrivateHeader;
+ std::optional<std::string> PrivateHeader;
};
// Weird double-indirect access to PP, which might not be ready yet when
// HeaderFiles is created but will be by the time it's used.
bool IsPrivateHeader;
};
- llvm::Optional<FrameworkHeaderPath>
+ std::optional<FrameworkHeaderPath>
splitFrameworkHeaderPath(llvm::StringRef Path) {
using namespace llvm::sys;
path::reverse_iterator I = path::rbegin(Path);
// <Foundation/Foundation_Private.h> instead of
// <Foundation/NSObject_Private.h> which should be used instead of directly
// importing the header.
- llvm::Optional<std::string> getFrameworkUmbrellaSpelling(
+ std::optional<std::string> getFrameworkUmbrellaSpelling(
llvm::StringRef Framework, SrcMgr::CharacteristicKind HeadersDirKind,
HeaderSearch &HS, FrameworkHeaderPath &HeaderPath) {
auto Res = CacheFrameworkToUmbrellaHeaderSpelling.try_emplace(Framework);
// named `Framework`, e.g. `NSObject.h` in framework `Foundation` would
// give <Foundation/Foundation.h> if the umbrella header exists, otherwise
// <Foundation/NSObject.h>.
- llvm::Optional<llvm::StringRef> getFrameworkHeaderIncludeSpelling(
+ std::optional<llvm::StringRef> getFrameworkHeaderIncludeSpelling(
const FileEntry *FE, llvm::StringRef Framework, HeaderSearch &HS) {
auto Res = CachePathToFrameworkSpelling.try_emplace(FE->getName());
auto *CachedHeaderSpelling = &Res.first->second;
};
// Return the symbol location of the token at \p TokLoc.
-llvm::Optional<SymbolLocation>
+std::optional<SymbolLocation>
SymbolCollector::getTokenLocation(SourceLocation TokLoc) {
const auto &SM = ASTCtx->getSourceManager();
auto *FE = SM.getFileEntryForID(SM.getFileID(TokLoc));
std::string ReturnType = getReturnType(*CCS);
S.ReturnType = ReturnType;
- llvm::Optional<OpaqueType> TypeStorage;
+ std::optional<OpaqueType> TypeStorage;
if (S.Flags & Symbol::IndexedForCodeCompletion) {
TypeStorage = OpaqueType::fromCompletionResult(*ASTCtx, SymbolCompletion);
if (TypeStorage)
void processRelations(const NamedDecl &ND, const SymbolID &ID,
ArrayRef<index::SymbolRelation> Relations);
- llvm::Optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc);
+ std::optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc);
- llvm::Optional<std::string> getIncludeHeader(const Symbol &S, FileID);
+ std::optional<std::string> getIncludeHeader(const Symbol &S, FileID);
SymbolID getSymbolIDCached(const Decl *D);
SymbolID getSymbolIDCached(const llvm::StringRef MacroName,
std::pair<clang::clangd::SymbolID, std::vector<clang::clangd::Ref>>;
// This is a pale imitation of std::variant<Symbol, RefBundle, Relation>
struct VariantEntry {
- llvm::Optional<clang::clangd::Symbol> Symbol;
- llvm::Optional<RefBundle> Refs;
- llvm::Optional<clang::clangd::Relation> Relation;
- llvm::Optional<clang::clangd::IncludeGraphNode> Source;
- llvm::Optional<clang::tooling::CompileCommand> Cmd;
+ std::optional<clang::clangd::Symbol> Symbol;
+ std::optional<RefBundle> Refs;
+ std::optional<clang::clangd::Relation> Relation;
+ std::optional<clang::clangd::IncludeGraphNode> Source;
+ std::optional<clang::tooling::CompileCommand> Cmd;
};
// A class helps YAML to serialize the 32-bit encoded position (Line&Column),
// as YAMLIO can't directly map bitfields.
llvm::UniqueStringSaver Strings(Arena);
llvm::yaml::Input Yin(Data, &Strings);
IncludeGraph Sources;
- llvm::Optional<tooling::CompileCommand> Cmd;
+ std::optional<tooling::CompileCommand> Cmd;
while (Yin.setCurrentDocument()) {
llvm::yaml::EmptyContext Ctx;
VariantEntry Variant;
for (const auto &IDAndScore : IDAndScores) {
const DocID SymbolDocID = IDAndScore.first;
const auto *Sym = Symbols[SymbolDocID];
- const llvm::Optional<float> Score = Filter.match(Sym->Name);
+ const std::optional<float> Score = Filter.match(Sym->Name);
if (!Score)
continue;
// Combine Fuzzy Matching score, precomputed symbol quality and boosting
return runCommand(ExecCommand, *Index) ? 0 : 1;
llvm::LineEditor LE("dexp");
- while (llvm::Optional<std::string> Request = LE.readLine())
+ while (std::optional<std::string> Request = LE.readLine())
runCommand(std::move(*Request), *Index);
}
auto Logger = makeLogger(LogPrefix.getValue(), llvm::errs());
clang::clangd::LoggingSession LoggingSession(*Logger);
- llvm::Optional<llvm::raw_fd_ostream> TracerStream;
+ std::optional<llvm::raw_fd_ostream> TracerStream;
std::unique_ptr<clang::clangd::trace::EventTracer> Tracer;
if (!TraceFile.empty()) {
std::error_code EC;
}
}
- llvm::Optional<clang::clangd::trace::Session> TracingSession;
+ std::optional<clang::clangd::trace::Session> TracingSession;
if (Tracer)
TracingSession.emplace(*Tracer);
// 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<const Decl *> insertionDecl(const DeclContext &DC,
- const Anchor &A) {
+std::optional<const Decl *> insertionDecl(const DeclContext &DC,
+ const Anchor &A) {
bool LastMatched = false;
bool ReturnNext = false;
for (const auto *D : DC.decls()) {
namespace clangd {
namespace {
-llvm::Optional<std::string> filePath(const SymbolLocation &Loc,
- llvm::StringRef HintFilePath) {
+std::optional<std::string> filePath(const SymbolLocation &Loc,
+ llvm::StringRef HintFilePath) {
if (!Loc)
return std::nullopt;
auto Path = URI::resolve(Loc.FileURI, HintFilePath);
SameName,
};
-llvm::Optional<ReasonToReject> renameable(const NamedDecl &RenameDecl,
- StringRef MainFilePath,
- const SymbolIndex *Index,
- const RenameOptions& Opts) {
+std::optional<ReasonToReject> 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<CXXMethodDecl>(&RenameDecl)) {
// Check if we can rename the given RenameDecl into NewName.
// Return details if the rename would produce a conflict.
-llvm::Optional<InvalidName> checkName(const NamedDecl &RenameDecl,
- llvm::StringRef NewName) {
+std::optional<InvalidName> 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<InvalidName> Result;
+ std::optional<InvalidName> Result;
if (isKeyword(NewName, ASTCtx.getLangOpts()))
Result = InvalidName{InvalidName::Keywords, NewName.str()};
else if (!mayBeValidIdentifier(NewName))
// 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::vector<Range>>
+std::optional<std::vector<Range>>
adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier,
std::vector<Range> Indexed, const LangOptions &LangOpts) {
trace::Span Tracer("AdjustRenameRanges");
return getMappedRanges(Indexed, Lexed);
}
-llvm::Optional<std::vector<Range>> getMappedRanges(ArrayRef<Range> Indexed,
- ArrayRef<Range> Lexed) {
+std::optional<std::vector<Range>> getMappedRanges(ArrayRef<Range> Indexed,
+ ArrayRef<Range> Lexed) {
trace::Span Tracer("GetMappedRanges");
assert(!Indexed.empty());
assert(llvm::is_sorted(Indexed));
/// The API assumes that Indexed contains only named occurrences (each
/// occurrence has the same length).
/// REQUIRED: Indexed is sorted.
-llvm::Optional<std::vector<Range>>
+std::optional<std::vector<Range>>
adjustRenameRanges(llvm::StringRef DraftCode, llvm::StringRef Identifier,
std::vector<Range> Indexed, const LangOptions &LangOpts);
/// Exposed for testing only.
///
/// REQUIRED: Indexed and Lexed are sorted.
-llvm::Optional<std::vector<Range>> getMappedRanges(ArrayRef<Range> Indexed,
- ArrayRef<Range> Lexed);
+std::optional<std::vector<Range>> getMappedRanges(ArrayRef<Range> Indexed,
+ ArrayRef<Range> Lexed);
/// Evaluates how good the mapped result is. 0 indicates a perfect match.
///
/// Exposed for testing only.
struct Effect {
/// A message to be displayed to the user.
- llvm::Optional<std::string> ShowMessage;
+ std::optional<std::string> ShowMessage;
FileEdits ApplyEdits;
/// Whether the edits should be formatted before presenting to the client.
/// Note that it applies to all files.
// 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<SourceLocation> getSemicolonForDecl(const FunctionDecl *FD) {
+std::optional<SourceLocation> getSemicolonForDecl(const FunctionDecl *FD) {
const SourceManager &SM = FD->getASTContext().getSourceManager();
const LangOptions &LangOpts = FD->getASTContext().getLangOpts();
return FD->getBeginLoc();
}
-llvm::Optional<tooling::Replacement>
+std::optional<tooling::Replacement>
addInlineIfInHeader(const FunctionDecl *FD) {
// This includes inline functions and constexpr functions.
if (FD->isInlined() || llvm::isa<CXXMethodDecl>(FD))
return nullptr;
}
-llvm::Optional<Path> getSourceFile(llvm::StringRef FileName,
- const Tweak::Selection &Sel) {
+std::optional<Path> getSourceFile(llvm::StringRef FileName,
+ const Tweak::Selection &Sel) {
assert(Sel.FS);
if (auto Source = getCorrespondingHeaderOrSource(FileName, Sel.FS))
return *Source;
// 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<const DeclContext *>
+std::optional<const DeclContext *>
findContextForNS(llvm::StringRef TargetNS, const DeclContext *CurContext) {
assert(TargetNS.empty() || TargetNS.endswith("::"));
// Skip any non-namespace contexts, e.g. TagDecls, functions/methods.
return N.get<Decl>() || N.get<Stmt>() || N.get<Type>();
}
- llvm::Optional<DynTypedNode> Node;
+ std::optional<DynTypedNode> Node;
};
REGISTER_TWEAK(DumpAST)
Expected<Tweak::Effect> ExpandAutoType::apply(const Selection& Inputs) {
auto &SrcMgr = Inputs.AST->getSourceManager();
- llvm::Optional<clang::QualType> DeducedType =
+ std::optional<clang::QualType> DeducedType =
getDeducedType(Inputs.AST->getASTContext(), AutoRange.getBegin());
// if we can't resolve the type, return an error message
// Zone Range is the union of SourceRanges of all child Nodes in Parent since
// all child Nodes are RootStmts
-llvm::Optional<SourceRange> findZoneRange(const Node *Parent,
- const SourceManager &SM,
- const LangOptions &LangOpts) {
+std::optional<SourceRange> findZoneRange(const Node *Parent,
+ const SourceManager &SM,
+ const LangOptions &LangOpts) {
SourceRange SR;
if (auto BeginFileRange = toHalfOpenFileRange(
SM, LangOpts, Parent->Children.front()->ASTNode.getSourceRange()))
// 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<SourceRange>
+std::optional<SourceRange>
computeEnclosingFuncRange(const FunctionDecl *EnclosingFunction,
const SourceManager &SM,
const LangOptions &LangOpts) {
// FIXME: Check we're not extracting from the initializer/condition of a control
// flow structure.
-llvm::Optional<ExtractionZone> findExtractionZone(const Node *CommonAnc,
- const SourceManager &SM,
- const LangOptions &LangOpts) {
+std::optional<ExtractionZone> findExtractionZone(const Node *CommonAnc,
+ const SourceManager &SM,
+ const LangOptions &LangOpts) {
ExtractionZone ExtZone;
ExtZone.Parent = getParentOfRootStmts(CommonAnc);
if (!ExtZone.Parent || ExtZone.Parent->Children.empty())
std::vector<Parameter> Parameters;
SourceRange BodyRange;
SourceLocation DefinitionPoint;
- llvm::Optional<SourceLocation> ForwardDeclarationPoint;
+ std::optional<SourceLocation> ForwardDeclarationPoint;
const CXXRecordDecl *EnclosingClass = nullptr;
const NestedNameSpecifier *DefinitionQualifier = nullptr;
const DeclContext *SemanticDC = nullptr;
else // Could be a dynamic property or a property in a header.
Assignee = ("self." + Name).str();
}
- static llvm::Optional<MethodParameter> parameterFor(const Decl &D) {
+ static std::optional<MethodParameter> parameterFor(const Decl &D) {
if (const auto *ID = dyn_cast<ObjCIvarDecl>(&D))
return MethodParameter(*ID);
if (const auto *PD = dyn_cast<ObjCPropertyDecl>(&D))
llvm::Expected<tooling::Replacement>
removeUsingDirective(ASTContext &Ctx, const UsingDirectiveDecl *D) {
auto &SM = Ctx.getSourceManager();
- llvm::Optional<Token> NextTok =
+ std::optional<Token> NextTok =
Lexer::findNextToken(D->getEndLoc(), SM, Ctx.getLangOpts());
if (!NextTok || NextTok->isNot(tok::semi))
return error("no semicolon after using-directive");
format::FormatStyle Style;
// from buildAST
std::shared_ptr<const PreambleData> Preamble;
- llvm::Optional<ParsedAST> AST;
+ std::optional<ParsedAST> AST;
FileIndex Index;
public:
// Prepare inputs and build CompilerInvocation (parsed compile command).
bool buildInvocation(const ThreadsafeFS &TFS,
- llvm::Optional<std::string> Contents) {
+ std::optional<std::string> Contents) {
StoreDiags CaptureInvocationDiags;
std::vector<std::string> CC1Args;
Inputs.CompileCommand = Cmd;
}
llvm::SmallString<0> FakeFile;
- llvm::Optional<std::string> Contents;
+ std::optional<std::string> Contents;
if (File.empty()) {
llvm::sys::path::system_temp_directory(false, FakeFile);
llvm::sys::path::append(FakeFile, "test.cc");
public:
FlagsConfigProvider() {
- llvm::Optional<Config::CDBSearchSpec> CDBSearch;
- llvm::Optional<Config::ExternalIndexSpec> IndexSpec;
- llvm::Optional<Config::BackgroundPolicy> BGPolicy;
+ std::optional<Config::CDBSearchSpec> CDBSearch;
+ std::optional<Config::ExternalIndexSpec> IndexSpec;
+ std::optional<Config::BackgroundPolicy> BGPolicy;
// If --compile-commands-dir arg was invoked, check value and override
// default path.
clang::format::DefaultFallbackStyle = FallbackStyle.c_str();
// Validate command line arguments.
- llvm::Optional<llvm::raw_fd_ostream> InputMirrorStream;
+ std::optional<llvm::raw_fd_ostream> InputMirrorStream;
if (!InputMirrorFile.empty()) {
std::error_code EC;
InputMirrorStream.emplace(InputMirrorFile, /*ref*/ EC,
// 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<llvm::raw_fd_ostream> TracerStream;
+ std::optional<llvm::raw_fd_ostream> TracerStream;
std::unique_ptr<trace::EventTracer> Tracer;
const char *JSONTraceFile = getenv("CLANGD_TRACE");
const char *MetricsCSVFile = getenv("CLANGD_METRICS");
}
}
- llvm::Optional<trace::Session> TracingSession;
+ std::optional<trace::Session> TracingSession;
if (Tracer)
TracingSession.emplace(*Tracer);
Logger L;
LoggingSession LogSession;
- llvm::Optional<ClangdLSPServer> Server;
- llvm::Optional<std::thread> ServerThread;
+ std::optional<ClangdLSPServer> Server;
+ std::optional<std::thread> ServerThread;
LSPClient Client;
};
ElementsAre(llvm::json::Value(2), llvm::json::Value(10)));
}
-// Creates a Callback that writes its received value into an Optional<Expected>.
+// Creates a Callback that writes its received value into an
+// std::optional<Expected>.
template <typename T>
llvm::unique_function<void(llvm::Expected<T>)>
-capture(llvm::Optional<llvm::Expected<T>> &Out) {
+capture(std::optional<llvm::Expected<T>> &Out) {
Out.reset();
return [&Out](llvm::Expected<T> V) { Out.emplace(std::move(V)); };
}
DelayedCompilationDatabase(Notification &CanReturnCommand)
: CanReturnCommand(CanReturnCommand) {}
- llvm::Optional<tooling::CompileCommand>
+ std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override {
// FIXME: make this timeout and fail instead of waiting forever in case
// something goes wrong.
TEST_F(ConfigCompileTests, ExternalBlockMountPoint) {
auto GetFrag = [](llvm::StringRef Directory,
- llvm::Optional<const char *> MountPoint) {
+ std::optional<const char *> MountPoint) {
Fragment Frag;
Frag.Source.Directory = Directory.str();
Fragment::IndexBlock::ExternalBlock External;
std::string Message;
llvm::SourceMgr::DiagKind Kind;
Position Pos;
- llvm::Optional<Range> Rng;
+ std::optional<Range> Rng;
friend void PrintTo(const Diag &D, std::ostream *OS) {
*OS << (D.Kind == llvm::SourceMgr::DK_Error ? "error: " : "warning: ")
}
/// An overload for convenience.
- llvm::Optional<OpaqueType> fromCompletionResult(const NamedDecl *D) {
+ std::optional<OpaqueType> fromCompletionResult(const NamedDecl *D) {
return OpaqueType::fromCompletionResult(
astCtx(), CodeCompletionResult(D, CCP_Declaration));
}
private:
// Set after calling build().
- llvm::Optional<ParsedAST> AST;
+ std::optional<ParsedAST> AST;
};
TEST_F(ExpectedTypeConversionTest, BasicTypes) {
class OverlayCDBTest : public ::testing::Test {
class BaseCDB : public GlobalCompilationDatabase {
public:
- llvm::Optional<tooling::CompileCommand>
+ std::optional<tooling::CompileCommand>
getCompileCommand(llvm::StringRef File) const override {
if (File == testPath("foo.cc"))
return cmd(File, "-DA=1");
return cmd(File, "-DA=2");
}
- llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override {
+ std::optional<ProjectInfo> getProjectInfo(PathRef File) const override {
return ProjectInfo{testRoot()};
}
};
FS.Files[FooCpp];
FS.Files[FooH];
FS.Files[Invalid];
- Optional<Path> PathResult =
+ std::optional<Path> PathResult =
getCorrespondingHeaderOrSource(FooCpp, FS.view(std::nullopt));
EXPECT_TRUE(PathResult.has_value());
ASSERT_EQ(*PathResult, FooH);
// Test for switch from .h header to .cc source
struct {
llvm::StringRef HeaderCode;
- llvm::Optional<std::string> ExpectedSource;
+ std::optional<std::string> ExpectedSource;
} TestCases[] = {
{"// empty, no header found", std::nullopt},
{R"cpp(
// Test for switching from .cc source file to .h header.
struct {
llvm::StringRef SourceCode;
- llvm::Optional<std::string> ExpectedResult;
+ std::optional<std::string> ExpectedResult;
} TestCases[] = {
{"// empty, no header found", std::nullopt},
{R"cpp(
return Path.value_or("");
}
- llvm::Optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
- tooling::IncludeDirective Directive) {
+ std::optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
+ tooling::IncludeDirective Directive) {
Clang = setupClang();
PreprocessOnlyAction Action;
EXPECT_TRUE(
}
llvm::json::Value toJSON(const Foo &F) { return F.X; }
-// Creates a Callback that writes its received value into an Optional<Expected>.
+// Creates a Callback that writes its received value into an
+// std::optional<Expected>.
template <typename T>
llvm::unique_function<void(llvm::Expected<T>)>
-capture(llvm::Optional<llvm::Expected<T>> &Out) {
+capture(std::optional<llvm::Expected<T>> &Out) {
Out.reset();
return [&Out](llvm::Expected<T> V) { Out.emplace(std::move(V)); };
}
UnorderedElementsAre("notify"));
ASSERT_THAT(RawHandlers.CommandHandlers.keys(),
UnorderedElementsAre("cmdPlusOne"));
- llvm::Optional<llvm::Expected<llvm::json::Value>> Reply;
+ std::optional<llvm::Expected<llvm::json::Value>> Reply;
auto &RawPlusOne = RawHandlers.MethodHandlers["plusOne"];
RawPlusOne(1, capture(Reply));
LSPBinder::OutgoingMethod<Foo, Foo> Fail;
Fail = Binder.outgoingMethod("fail");
- llvm::Optional<llvm::Expected<Foo>> Reply;
+ std::optional<llvm::Expected<Foo>> 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<llvm::Expected<std::string>> WrongTypeReply;
+ std::optional<llvm::Expected<std::string>> WrongTypeReply;
WrongSignature(Foo{2}, capture(WrongTypeReply));
EXPECT_THAT(RawOutgoing.take("wrongSignature"),
ElementsAre(llvm::json::Value(2)));
void LSPClient::sync() { call("sync", nullptr).takeValue(); }
-llvm::Optional<std::vector<llvm::json::Value>>
+std::optional<std::vector<llvm::json::Value>>
LSPClient::diagnostics(llvm::StringRef Path) {
sync();
auto Notifications = takeNotifications("textDocument/publishDiagnostics");
Field(&Inclusion::Resolved, testPath("a.h")))));
}
-llvm::Optional<ParsedAST> createPatchedAST(llvm::StringRef Baseline,
- llvm::StringRef Modified) {
+std::optional<ParsedAST> createPatchedAST(llvm::StringRef Baseline,
+ llvm::StringRef Modified) {
auto BaselinePreamble = TestTU::withCode(Baseline).preamble();
if (!BaselinePreamble) {
ADD_FAILURE() << "Failed to build baseline preamble";
}
class SpelledWordsTest : public ::testing::Test {
- llvm::Optional<ParsedAST> AST;
+ std::optional<ParsedAST> AST;
- llvm::Optional<SpelledWord> tryWord(const char *Text) {
+ std::optional<SpelledWord> tryWord(const char *Text) {
llvm::Annotations A(Text);
auto TU = TestTU::withCode(A.code());
AST = TU.build();
const auto &Func = cast<FunctionDecl>(findDecl(AST, "test"));
const auto &Body = cast<CompoundStmt>(Func.getBody());
const auto &Loop = cast<WhileStmt>(*Body->child_begin());
- llvm::Optional<SourceRange> Range = toHalfOpenFileRange(
+ std::optional<SourceRange> Range = toHalfOpenFileRange(
AST.getSourceManager(), AST.getLangOpts(), Loop->getSourceRange());
ASSERT_TRUE(Range) << "Failed to get file range";
EXPECT_EQ(AST.getSourceManager().getFileOffset(Range->getBegin()),
std::string HeaderName = "f.h";
std::string FileName = "f.cpp";
TestTU File;
- llvm::Optional<ParsedAST> AST; // Initialized after build.
+ std::optional<ParsedAST> AST; // Initialized after build.
};
TEST_F(ShouldCollectSymbolTest, ShouldCollectSymbol) {
CollectorOpts.RefFilter = RefKind::All;
CollectorOpts.CollectMainFileRefs = true;
runSymbolCollector("", Code.code());
- auto FindRefWithRange = [&](Range R) -> Optional<Ref> {
+ auto FindRefWithRange = [&](Range R) -> std::optional<Ref> {
for (auto &Entry : Refs) {
for (auto &Ref : Entry.second) {
if (rangesMatch(Ref.Location, R))
std::vector<SymbolDetails> Expected;
for (const auto &Sym : T.second) {
- llvm::Optional<Location> Decl, Def;
+ std::optional<Location> Decl, Def;
if (Sym.DeclMarker)
Decl = Location{URIForFile::canonicalize(testPath(TU.Filename), ""),
TestInput.range(Sym.DeclMarker)};
/// T Result;
/// someAsyncFunc(Param1, Param2, /*Callback=*/capture(Result));
template <typename T> struct CaptureProxy {
- CaptureProxy(llvm::Optional<T> &Target) : Target(&Target) { assert(!Target); }
+ CaptureProxy(std::optional<T> &Target) : Target(&Target) { assert(!Target); }
CaptureProxy(const CaptureProxy &) = delete;
CaptureProxy &operator=(const CaptureProxy &) = delete;
}
private:
- llvm::Optional<T> *Target;
+ std::optional<T> *Target;
// Using shared_ptr to workaround compilation errors with MSVC.
// MSVC only allows default-constructible and copyable objects as future<>
// arguments.
std::future<std::shared_ptr<T>> Future;
};
-template <typename T> CaptureProxy<T> capture(llvm::Optional<T> &Target) {
+template <typename T> CaptureProxy<T> capture(std::optional<T> &Target) {
return CaptureProxy<T>(Target);
}
} // namespace
llvm::Expected<CodeCompleteResult>
runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
clangd::CodeCompleteOptions Opts) {
- llvm::Optional<llvm::Expected<CodeCompleteResult>> Result;
+ std::optional<llvm::Expected<CodeCompleteResult>> Result;
Server.codeComplete(File, Pos, Opts, capture(Result));
return std::move(*Result);
}
llvm::Expected<SignatureHelp> runSignatureHelp(ClangdServer &Server,
PathRef File, Position Pos,
MarkupKind DocumentationFormat) {
- llvm::Optional<llvm::Expected<SignatureHelp>> Result;
+ std::optional<llvm::Expected<SignatureHelp>> Result;
Server.signatureHelp(File, Pos, DocumentationFormat, capture(Result));
return std::move(*Result);
}
llvm::Expected<std::vector<LocatedSymbol>>
runLocateSymbolAt(ClangdServer &Server, PathRef File, Position Pos) {
- llvm::Optional<llvm::Expected<std::vector<LocatedSymbol>>> Result;
+ std::optional<llvm::Expected<std::vector<LocatedSymbol>>> Result;
Server.locateSymbolAt(File, Pos, capture(Result));
return std::move(*Result);
}
llvm::Expected<std::vector<DocumentHighlight>>
runFindDocumentHighlights(ClangdServer &Server, PathRef File, Position Pos) {
- llvm::Optional<llvm::Expected<std::vector<DocumentHighlight>>> Result;
+ std::optional<llvm::Expected<std::vector<DocumentHighlight>>> Result;
Server.findDocumentHighlights(File, Pos, capture(Result));
return std::move(*Result);
}
llvm::Expected<RenameResult> runRename(ClangdServer &Server, PathRef File,
Position Pos, llvm::StringRef NewName,
const RenameOptions &RenameOpts) {
- llvm::Optional<llvm::Expected<RenameResult>> Result;
+ std::optional<llvm::Expected<RenameResult>> Result;
Server.rename(File, Pos, NewName, RenameOpts, capture(Result));
return std::move(*Result);
}
llvm::Expected<RenameResult>
runPrepareRename(ClangdServer &Server, PathRef File, Position Pos,
- llvm::Optional<std::string> NewName,
+ std::optional<std::string> NewName,
const RenameOptions &RenameOpts) {
- llvm::Optional<llvm::Expected<RenameResult>> Result;
+ std::optional<llvm::Expected<RenameResult>> Result;
Server.prepareRename(File, Pos, NewName, RenameOpts, capture(Result));
return std::move(*Result);
}
llvm::Expected<tooling::Replacements>
-runFormatFile(ClangdServer &Server, PathRef File, llvm::Optional<Range> Rng) {
- llvm::Optional<llvm::Expected<tooling::Replacements>> Result;
+runFormatFile(ClangdServer &Server, PathRef File, std::optional<Range> Rng) {
+ std::optional<llvm::Expected<tooling::Replacements>> Result;
Server.formatFile(File, Rng, capture(Result));
return std::move(*Result);
}
llvm::Expected<std::vector<SelectionRange>>
runSemanticRanges(ClangdServer &Server, PathRef File,
const std::vector<Position> &Pos) {
- llvm::Optional<llvm::Expected<std::vector<SelectionRange>>> Result;
+ std::optional<llvm::Expected<std::vector<SelectionRange>>> Result;
Server.semanticRanges(File, Pos, capture(Result));
return std::move(*Result);
}
-llvm::Expected<llvm::Optional<clangd::Path>>
+llvm::Expected<std::optional<clangd::Path>>
runSwitchHeaderSource(ClangdServer &Server, PathRef File) {
- llvm::Optional<llvm::Expected<llvm::Optional<clangd::Path>>> Result;
+ std::optional<llvm::Expected<std::optional<clangd::Path>>> Result;
Server.switchSourceHeader(File, capture(Result));
return std::move(*Result);
}
llvm::Expected<RenameResult>
runPrepareRename(ClangdServer &Server, PathRef File, Position Pos,
- llvm::Optional<std::string> NewName,
+ std::optional<std::string> NewName,
const clangd::RenameOptions &RenameOpts);
llvm::Expected<tooling::Replacements>
-runFormatFile(ClangdServer &Server, PathRef File, llvm::Optional<Range>);
+runFormatFile(ClangdServer &Server, PathRef File, std::optional<Range>);
SymbolSlab runFuzzyFind(const SymbolIndex &Index, StringRef Query);
SymbolSlab runFuzzyFind(const SymbolIndex &Index, const FuzzyFindRequest &Req);
runSemanticRanges(ClangdServer &Server, PathRef File,
const std::vector<Position> &Pos);
-llvm::Expected<llvm::Optional<clangd::Path>>
+llvm::Expected<std::optional<clangd::Path>>
runSwitchHeaderSource(ClangdServer &Server, PathRef File);
llvm::Error runCustomAction(ClangdServer &Server, PathRef File,
OK = testPath("ok.h"),
NotIncluded = testPath("not_included.h");
struct NoHeadersCDB : public GlobalCompilationDatabase {
- llvm::Optional<tooling::CompileCommand>
+ std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override {
if (File == NoCmd || File == NotIncluded || FailAll)
return std::nullopt;
std::vector<RequestID> Releases;
llvm::DenseMap<RequestID, Callback> Callbacks;
// If set, the notification is signalled after acquiring the specified ID.
- llvm::Optional<std::pair<RequestID, Notification *>> Notify;
+ std::optional<std::pair<RequestID, Notification *>> Notify;
RequestID acquire(llvm::StringRef Filename, Callback CB) override {
RequestID ID;
// -ffreestanding avoids implicit stdc-predef.h.
}
-llvm::Optional<ProjectInfo>
+std::optional<ProjectInfo>
MockCompilationDatabase::getProjectInfo(PathRef File) const {
return ProjectInfo{std::string(Directory)};
}
-llvm::Optional<tooling::CompileCommand>
+std::optional<tooling::CompileCommand>
MockCompilationDatabase::getCompileCommand(PathRef File) const {
if (ExtraClangFlags.empty())
return std::nullopt;
MockCompilationDatabase(StringRef Directory = StringRef(),
StringRef RelPathPrefix = StringRef());
- llvm::Optional<tooling::CompileCommand>
+ std::optional<tooling::CompileCommand>
getCompileCommand(PathRef File) const override;
- llvm::Optional<ProjectInfo> getProjectInfo(PathRef File) const override;
+ std::optional<ProjectInfo> getProjectInfo(PathRef File) const override;
std::vector<std::string> ExtraClangFlags;
return Index;
}
-Optional<ParsedAST> TestWorkspace::openFile(llvm::StringRef Filename) {
+std::optional<ParsedAST> TestWorkspace::openFile(llvm::StringRef Filename) {
auto It = Inputs.find(Filename);
if (It == Inputs.end()) {
ADD_FAILURE() << "Accessing non-existing file: " << Filename;
std::unique_ptr<SymbolIndex> index();
- Optional<ParsedAST> openFile(llvm::StringRef Filename);
+ std::optional<ParsedAST> openFile(llvm::StringRef Filename);
private:
struct SourceFile {
}
MATCHER_P3(sym, Name, Decl, DefOrNone, "") {
- llvm::Optional<Range> Def = DefOrNone;
+ std::optional<Range> Def = DefOrNone;
if (Name != arg.Name) {
*result_listener << "Name is " << arg.Name;
return false;
)objc"};
for (const char *Test : Tests) {
Annotations T(Test);
- llvm::Optional<Range> WantDecl;
- llvm::Optional<Range> WantDef;
+ std::optional<Range> WantDecl;
+ std::optional<Range> WantDef;
if (!T.ranges().empty())
WantDecl = WantDef = T.range();
if (!T.ranges("decl").empty())
ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
EXPECT_TRUE(Results[0].ID) << Test;
- llvm::Optional<Range> GotDef;
+ std::optional<Range> GotDef;
if (Results[0].Definition)
GotDef = Results[0].Definition->range;
EXPECT_EQ(WantDef, GotDef) << Test;
// N starts at 0.
struct ExpectedRanges {
Range WantDecl;
- llvm::Optional<Range> WantDef;
+ std::optional<Range> WantDef;
};
const char *Tests[] = {
R"objc(
for (size_t Idx = 0; Idx < Ranges.size(); Idx++) {
EXPECT_EQ(Results[Idx].PreferredDeclaration.range, Ranges[Idx].WantDecl)
<< "($decl" << Idx << ")" << Test;
- llvm::Optional<Range> GotDef;
+ std::optional<Range> GotDef;
if (Results[Idx].Definition)
GotDef = Results[Idx].Definition->range;
EXPECT_EQ(GotDef, Ranges[Idx].WantDef) << "($def" << Idx << ")" << Test;
for (const char *Test : Tests) {
Annotations T(Test);
- llvm::Optional<Range> WantDecl;
- llvm::Optional<Range> WantDef;
+ std::optional<Range> WantDecl;
+ std::optional<Range> WantDef;
if (!T.ranges().empty())
WantDecl = WantDef = T.range();
if (!T.ranges("decl").empty())
} else {
ASSERT_THAT(Results, ::testing::SizeIs(1)) << Test;
EXPECT_EQ(Results[0].PreferredDeclaration.range, *WantDecl) << Test;
- llvm::Optional<Range> GotDef;
+ std::optional<Range> GotDef;
if (Results[0].Definition)
GotDef = Results[0].Definition->range;
EXPECT_EQ(WantDef, GotDef) << Test;
for (const char *Test : Tests) {
Annotations T(Test);
- llvm::Optional<Range> WantDecl;
+ std::optional<Range> WantDecl;
if (!T.ranges().empty())
WantDecl = T.range();
Annotations T(Test);
auto AST = TestTU::withCode(T.code()).build();
const auto &SM = AST.getSourceManager();
- llvm::Optional<Range> Nearby;
+ std::optional<Range> Nearby;
auto Word =
SpelledWord::touching(cantFail(sourceLocationInMainFile(SM, T.point())),
AST.getTokens(), AST.getLangOpts());
TEST(FindReferences, NoQueryForLocalSymbols) {
struct RecordingIndex : public MemIndex {
- mutable Optional<llvm::DenseSet<SymbolID>> RefIDs;
+ mutable std::optional<llvm::DenseSet<SymbolID>> RefIDs;
bool refs(const RefsRequest &Req,
llvm::function_ref<void(const Ref &)>) const override {
RefIDs = Req.IDs;
std::string Result;
read(
FS, FreshTime,
- [&](llvm::Optional<llvm::StringRef> Data) {
+ [&](std::optional<llvm::StringRef> Data) {
GotParse = true;
Value = Data.value_or("").str();
},
// Prepare and apply the specified tweak based on the selection in Input.
// Returns std::nullopt if and only if prepare() failed.
-llvm::Optional<llvm::Expected<Tweak::Effect>>
+std::optional<llvm::Expected<Tweak::Effect>>
applyTweak(ParsedAST &AST, llvm::Annotations::Range Range, StringRef TweakID,
const SymbolIndex *Index, llvm::vfs::FileSystem *FS) {
- llvm::Optional<llvm::Expected<Tweak::Effect>> Result;
+ std::optional<llvm::Expected<Tweak::Effect>> Result;
SelectionTree::createEach(AST.getASTContext(), AST.getTokens(), Range.Begin,
Range.End, [&](SelectionTree ST) {
Tweak::Selection S(Index, AST, Range.Begin,
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<StringRef>("2.0")) {
+ if (!Object ||
+ Object->getString("jsonrpc") != std::optional<StringRef>("2.0")) {
elog("Not a JSON-RPC 2.0 message: {0:2}", Message);
return false;
}
// ID may be any JSON value. If absent, this is a notification.
- Optional<json::Value> ID;
+ std::optional<json::Value> ID;
if (auto *I = Object->get("id"))
ID = std::move(*I);
auto Method = Object->getString("method");
average clang-tidy check.
This check identifies unsafe accesses to values contained in
-``std::optional<T>``, ``absl::optional<T>``, or ``base::Optional<T>``
+``std::optional<T>``, ``absl::optional<T>``, or ``base::std::optional<T>``
objects. Below we will refer to all these types collectively as
``optional<T>``.
/// 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<unsigned> Taken;
+ std::optional<unsigned> Taken;
};
/// Some piece of the file. {One of Code, Directive, Conditional}.
// 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<DirectiveTree::Directive> parse(DirectiveTree *Tree,
+ std::optional<DirectiveTree::Directive> parse(DirectiveTree *Tree,
bool TopLevel) {
auto StartsDirective =
[&, AllowDirectiveAt((const Token *)nullptr)]() mutable {
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<bool> isTakenWhenReached(const DirectiveTree::Directive &Dir) {
+ std::optional<bool> isTakenWhenReached(const DirectiveTree::Directive &Dir) {
switch (Dir.Kind) {
case clang::tok::pp_if:
case clang::tok::pp_elif:
// Does the condition consist of exactly one token?
if (&Value >= Tokens.end() || &Value.nextNC() < Tokens.end())
return std::nullopt;
- return llvm::StringSwitch<llvm::Optional<bool>>(Value.text())
+ return llvm::StringSwitch<std::optional<bool>>(Value.text())
.Cases("true", "1", true)
.Cases("false", "0", false)
.Default(std::nullopt);
llvm::DenseMap<const ForestNode *, size_t> ReferenceIds;
std::string Result;
constexpr Token::Index KEnd = std::numeric_limits<Token::Index>::max();
- std::function<void(const ForestNode *, Token::Index, llvm::Optional<SymbolID>,
+ std::function<void(const ForestNode *, Token::Index, std::optional<SymbolID>,
LineDecoration &LineDec)>
Dump = [&](const ForestNode *P, Token::Index End,
- llvm::Optional<SymbolID> ElidedParent,
- LineDecoration LineDec) {
+ std::optional<SymbolID> ElidedParent, LineDecoration LineDec) {
bool SharedNode = VisitCounts.find(P)->getSecond() > 1;
llvm::ArrayRef<const ForestNode *> Children;
auto EndOfElement = [&](size_t ChildIndex) {
});
// We may find multiple winners, but they will have the same range.
- llvm::Optional<Token::Range> RecoveryRange;
+ std::optional<Token::Range> RecoveryRange;
std::vector<const PlaceholderRecovery *> BestOptions;
for (const PlaceholderRecovery &Option : Options) {
// If this starts further left than options we've already found, then
if (!Sequences.empty() || Heads->size() != NextPopHead + 1)
return false;
const GSS::Node *Head = Heads->back();
- llvm::Optional<RuleID> RID;
+ std::optional<RuleID> RID;
for (RuleID R : Lang.Table.getReduceRules(Head->State)) {
if (RID.has_value())
return false;
clang::LangOptions LangOpts = clang::pseudo::genericLangOpts();
std::string SourceText;
- llvm::Optional<clang::pseudo::TokenStream> RawStream;
- llvm::Optional<TokenStream> PreprocessedStream;
- llvm::Optional<clang::pseudo::TokenStream> ParseableStream;
+ std::optional<clang::pseudo::TokenStream> RawStream;
+ std::optional<TokenStream> PreprocessedStream;
+ std::optional<clang::pseudo::TokenStream> ParseableStream;
if (Source.getNumOccurrences()) {
SourceText = readOrDie(Source);
RawStream = clang::pseudo::lex(SourceText, LangOpts);
auto DirectiveStructure = clang::pseudo::DirectiveTree::parse(*RawStream);
clang::pseudo::chooseConditionalBranches(DirectiveStructure, *RawStream);
- llvm::Optional<TokenStream> Preprocessed;
+ std::optional<TokenStream> Preprocessed;
if (StripDirectives) {
Preprocessed = DirectiveStructure.stripDirectives(*Stream);
Stream = &*Preprocessed;
if (ParseableStream) {
clang::pseudo::ForestArena Arena;
clang::pseudo::GSS GSS;
- llvm::Optional<clang::pseudo::SymbolID> StartSymID =
+ std::optional<clang::pseudo::SymbolID> StartSymID =
Lang.G.findNonterminal(StartSymbol);
if (!StartSymID) {
llvm::errs() << llvm::formatv(
void check(const MatchFinder::MatchResult &Result) override {
const auto *D = Result.Nodes.getNodeAs<VarDecl>("var");
using utils::fixit::addQualifierToVarDecl;
- Optional<FixItHint> Fix = addQualifierToVarDecl(
+ std::optional<FixItHint> Fix = addQualifierToVarDecl(
*D, *Result.Context, DeclSpec::TQ::TQ_const, CT, CP);
auto Diag = diag(D->getBeginLoc(), "doing const transformation");
if (Fix)
std::string Message;
llvm::SourceMgr::DiagKind Kind;
size_t Pos;
- Optional<llvm::Annotations::Range> Range;
+ std::optional<llvm::Annotations::Range> Range;
friend void PrintTo(const Diag &D, std::ostream *OS) {
*OS << (D.Kind == llvm::SourceMgr::DK_Error ? "error: " : "warning: ")
template <typename T>
static std::string runCheck(StringRef Code, const Twine &Filename,
- Optional<StringRef> ExpectedWarning,
+ std::optional<StringRef> ExpectedWarning,
std::map<StringRef, StringRef> PathsToContent =
std::map<StringRef, StringRef>()) {
std::vector<ClangTidyError> Errors;
return Result;
}
-static std::string runHeaderGuardCheck(StringRef Code, const Twine &Filename,
- Optional<StringRef> ExpectedWarning) {
+static std::string
+runHeaderGuardCheck(StringRef Code, const Twine &Filename,
+ std::optional<StringRef> ExpectedWarning) {
return runCheck<LLVMHeaderGuardCheck>(Code, Filename,
std::move(ExpectedWarning));
}
static std::string
runIncludeOrderCheck(StringRef Code, const Twine &Filename,
- Optional<StringRef> ExpectedWarning,
+ std::optional<StringRef> ExpectedWarning,
llvm::ArrayRef<llvm::StringLiteral> Includes) {
std::map<StringRef, StringRef> PathsToContent;
for (auto Include : Includes)
static std::string
runHeaderGuardCheckWithEndif(StringRef Code, const Twine &Filename,
- Optional<StringRef> ExpectedWarning) {
+ std::optional<StringRef> ExpectedWarning) {
return runCheck<WithEndifComment>(Code, Filename, std::move(ExpectedWarning));
}
} // namespace
}
// A trivial rewrite-rule generator that requires Objective-C code.
-Optional<RewriteRuleWith<std::string>>
+std::optional<RewriteRuleWith<std::string>>
needsObjC(const LangOptions &LangOpts,
const ClangTidyCheck::OptionsView &Options) {
if (!LangOpts.ObjC)
}
// A trivial rewrite rule generator that checks config options.
-Optional<RewriteRuleWith<std::string>>
+std::optional<RewriteRuleWith<std::string>>
noSkip(const LangOptions &LangOpts,
const ClangTidyCheck::OptionsView &Options) {
if (Options.get("Skip", "false") == "true")