LanguageClient: Avoid calling throwing functions

Similar to with std::optional we want to avoid calling throwing
functions for std::variant, which includes std::get.
In many cases this also avoids the chain of `std::holds_alternative` +
`std::get` calls. And we never declare any `throws`.

Change-Id: I14f62ddef921b6bee90226ea34d1ffa62629bdc3
Reviewed-by: David Schulz <david.schulz@qt.io>
Reviewed-by: <github-actions-qt-creator@cristianadam.eu>
This commit is contained in:
Eike Ziller
2024-05-06 16:49:18 +02:00
parent 67072d3f5b
commit 770f1b0376
18 changed files with 129 additions and 135 deletions

View File

@@ -93,7 +93,8 @@ private:
template<typename T, typename V>
JsonObject::iterator JsonObject::insertVariant(const Key key, const V &variant)
{
return std::holds_alternative<T>(variant) ? insert(key, std::get<T>(variant)) : end();
const auto v = std::get_if<T>(&variant);
return v ? insert(key, *v) : end();
}
template<typename T1, typename T2, typename... Args, typename V>

View File

@@ -68,19 +68,19 @@ public:
private:
friend size_t qHash(const MessageId &id)
{
if (std::holds_alternative<int>(id))
return QT_PREPEND_NAMESPACE(qHash(std::get<int>(id)));
if (std::holds_alternative<QString>(id))
return QT_PREPEND_NAMESPACE(qHash(std::get<QString>(id)));
if (const int *iid = std::get_if<int>(&id))
return QT_PREPEND_NAMESPACE(qHash(*iid));
if (const QString *sid = std::get_if<QString>(&id))
return QT_PREPEND_NAMESPACE(qHash(*sid));
return QT_PREPEND_NAMESPACE(qHash(0));
}
friend QDebug operator<<(QDebug stream, const MessageId &id)
{
if (std::holds_alternative<int>(id))
stream << std::get<int>(id);
if (const int *iid = std::get_if<int>(&id))
stream << *iid;
else
stream << std::get<QString>(id);
stream << *std::get_if<QString>(&id);
return stream;
}
};

View File

@@ -303,8 +303,8 @@ HoverContent::HoverContent(const QJsonValue &value)
bool HoverContent::isValid() const
{
if (std::holds_alternative<MarkedString>(*this))
return std::get<MarkedString>(*this).isValid();
if (const auto s = std::get_if<MarkedString>(this))
return s->isValid();
return true;
}

View File

@@ -101,10 +101,10 @@ MarkupOrString::MarkupOrString(const QJsonValue &val)
QJsonValue MarkupOrString::toJson() const
{
if (std::holds_alternative<QString>(*this))
return std::get<QString>(*this);
if (std::holds_alternative<MarkupContent>(*this))
return QJsonValue(std::get<MarkupContent>(*this));
if (const auto s = std::get_if<QString>(this))
return *s;
if (const auto c = std::get_if<MarkupContent>(this))
return QJsonValue(*c);
return {};
}

View File

@@ -89,15 +89,16 @@ public:
QList<T> toListOrEmpty() const
{
if (std::holds_alternative<QList<T>>(*this))
return std::get<QList<T>>(*this);
if (const auto l = std::get_if<QList<T>>(this))
return *l;
return {};
}
QList<T> toList() const
{
QTC_ASSERT(std::holds_alternative<QList<T>>(*this), return {});
return std::get<QList<T>>(*this);
const auto l = std::get_if<QList<T>>(this);
QTC_ASSERT(l, return {});
return *l;
}
bool isNull() const { return std::holds_alternative<std::nullptr_t>(*this); }
};
@@ -127,15 +128,17 @@ public:
T value(const T &defaultValue = T()) const
{
QTC_ASSERT(std::holds_alternative<T>(*this), return defaultValue);
return std::get<T>(*this);
const auto t = std::get_if<T>(this);
QTC_ASSERT(t, return defaultValue);
return *t;
}
template<typename Type>
LanguageClientValue<Type> transform()
{
QTC_ASSERT(!std::holds_alternative<T>(*this), return LanguageClientValue<Type>());
return Type(std::get<T>(*this));
const auto t = std::get_if<T>(this);
QTC_ASSERT(t, return LanguageClientValue<Type>());
return Type(*t);
}
bool isNull() const { return std::holds_alternative<std::nullptr_t>(*this); }

View File

@@ -21,9 +21,9 @@ ProgressToken::ProgressToken(const QJsonValue &value)
ProgressToken::operator QJsonValue() const
{
if (std::holds_alternative<QString>(*this))
return QJsonValue(std::get<QString>(*this));
return QJsonValue(std::get<int>(*this));
if (const auto s = std::get_if<QString>(this))
return QJsonValue(*s);
return QJsonValue(*std::get_if<int>(this));
}
ProgressParams::ProgressType ProgressParams::value() const

View File

@@ -189,10 +189,10 @@ void ServerCapabilities::setCallHierarchyProvider(
const std::variant<bool, WorkDoneProgressOptions> &callHierarchyProvider)
{
QJsonValue val;
if (std::holds_alternative<bool>(callHierarchyProvider))
val = std::get<bool>(callHierarchyProvider);
else if (std::holds_alternative<WorkDoneProgressOptions>(callHierarchyProvider))
val = QJsonObject(std::get<WorkDoneProgressOptions>(callHierarchyProvider));
if (const auto boolvalue = std::get_if<bool>(&callHierarchyProvider))
val = *boolvalue;
else if (const auto options = std::get_if<WorkDoneProgressOptions>(&callHierarchyProvider))
val = QJsonObject(*options);
insert(callHierarchyProviderKey, val);
}
@@ -211,10 +211,10 @@ void ServerCapabilities::setTypeHierarchyProvider(
const std::variant<bool, WorkDoneProgressOptions> &typeHierarchyProvider)
{
QJsonValue val;
if (std::holds_alternative<bool>(typeHierarchyProvider))
val = std::get<bool>(typeHierarchyProvider);
else if (std::holds_alternative<WorkDoneProgressOptions>(typeHierarchyProvider))
val = QJsonObject(std::get<WorkDoneProgressOptions>(typeHierarchyProvider));
if (const auto boolvalue = std::get_if<bool>(&typeHierarchyProvider))
val = *boolvalue;
else if (const auto options = std::get_if<WorkDoneProgressOptions>(&typeHierarchyProvider))
val = QJsonObject(*options);
insert(typeHierarchyProviderKey, val);
}

View File

@@ -64,10 +64,11 @@ ExecuteCommandParams::ExecuteCommandParams(const Command &command)
LanguageServerProtocol::WorkSpaceFolderResult::operator const QJsonValue() const
{
if (!std::holds_alternative<QList<WorkSpaceFolder>>(*this))
const auto folders = std::get_if<QList<WorkSpaceFolder>>(this);
if (!folders)
return QJsonValue::Null;
QJsonArray array;
for (const auto &folder : std::get<QList<WorkSpaceFolder>>(*this))
for (const auto &folder : *folders)
array.append(QJsonValue(folder));
return array;
}

View File

@@ -903,7 +903,8 @@ void ClientPrivate::requestDocumentHighlightsNow(TextEditor::TextEditorWidget *w
= m_serverCapabilities.documentHighlightProvider();
if (!provider.has_value())
return;
if (std::holds_alternative<bool>(*provider) && !std::get<bool>(*provider))
const auto boolvalue = std::get_if<bool>(&*provider);
if (boolvalue && !*boolvalue)
return;
}
@@ -935,7 +936,8 @@ void ClientPrivate::requestDocumentHighlightsNow(TextEditor::TextEditorWidget *w
const QTextCharFormat &format =
widget->textDocument()->fontSettings().toTextCharFormat(TextEditor::C_OCCURRENCES);
QTextDocument *document = widget->document();
for (const auto &highlight : std::get<QList<DocumentHighlight>>(*result)) {
const auto highlights = std::get_if<QList<DocumentHighlight>>(&*result);
for (const auto &highlight : *highlights) {
QTextEdit::ExtraSelection selection{widget->textCursor(), format};
const int &start = highlight.range().start().toPositionInDocument(document);
const int &end = highlight.range().end().toPositionInDocument(document);
@@ -1435,7 +1437,8 @@ void Client::requestCodeActions(const CodeActionRequest &request)
} else {
std::variant<bool, CodeActionOptions> provider
= d->m_serverCapabilities.codeActionProvider().value_or(false);
if (!(std::holds_alternative<CodeActionOptions>(provider) || std::get<bool>(provider)))
const auto boolvalue = std::get_if<bool>(&provider);
if (boolvalue && !*boolvalue)
return;
}
@@ -1661,8 +1664,8 @@ bool Client::supportsDocumentSymbols(const TextEditor::TextDocument *doc) const
= capabilities().documentSymbolProvider();
if (!provider.has_value())
return false;
if (std::holds_alternative<bool>(*provider))
return std::get<bool>(*provider);
if (const auto boolvalue = std::get_if<bool>(&*provider))
return *boolvalue;
return true;
}
@@ -2233,10 +2236,10 @@ bool ClientPrivate::sendWorkspceFolderChanges() const
if (auto folder = workspace->workspaceFolders()) {
if (folder->supported().value_or(false)) {
// holds either the Id for deregistration or whether it is registered
auto notification = folder->changeNotifications().value_or(false);
return std::holds_alternative<QString>(notification)
|| (std::holds_alternative<bool>(notification)
&& std::get<bool>(notification));
const std::variant<QString, bool> notification
= folder->changeNotifications().value_or(false);
const auto boolvalue = std::get_if<bool>(&notification);
return !boolvalue || *boolvalue;
}
}
}

View File

@@ -29,7 +29,8 @@ bool ClientWorkspaceSymbolRequest::preStartCheck()
= client()->capabilities().workspaceSymbolProvider();
if (!capability.has_value())
return false;
if (std::holds_alternative<bool>(*capability) && !std::get<bool>(*capability))
const auto boolvalue = std::get_if<bool>(&*capability);
if (boolvalue && !boolvalue)
return false;
return true;

View File

@@ -123,11 +123,11 @@ QString LanguageClientCompletionItem::detail() const
if (auto _doc = m_item.documentation()) {
auto doc = *_doc;
QString detailDocText;
if (std::holds_alternative<QString>(doc)) {
detailDocText = std::get<QString>(doc);
} else if (std::holds_alternative<MarkupContent>(doc)) {
if (const auto s = std::get_if<QString>(&doc)) {
detailDocText = *s;
} else if (const auto m = std::get_if<MarkupContent>(&doc)) {
// TODO markdown parser?
detailDocText = std::get<MarkupContent>(doc).content();
detailDocText = m->content();
}
if (!detailDocText.isEmpty())
return detailDocText;
@@ -495,12 +495,10 @@ void LanguageClientCompletionAssistProcessor::handleCompletionResponse(
}
QList<CompletionItem> items;
if (std::holds_alternative<CompletionList>(*result)) {
const auto &list = std::get<CompletionList>(*result);
items = list.items().value_or(QList<CompletionItem>());
} else if (std::holds_alternative<QList<CompletionItem>>(*result)) {
items = std::get<QList<CompletionItem>>(*result);
}
if (const auto list = std::get_if<CompletionList>(&*result))
items = list->items().value_or(QList<CompletionItem>());
else if (const auto l = std::get_if<QList<CompletionItem>>(&*result))
items = *l;
auto proposalItems = generateCompletionItems(items);
if (!m_snippetsGroup.isEmpty()) {
proposalItems << TextEditor::SnippetAssistCollector(m_snippetsGroup,

View File

@@ -69,7 +69,8 @@ QFutureWatcher<ChangeSet> *LanguageClientFormatter::format(
= m_client->capabilities().documentRangeFormattingProvider();
if (!provider.has_value())
return nullptr;
if (std::holds_alternative<bool>(*provider) && !std::get<bool>(*provider))
const auto boolvalue = std::get_if<bool>(&*provider);
if (boolvalue && !*boolvalue)
return nullptr;
}
DocumentRangeFormattingParams params;

View File

@@ -87,9 +87,8 @@ void HoverHandler::identifyMatch(TextEditor::TextEditorWidget *editorWidget,
const std::optional<std::variant<bool, WorkDoneProgressOptions>> &provider
= m_client->capabilities().hoverProvider();
bool sendMessage = provider.has_value();
if (sendMessage && std::holds_alternative<bool>(*provider))
sendMessage = std::get<bool>(*provider);
const bool *boolvalue = provider.has_value() ? std::get_if<bool>(&*provider) : nullptr;
bool sendMessage = provider.has_value() && (!boolvalue || *boolvalue);
if (std::optional<bool> registered = m_client->dynamicCapabilities().isRegistered(
HoverRequest::methodName)) {
sendMessage = *registered;

View File

@@ -228,10 +228,10 @@ void LanguageClientOutlineWidget::handleResponse(const DocumentUri &uri,
{
if (uri != m_uri)
return;
if (std::holds_alternative<QList<SymbolInformation>>(result))
m_model.setInfo(std::get<QList<SymbolInformation>>(result));
else if (std::holds_alternative<QList<DocumentSymbol>>(result))
m_model.setInfo(std::get<QList<DocumentSymbol>>(result));
if (const auto i = std::get_if<QList<SymbolInformation>>(&result))
m_model.setInfo(*i);
else if (const auto s = std::get_if<QList<DocumentSymbol>>(&result))
m_model.setInfo(*s);
else
m_model.clear();
@@ -369,10 +369,10 @@ void OutlineComboBox::updateModel(const DocumentUri &resultUri, const DocumentSy
{
if (m_uri != resultUri)
return;
if (std::holds_alternative<QList<SymbolInformation>>(result))
m_model.setInfo(std::get<QList<SymbolInformation>>(result));
else if (std::holds_alternative<QList<DocumentSymbol>>(result))
m_model.setInfo(std::get<QList<DocumentSymbol>>(result));
if (const auto i = std::get_if<QList<SymbolInformation>>(&result))
m_model.setInfo(*i);
else if (const auto s = std::get_if<QList<DocumentSymbol>>(&result))
m_model.setInfo(*i);
else
m_model.clear();

View File

@@ -100,9 +100,8 @@ static MessageId sendTextDocumentPositionParamsRequest(Client *client,
sendMessage = supportedFile;
} else {
const auto provider = std::mem_fn(member)(serverCapability);
sendMessage = provider.has_value();
if (sendMessage && std::holds_alternative<bool>(*provider))
sendMessage = std::get<bool>(*provider);
const bool *boolvalue = provider.has_value() ? std::get_if<bool>(&*provider) : nullptr;
sendMessage = provider.has_value() && (!boolvalue || *boolvalue);
}
if (sendMessage) {
client->sendMessage(request);
@@ -191,9 +190,8 @@ bool SymbolSupport::supportsFindLink(TextEditor::TextDocument *document, LinkTar
else
supported = m_client->isSupportedUri(uri);
} else {
supported = provider.has_value();
if (supported && std::holds_alternative<bool>(*provider))
supported = std::get<bool>(*provider);
const bool *boolvalue = provider.has_value() ? std::get_if<bool>(&*provider) : nullptr;
supported = provider.has_value() && (!boolvalue || *boolvalue);
}
return supported;
}
@@ -259,8 +257,8 @@ bool SymbolSupport::supportsFindUsages(TextEditor::TextDocument *document) const
return false;
}
} else if (auto referencesProvider = m_client->capabilities().referencesProvider()) {
if (std::holds_alternative<bool>(*referencesProvider)) {
if (!std::get<bool>(*referencesProvider))
if (const auto b = std::get_if<bool>(&*referencesProvider)) {
if (!*b)
return false;
}
} else {
@@ -447,13 +445,11 @@ static bool supportsRename(Client *client,
}
}
if (auto renameProvider = client->capabilities().renameProvider()) {
if (std::holds_alternative<bool>(*renameProvider)) {
if (!std::get<bool>(*renameProvider))
if (const auto b = std::get_if<bool>(&*renameProvider)) {
if (!*b)
return false;
} else if (std::holds_alternative<ServerCapabilities::RenameOptions>(*renameProvider)) {
prepareSupported = std::get<ServerCapabilities::RenameOptions>(*renameProvider)
.prepareProvider()
.value_or(false);
} else if (const auto opt = std::get_if<ServerCapabilities::RenameOptions>(&*renameProvider)) {
prepareSupported = opt->prepareProvider().value_or(false);
}
} else {
return false;
@@ -524,19 +520,17 @@ void SymbolSupport::requestPrepareRename(TextEditor::TextDocument *document,
const std::optional<PrepareRenameResult> &result = response.result();
if (result.has_value()) {
if (std::holds_alternative<PlaceHolderResult>(*result)) {
auto placeHolderResult = std::get<PlaceHolderResult>(*result);
startRenameSymbol(params,
placeholder.isEmpty() ? placeHolderResult.placeHolder()
: placeholder,
if (const auto placeHolderResult = std::get_if<PlaceHolderResult>(&*result)) {
startRenameSymbol(
params,
placeholder.isEmpty() ? placeHolderResult->placeHolder() : placeholder,
oldSymbolName,
callback,
preferLowerCaseFileNames);
} else if (std::holds_alternative<Range>(*result)) {
auto range = std::get<Range>(*result);
} else if (const auto range = std::get_if<Range>(&*result)) {
if (document) {
const int start = range.start().toPositionInDocument(document->document());
const int end = range.end().toPositionInDocument(document->document());
const int start = range->start().toPositionInDocument(document->document());
const int end = range->end().toPositionInDocument(document->document());
const QString reportedSymbolName = document->textAt(start, end - start);
startRenameSymbol(params,
derivePlaceholder(reportedSymbolName, placeholder),
@@ -586,28 +580,24 @@ Utils::SearchResultItems generateReplaceItems(const WorkspaceEdit &edits,
const DocumentUri::PathMapper &pathMapper = client->hostPathMapper();
if (!documentChanges.isEmpty()) {
for (const DocumentChange &documentChange : std::as_const(documentChanges)) {
if (std::holds_alternative<TextDocumentEdit>(documentChange)) {
const TextDocumentEdit edit = std::get<TextDocumentEdit>(documentChange);
rangesInDocument[edit.textDocument().uri().toFilePath(pathMapper)] = convertEdits(
edit.edits());
if (const auto edit = std::get_if<TextDocumentEdit>(&documentChange)) {
rangesInDocument[edit->textDocument().uri().toFilePath(pathMapper)] = convertEdits(
edit->edits());
} else {
Utils::SearchResultItem item;
if (std::holds_alternative<CreateFileOperation>(documentChange)) {
auto op = std::get<CreateFileOperation>(documentChange);
item.setLineText(op.message(pathMapper));
item.setFilePath(op.uri().toFilePath(pathMapper));
item.setUserData(QVariant(op));
} else if (std::holds_alternative<RenameFileOperation>(documentChange)) {
auto op = std::get<RenameFileOperation>(documentChange);
item.setLineText(op.message(pathMapper));
item.setFilePath(op.oldUri().toFilePath(pathMapper));
item.setUserData(QVariant(op));
} else if (std::holds_alternative<DeleteFileOperation>(documentChange)) {
auto op = std::get<DeleteFileOperation>(documentChange);
item.setLineText(op.message(pathMapper));
item.setFilePath(op.uri().toFilePath(pathMapper));
item.setUserData(QVariant(op));
if (const auto op = std::get_if<CreateFileOperation>(&documentChange)) {
item.setLineText(op->message(pathMapper));
item.setFilePath(op->uri().toFilePath(pathMapper));
item.setUserData(QVariant(*op));
} else if (const auto op = std::get_if<RenameFileOperation>(&documentChange)) {
item.setLineText(op->message(pathMapper));
item.setFilePath(op->oldUri().toFilePath(pathMapper));
item.setUserData(QVariant(*op));
} else if (const auto op = std::get_if<DeleteFileOperation>(&documentChange)) {
item.setLineText(op->message(pathMapper));
item.setFilePath(op->uri().toFilePath(pathMapper));
item.setUserData(QVariant(*op));
}
items << item;

View File

@@ -349,13 +349,12 @@ bool applyDocumentChange(const Client *client, const DocumentChange &change)
if (!client)
return false;
if (std::holds_alternative<TextDocumentEdit>(change)) {
return applyTextDocumentEdit(client, std::get<TextDocumentEdit>(change));
} else if (std::holds_alternative<CreateFileOperation>(change)) {
const auto createOperation = std::get<CreateFileOperation>(change);
const FilePath filePath = createOperation.uri().toFilePath(client->hostPathMapper());
if (const auto e = std::get_if<TextDocumentEdit>(&change)) {
return applyTextDocumentEdit(client, *e);
} else if (const auto createOperation = std::get_if<CreateFileOperation>(&change)) {
const FilePath filePath = createOperation->uri().toFilePath(client->hostPathMapper());
if (filePath.exists()) {
if (const std::optional<CreateFileOptions> options = createOperation.options()) {
if (const std::optional<CreateFileOptions> options = createOperation->options()) {
if (options->overwrite().value_or(false)) {
if (!filePath.removeFile())
return false;
@@ -365,16 +364,15 @@ bool applyDocumentChange(const Client *client, const DocumentChange &change)
}
}
return filePath.ensureExistingFile();
} else if (std::holds_alternative<RenameFileOperation>(change)) {
const RenameFileOperation renameOperation = std::get<RenameFileOperation>(change);
const FilePath oldPath = renameOperation.oldUri().toFilePath(client->hostPathMapper());
} else if (const auto renameOperation = std::get_if<RenameFileOperation>(&change)) {
const FilePath oldPath = renameOperation->oldUri().toFilePath(client->hostPathMapper());
if (!oldPath.exists())
return false;
const FilePath newPath = renameOperation.newUri().toFilePath(client->hostPathMapper());
const FilePath newPath = renameOperation->newUri().toFilePath(client->hostPathMapper());
if (oldPath == newPath)
return true;
if (newPath.exists()) {
if (const std::optional<CreateFileOptions> options = renameOperation.options()) {
if (const std::optional<CreateFileOptions> options = renameOperation->options()) {
if (options->overwrite().value_or(false)) {
if (!newPath.removeFile())
return false;
@@ -384,10 +382,9 @@ bool applyDocumentChange(const Client *client, const DocumentChange &change)
}
}
return oldPath.renameFile(newPath);
} else if (std::holds_alternative<DeleteFileOperation>(change)) {
const auto deleteOperation = std::get<DeleteFileOperation>(change);
const FilePath filePath = deleteOperation.uri().toFilePath(client->hostPathMapper());
if (const std::optional<DeleteFileOptions> options = deleteOperation.options()) {
} else if (const auto deleteOperation = std::get_if<DeleteFileOperation>(&change)) {
const FilePath filePath = deleteOperation->uri().toFilePath(client->hostPathMapper());
if (const std::optional<DeleteFileOptions> options = deleteOperation->options()) {
if (!filePath.exists())
return options->ignoreIfNotExists().value_or(false);
if (filePath.isDir() && options->recursive().value_or(false))

View File

@@ -69,10 +69,10 @@ bool ProgressManager::isProgressEndMessage(const LanguageServerProtocol::Progres
Utils::Id languageClientProgressId(const ProgressToken &token)
{
constexpr char k_LanguageClientProgressId[] = "LanguageClient.ProgressId.";
auto toString = [](const ProgressToken &token){
if (std::holds_alternative<int>(token))
return QString::number(std::get<int>(token));
return std::get<QString>(token);
auto toString = [](const ProgressToken &token) {
if (const auto i = std::get_if<int>(&token))
return QString::number(*i);
return *std::get_if<QString>(&token);
};
return Utils::Id(k_LanguageClientProgressId).withSuffix(toString(token));
}

View File

@@ -251,11 +251,11 @@ void SnippetParsingTest::testSnippetParsing()
QFETCH(Parts, parts);
SnippetParseResult result = LanguageClient::parseSnippet(input);
QCOMPARE(std::holds_alternative<ParsedSnippet>(result), success);
const auto snippet = std::get_if<ParsedSnippet>(&result);
QCOMPARE(snippet != nullptr, success);
if (!success)
return;
ParsedSnippet snippet = std::get<ParsedSnippet>(result);
auto rangesCompare = [&](const ParsedSnippet::Part &actual, const SnippetPart &expected) {
QCOMPARE(actual.text, expected.text);
@@ -264,10 +264,10 @@ void SnippetParsingTest::testSnippetParsing()
QCOMPARE(manglerId, expected.manglerId);
};
QCOMPARE(snippet.parts.count(), parts.count());
QCOMPARE(snippet->parts.count(), parts.count());
for (int i = 0; i < parts.count(); ++i)
rangesCompare(snippet.parts.at(i), parts.at(i));
rangesCompare(snippet->parts.at(i), parts.at(i));
}
QObject *createSnippetParsingTest()