2021-04-20 14:42:29 +02:00
|
|
|
/****************************************************************************
|
|
|
|
|
**
|
|
|
|
|
** Copyright (C) 2021 The Qt Company Ltd.
|
|
|
|
|
** Contact: https://www.qt.io/licensing/
|
|
|
|
|
**
|
|
|
|
|
** This file is part of Qt Creator.
|
|
|
|
|
**
|
|
|
|
|
** Commercial License Usage
|
|
|
|
|
** Licensees holding valid commercial Qt licenses may use this file in
|
|
|
|
|
** accordance with the commercial license agreement provided with the
|
|
|
|
|
** Software or, alternatively, in accordance with the terms contained in
|
|
|
|
|
** a written agreement between you and The Qt Company. For licensing terms
|
|
|
|
|
** and conditions see https://www.qt.io/terms-conditions. For further
|
|
|
|
|
** information use the contact form at https://www.qt.io/contact-us.
|
|
|
|
|
**
|
|
|
|
|
** GNU General Public License Usage
|
|
|
|
|
** Alternatively, this file may be used under the terms of the GNU
|
|
|
|
|
** General Public License version 3 as published by the Free Software
|
|
|
|
|
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
|
|
|
|
|
** included in the packaging of this file. Please review the following
|
|
|
|
|
** information to ensure the GNU General Public License requirements will
|
|
|
|
|
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
|
|
|
|
|
**
|
|
|
|
|
****************************************************************************/
|
|
|
|
|
|
|
|
|
|
#include "clangdclient.h"
|
|
|
|
|
|
2021-06-18 16:30:03 +02:00
|
|
|
#include "clangcompletioncontextanalyzer.h"
|
2022-04-28 12:10:53 +02:00
|
|
|
#include "clangconstants.h"
|
2022-05-18 18:15:41 +02:00
|
|
|
#include "clangdast.h"
|
2022-06-07 11:19:41 +02:00
|
|
|
#include "clangdfollowsymbol.h"
|
2022-05-02 07:02:30 +02:00
|
|
|
#include "clangdlocatorfilters.h"
|
2021-06-18 16:30:03 +02:00
|
|
|
#include "clangpreprocessorassistproposalitem.h"
|
2021-06-02 17:51:31 +02:00
|
|
|
#include "clangtextmark.h"
|
2021-07-14 17:07:34 +02:00
|
|
|
#include "clangutils.h"
|
2022-05-30 13:39:08 +02:00
|
|
|
#include "clangdsemantichighlighting.h"
|
|
|
|
|
#include "tasktimers.h"
|
2021-06-02 17:51:31 +02:00
|
|
|
|
2021-05-19 15:51:25 +02:00
|
|
|
#include <coreplugin/editormanager/editormanager.h>
|
2021-04-21 14:29:49 +02:00
|
|
|
#include <coreplugin/find/searchresultitem.h>
|
|
|
|
|
#include <coreplugin/find/searchresultwindow.h>
|
2021-12-02 13:18:02 +01:00
|
|
|
#include <cplusplus/AST.h>
|
|
|
|
|
#include <cplusplus/ASTPath.h>
|
2021-04-21 14:29:49 +02:00
|
|
|
#include <cplusplus/FindUsages.h>
|
2021-06-18 16:30:03 +02:00
|
|
|
#include <cplusplus/Icons.h>
|
|
|
|
|
#include <cplusplus/MatchingText.h>
|
|
|
|
|
#include <cppeditor/cppeditorconstants.h>
|
2021-08-30 10:58:08 +02:00
|
|
|
#include <cppeditor/cppcodemodelsettings.h>
|
2021-09-28 15:10:47 +02:00
|
|
|
#include <cppeditor/cppcompletionassistprocessor.h>
|
2021-09-13 16:09:04 +02:00
|
|
|
#include <cppeditor/cppcompletionassistprovider.h>
|
2021-08-30 10:58:08 +02:00
|
|
|
#include <cppeditor/cppdoxygen.h>
|
2021-09-01 18:08:54 +02:00
|
|
|
#include <cppeditor/cppeditorwidget.h>
|
2021-08-30 10:58:08 +02:00
|
|
|
#include <cppeditor/cppfindreferences.h>
|
|
|
|
|
#include <cppeditor/cppmodelmanager.h>
|
2022-02-03 10:36:40 +01:00
|
|
|
#include <cppeditor/cpprefactoringchanges.h>
|
2021-08-30 10:58:08 +02:00
|
|
|
#include <cppeditor/cpptoolsreuse.h>
|
|
|
|
|
#include <cppeditor/cppvirtualfunctionassistprovider.h>
|
|
|
|
|
#include <cppeditor/cppvirtualfunctionproposalitem.h>
|
|
|
|
|
#include <cppeditor/semantichighlighter.h>
|
2022-04-28 17:15:39 +02:00
|
|
|
#include <cppeditor/cppsemanticinfo.h>
|
2022-05-19 14:55:15 +02:00
|
|
|
#include <languageclient/diagnosticmanager.h>
|
|
|
|
|
#include <languageclient/documentsymbolcache.h>
|
|
|
|
|
#include <languageclient/languageclientcompletionassist.h>
|
|
|
|
|
#include <languageclient/languageclientfunctionhint.h>
|
|
|
|
|
#include <languageclient/languageclienthoverhandler.h>
|
2021-04-20 14:42:29 +02:00
|
|
|
#include <languageclient/languageclientinterface.h>
|
2021-11-01 07:25:07 +01:00
|
|
|
#include <languageclient/languageclientmanager.h>
|
2022-05-19 14:55:15 +02:00
|
|
|
#include <languageclient/languageclientquickfix.h>
|
|
|
|
|
#include <languageclient/languageclientsymbolsupport.h>
|
2021-06-02 17:51:31 +02:00
|
|
|
#include <languageclient/languageclientutils.h>
|
2022-05-19 14:55:15 +02:00
|
|
|
#include <languageserverprotocol/clientcapabilities.h>
|
|
|
|
|
#include <languageserverprotocol/progresssupport.h>
|
2021-05-19 13:22:49 +02:00
|
|
|
#include <projectexplorer/project.h>
|
2021-05-18 12:59:15 +02:00
|
|
|
#include <projectexplorer/projecttree.h>
|
|
|
|
|
#include <projectexplorer/session.h>
|
2022-04-28 12:10:53 +02:00
|
|
|
#include <projectexplorer/taskhub.h>
|
2021-05-18 12:59:15 +02:00
|
|
|
#include <texteditor/basefilefind.h>
|
2021-05-19 15:51:25 +02:00
|
|
|
#include <texteditor/codeassist/assistinterface.h>
|
|
|
|
|
#include <texteditor/codeassist/iassistprocessor.h>
|
|
|
|
|
#include <texteditor/codeassist/iassistprovider.h>
|
2021-06-18 16:30:03 +02:00
|
|
|
#include <texteditor/codeassist/textdocumentmanipulatorinterface.h>
|
|
|
|
|
#include <texteditor/texteditorsettings.h>
|
2021-05-19 15:51:25 +02:00
|
|
|
#include <texteditor/texteditor.h>
|
2021-05-18 12:59:15 +02:00
|
|
|
#include <utils/algorithm.h>
|
2022-02-01 17:39:00 +01:00
|
|
|
#include <utils/fileutils.h>
|
2021-11-16 14:12:41 +01:00
|
|
|
#include <utils/itemviews.h>
|
2021-06-09 09:47:26 +02:00
|
|
|
#include <utils/runextensions.h>
|
2021-11-16 14:12:41 +01:00
|
|
|
#include <utils/treemodel.h>
|
2021-11-10 14:44:41 +01:00
|
|
|
#include <utils/utilsicons.h>
|
2021-04-20 14:42:29 +02:00
|
|
|
|
2021-11-16 14:12:41 +01:00
|
|
|
#include <QAction>
|
2021-05-18 12:59:15 +02:00
|
|
|
#include <QCheckBox>
|
2021-10-01 12:23:05 +02:00
|
|
|
#include <QElapsedTimer>
|
2021-04-21 14:29:49 +02:00
|
|
|
#include <QFile>
|
|
|
|
|
#include <QHash>
|
2021-11-16 14:12:41 +01:00
|
|
|
#include <QHeaderView>
|
|
|
|
|
#include <QMenu>
|
2021-05-19 15:51:25 +02:00
|
|
|
#include <QPair>
|
2021-04-21 14:29:49 +02:00
|
|
|
#include <QPointer>
|
|
|
|
|
#include <QRegularExpression>
|
2021-11-16 14:12:41 +01:00
|
|
|
#include <QVBoxLayout>
|
|
|
|
|
#include <QWidget>
|
2021-04-21 14:29:49 +02:00
|
|
|
|
2021-11-16 14:12:41 +01:00
|
|
|
#include <cmath>
|
2021-05-19 15:51:25 +02:00
|
|
|
#include <set>
|
2021-06-09 09:47:26 +02:00
|
|
|
#include <unordered_map>
|
2021-10-06 13:27:23 +02:00
|
|
|
#include <utility>
|
2021-05-19 15:51:25 +02:00
|
|
|
|
2021-04-21 14:29:49 +02:00
|
|
|
using namespace CPlusPlus;
|
|
|
|
|
using namespace Core;
|
2021-04-20 14:42:29 +02:00
|
|
|
using namespace LanguageClient;
|
2021-04-20 15:46:35 +02:00
|
|
|
using namespace LanguageServerProtocol;
|
2021-05-18 12:59:15 +02:00
|
|
|
using namespace ProjectExplorer;
|
2021-09-28 13:21:59 +02:00
|
|
|
using namespace TextEditor;
|
2021-04-20 14:42:29 +02:00
|
|
|
|
|
|
|
|
namespace ClangCodeModel {
|
|
|
|
|
namespace Internal {
|
|
|
|
|
|
2022-06-07 11:19:41 +02:00
|
|
|
Q_LOGGING_CATEGORY(clangdLog, "qtc.clangcodemodel.clangd", QtWarningMsg);
|
2021-07-15 11:39:56 +02:00
|
|
|
static Q_LOGGING_CATEGORY(clangdLogServer, "qtc.clangcodemodel.clangd.server", QtWarningMsg);
|
|
|
|
|
static Q_LOGGING_CATEGORY(clangdLogAst, "qtc.clangcodemodel.clangd.ast", QtWarningMsg);
|
2021-10-15 11:31:13 +02:00
|
|
|
static Q_LOGGING_CATEGORY(clangdLogCompletion, "qtc.clangcodemodel.clangd.completion",
|
|
|
|
|
QtWarningMsg);
|
2021-04-20 15:46:35 +02:00
|
|
|
static QString indexingToken() { return "backgroundIndexProgress"; }
|
|
|
|
|
|
2022-05-18 18:15:41 +02:00
|
|
|
static Usage::Type getUsageType(const ClangdAstPath &path)
|
2021-04-21 14:29:49 +02:00
|
|
|
{
|
|
|
|
|
bool potentialWrite = false;
|
2021-12-09 17:59:10 +01:00
|
|
|
bool isFunction = false;
|
2021-04-21 14:29:49 +02:00
|
|
|
const bool symbolIsDataType = path.last().role() == "type" && path.last().kind() == "Record";
|
2021-12-09 17:59:10 +01:00
|
|
|
const auto isPotentialWrite = [&] { return potentialWrite && !isFunction; };
|
2021-04-21 14:29:49 +02:00
|
|
|
for (auto pathIt = path.rbegin(); pathIt != path.rend(); ++pathIt) {
|
|
|
|
|
if (pathIt->arcanaContains("non_odr_use_unevaluated"))
|
|
|
|
|
return Usage::Type::Other;
|
|
|
|
|
if (pathIt->kind() == "CXXDelete")
|
|
|
|
|
return Usage::Type::Write;
|
|
|
|
|
if (pathIt->kind() == "CXXNew")
|
|
|
|
|
return Usage::Type::Other;
|
|
|
|
|
if (pathIt->kind() == "Switch" || pathIt->kind() == "If")
|
|
|
|
|
return Usage::Type::Read;
|
2021-12-09 17:59:10 +01:00
|
|
|
if (pathIt->kind() == "Call")
|
|
|
|
|
return isFunction ? Usage::Type::Other
|
|
|
|
|
: potentialWrite ? Usage::Type::WritableRef : Usage::Type::Read;
|
|
|
|
|
if (pathIt->kind() == "CXXMemberCall") {
|
|
|
|
|
const auto children = pathIt->children();
|
|
|
|
|
if (children && children->size() == 1
|
|
|
|
|
&& children->first() == path.last()
|
|
|
|
|
&& children->first().arcanaContains("bound member function")) {
|
|
|
|
|
return Usage::Type::Other;
|
|
|
|
|
}
|
|
|
|
|
return isPotentialWrite() ? Usage::Type::WritableRef : Usage::Type::Read;
|
|
|
|
|
}
|
2021-04-21 14:29:49 +02:00
|
|
|
if ((pathIt->kind() == "DeclRef" || pathIt->kind() == "Member")
|
|
|
|
|
&& pathIt->arcanaContains("lvalue")) {
|
2021-12-09 17:59:10 +01:00
|
|
|
if (pathIt->arcanaContains(" Function "))
|
|
|
|
|
isFunction = true;
|
|
|
|
|
else
|
|
|
|
|
potentialWrite = true;
|
2021-04-21 14:29:49 +02:00
|
|
|
}
|
|
|
|
|
if (pathIt->role() == "declaration") {
|
|
|
|
|
if (symbolIsDataType)
|
|
|
|
|
return Usage::Type::Other;
|
|
|
|
|
if (pathIt->arcanaContains("cinit")) {
|
|
|
|
|
if (pathIt == path.rbegin())
|
|
|
|
|
return Usage::Type::Initialization;
|
|
|
|
|
if (pathIt->childContainsRange(0, path.last().range()))
|
|
|
|
|
return Usage::Type::Initialization;
|
2021-12-09 17:59:10 +01:00
|
|
|
if (isFunction)
|
|
|
|
|
return Usage::Type::Read;
|
2021-04-21 14:29:49 +02:00
|
|
|
if (!pathIt->hasConstType())
|
|
|
|
|
return Usage::Type::WritableRef;
|
|
|
|
|
return Usage::Type::Read;
|
|
|
|
|
}
|
|
|
|
|
return Usage::Type::Declaration;
|
|
|
|
|
}
|
|
|
|
|
if (pathIt->kind() == "MemberInitializer")
|
|
|
|
|
return pathIt == path.rbegin() ? Usage::Type::Write : Usage::Type::Read;
|
|
|
|
|
if (pathIt->kind() == "UnaryOperator"
|
|
|
|
|
&& (pathIt->detailIs("++") || pathIt->detailIs("--"))) {
|
|
|
|
|
return Usage::Type::Write;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// LLVM uses BinaryOperator only for built-in types; for classes, CXXOperatorCall
|
|
|
|
|
// is used. The latter has an additional node at index 0, so the left-hand side
|
|
|
|
|
// of an assignment is at index 1.
|
|
|
|
|
const bool isBinaryOp = pathIt->kind() == "BinaryOperator";
|
|
|
|
|
const bool isOpCall = pathIt->kind() == "CXXOperatorCall";
|
|
|
|
|
if (isBinaryOp || isOpCall) {
|
|
|
|
|
if (isOpCall && symbolIsDataType) // Constructor invocation.
|
|
|
|
|
return Usage::Type::Other;
|
|
|
|
|
|
|
|
|
|
const QString op = pathIt->operatorString();
|
|
|
|
|
if (op.endsWith("=") && op != "==") { // Assignment.
|
|
|
|
|
const int lhsIndex = isBinaryOp ? 0 : 1;
|
|
|
|
|
if (pathIt->childContainsRange(lhsIndex, path.last().range()))
|
|
|
|
|
return Usage::Type::Write;
|
2021-12-09 17:59:10 +01:00
|
|
|
return isPotentialWrite() ? Usage::Type::WritableRef : Usage::Type::Read;
|
2021-04-21 14:29:49 +02:00
|
|
|
}
|
|
|
|
|
return Usage::Type::Read;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (pathIt->kind() == "ImplicitCast") {
|
|
|
|
|
if (pathIt->detailIs("FunctionToPointerDecay"))
|
|
|
|
|
return Usage::Type::Other;
|
|
|
|
|
if (pathIt->hasConstType())
|
|
|
|
|
return Usage::Type::Read;
|
|
|
|
|
potentialWrite = true;
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Usage::Type::Other;
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-19 15:51:25 +02:00
|
|
|
class SymbolDetails : public JsonObject
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
using JsonObject::JsonObject;
|
|
|
|
|
|
|
|
|
|
static constexpr char usrKey[] = "usr";
|
|
|
|
|
|
|
|
|
|
// the unqualified name of the symbol
|
|
|
|
|
QString name() const { return typedValue<QString>(nameKey); }
|
|
|
|
|
|
|
|
|
|
// the enclosing namespace, class etc (without trailing ::)
|
|
|
|
|
// [NOTE: This is not true, the trailing colons are included]
|
|
|
|
|
QString containerName() const { return typedValue<QString>(containerNameKey); }
|
|
|
|
|
|
|
|
|
|
// the clang-specific “unified symbol resolution” identifier
|
|
|
|
|
QString usr() const { return typedValue<QString>(usrKey); }
|
|
|
|
|
|
|
|
|
|
// the clangd-specific opaque symbol ID
|
|
|
|
|
Utils::optional<QString> id() const { return optionalValue<QString>(idKey); }
|
|
|
|
|
|
|
|
|
|
bool isValid() const override
|
|
|
|
|
{
|
|
|
|
|
return contains(nameKey) && contains(containerNameKey) && contains(usrKey);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
class SymbolInfoRequest : public Request<LanguageClientArray<SymbolDetails>, std::nullptr_t, TextDocumentPositionParams>
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
using Request::Request;
|
|
|
|
|
explicit SymbolInfoRequest(const TextDocumentPositionParams ¶ms)
|
|
|
|
|
: Request("textDocument/symbolInfo", params) {}
|
|
|
|
|
};
|
|
|
|
|
|
2022-02-01 17:39:00 +01:00
|
|
|
void setupClangdConfigFile()
|
|
|
|
|
{
|
2022-05-16 16:40:29 +02:00
|
|
|
const Utils::FilePath targetConfigFile = CppEditor::ClangdSettings::clangdUserConfigFilePath();
|
|
|
|
|
const Utils::FilePath baseDir = targetConfigFile.parentDir();
|
2022-02-01 17:39:00 +01:00
|
|
|
baseDir.ensureWritableDir();
|
|
|
|
|
Utils::FileReader configReader;
|
|
|
|
|
const QByteArray firstLine = "# This file was generated by Qt Creator and will be overwritten "
|
|
|
|
|
"unless you remove this line.";
|
|
|
|
|
if (!configReader.fetch(targetConfigFile) || configReader.data().startsWith(firstLine)) {
|
|
|
|
|
Utils::FileSaver saver(targetConfigFile);
|
|
|
|
|
saver.write(firstLine + '\n');
|
|
|
|
|
saver.write("Hover:\n");
|
|
|
|
|
saver.write(" ShowAKA: Yes\n");
|
2022-05-16 16:50:38 +02:00
|
|
|
saver.write("Diagnostics:\n");
|
|
|
|
|
saver.write(" UnusedIncludes: Strict\n");
|
2022-02-01 17:39:00 +01:00
|
|
|
QTC_CHECK(saver.finalize());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-28 14:55:54 +02:00
|
|
|
static BaseClientInterface *clientInterface(Project *project, const Utils::FilePath &jsonDbDir)
|
2021-04-20 14:42:29 +02:00
|
|
|
{
|
2021-06-25 17:40:20 +02:00
|
|
|
QString indexingOption = "--background-index";
|
2021-08-30 10:58:08 +02:00
|
|
|
const CppEditor::ClangdSettings settings(CppEditor::ClangdProjectSettings(project).settings());
|
2021-10-29 16:46:34 +02:00
|
|
|
if (!settings.indexingEnabled() || jsonDbDir.isEmpty())
|
2021-06-25 17:40:20 +02:00
|
|
|
indexingOption += "=0";
|
2021-10-27 11:03:42 +02:00
|
|
|
const QString headerInsertionOption = QString("--header-insertion=")
|
|
|
|
|
+ (settings.autoIncludeHeaders() ? "iwyu" : "never");
|
|
|
|
|
Utils::CommandLine cmd{settings.clangdFilePath(), {indexingOption, headerInsertionOption,
|
2021-11-01 12:17:37 +01:00
|
|
|
"--limit-results=0", "--limit-references=0", "--clang-tidy=0"}};
|
2021-06-28 14:55:54 +02:00
|
|
|
if (settings.workerThreadLimit() != 0)
|
|
|
|
|
cmd.addArg("-j=" + QString::number(settings.workerThreadLimit()));
|
2021-04-20 14:42:29 +02:00
|
|
|
if (!jsonDbDir.isEmpty())
|
2021-04-30 08:25:10 +02:00
|
|
|
cmd.addArg("--compile-commands-dir=" + jsonDbDir.toString());
|
2021-07-15 11:39:56 +02:00
|
|
|
if (clangdLogServer().isDebugEnabled())
|
2021-04-30 08:25:10 +02:00
|
|
|
cmd.addArgs({"--log=verbose", "--pretty"});
|
2022-05-02 17:18:46 +02:00
|
|
|
cmd.addArg("--use-dirty-headers");
|
2021-04-20 14:42:29 +02:00
|
|
|
const auto interface = new StdIOClientInterface;
|
2021-04-30 08:25:10 +02:00
|
|
|
interface->setCommandLine(cmd);
|
2021-04-20 14:42:29 +02:00
|
|
|
return interface;
|
|
|
|
|
}
|
|
|
|
|
|
2021-04-21 14:29:49 +02:00
|
|
|
class ReferencesFileData {
|
|
|
|
|
public:
|
|
|
|
|
QList<QPair<Range, QString>> rangesAndLineText;
|
|
|
|
|
QString fileContent;
|
2022-05-18 18:15:41 +02:00
|
|
|
ClangdAstNode ast;
|
2021-04-21 14:29:49 +02:00
|
|
|
};
|
2021-05-18 12:59:15 +02:00
|
|
|
class ReplacementData {
|
|
|
|
|
public:
|
|
|
|
|
QString oldSymbolName;
|
|
|
|
|
QString newSymbolName;
|
|
|
|
|
QSet<Utils::FilePath> fileRenameCandidates;
|
|
|
|
|
};
|
2021-04-21 14:29:49 +02:00
|
|
|
class ReferencesData {
|
|
|
|
|
public:
|
|
|
|
|
QMap<DocumentUri, ReferencesFileData> fileData;
|
|
|
|
|
QList<MessageId> pendingAstRequests;
|
|
|
|
|
QPointer<SearchResult> search;
|
2021-05-18 12:59:15 +02:00
|
|
|
Utils::optional<ReplacementData> replacementData;
|
2021-04-21 14:29:49 +02:00
|
|
|
quint64 key;
|
2021-05-18 12:59:15 +02:00
|
|
|
bool canceled = false;
|
2021-08-30 10:58:08 +02:00
|
|
|
bool categorize = CppEditor::codeModelSettings()->categorizeFindReferences();
|
2021-04-21 14:29:49 +02:00
|
|
|
};
|
|
|
|
|
|
2021-05-31 15:57:44 +02:00
|
|
|
class SwitchDeclDefData {
|
|
|
|
|
public:
|
2021-09-28 13:21:59 +02:00
|
|
|
SwitchDeclDefData(quint64 id, TextDocument *doc, const QTextCursor &cursor,
|
2021-09-01 18:08:54 +02:00
|
|
|
CppEditor::CppEditorWidget *editorWidget,
|
2022-06-03 15:17:33 +02:00
|
|
|
const Utils::LinkHandler &callback)
|
2021-05-31 15:57:44 +02:00
|
|
|
: id(id), document(doc), uri(DocumentUri::fromFilePath(doc->filePath())),
|
2022-06-03 15:17:33 +02:00
|
|
|
cursor(cursor), editorWidget(editorWidget), callback(callback) {}
|
2021-05-31 15:57:44 +02:00
|
|
|
|
2022-05-18 18:15:41 +02:00
|
|
|
Utils::optional<ClangdAstNode> getFunctionNode() const
|
2021-05-31 15:57:44 +02:00
|
|
|
{
|
|
|
|
|
QTC_ASSERT(ast, return {});
|
|
|
|
|
|
2022-05-18 18:15:41 +02:00
|
|
|
const ClangdAstPath path = getAstPath(*ast, Range(cursor));
|
2021-05-31 15:57:44 +02:00
|
|
|
for (auto it = path.rbegin(); it != path.rend(); ++it) {
|
|
|
|
|
if (it->role() == "declaration"
|
|
|
|
|
&& (it->kind() == "CXXMethod" || it->kind() == "CXXConversion"
|
2022-06-20 13:25:01 +02:00
|
|
|
|| it->kind() == "CXXConstructor" || it->kind() == "CXXDestructor"
|
|
|
|
|
|| it->kind() == "Function")) {
|
2021-05-31 15:57:44 +02:00
|
|
|
return *it;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-18 18:15:41 +02:00
|
|
|
QTextCursor cursorForFunctionName(const ClangdAstNode &functionNode) const
|
2021-05-31 15:57:44 +02:00
|
|
|
{
|
|
|
|
|
QTC_ASSERT(docSymbols, return {});
|
|
|
|
|
|
|
|
|
|
const auto symbolList = Utils::get_if<QList<DocumentSymbol>>(&*docSymbols);
|
|
|
|
|
if (!symbolList)
|
|
|
|
|
return {};
|
|
|
|
|
const Range &astRange = functionNode.range();
|
|
|
|
|
QList symbolsToCheck = *symbolList;
|
|
|
|
|
while (!symbolsToCheck.isEmpty()) {
|
|
|
|
|
const DocumentSymbol symbol = symbolsToCheck.takeFirst();
|
|
|
|
|
if (symbol.range() == astRange)
|
|
|
|
|
return symbol.selectionRange().start().toTextCursor(document->document());
|
|
|
|
|
if (symbol.range().contains(astRange))
|
|
|
|
|
symbolsToCheck << symbol.children().value_or(QList<DocumentSymbol>());
|
|
|
|
|
}
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const quint64 id;
|
2021-09-28 13:21:59 +02:00
|
|
|
const QPointer<TextDocument> document;
|
2021-05-31 15:57:44 +02:00
|
|
|
const DocumentUri uri;
|
|
|
|
|
const QTextCursor cursor;
|
2021-09-01 18:08:54 +02:00
|
|
|
const QPointer<CppEditor::CppEditorWidget> editorWidget;
|
2022-06-03 14:58:37 +02:00
|
|
|
Utils::LinkHandler callback;
|
2021-05-31 15:57:44 +02:00
|
|
|
Utils::optional<DocumentSymbolsResult> docSymbols;
|
2022-05-18 18:15:41 +02:00
|
|
|
Utils::optional<ClangdAstNode> ast;
|
2021-05-31 15:57:44 +02:00
|
|
|
};
|
|
|
|
|
|
2021-06-01 18:14:12 +02:00
|
|
|
class LocalRefsData {
|
|
|
|
|
public:
|
2021-09-28 13:21:59 +02:00
|
|
|
LocalRefsData(quint64 id, TextDocument *doc, const QTextCursor &cursor,
|
2022-04-29 16:52:48 +02:00
|
|
|
CppEditor::RenameCallback &&callback)
|
2021-06-01 18:14:12 +02:00
|
|
|
: id(id), document(doc), cursor(cursor), callback(std::move(callback)),
|
|
|
|
|
uri(DocumentUri::fromFilePath(doc->filePath())), revision(doc->document()->revision())
|
|
|
|
|
{}
|
|
|
|
|
|
|
|
|
|
~LocalRefsData()
|
|
|
|
|
{
|
|
|
|
|
if (callback)
|
|
|
|
|
callback({}, {}, revision);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const quint64 id;
|
2021-09-28 13:21:59 +02:00
|
|
|
const QPointer<TextDocument> document;
|
2021-06-01 18:14:12 +02:00
|
|
|
const QTextCursor cursor;
|
2022-04-29 16:52:48 +02:00
|
|
|
CppEditor::RenameCallback callback;
|
2021-06-01 18:14:12 +02:00
|
|
|
const DocumentUri uri;
|
|
|
|
|
const int revision;
|
|
|
|
|
};
|
|
|
|
|
|
2021-06-02 17:51:31 +02:00
|
|
|
class DiagnosticsCapabilities : public JsonObject
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
using JsonObject::JsonObject;
|
|
|
|
|
void enableCategorySupport() { insert("categorySupport", true); }
|
|
|
|
|
void enableCodeActionsInline() {insert("codeActionsInline", true);}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
class ClangdTextDocumentClientCapabilities : public TextDocumentClientCapabilities
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
using TextDocumentClientCapabilities::TextDocumentClientCapabilities;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
void setPublishDiagnostics(const DiagnosticsCapabilities &caps)
|
|
|
|
|
{ insert("publishDiagnostics", caps); }
|
|
|
|
|
};
|
2021-05-19 15:51:25 +02:00
|
|
|
|
2021-09-28 15:10:47 +02:00
|
|
|
|
2021-11-10 12:35:06 +01:00
|
|
|
enum class CustomAssistMode { Doxygen, Preprocessor, IncludePath };
|
2021-09-28 15:10:47 +02:00
|
|
|
class CustomAssistProcessor : public IAssistProcessor
|
2021-06-18 16:30:03 +02:00
|
|
|
{
|
|
|
|
|
public:
|
2021-11-10 12:35:06 +01:00
|
|
|
CustomAssistProcessor(ClangdClient *client, int position, int endPos,
|
|
|
|
|
unsigned completionOperator, CustomAssistMode mode)
|
2021-09-15 11:35:19 +02:00
|
|
|
: m_client(client)
|
|
|
|
|
, m_position(position)
|
2021-11-10 12:35:06 +01:00
|
|
|
, m_endPos(endPos)
|
2021-09-15 11:35:19 +02:00
|
|
|
, m_completionOperator(completionOperator)
|
2021-09-28 15:10:47 +02:00
|
|
|
, m_mode(mode)
|
2021-09-15 11:35:19 +02:00
|
|
|
{}
|
2021-06-18 16:30:03 +02:00
|
|
|
|
|
|
|
|
private:
|
2021-09-28 15:10:47 +02:00
|
|
|
IAssistProposal *perform(const AssistInterface *interface) override
|
2021-06-18 16:30:03 +02:00
|
|
|
{
|
2021-09-28 13:21:59 +02:00
|
|
|
QList<AssistProposalItemInterface *> completions;
|
2021-09-28 15:10:47 +02:00
|
|
|
switch (m_mode) {
|
|
|
|
|
case CustomAssistMode::Doxygen:
|
|
|
|
|
for (int i = 1; i < CppEditor::T_DOXY_LAST_TAG; ++i) {
|
|
|
|
|
completions << createItem(QLatin1String(CppEditor::doxygenTagSpell(i)),
|
|
|
|
|
CPlusPlus::Icons::keywordIcon());
|
|
|
|
|
}
|
|
|
|
|
break;
|
2021-11-10 12:35:06 +01:00
|
|
|
case CustomAssistMode::Preprocessor: {
|
2021-09-28 15:10:47 +02:00
|
|
|
static QIcon macroIcon = Utils::CodeModelIcon::iconForType(Utils::CodeModelIcon::Macro);
|
|
|
|
|
for (const QString &completion
|
2021-10-08 10:15:51 +02:00
|
|
|
: CppEditor::CppCompletionAssistProcessor::preprocessorCompletions()) {
|
2021-09-28 15:10:47 +02:00
|
|
|
completions << createItem(completion, macroIcon);
|
|
|
|
|
}
|
2021-10-08 10:15:51 +02:00
|
|
|
if (CppEditor::ProjectFile::isObjC(interface->filePath().toString()))
|
|
|
|
|
completions << createItem("import", macroIcon);
|
|
|
|
|
break;
|
2021-06-18 16:30:03 +02:00
|
|
|
}
|
2021-11-10 12:35:06 +01:00
|
|
|
case ClangCodeModel::Internal::CustomAssistMode::IncludePath: {
|
|
|
|
|
HeaderPaths headerPaths;
|
|
|
|
|
const CppEditor::ProjectPart::ConstPtr projectPart
|
|
|
|
|
= projectPartForFile(interface->filePath().toString());
|
|
|
|
|
if (projectPart)
|
|
|
|
|
headerPaths = projectPart->headerPaths;
|
2022-04-27 16:02:08 +02:00
|
|
|
completions = completeInclude(m_endPos, m_completionOperator, interface, headerPaths);
|
2021-11-10 12:35:06 +01:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-09-28 13:21:59 +02:00
|
|
|
GenericProposalModelPtr model(new GenericProposalModel);
|
2021-06-18 16:30:03 +02:00
|
|
|
model->loadContent(completions);
|
2021-09-28 13:21:59 +02:00
|
|
|
const auto proposal = new GenericProposal(m_position, model);
|
2021-09-15 11:35:19 +02:00
|
|
|
if (m_client->testingEnabled()) {
|
|
|
|
|
emit m_client->proposalReady(proposal);
|
2021-06-18 16:30:03 +02:00
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
return proposal;
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-28 15:10:47 +02:00
|
|
|
AssistProposalItemInterface *createItem(const QString &text, const QIcon &icon) const
|
|
|
|
|
{
|
|
|
|
|
const auto item = new ClangPreprocessorAssistProposalItem;
|
|
|
|
|
item->setText(text);
|
|
|
|
|
item->setIcon(icon);
|
|
|
|
|
item->setCompletionOperator(m_completionOperator);
|
|
|
|
|
return item;
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-27 16:02:08 +02:00
|
|
|
/**
|
|
|
|
|
* @brief Creates completion proposals for #include and given cursor
|
|
|
|
|
* @param position - cursor placed after opening bracked or quote
|
|
|
|
|
* @param completionOperator - the type of token
|
|
|
|
|
* @param interface - relevant document data
|
|
|
|
|
* @param headerPaths - the include paths
|
|
|
|
|
* @return the list of completion items
|
|
|
|
|
*/
|
|
|
|
|
static QList<AssistProposalItemInterface *> completeInclude(
|
|
|
|
|
int position, unsigned completionOperator, const TextEditor::AssistInterface *interface,
|
|
|
|
|
const ProjectExplorer::HeaderPaths &headerPaths)
|
|
|
|
|
{
|
|
|
|
|
QTextCursor cursor(interface->textDocument());
|
|
|
|
|
cursor.setPosition(position);
|
|
|
|
|
QString directoryPrefix;
|
|
|
|
|
if (completionOperator == T_SLASH) {
|
|
|
|
|
QTextCursor c = cursor;
|
|
|
|
|
c.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
|
|
|
|
|
QString sel = c.selectedText();
|
|
|
|
|
int startCharPos = sel.indexOf(QLatin1Char('"'));
|
|
|
|
|
if (startCharPos == -1) {
|
|
|
|
|
startCharPos = sel.indexOf(QLatin1Char('<'));
|
|
|
|
|
completionOperator = T_ANGLE_STRING_LITERAL;
|
|
|
|
|
} else {
|
|
|
|
|
completionOperator = T_STRING_LITERAL;
|
|
|
|
|
}
|
|
|
|
|
if (startCharPos != -1)
|
|
|
|
|
directoryPrefix = sel.mid(startCharPos + 1, sel.length() - 1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Make completion for all relevant includes
|
|
|
|
|
ProjectExplorer::HeaderPaths allHeaderPaths = headerPaths;
|
|
|
|
|
const auto currentFilePath = ProjectExplorer::HeaderPath::makeUser(
|
|
|
|
|
interface->filePath().toFileInfo().path());
|
|
|
|
|
if (!allHeaderPaths.contains(currentFilePath))
|
|
|
|
|
allHeaderPaths.append(currentFilePath);
|
|
|
|
|
|
|
|
|
|
const ::Utils::MimeType mimeType = ::Utils::mimeTypeForName("text/x-c++hdr");
|
|
|
|
|
const QStringList suffixes = mimeType.suffixes();
|
|
|
|
|
|
|
|
|
|
QList<AssistProposalItemInterface *> completions;
|
2022-05-20 10:54:09 +02:00
|
|
|
for (const ProjectExplorer::HeaderPath &headerPath : qAsConst(allHeaderPaths)) {
|
2022-04-27 16:02:08 +02:00
|
|
|
QString realPath = headerPath.path;
|
|
|
|
|
if (!directoryPrefix.isEmpty()) {
|
|
|
|
|
realPath += QLatin1Char('/');
|
|
|
|
|
realPath += directoryPrefix;
|
|
|
|
|
if (headerPath.type == ProjectExplorer::HeaderPathType::Framework)
|
|
|
|
|
realPath += QLatin1String(".framework/Headers");
|
|
|
|
|
}
|
|
|
|
|
completions << completeIncludePath(realPath, suffixes, completionOperator);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
QList<QPair<AssistProposalItemInterface *, QString>> completionsForSorting;
|
|
|
|
|
for (AssistProposalItemInterface * const item : qAsConst(completions)) {
|
|
|
|
|
QString s = item->text();
|
|
|
|
|
s.replace('/', QChar(0)); // The dir separator should compare less than anything else.
|
|
|
|
|
completionsForSorting << qMakePair(item, s);
|
|
|
|
|
}
|
|
|
|
|
Utils::sort(completionsForSorting, [](const auto &left, const auto &right) {
|
|
|
|
|
return left.second < right.second;
|
|
|
|
|
});
|
|
|
|
|
for (int i = 0; i < completionsForSorting.count(); ++i)
|
|
|
|
|
completions[i] = completionsForSorting[i].first;
|
|
|
|
|
|
|
|
|
|
return completions;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @brief Finds #include completion proposals using given include path
|
|
|
|
|
* @param realPath - one of directories where compiler searches includes
|
|
|
|
|
* @param suffixes - file suffixes for C/C++ header files
|
|
|
|
|
* @return a list of matching completion items
|
|
|
|
|
*/
|
|
|
|
|
static QList<AssistProposalItemInterface *> completeIncludePath(
|
|
|
|
|
const QString &realPath, const QStringList &suffixes, unsigned completionOperator)
|
|
|
|
|
{
|
|
|
|
|
QList<AssistProposalItemInterface *> completions;
|
|
|
|
|
QDirIterator i(realPath, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
|
|
|
|
|
//: Parent folder for proposed #include completion
|
|
|
|
|
const QString hint = ClangdClient::tr("Location: %1")
|
|
|
|
|
.arg(QDir::toNativeSeparators(QDir::cleanPath(realPath)));
|
|
|
|
|
while (i.hasNext()) {
|
|
|
|
|
const QString fileName = i.next();
|
|
|
|
|
const QFileInfo fileInfo = i.fileInfo();
|
|
|
|
|
const QString suffix = fileInfo.suffix();
|
|
|
|
|
if (suffix.isEmpty() || suffixes.contains(suffix)) {
|
|
|
|
|
QString text = fileName.mid(realPath.length() + 1);
|
|
|
|
|
if (fileInfo.isDir())
|
|
|
|
|
text += QLatin1Char('/');
|
|
|
|
|
|
|
|
|
|
auto *item = new ClangPreprocessorAssistProposalItem;
|
|
|
|
|
item->setText(text);
|
|
|
|
|
item->setDetail(hint);
|
|
|
|
|
item->setIcon(CPlusPlus::Icons::keywordIcon());
|
|
|
|
|
item->setCompletionOperator(completionOperator);
|
|
|
|
|
completions.append(item);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return completions;
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-15 11:35:19 +02:00
|
|
|
ClangdClient * const m_client;
|
2021-06-18 16:30:03 +02:00
|
|
|
const int m_position;
|
2021-11-10 12:35:06 +01:00
|
|
|
const int m_endPos;
|
2021-06-18 16:30:03 +02:00
|
|
|
const unsigned m_completionOperator;
|
2021-09-28 15:10:47 +02:00
|
|
|
const CustomAssistMode m_mode;
|
2021-06-18 16:30:03 +02:00
|
|
|
};
|
|
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
static qint64 getRevision(const TextDocument *doc)
|
2021-09-27 16:24:37 +02:00
|
|
|
{
|
|
|
|
|
return doc->document()->revision();
|
|
|
|
|
}
|
|
|
|
|
static qint64 getRevision(const Utils::FilePath &fp)
|
|
|
|
|
{
|
|
|
|
|
return fp.lastModified().toMSecsSinceEpoch();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
template<typename DocType, typename DataType> class VersionedDocData
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
VersionedDocData(const DocType &doc, const DataType &data) :
|
|
|
|
|
revision(getRevision(doc)), data(data) {}
|
|
|
|
|
|
|
|
|
|
const qint64 revision;
|
|
|
|
|
const DataType data;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
template<typename DocType, typename DataType> class VersionedDataCache
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
void insert(const DocType &doc, const DataType &data)
|
|
|
|
|
{
|
|
|
|
|
m_data.emplace(std::make_pair(doc, VersionedDocData(doc, data)));
|
|
|
|
|
}
|
|
|
|
|
void remove(const DocType &doc) { m_data.erase(doc); }
|
|
|
|
|
Utils::optional<VersionedDocData<DocType, DataType>> take(const DocType &doc)
|
|
|
|
|
{
|
|
|
|
|
const auto it = m_data.find(doc);
|
|
|
|
|
if (it == m_data.end())
|
|
|
|
|
return {};
|
|
|
|
|
const auto data = it->second;
|
|
|
|
|
m_data.erase(it);
|
|
|
|
|
return data;
|
|
|
|
|
}
|
|
|
|
|
Utils::optional<DataType> get(const DocType &doc)
|
|
|
|
|
{
|
|
|
|
|
const auto it = m_data.find(doc);
|
|
|
|
|
if (it == m_data.end())
|
|
|
|
|
return {};
|
|
|
|
|
if (it->second.revision != getRevision(doc)) {
|
|
|
|
|
m_data.erase(it);
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
return it->second.data;
|
|
|
|
|
}
|
|
|
|
|
private:
|
|
|
|
|
std::unordered_map<DocType, VersionedDocData<DocType, DataType>> m_data;
|
|
|
|
|
};
|
|
|
|
|
|
2021-11-16 14:12:41 +01:00
|
|
|
class MemoryTreeModel;
|
|
|
|
|
class MemoryUsageWidget : public QWidget
|
|
|
|
|
{
|
|
|
|
|
Q_DECLARE_TR_FUNCTIONS(MemoryUsageWidget)
|
|
|
|
|
public:
|
|
|
|
|
MemoryUsageWidget(ClangdClient *client);
|
2022-02-09 09:58:48 +01:00
|
|
|
~MemoryUsageWidget();
|
2021-11-16 14:12:41 +01:00
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
void setupUi();
|
|
|
|
|
void getMemoryTree();
|
|
|
|
|
|
|
|
|
|
ClangdClient * const m_client;
|
|
|
|
|
MemoryTreeModel * const m_model;
|
|
|
|
|
Utils::TreeView m_view;
|
2022-02-09 09:58:48 +01:00
|
|
|
Utils::optional<MessageId> m_currentRequest;
|
2021-11-16 14:12:41 +01:00
|
|
|
};
|
|
|
|
|
|
2022-04-21 13:02:09 +02:00
|
|
|
class HighlightingData
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
// For all QPairs, the int member is the corresponding document version.
|
|
|
|
|
QPair<QList<ExpandedSemanticToken>, int> previousTokens;
|
|
|
|
|
|
|
|
|
|
// The ranges of symbols referring to virtual functions,
|
|
|
|
|
// as extracted by the highlighting procedure.
|
|
|
|
|
QPair<QList<Range>, int> virtualRanges;
|
|
|
|
|
|
|
|
|
|
// The highlighter is owned by its document.
|
|
|
|
|
CppEditor::SemanticHighlighter *highlighter = nullptr;
|
|
|
|
|
};
|
|
|
|
|
|
2021-04-21 14:29:49 +02:00
|
|
|
class ClangdClient::Private
|
|
|
|
|
{
|
|
|
|
|
public:
|
2021-07-01 04:17:54 +02:00
|
|
|
Private(ClangdClient *q, Project *project)
|
2021-08-30 10:58:08 +02:00
|
|
|
: q(q), settings(CppEditor::ClangdProjectSettings(project).settings()) {}
|
2021-04-21 14:29:49 +02:00
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
void findUsages(TextDocument *document, const QTextCursor &cursor,
|
2021-09-03 12:48:29 +02:00
|
|
|
const QString &searchTerm, const Utils::optional<QString> &replacement,
|
|
|
|
|
bool categorize);
|
2021-04-21 14:29:49 +02:00
|
|
|
void handleFindUsagesResult(quint64 key, const QList<Location> &locations);
|
2021-05-18 12:59:15 +02:00
|
|
|
static void handleRenameRequest(const SearchResult *search,
|
|
|
|
|
const ReplacementData &replacementData,
|
|
|
|
|
const QString &newSymbolName,
|
|
|
|
|
const QList<Core::SearchResultItem> &checkedItems,
|
|
|
|
|
bool preserveCase);
|
|
|
|
|
void addSearchResultsForFile(ReferencesData &refData, const Utils::FilePath &file,
|
2021-04-21 14:29:49 +02:00
|
|
|
const ReferencesFileData &fileData);
|
2021-05-18 12:59:15 +02:00
|
|
|
void reportAllSearchResultsAndFinish(ReferencesData &data);
|
2021-04-21 14:29:49 +02:00
|
|
|
void finishSearch(const ReferencesData &refData, bool canceled);
|
|
|
|
|
|
2021-05-31 15:57:44 +02:00
|
|
|
void handleDeclDefSwitchReplies();
|
|
|
|
|
|
2022-05-07 00:44:03 +03:00
|
|
|
Utils::optional<QString> getContainingFunctionName(const ClangdAstPath &astPath, const Range& range);
|
|
|
|
|
|
2021-12-02 13:18:02 +01:00
|
|
|
static CppEditor::CppEditorWidget *widgetFromDocument(const TextDocument *doc);
|
2021-06-01 18:14:12 +02:00
|
|
|
QString searchTermFromCursor(const QTextCursor &cursor) const;
|
2021-12-03 12:54:21 +01:00
|
|
|
QTextCursor adjustedCursor(const QTextCursor &cursor, const TextDocument *doc);
|
2021-06-01 18:14:12 +02:00
|
|
|
|
2021-06-04 12:40:26 +02:00
|
|
|
void setHelpItemForTooltip(const MessageId &token, const QString &fqn = {},
|
|
|
|
|
HelpItem::Category category = HelpItem::Unknown,
|
|
|
|
|
const QString &type = {});
|
|
|
|
|
|
2021-10-22 15:06:46 +02:00
|
|
|
void handleSemanticTokens(TextDocument *doc, const QList<ExpandedSemanticToken> &tokens,
|
2021-11-15 14:58:40 +01:00
|
|
|
int version, bool force);
|
2021-06-09 09:47:26 +02:00
|
|
|
|
2022-06-07 11:19:41 +02:00
|
|
|
MessageId getAndHandleAst(const TextDocOrFile &doc, const AstHandler &astHandler,
|
2021-10-07 10:58:54 +02:00
|
|
|
AstCallbackMode callbackMode, const Range &range = {});
|
2021-09-27 16:24:37 +02:00
|
|
|
|
2021-04-21 14:29:49 +02:00
|
|
|
ClangdClient * const q;
|
2021-08-30 10:58:08 +02:00
|
|
|
const CppEditor::ClangdSettings::Data settings;
|
2021-04-21 14:29:49 +02:00
|
|
|
QHash<quint64, ReferencesData> runningFindUsages;
|
2022-06-07 11:19:41 +02:00
|
|
|
ClangdFollowSymbol *followSymbol = nullptr;
|
2021-05-31 15:57:44 +02:00
|
|
|
Utils::optional<SwitchDeclDefData> switchDeclDefData;
|
2021-06-01 18:14:12 +02:00
|
|
|
Utils::optional<LocalRefsData> localRefsData;
|
2021-04-21 14:29:49 +02:00
|
|
|
Utils::optional<QVersionNumber> versionNumber;
|
2021-10-06 13:27:23 +02:00
|
|
|
|
2022-04-21 13:02:09 +02:00
|
|
|
QHash<TextDocument *, HighlightingData> highlightingData;
|
2022-02-08 11:49:37 +01:00
|
|
|
QHash<Utils::FilePath, CppEditor::BaseEditorDocumentParser::Configuration> parserConfigs;
|
2022-05-11 12:30:57 +02:00
|
|
|
QHash<Utils::FilePath, Tasks> issuePaneEntries;
|
2021-11-03 15:30:57 +01:00
|
|
|
|
2022-05-18 18:15:41 +02:00
|
|
|
VersionedDataCache<const TextDocument *, ClangdAstNode> astCache;
|
|
|
|
|
VersionedDataCache<Utils::FilePath, ClangdAstNode> externalAstCache;
|
2021-10-01 12:23:05 +02:00
|
|
|
TaskTimer highlightingTimer{"highlighting"};
|
2021-06-02 16:32:54 +02:00
|
|
|
quint64 nextJobId = 0;
|
2021-04-21 14:29:49 +02:00
|
|
|
bool isFullyIndexed = false;
|
|
|
|
|
bool isTesting = false;
|
|
|
|
|
};
|
|
|
|
|
|
2021-06-18 16:30:03 +02:00
|
|
|
class ClangdCompletionCapabilities : public TextDocumentClientCapabilities::CompletionCapabilities
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
explicit ClangdCompletionCapabilities(const JsonObject &object)
|
|
|
|
|
: TextDocumentClientCapabilities::CompletionCapabilities(object)
|
|
|
|
|
{
|
|
|
|
|
insert("editsNearCursor", true); // For dot-to-arrow correction.
|
2021-11-03 15:08:38 +01:00
|
|
|
if (Utils::optional<CompletionItemCapbilities> completionItemCaps = completionItem()) {
|
|
|
|
|
completionItemCaps->setSnippetSupport(false);
|
|
|
|
|
setCompletionItem(*completionItemCaps);
|
|
|
|
|
}
|
2021-06-18 16:30:03 +02:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2021-09-27 11:08:59 +02:00
|
|
|
class ClangdCompletionItem : public LanguageClientCompletionItem
|
2021-09-15 11:35:19 +02:00
|
|
|
{
|
2021-09-27 11:08:59 +02:00
|
|
|
public:
|
|
|
|
|
using LanguageClientCompletionItem::LanguageClientCompletionItem;
|
|
|
|
|
void apply(TextDocumentManipulatorInterface &manipulator,
|
|
|
|
|
int basePosition) const override;
|
2021-11-10 14:44:41 +01:00
|
|
|
|
|
|
|
|
enum class SpecialQtType { Signal, Slot, None };
|
|
|
|
|
static SpecialQtType getQtType(const CompletionItem &item);
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
QIcon icon() const override;
|
2022-06-17 09:48:54 +02:00
|
|
|
QString text() const override;
|
2021-09-15 11:35:19 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
class ClangdClient::ClangdCompletionAssistProcessor : public LanguageClientCompletionAssistProcessor
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
ClangdCompletionAssistProcessor(ClangdClient *client, const QString &snippetsGroup)
|
2021-09-27 11:08:59 +02:00
|
|
|
: LanguageClientCompletionAssistProcessor(client, snippetsGroup)
|
2021-09-15 11:35:19 +02:00
|
|
|
, m_client(client)
|
|
|
|
|
{
|
2022-03-04 19:42:46 +01:00
|
|
|
m_timer.start();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
~ClangdCompletionAssistProcessor()
|
|
|
|
|
{
|
|
|
|
|
qCDebug(clangdLogTiming).noquote().nospace()
|
|
|
|
|
<< "ClangdCompletionAssistProcessor took: " << m_timer.elapsed() << " ms";
|
2021-09-15 11:35:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private:
|
2021-09-28 13:21:59 +02:00
|
|
|
IAssistProposal *perform(const AssistInterface *interface) override
|
2021-09-15 11:35:19 +02:00
|
|
|
{
|
|
|
|
|
if (m_client->d->isTesting) {
|
2021-09-28 13:21:59 +02:00
|
|
|
setAsyncCompletionAvailableHandler([this](IAssistProposal *proposal) {
|
2021-09-15 11:35:19 +02:00
|
|
|
emit m_client->proposalReady(proposal);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
return LanguageClientCompletionAssistProcessor::perform(interface);
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-27 11:08:59 +02:00
|
|
|
QList<AssistProposalItemInterface *> generateCompletionItems(
|
|
|
|
|
const QList<LanguageServerProtocol::CompletionItem> &items) const override;
|
2021-09-15 11:35:19 +02:00
|
|
|
|
|
|
|
|
ClangdClient * const m_client;
|
2022-03-04 19:42:46 +01:00
|
|
|
QElapsedTimer m_timer;
|
2021-09-15 11:35:19 +02:00
|
|
|
};
|
|
|
|
|
|
2021-09-27 11:08:59 +02:00
|
|
|
QList<AssistProposalItemInterface *>
|
|
|
|
|
ClangdClient::ClangdCompletionAssistProcessor::generateCompletionItems(
|
|
|
|
|
const QList<LanguageServerProtocol::CompletionItem> &items) const
|
|
|
|
|
{
|
|
|
|
|
qCDebug(clangdLog) << "received" << items.count() << "completions";
|
|
|
|
|
|
|
|
|
|
auto itemGenerator = [](const QList<LanguageServerProtocol::CompletionItem> &items) {
|
|
|
|
|
return Utils::transform<QList<AssistProposalItemInterface *>>(
|
|
|
|
|
items, [](const LanguageServerProtocol::CompletionItem &item) {
|
|
|
|
|
return new ClangdCompletionItem(item);
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// If there are signals among the candidates, we employ the built-in code model to find out
|
|
|
|
|
// whether the cursor was on the second argument of a (dis)connect() call.
|
|
|
|
|
// If so, we offer only signals, as nothing else makes sense in that context.
|
|
|
|
|
static const auto criterion = [](const CompletionItem &ci) {
|
2021-11-10 14:44:41 +01:00
|
|
|
return ClangdCompletionItem::getQtType(ci) == ClangdCompletionItem::SpecialQtType::Signal;
|
2021-09-27 11:08:59 +02:00
|
|
|
};
|
|
|
|
|
const QTextDocument *doc = document();
|
|
|
|
|
const int pos = basePos();
|
|
|
|
|
if (!doc || pos < 0 || !Utils::anyOf(items, criterion))
|
|
|
|
|
return itemGenerator(items);
|
|
|
|
|
const QString content = doc->toPlainText();
|
|
|
|
|
const bool requiresSignal = CppEditor::CppModelManager::instance()
|
|
|
|
|
->positionRequiresSignal(filePath().toString(),
|
|
|
|
|
content.toUtf8(),
|
|
|
|
|
pos);
|
|
|
|
|
if (requiresSignal)
|
|
|
|
|
return itemGenerator(Utils::filtered(items, criterion));
|
|
|
|
|
return itemGenerator(items);
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-15 08:10:30 +02:00
|
|
|
class ClangdClient::ClangdCompletionAssistProvider : public LanguageClientCompletionAssistProvider
|
2021-09-13 16:09:04 +02:00
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
ClangdCompletionAssistProvider(ClangdClient *client);
|
|
|
|
|
|
|
|
|
|
private:
|
2021-10-08 10:15:51 +02:00
|
|
|
IAssistProcessor *createProcessor(const AssistInterface *interface) const override;
|
2021-09-15 08:10:30 +02:00
|
|
|
|
2021-09-13 16:09:04 +02:00
|
|
|
int activationCharSequenceLength() const override { return 3; }
|
|
|
|
|
bool isActivationCharSequence(const QString &sequence) const override;
|
|
|
|
|
bool isContinuationChar(const QChar &c) const override;
|
|
|
|
|
|
2021-10-08 10:15:51 +02:00
|
|
|
bool isInCommentOrString(const AssistInterface *interface) const;
|
|
|
|
|
|
2021-09-15 11:35:19 +02:00
|
|
|
ClangdClient * const m_client;
|
2021-09-13 16:09:04 +02:00
|
|
|
};
|
|
|
|
|
|
2022-01-31 13:10:28 +01:00
|
|
|
class ClangdQuickFixProcessor : public LanguageClientQuickFixAssistProcessor
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
ClangdQuickFixProcessor(LanguageClient::Client *client)
|
|
|
|
|
: LanguageClientQuickFixAssistProcessor(client)
|
|
|
|
|
{
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
IAssistProposal *perform(const AssistInterface *interface) override
|
|
|
|
|
{
|
|
|
|
|
m_interface = interface;
|
|
|
|
|
|
|
|
|
|
// Step 1: Collect clangd code actions asynchronously
|
|
|
|
|
LanguageClientQuickFixAssistProcessor::perform(interface);
|
|
|
|
|
|
|
|
|
|
// Step 2: Collect built-in quickfixes synchronously
|
|
|
|
|
m_builtinOps = CppEditor::quickFixOperations(interface);
|
|
|
|
|
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-13 14:57:08 +02:00
|
|
|
TextEditor::GenericProposal *handleCodeActionResult(const CodeActionResult &result) override
|
2022-01-31 13:10:28 +01:00
|
|
|
{
|
2022-05-13 14:57:08 +02:00
|
|
|
auto toOperation =
|
|
|
|
|
[=](const Utils::variant<Command, CodeAction> &item) -> QuickFixOperation * {
|
|
|
|
|
if (auto action = Utils::get_if<CodeAction>(&item)) {
|
|
|
|
|
const Utils::optional<QList<Diagnostic>> diagnostics = action->diagnostics();
|
|
|
|
|
if (!diagnostics.has_value() || diagnostics->isEmpty())
|
|
|
|
|
return new CodeActionQuickFixOperation(*action, client());
|
|
|
|
|
}
|
|
|
|
|
if (auto command = Utils::get_if<Command>(&item))
|
|
|
|
|
return new CommandQuickFixOperation(*command, client());
|
|
|
|
|
return nullptr;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (auto list = Utils::get_if<QList<Utils::variant<Command, CodeAction>>>(&result)) {
|
|
|
|
|
QuickFixOperations ops;
|
|
|
|
|
for (const Utils::variant<Command, CodeAction> &item : *list) {
|
|
|
|
|
if (QuickFixOperation *op = toOperation(item)) {
|
|
|
|
|
op->setDescription("clangd: " + op->description());
|
|
|
|
|
ops << op;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return GenericProposal::createProposal(m_interface, ops + m_builtinOps);
|
|
|
|
|
}
|
|
|
|
|
return nullptr;
|
2022-01-31 13:10:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
QuickFixOperations m_builtinOps;
|
|
|
|
|
const AssistInterface *m_interface = nullptr;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
class ClangdQuickFixProvider : public LanguageClientQuickFixProvider
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
ClangdQuickFixProvider(ClangdClient *client) : LanguageClientQuickFixProvider(client) {};
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
IAssistProcessor *createProcessor(const TextEditor::AssistInterface *) const override
|
|
|
|
|
{
|
|
|
|
|
return new ClangdQuickFixProcessor(client());
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2022-02-16 12:26:15 +01:00
|
|
|
static void addToCompilationDb(QJsonObject &cdb,
|
2022-05-05 17:34:31 +02:00
|
|
|
const CppEditor::ProjectPart &projectPart,
|
2022-05-05 15:50:46 +02:00
|
|
|
CppEditor::UsePrecompiledHeaders usePch,
|
2022-05-05 17:34:31 +02:00
|
|
|
const QJsonArray &projectPartOptions,
|
2022-02-16 12:26:15 +01:00
|
|
|
const Utils::FilePath &workingDir,
|
2022-05-05 15:36:58 +02:00
|
|
|
const CppEditor::ProjectFile &sourceFile)
|
2022-02-16 12:26:15 +01:00
|
|
|
{
|
2022-05-05 17:34:31 +02:00
|
|
|
QJsonArray args = clangOptionsForFile(sourceFile, projectPart, projectPartOptions, usePch);
|
2022-02-16 12:26:15 +01:00
|
|
|
|
|
|
|
|
// TODO: clangd seems to apply some heuristics depending on what we put here.
|
|
|
|
|
// Should we make use of them or keep using our own?
|
|
|
|
|
args.prepend("clang");
|
|
|
|
|
|
2022-05-05 15:36:58 +02:00
|
|
|
const QString fileString = Utils::FilePath::fromString(sourceFile.path).toUserOutput();
|
|
|
|
|
args.append(fileString);
|
2022-02-16 12:26:15 +01:00
|
|
|
QJsonObject value;
|
|
|
|
|
value.insert("workingDirectory", workingDir.toString());
|
2022-05-05 17:34:31 +02:00
|
|
|
value.insert("compilationCommand", args);
|
2022-05-05 15:36:58 +02:00
|
|
|
cdb.insert(fileString, value);
|
2022-02-16 12:26:15 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static void addCompilationDb(QJsonObject &parentObject, const QJsonObject &cdb)
|
|
|
|
|
{
|
|
|
|
|
parentObject.insert("compilationDatabaseChanges", cdb);
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-18 12:59:15 +02:00
|
|
|
ClangdClient::ClangdClient(Project *project, const Utils::FilePath &jsonDbDir)
|
2021-07-01 04:17:54 +02:00
|
|
|
: Client(clientInterface(project, jsonDbDir)), d(new Private(this, project))
|
2021-04-20 14:42:29 +02:00
|
|
|
{
|
|
|
|
|
setName(tr("clangd"));
|
|
|
|
|
LanguageFilter langFilter;
|
2021-06-04 09:43:22 +02:00
|
|
|
langFilter.mimeTypes = QStringList{"text/x-chdr", "text/x-csrc",
|
|
|
|
|
"text/x-c++hdr", "text/x-c++src", "text/x-objc++src", "text/x-objcsrc"};
|
2021-04-20 14:42:29 +02:00
|
|
|
setSupportedLanguage(langFilter);
|
2021-06-02 17:51:31 +02:00
|
|
|
setActivateDocumentAutomatically(true);
|
2021-10-15 10:40:02 +02:00
|
|
|
setLogTarget(LogTarget::Console);
|
2021-09-13 16:09:04 +02:00
|
|
|
setCompletionAssistProvider(new ClangdCompletionAssistProvider(this));
|
2022-01-31 13:10:28 +01:00
|
|
|
setQuickFixAssistProvider(new ClangdQuickFixProvider(this));
|
2021-07-14 17:07:34 +02:00
|
|
|
if (!project) {
|
|
|
|
|
QJsonObject initOptions;
|
2022-05-09 16:16:51 +02:00
|
|
|
const Utils::FilePath includeDir
|
|
|
|
|
= CppEditor::ClangdSettings(d->settings).clangdIncludePath();
|
2022-05-04 16:48:48 +02:00
|
|
|
CppEditor::CompilerOptionsBuilder optionsBuilder = clangOptionsBuilder(
|
|
|
|
|
*CppEditor::CppModelManager::instance()->fallbackProjectPart(),
|
2022-05-19 14:48:09 +02:00
|
|
|
warningsConfigForProject(nullptr), includeDir);
|
2022-05-05 15:50:46 +02:00
|
|
|
const CppEditor::UsePrecompiledHeaders usePch = CppEditor::getPchUsage();
|
2022-05-05 17:34:31 +02:00
|
|
|
const QJsonArray projectPartOptions = fullProjectPartOptions(
|
2022-05-19 14:48:09 +02:00
|
|
|
optionsBuilder, globalClangOptions());
|
2022-05-05 17:34:31 +02:00
|
|
|
const QJsonArray clangOptions = clangOptionsForFile({}, optionsBuilder.projectPart(),
|
|
|
|
|
projectPartOptions, usePch);
|
|
|
|
|
initOptions.insert("fallbackFlags", clangOptions);
|
2021-07-14 17:07:34 +02:00
|
|
|
setInitializationOptions(initOptions);
|
|
|
|
|
}
|
2021-11-01 07:25:07 +01:00
|
|
|
auto isRunningClangdClient = [](const LanguageClient::Client *c) {
|
|
|
|
|
return qobject_cast<const ClangdClient *>(c) && c->state() != Client::ShutdownRequested
|
|
|
|
|
&& c->state() != Client::Shutdown;
|
|
|
|
|
};
|
|
|
|
|
const QList<Client *> clients =
|
|
|
|
|
Utils::filtered(LanguageClientManager::clientsForProject(project), isRunningClangdClient);
|
|
|
|
|
QTC_CHECK(clients.isEmpty());
|
|
|
|
|
for (const Client *client : clients)
|
|
|
|
|
qCWarning(clangdLog) << client->name() << client->stateString();
|
2021-06-02 17:51:31 +02:00
|
|
|
ClientCapabilities caps = Client::defaultClientCapabilities();
|
|
|
|
|
Utils::optional<TextDocumentClientCapabilities> textCaps = caps.textDocument();
|
|
|
|
|
if (textCaps) {
|
|
|
|
|
ClangdTextDocumentClientCapabilities clangdTextCaps(*textCaps);
|
|
|
|
|
clangdTextCaps.clearDocumentHighlight();
|
|
|
|
|
DiagnosticsCapabilities diagnostics;
|
|
|
|
|
diagnostics.enableCategorySupport();
|
|
|
|
|
diagnostics.enableCodeActionsInline();
|
|
|
|
|
clangdTextCaps.setPublishDiagnostics(diagnostics);
|
2021-06-18 16:30:03 +02:00
|
|
|
Utils::optional<TextDocumentClientCapabilities::CompletionCapabilities> completionCaps
|
|
|
|
|
= textCaps->completion();
|
|
|
|
|
if (completionCaps)
|
|
|
|
|
clangdTextCaps.setCompletion(ClangdCompletionCapabilities(*completionCaps));
|
2021-06-02 17:51:31 +02:00
|
|
|
caps.setTextDocument(clangdTextCaps);
|
|
|
|
|
}
|
2021-04-20 14:42:29 +02:00
|
|
|
caps.clearExperimental();
|
|
|
|
|
setClientCapabilities(caps);
|
|
|
|
|
setLocatorsEnabled(false);
|
2021-08-11 11:20:42 +02:00
|
|
|
setAutoRequestCodeActions(false); // clangd sends code actions inside diagnostics
|
2022-02-15 15:34:41 +01:00
|
|
|
if (project) {
|
|
|
|
|
setProgressTitleForToken(indexingToken(),
|
|
|
|
|
tr("Indexing %1 with clangd").arg(project->displayName()));
|
|
|
|
|
}
|
2021-04-20 14:42:29 +02:00
|
|
|
setCurrentProject(project);
|
2021-08-12 12:00:58 +02:00
|
|
|
setDocumentChangeUpdateThreshold(d->settings.documentUpdateThreshold);
|
2021-09-30 13:19:50 +02:00
|
|
|
setSymbolStringifier(displayNameFromDocumentSymbol);
|
2021-10-22 15:06:46 +02:00
|
|
|
setSemanticTokensHandler([this](TextDocument *doc, const QList<ExpandedSemanticToken> &tokens,
|
2021-11-15 14:58:40 +01:00
|
|
|
int version, bool force) {
|
|
|
|
|
d->handleSemanticTokens(doc, tokens, version, force);
|
2021-06-09 09:47:26 +02:00
|
|
|
});
|
2021-06-04 12:40:26 +02:00
|
|
|
hoverHandler()->setHelpItemProvider([this](const HoverRequest::Response &response,
|
|
|
|
|
const DocumentUri &uri) {
|
|
|
|
|
gatherHelpItemForTooltip(response, uri);
|
|
|
|
|
});
|
|
|
|
|
|
2021-07-19 14:49:08 +02:00
|
|
|
connect(this, &Client::workDone, this,
|
|
|
|
|
[this, p = QPointer(project)](const ProgressToken &token) {
|
2021-04-20 15:46:35 +02:00
|
|
|
const QString * const val = Utils::get_if<QString>(&token);
|
2021-04-21 14:29:49 +02:00
|
|
|
if (val && *val == indexingToken()) {
|
|
|
|
|
d->isFullyIndexed = true;
|
|
|
|
|
emit indexingFinished();
|
2021-05-19 13:22:49 +02:00
|
|
|
#ifdef WITH_TESTS
|
2021-07-19 14:49:08 +02:00
|
|
|
if (p)
|
|
|
|
|
emit p->indexingFinished("Indexer.Clangd");
|
2021-05-19 13:22:49 +02:00
|
|
|
#endif
|
2021-04-21 14:29:49 +02:00
|
|
|
}
|
2021-04-20 15:46:35 +02:00
|
|
|
});
|
2021-04-21 14:29:49 +02:00
|
|
|
|
|
|
|
|
connect(this, &Client::initialized, this, [this] {
|
2022-05-02 07:02:30 +02:00
|
|
|
auto currentDocumentFilter = static_cast<ClangdCurrentDocumentFilter *>(
|
|
|
|
|
CppEditor::CppModelManager::instance()->currentDocumentFilter());
|
|
|
|
|
currentDocumentFilter->updateCurrentClient();
|
2021-04-21 14:29:49 +02:00
|
|
|
// If we get this signal while there are pending searches, it means that
|
|
|
|
|
// the client was re-initialized, i.e. clangd crashed.
|
|
|
|
|
|
|
|
|
|
// Report all search results found so far.
|
|
|
|
|
for (quint64 key : d->runningFindUsages.keys())
|
2021-05-18 12:59:15 +02:00
|
|
|
d->reportAllSearchResultsAndFinish(d->runningFindUsages[key]);
|
2021-04-21 14:29:49 +02:00
|
|
|
QTC_CHECK(d->runningFindUsages.isEmpty());
|
|
|
|
|
});
|
|
|
|
|
|
2021-05-31 15:57:44 +02:00
|
|
|
connect(documentSymbolCache(), &DocumentSymbolCache::gotSymbols, this,
|
|
|
|
|
[this](const DocumentUri &uri, const DocumentSymbolsResult &symbols) {
|
|
|
|
|
if (!d->switchDeclDefData || d->switchDeclDefData->uri != uri)
|
|
|
|
|
return;
|
|
|
|
|
d->switchDeclDefData->docSymbols = symbols;
|
|
|
|
|
if (d->switchDeclDefData->ast)
|
|
|
|
|
d->handleDeclDefSwitchReplies();
|
|
|
|
|
});
|
|
|
|
|
|
2021-04-20 14:42:29 +02:00
|
|
|
start();
|
|
|
|
|
}
|
|
|
|
|
|
2021-04-21 14:29:49 +02:00
|
|
|
ClangdClient::~ClangdClient()
|
|
|
|
|
{
|
2022-06-07 11:19:41 +02:00
|
|
|
if (d->followSymbol)
|
|
|
|
|
d->followSymbol->clear();
|
2021-04-21 14:29:49 +02:00
|
|
|
delete d;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bool ClangdClient::isFullyIndexed() const { return d->isFullyIndexed; }
|
|
|
|
|
|
|
|
|
|
void ClangdClient::openExtraFile(const Utils::FilePath &filePath, const QString &content)
|
|
|
|
|
{
|
|
|
|
|
QFile cxxFile(filePath.toString());
|
|
|
|
|
if (content.isEmpty() && !cxxFile.open(QIODevice::ReadOnly))
|
|
|
|
|
return;
|
|
|
|
|
TextDocumentItem item;
|
|
|
|
|
item.setLanguageId("cpp");
|
|
|
|
|
item.setUri(DocumentUri::fromFilePath(filePath));
|
|
|
|
|
item.setText(!content.isEmpty() ? content : QString::fromUtf8(cxxFile.readAll()));
|
|
|
|
|
item.setVersion(0);
|
2022-05-12 09:51:39 +02:00
|
|
|
sendMessage(DidOpenTextDocumentNotification(DidOpenTextDocumentParams(item)),
|
2021-07-08 12:23:12 +02:00
|
|
|
SendDocUpdates::Ignore);
|
2021-04-21 14:29:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ClangdClient::closeExtraFile(const Utils::FilePath &filePath)
|
|
|
|
|
{
|
2022-05-12 09:51:39 +02:00
|
|
|
sendMessage(DidCloseTextDocumentNotification(DidCloseTextDocumentParams(
|
2021-07-08 12:23:12 +02:00
|
|
|
TextDocumentIdentifier{DocumentUri::fromFilePath(filePath)})),
|
|
|
|
|
SendDocUpdates::Ignore);
|
2021-04-21 14:29:49 +02:00
|
|
|
}
|
|
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
void ClangdClient::findUsages(TextDocument *document, const QTextCursor &cursor,
|
2021-05-18 12:59:15 +02:00
|
|
|
const Utils::optional<QString> &replacement)
|
2021-04-21 14:29:49 +02:00
|
|
|
{
|
2021-08-02 18:03:34 +02:00
|
|
|
// Quick check: Are we even on anything searchable?
|
2022-06-09 13:24:33 +02:00
|
|
|
const QTextCursor adjustedCursor = d->adjustedCursor(cursor, document);
|
|
|
|
|
const QString searchTerm = d->searchTermFromCursor(adjustedCursor);
|
2021-10-28 10:23:55 +02:00
|
|
|
if (searchTerm.isEmpty())
|
2021-04-21 14:29:49 +02:00
|
|
|
return;
|
|
|
|
|
|
2021-10-28 10:23:55 +02:00
|
|
|
const bool categorize = CppEditor::codeModelSettings()->categorizeFindReferences();
|
|
|
|
|
|
|
|
|
|
// If it's a "normal" symbol, go right ahead.
|
|
|
|
|
if (searchTerm != "operator" && Utils::allOf(searchTerm, [](const QChar &c) {
|
|
|
|
|
return c.isLetterOrNumber() || c == '_';
|
|
|
|
|
})) {
|
2021-12-02 13:18:02 +01:00
|
|
|
d->findUsages(document, adjustedCursor, searchTerm, replacement, categorize);
|
2021-10-28 10:23:55 +02:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Otherwise get the proper spelling of the search term from clang, so we can put it into the
|
2021-08-02 18:03:34 +02:00
|
|
|
// search widget.
|
2022-06-07 11:19:41 +02:00
|
|
|
const auto symbolInfoHandler = [this, doc = QPointer(document), adjustedCursor, replacement, categorize]
|
|
|
|
|
(const QString &, const QString &name, const MessageId &) {
|
2021-08-02 18:03:34 +02:00
|
|
|
if (!doc)
|
|
|
|
|
return;
|
2022-06-07 11:19:41 +02:00
|
|
|
if (name.isEmpty())
|
2021-08-02 18:03:34 +02:00
|
|
|
return;
|
2022-06-07 11:19:41 +02:00
|
|
|
d->findUsages(doc.data(), adjustedCursor, name, replacement, categorize);
|
|
|
|
|
};
|
|
|
|
|
requestSymbolInfo(document->filePath(), Range(adjustedCursor).start(), symbolInfoHandler);
|
2021-08-02 18:03:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ClangdClient::handleDiagnostics(const PublishDiagnosticsParams ¶ms)
|
|
|
|
|
{
|
|
|
|
|
const DocumentUri &uri = params.uri();
|
|
|
|
|
Client::handleDiagnostics(params);
|
2021-09-08 13:24:45 +02:00
|
|
|
const int docVersion = documentVersion(uri.toFilePath());
|
|
|
|
|
if (params.version().value_or(docVersion) != docVersion)
|
|
|
|
|
return;
|
2021-08-02 18:03:34 +02:00
|
|
|
for (const Diagnostic &diagnostic : params.diagnostics()) {
|
|
|
|
|
const ClangdDiagnostic clangdDiagnostic(diagnostic);
|
2022-05-17 12:34:00 +02:00
|
|
|
auto codeActions = clangdDiagnostic.codeActions();
|
2022-02-04 10:59:11 +01:00
|
|
|
if (codeActions && !codeActions->isEmpty()) {
|
2022-05-17 12:34:00 +02:00
|
|
|
for (CodeAction &action : *codeActions)
|
2022-05-13 08:35:01 +02:00
|
|
|
action.setDiagnostics({diagnostic});
|
2022-05-17 12:34:00 +02:00
|
|
|
LanguageClient::updateCodeActionRefactoringMarker(this, *codeActions, uri);
|
2022-02-04 10:59:11 +01:00
|
|
|
} else {
|
|
|
|
|
// We know that there's only one kind of diagnostic for which clangd has
|
|
|
|
|
// a quickfix tweak, so let's not be wasteful.
|
|
|
|
|
const Diagnostic::Code code = diagnostic.code().value_or(Diagnostic::Code());
|
|
|
|
|
const QString * const codeString = Utils::get_if<QString>(&code);
|
|
|
|
|
if (codeString && *codeString == "-Wswitch")
|
|
|
|
|
requestCodeActions(uri, diagnostic);
|
|
|
|
|
}
|
2021-08-02 18:03:34 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
void ClangdClient::handleDocumentOpened(TextDocument *doc)
|
2021-09-27 16:24:37 +02:00
|
|
|
{
|
|
|
|
|
const auto data = d->externalAstCache.take(doc->filePath());
|
|
|
|
|
if (!data)
|
|
|
|
|
return;
|
|
|
|
|
if (data->revision == getRevision(doc->filePath()))
|
|
|
|
|
d->astCache.insert(doc, data->data);
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
void ClangdClient::handleDocumentClosed(TextDocument *doc)
|
2021-08-02 18:03:34 +02:00
|
|
|
{
|
2022-04-21 13:02:09 +02:00
|
|
|
d->highlightingData.remove(doc);
|
2021-09-27 16:24:37 +02:00
|
|
|
d->astCache.remove(doc);
|
2022-02-08 11:49:37 +01:00
|
|
|
d->parserConfigs.remove(doc->filePath());
|
2021-08-02 18:03:34 +02:00
|
|
|
}
|
|
|
|
|
|
2021-12-02 13:18:02 +01:00
|
|
|
QTextCursor ClangdClient::adjustedCursorForHighlighting(const QTextCursor &cursor,
|
|
|
|
|
TextEditor::TextDocument *doc)
|
|
|
|
|
{
|
2021-12-03 12:54:21 +01:00
|
|
|
return d->adjustedCursor(cursor, doc);
|
2021-12-02 13:18:02 +01:00
|
|
|
}
|
|
|
|
|
|
2021-11-16 14:12:41 +01:00
|
|
|
const LanguageClient::Client::CustomInspectorTabs ClangdClient::createCustomInspectorTabs()
|
|
|
|
|
{
|
|
|
|
|
return {std::make_pair(new MemoryUsageWidget(this), tr("Memory Usage"))};
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-01 07:34:49 +02:00
|
|
|
class ClangdDiagnosticManager : public LanguageClient::DiagnosticManager
|
|
|
|
|
{
|
|
|
|
|
using LanguageClient::DiagnosticManager::DiagnosticManager;
|
|
|
|
|
|
2022-05-11 12:30:57 +02:00
|
|
|
ClangdClient *getClient() const { return qobject_cast<ClangdClient *>(client()); }
|
|
|
|
|
|
|
|
|
|
bool isCurrentDocument(const Utils::FilePath &filePath) const
|
|
|
|
|
{
|
|
|
|
|
const IDocument * const doc = EditorManager::currentDocument();
|
|
|
|
|
return doc && doc->filePath() == filePath;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void showDiagnostics(const DocumentUri &uri, int version) override
|
|
|
|
|
{
|
|
|
|
|
const Utils::FilePath filePath = uri.toFilePath();
|
|
|
|
|
getClient()->clearTasks(filePath);
|
|
|
|
|
DiagnosticManager::showDiagnostics(uri, version);
|
|
|
|
|
if (isCurrentDocument(filePath))
|
|
|
|
|
getClient()->switchIssuePaneEntries(filePath);
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-01 07:34:49 +02:00
|
|
|
void hideDiagnostics(const Utils::FilePath &filePath) override
|
|
|
|
|
{
|
|
|
|
|
DiagnosticManager::hideDiagnostics(filePath);
|
2022-05-11 12:30:57 +02:00
|
|
|
if (isCurrentDocument(filePath))
|
|
|
|
|
TaskHub::clearTasks(Constants::TASK_CATEGORY_DIAGNOSTICS);
|
2022-04-01 07:34:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
QList<Diagnostic> filteredDiagnostics(const QList<Diagnostic> &diagnostics) const override
|
|
|
|
|
{
|
|
|
|
|
return Utils::filtered(diagnostics, [](const Diagnostic &diag){
|
|
|
|
|
const Diagnostic::Code code = diag.code().value_or(Diagnostic::Code());
|
|
|
|
|
const QString * const codeString = Utils::get_if<QString>(&code);
|
|
|
|
|
return !codeString || *codeString != "drv_unknown_argument";
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
TextMark *createTextMark(const Utils::FilePath &filePath,
|
|
|
|
|
const Diagnostic &diagnostic,
|
|
|
|
|
bool isProjectFile) const override
|
|
|
|
|
{
|
2022-05-11 12:30:57 +02:00
|
|
|
return new ClangdTextMark(filePath, diagnostic, isProjectFile, getClient());
|
2022-04-01 07:34:49 +02:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
DiagnosticManager *ClangdClient::createDiagnosticManager()
|
|
|
|
|
{
|
|
|
|
|
auto diagnosticManager = new ClangdDiagnosticManager(this);
|
|
|
|
|
if (d->isTesting) {
|
|
|
|
|
connect(diagnosticManager, &DiagnosticManager::textMarkCreated,
|
|
|
|
|
this, &ClangdClient::textMarkCreated);
|
|
|
|
|
}
|
|
|
|
|
return diagnosticManager;
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-03 10:36:40 +01:00
|
|
|
RefactoringChangesData *ClangdClient::createRefactoringChangesBackend() const
|
|
|
|
|
{
|
|
|
|
|
return new CppEditor::CppRefactoringChangesData(
|
|
|
|
|
CppEditor::CppModelManager::instance()->snapshot());
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-02 18:03:34 +02:00
|
|
|
QVersionNumber ClangdClient::versionNumber() const
|
|
|
|
|
{
|
|
|
|
|
if (d->versionNumber)
|
|
|
|
|
return d->versionNumber.value();
|
|
|
|
|
|
|
|
|
|
const QRegularExpression versionPattern("^clangd version (\\d+)\\.(\\d+)\\.(\\d+).*$");
|
|
|
|
|
QTC_CHECK(versionPattern.isValid());
|
|
|
|
|
const QRegularExpressionMatch match = versionPattern.match(serverVersion());
|
|
|
|
|
if (match.isValid()) {
|
|
|
|
|
d->versionNumber.emplace({match.captured(1).toInt(), match.captured(2).toInt(),
|
|
|
|
|
match.captured(3).toInt()});
|
|
|
|
|
} else {
|
|
|
|
|
qCWarning(clangdLog) << "Failed to parse clangd server string" << serverVersion();
|
|
|
|
|
d->versionNumber.emplace({0});
|
|
|
|
|
}
|
|
|
|
|
return d->versionNumber.value();
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-30 10:58:08 +02:00
|
|
|
CppEditor::ClangdSettings::Data ClangdClient::settingsData() const { return d->settings; }
|
2021-08-02 18:03:34 +02:00
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
void ClangdClient::Private::findUsages(TextDocument *document,
|
2021-08-02 18:03:34 +02:00
|
|
|
const QTextCursor &cursor, const QString &searchTerm,
|
2021-09-03 12:48:29 +02:00
|
|
|
const Utils::optional<QString> &replacement, bool categorize)
|
2021-08-02 18:03:34 +02:00
|
|
|
{
|
2021-04-21 14:29:49 +02:00
|
|
|
ReferencesData refData;
|
2021-08-02 18:03:34 +02:00
|
|
|
refData.key = nextJobId++;
|
2021-09-03 12:48:29 +02:00
|
|
|
refData.categorize = categorize;
|
2021-05-18 12:59:15 +02:00
|
|
|
if (replacement) {
|
|
|
|
|
ReplacementData replacementData;
|
|
|
|
|
replacementData.oldSymbolName = searchTerm;
|
|
|
|
|
replacementData.newSymbolName = *replacement;
|
|
|
|
|
if (replacementData.newSymbolName.isEmpty())
|
|
|
|
|
replacementData.newSymbolName = replacementData.oldSymbolName;
|
|
|
|
|
refData.replacementData = replacementData;
|
|
|
|
|
}
|
2021-08-02 18:03:34 +02:00
|
|
|
|
2021-04-21 14:29:49 +02:00
|
|
|
refData.search = SearchResultWindow::instance()->startNewSearch(
|
|
|
|
|
tr("C++ Usages:"),
|
|
|
|
|
{},
|
|
|
|
|
searchTerm,
|
2021-05-18 12:59:15 +02:00
|
|
|
replacement ? SearchResultWindow::SearchAndReplace : SearchResultWindow::SearchOnly,
|
2021-04-21 14:29:49 +02:00
|
|
|
SearchResultWindow::PreserveCaseDisabled,
|
|
|
|
|
"CppEditor");
|
2021-05-26 17:24:18 +02:00
|
|
|
if (refData.categorize)
|
2021-08-30 10:58:08 +02:00
|
|
|
refData.search->setFilter(new CppEditor::CppSearchResultFilter);
|
2021-05-18 12:59:15 +02:00
|
|
|
if (refData.replacementData) {
|
|
|
|
|
refData.search->setTextToReplace(refData.replacementData->newSymbolName);
|
|
|
|
|
const auto renameFilesCheckBox = new QCheckBox;
|
|
|
|
|
renameFilesCheckBox->setVisible(false);
|
|
|
|
|
refData.search->setAdditionalReplaceWidget(renameFilesCheckBox);
|
|
|
|
|
const auto renameHandler =
|
|
|
|
|
[search = refData.search](const QString &newSymbolName,
|
|
|
|
|
const QList<SearchResultItem> &checkedItems,
|
|
|
|
|
bool preserveCase) {
|
|
|
|
|
const auto replacementData = search->userData().value<ReplacementData>();
|
|
|
|
|
Private::handleRenameRequest(search, replacementData, newSymbolName, checkedItems,
|
|
|
|
|
preserveCase);
|
|
|
|
|
};
|
|
|
|
|
connect(refData.search, &SearchResult::replaceButtonClicked, renameHandler);
|
|
|
|
|
}
|
2021-04-21 14:29:49 +02:00
|
|
|
connect(refData.search, &SearchResult::activated, [](const SearchResultItem& item) {
|
|
|
|
|
Core::EditorManager::openEditorAtSearchResult(item);
|
|
|
|
|
});
|
|
|
|
|
SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
|
2021-08-02 18:03:34 +02:00
|
|
|
runningFindUsages.insert(refData.key, refData);
|
2021-04-21 14:29:49 +02:00
|
|
|
|
2021-08-02 18:03:34 +02:00
|
|
|
const Utils::optional<MessageId> requestId = q->symbolSupport().findUsages(
|
2021-04-21 14:29:49 +02:00
|
|
|
document, cursor, [this, key = refData.key](const QList<Location> &locations) {
|
2021-08-02 18:03:34 +02:00
|
|
|
handleFindUsagesResult(key, locations);
|
2021-04-21 14:29:49 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!requestId) {
|
2021-08-02 18:03:34 +02:00
|
|
|
finishSearch(refData, false);
|
2021-04-21 14:29:49 +02:00
|
|
|
return;
|
|
|
|
|
}
|
2021-08-02 18:03:34 +02:00
|
|
|
QObject::connect(refData.search, &SearchResult::cancelled, q, [this, requestId, key = refData.key] {
|
|
|
|
|
const auto refData = runningFindUsages.find(key);
|
|
|
|
|
if (refData == runningFindUsages.end())
|
2021-04-21 14:29:49 +02:00
|
|
|
return;
|
2021-08-02 18:03:34 +02:00
|
|
|
q->cancelRequest(*requestId);
|
2021-05-18 12:59:15 +02:00
|
|
|
refData->canceled = true;
|
2021-08-02 18:03:34 +02:00
|
|
|
refData->search->disconnect(q);
|
|
|
|
|
finishSearch(*refData, true);
|
2021-04-21 14:29:49 +02:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-18 16:30:03 +02:00
|
|
|
void ClangdClient::enableTesting()
|
|
|
|
|
{
|
|
|
|
|
d->isTesting = true;
|
2021-09-15 11:35:19 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bool ClangdClient::testingEnabled() const
|
|
|
|
|
{
|
|
|
|
|
return d->isTesting;
|
2021-06-18 16:30:03 +02:00
|
|
|
}
|
|
|
|
|
|
2021-09-30 13:19:50 +02:00
|
|
|
QString ClangdClient::displayNameFromDocumentSymbol(SymbolKind kind, const QString &name,
|
|
|
|
|
const QString &detail)
|
|
|
|
|
{
|
|
|
|
|
switch (kind) {
|
|
|
|
|
case SymbolKind::Constructor:
|
|
|
|
|
return name + detail;
|
|
|
|
|
case SymbolKind::Method:
|
2022-05-25 17:33:01 +02:00
|
|
|
case SymbolKind::Function: {
|
|
|
|
|
const int lastParenOffset = detail.lastIndexOf(')');
|
|
|
|
|
if (lastParenOffset == -1)
|
2021-09-30 13:19:50 +02:00
|
|
|
return name;
|
2022-05-25 17:33:01 +02:00
|
|
|
int leftParensNeeded = 1;
|
|
|
|
|
int i = -1;
|
|
|
|
|
for (i = lastParenOffset - 1; i >= 0; --i) {
|
|
|
|
|
switch (detail.at(i).toLatin1()) {
|
|
|
|
|
case ')':
|
|
|
|
|
++leftParensNeeded;
|
|
|
|
|
break;
|
|
|
|
|
case '(':
|
|
|
|
|
--leftParensNeeded;
|
|
|
|
|
break;
|
|
|
|
|
default:
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
if (leftParensNeeded == 0)
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
if (leftParensNeeded > 0)
|
|
|
|
|
return name;
|
|
|
|
|
return name + detail.mid(i) + " -> " + detail.left(i);
|
2021-09-30 13:19:50 +02:00
|
|
|
}
|
|
|
|
|
case SymbolKind::Variable:
|
|
|
|
|
case SymbolKind::Field:
|
|
|
|
|
case SymbolKind::Constant:
|
|
|
|
|
if (detail.isEmpty())
|
|
|
|
|
return name;
|
|
|
|
|
return name + " -> " + detail;
|
|
|
|
|
default:
|
|
|
|
|
return name;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-12 11:33:07 +01:00
|
|
|
// Force re-parse of all open files that include the changed ui header.
|
|
|
|
|
// Otherwise, we potentially have stale diagnostics.
|
|
|
|
|
void ClangdClient::handleUiHeaderChange(const QString &fileName)
|
|
|
|
|
{
|
|
|
|
|
const QRegularExpression includeRex("#include.*" + fileName + R"([>"])");
|
2022-03-14 08:36:37 +01:00
|
|
|
const QList<Client *> &allClients = LanguageClientManager::clients();
|
2021-11-12 11:33:07 +01:00
|
|
|
for (Client * const client : allClients) {
|
|
|
|
|
if (!client->reachable() || !qobject_cast<ClangdClient *>(client))
|
|
|
|
|
continue;
|
|
|
|
|
for (IDocument * const doc : DocumentModel::openedDocuments()) {
|
|
|
|
|
const auto textDoc = qobject_cast<TextDocument *>(doc);
|
|
|
|
|
if (!textDoc || !client->documentOpen(textDoc))
|
|
|
|
|
continue;
|
|
|
|
|
const QTextCursor includePos = textDoc->document()->find(includeRex);
|
|
|
|
|
if (includePos.isNull())
|
|
|
|
|
continue;
|
|
|
|
|
qCDebug(clangdLog) << "updating" << textDoc->filePath() << "due to change in UI header"
|
|
|
|
|
<< fileName;
|
|
|
|
|
client->documentContentsChanged(textDoc, 0, 0, 0);
|
|
|
|
|
break; // No sane project includes the same UI header twice.
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-08 11:49:37 +01:00
|
|
|
void ClangdClient::updateParserConfig(const Utils::FilePath &filePath,
|
|
|
|
|
const CppEditor::BaseEditorDocumentParser::Configuration &config)
|
|
|
|
|
{
|
|
|
|
|
if (config.preferredProjectPartId.isEmpty())
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
CppEditor::BaseEditorDocumentParser::Configuration &cachedConfig = d->parserConfigs[filePath];
|
|
|
|
|
if (cachedConfig == config)
|
|
|
|
|
return;
|
|
|
|
|
cachedConfig = config;
|
|
|
|
|
|
|
|
|
|
// TODO: Also handle editorDefines (and usePrecompiledHeaders?)
|
|
|
|
|
const auto projectPart = CppEditor::CppModelManager::instance()
|
|
|
|
|
->projectPartForId(config.preferredProjectPartId);
|
|
|
|
|
if (!projectPart)
|
|
|
|
|
return;
|
|
|
|
|
QJsonObject cdbChanges;
|
2022-05-09 16:16:51 +02:00
|
|
|
const Utils::FilePath includeDir = CppEditor::ClangdSettings(d->settings).clangdIncludePath();
|
|
|
|
|
CppEditor::CompilerOptionsBuilder optionsBuilder = clangOptionsBuilder(
|
2022-05-19 14:48:09 +02:00
|
|
|
*projectPart, warningsConfigForProject(project()), includeDir);
|
2022-05-05 15:36:58 +02:00
|
|
|
const CppEditor::ProjectFile file(filePath.toString(),
|
|
|
|
|
CppEditor::ProjectFile::classify(filePath.toString()));
|
2022-05-05 17:34:31 +02:00
|
|
|
const QJsonArray projectPartOptions = fullProjectPartOptions(
|
2022-05-19 14:48:09 +02:00
|
|
|
optionsBuilder, globalClangOptions());
|
2022-05-05 17:34:31 +02:00
|
|
|
addToCompilationDb(cdbChanges, *projectPart, CppEditor::getPchUsage(), projectPartOptions,
|
|
|
|
|
filePath.parentDir(), file);
|
2022-02-16 12:26:15 +01:00
|
|
|
QJsonObject settings;
|
|
|
|
|
addCompilationDb(settings, cdbChanges);
|
2022-02-08 11:49:37 +01:00
|
|
|
DidChangeConfigurationParams configChangeParams;
|
|
|
|
|
configChangeParams.setSettings(settings);
|
2022-05-12 09:51:39 +02:00
|
|
|
sendMessage(DidChangeConfigurationNotification(configChangeParams));
|
2022-02-08 11:49:37 +01:00
|
|
|
}
|
|
|
|
|
|
2022-05-11 12:30:57 +02:00
|
|
|
void ClangdClient::switchIssuePaneEntries(const Utils::FilePath &filePath)
|
|
|
|
|
{
|
|
|
|
|
TaskHub::clearTasks(Constants::TASK_CATEGORY_DIAGNOSTICS);
|
|
|
|
|
const Tasks tasks = d->issuePaneEntries.value(filePath);
|
|
|
|
|
for (const Task &t : tasks)
|
|
|
|
|
TaskHub::addTask(t);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ClangdClient::addTask(const ProjectExplorer::Task &task)
|
|
|
|
|
{
|
|
|
|
|
d->issuePaneEntries[task.file] << task;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ClangdClient::clearTasks(const Utils::FilePath &filePath)
|
|
|
|
|
{
|
|
|
|
|
d->issuePaneEntries[filePath].clear();
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-07 11:19:41 +02:00
|
|
|
Utils::optional<bool> ClangdClient::hasVirtualFunctionAt(TextDocument *doc, int revision,
|
|
|
|
|
const Range &range)
|
|
|
|
|
{
|
|
|
|
|
const auto highlightingData = d->highlightingData.constFind(doc);
|
|
|
|
|
if (highlightingData == d->highlightingData.constEnd()
|
|
|
|
|
|| highlightingData->virtualRanges.second != revision) {
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
const auto matcher = [range](const Range &r) { return range.overlaps(r); };
|
|
|
|
|
return Utils::contains(highlightingData->virtualRanges.first, matcher);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
MessageId ClangdClient::getAndHandleAst(const TextDocOrFile &doc, const AstHandler &astHandler,
|
|
|
|
|
AstCallbackMode callbackMode, const Range &range)
|
|
|
|
|
{
|
|
|
|
|
return d->getAndHandleAst(doc, astHandler, callbackMode, range);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
MessageId ClangdClient::requestSymbolInfo(const Utils::FilePath &filePath, const Position &position,
|
|
|
|
|
const SymbolInfoHandler &handler)
|
|
|
|
|
{
|
|
|
|
|
const TextDocumentIdentifier docId(DocumentUri::fromFilePath(filePath));
|
|
|
|
|
const TextDocumentPositionParams params(docId, position);
|
|
|
|
|
SymbolInfoRequest symReq(params);
|
|
|
|
|
symReq.setResponseCallback([handler, reqId = symReq.id()]
|
|
|
|
|
(const SymbolInfoRequest::Response &response) {
|
|
|
|
|
const auto result = response.result();
|
|
|
|
|
if (!result) {
|
|
|
|
|
handler({}, {}, reqId);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// According to the documentation, we should receive a single
|
|
|
|
|
// object here, but it's a list. No idea what it means if there's
|
|
|
|
|
// more than one entry. We choose the first one.
|
|
|
|
|
const auto list = Utils::get_if<QList<SymbolDetails>>(&result.value());
|
|
|
|
|
if (!list || list->isEmpty()) {
|
|
|
|
|
handler({}, {}, reqId);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const SymbolDetails &sd = list->first();
|
|
|
|
|
handler(sd.name(), sd.containerName(), reqId);
|
|
|
|
|
});
|
|
|
|
|
sendMessage(symReq);
|
|
|
|
|
return symReq.id();
|
|
|
|
|
}
|
|
|
|
|
|
2021-04-21 14:29:49 +02:00
|
|
|
void ClangdClient::Private::handleFindUsagesResult(quint64 key, const QList<Location> &locations)
|
|
|
|
|
{
|
|
|
|
|
const auto refData = runningFindUsages.find(key);
|
|
|
|
|
if (refData == runningFindUsages.end())
|
|
|
|
|
return;
|
2021-05-18 12:59:15 +02:00
|
|
|
if (!refData->search || refData->canceled) {
|
2021-04-21 14:29:49 +02:00
|
|
|
finishSearch(*refData, true);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
refData->search->disconnect(q);
|
|
|
|
|
|
|
|
|
|
qCDebug(clangdLog) << "found" << locations.size() << "locations";
|
|
|
|
|
if (locations.isEmpty()) {
|
|
|
|
|
finishSearch(*refData, false);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
QObject::connect(refData->search, &SearchResult::cancelled, q, [this, key] {
|
|
|
|
|
const auto refData = runningFindUsages.find(key);
|
|
|
|
|
if (refData == runningFindUsages.end())
|
|
|
|
|
return;
|
2021-05-18 12:59:15 +02:00
|
|
|
refData->canceled = true;
|
2021-04-21 14:29:49 +02:00
|
|
|
refData->search->disconnect(q);
|
|
|
|
|
for (const MessageId &id : qAsConst(refData->pendingAstRequests))
|
|
|
|
|
q->cancelRequest(id);
|
|
|
|
|
refData->pendingAstRequests.clear();
|
|
|
|
|
finishSearch(*refData, true);
|
|
|
|
|
});
|
|
|
|
|
|
2021-09-23 17:04:33 +02:00
|
|
|
for (const Location &loc : locations)
|
2021-09-24 12:41:30 +02:00
|
|
|
refData->fileData[loc.uri()].rangesAndLineText << qMakePair(loc.range(), QString());
|
2021-11-19 16:19:02 +01:00
|
|
|
for (auto it = refData->fileData.begin(); it != refData->fileData.end();) {
|
|
|
|
|
const Utils::FilePath filePath = it.key().toFilePath();
|
|
|
|
|
if (!filePath.exists()) { // https://github.com/clangd/clangd/issues/935
|
|
|
|
|
it = refData->fileData.erase(it);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
const QStringList lines = SymbolSupport::getFileContents(filePath);
|
2021-04-21 14:29:49 +02:00
|
|
|
it->fileContent = lines.join('\n');
|
|
|
|
|
for (auto &rangeWithText : it.value().rangesAndLineText) {
|
|
|
|
|
const int lineNo = rangeWithText.first.start().line();
|
|
|
|
|
if (lineNo >= 0 && lineNo < lines.size())
|
|
|
|
|
rangeWithText.second = lines.at(lineNo);
|
|
|
|
|
}
|
2021-11-19 16:19:02 +01:00
|
|
|
++it;
|
2021-04-21 14:29:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
qCDebug(clangdLog) << "document count is" << refData->fileData.size();
|
2022-02-14 09:25:29 +01:00
|
|
|
if (refData->replacementData || !refData->categorize) {
|
2021-04-21 14:29:49 +02:00
|
|
|
qCDebug(clangdLog) << "skipping AST retrieval";
|
|
|
|
|
reportAllSearchResultsAndFinish(*refData);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for (auto it = refData->fileData.begin(); it != refData->fileData.end(); ++it) {
|
2021-09-28 13:21:59 +02:00
|
|
|
const TextDocument * const doc = q->documentForFilePath(it.key().toFilePath());
|
2021-09-27 16:24:37 +02:00
|
|
|
if (!doc)
|
2021-04-21 14:29:49 +02:00
|
|
|
q->openExtraFile(it.key().toFilePath(), it->fileContent);
|
|
|
|
|
it->fileContent.clear();
|
2021-09-27 16:24:37 +02:00
|
|
|
const auto docVariant = doc ? TextDocOrFile(doc) : TextDocOrFile(it.key().toFilePath());
|
2022-05-18 18:15:41 +02:00
|
|
|
const auto astHandler = [this, key, loc = it.key()](const ClangdAstNode &ast,
|
2021-09-27 16:24:37 +02:00
|
|
|
const MessageId &reqId) {
|
|
|
|
|
qCDebug(clangdLog) << "AST for" << loc.toFilePath();
|
2021-04-21 14:29:49 +02:00
|
|
|
const auto refData = runningFindUsages.find(key);
|
|
|
|
|
if (refData == runningFindUsages.end())
|
|
|
|
|
return;
|
2021-05-18 12:59:15 +02:00
|
|
|
if (!refData->search || refData->canceled)
|
2021-04-21 14:29:49 +02:00
|
|
|
return;
|
|
|
|
|
ReferencesFileData &data = refData->fileData[loc];
|
2021-09-27 16:24:37 +02:00
|
|
|
data.ast = ast;
|
|
|
|
|
refData->pendingAstRequests.removeOne(reqId);
|
2021-04-21 14:29:49 +02:00
|
|
|
qCDebug(clangdLog) << refData->pendingAstRequests.size()
|
|
|
|
|
<< "AST requests still pending";
|
|
|
|
|
addSearchResultsForFile(*refData, loc.toFilePath(), data);
|
|
|
|
|
refData->fileData.remove(loc);
|
|
|
|
|
if (refData->pendingAstRequests.isEmpty()) {
|
|
|
|
|
qDebug(clangdLog) << "retrieved all ASTs";
|
|
|
|
|
finishSearch(*refData, false);
|
|
|
|
|
}
|
2021-09-27 16:24:37 +02:00
|
|
|
};
|
|
|
|
|
const MessageId reqId = getAndHandleAst(docVariant, astHandler,
|
|
|
|
|
AstCallbackMode::AlwaysAsync);
|
|
|
|
|
refData->pendingAstRequests << reqId;
|
|
|
|
|
if (!doc)
|
2021-04-21 14:29:49 +02:00
|
|
|
q->closeExtraFile(it.key().toFilePath());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-18 12:59:15 +02:00
|
|
|
void ClangdClient::Private::handleRenameRequest(const SearchResult *search,
|
|
|
|
|
const ReplacementData &replacementData,
|
|
|
|
|
const QString &newSymbolName,
|
|
|
|
|
const QList<SearchResultItem> &checkedItems,
|
|
|
|
|
bool preserveCase)
|
|
|
|
|
{
|
2021-09-28 13:21:59 +02:00
|
|
|
const Utils::FilePaths filePaths = BaseFileFind::replaceAll(newSymbolName, checkedItems,
|
|
|
|
|
preserveCase);
|
2021-06-22 08:57:36 +02:00
|
|
|
if (!filePaths.isEmpty())
|
2021-05-18 12:59:15 +02:00
|
|
|
SearchResultWindow::instance()->hide();
|
|
|
|
|
|
|
|
|
|
const auto renameFilesCheckBox = qobject_cast<QCheckBox *>(search->additionalReplaceWidget());
|
|
|
|
|
QTC_ASSERT(renameFilesCheckBox, return);
|
|
|
|
|
if (!renameFilesCheckBox->isChecked())
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
QVector<Node *> fileNodes;
|
|
|
|
|
for (const Utils::FilePath &file : replacementData.fileRenameCandidates) {
|
|
|
|
|
Node * const node = ProjectTree::nodeForFile(file);
|
|
|
|
|
if (node)
|
|
|
|
|
fileNodes << node;
|
|
|
|
|
}
|
|
|
|
|
if (!fileNodes.isEmpty())
|
2021-08-30 10:58:08 +02:00
|
|
|
CppEditor::renameFilesForSymbol(replacementData.oldSymbolName, newSymbolName, fileNodes);
|
2021-05-18 12:59:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ClangdClient::Private::addSearchResultsForFile(ReferencesData &refData,
|
2021-04-21 14:29:49 +02:00
|
|
|
const Utils::FilePath &file,
|
|
|
|
|
const ReferencesFileData &fileData)
|
|
|
|
|
{
|
|
|
|
|
QList<SearchResultItem> items;
|
|
|
|
|
qCDebug(clangdLog) << file << "has valid AST:" << fileData.ast.isValid();
|
|
|
|
|
for (const auto &rangeWithText : fileData.rangesAndLineText) {
|
|
|
|
|
const Range &range = rangeWithText.first;
|
2022-05-07 00:44:03 +03:00
|
|
|
const ClangdAstPath astPath = getAstPath(fileData.ast, range);
|
|
|
|
|
const Usage::Type usageType = fileData.ast.isValid() ? getUsageType(astPath)
|
|
|
|
|
: Usage::Type::Other;
|
|
|
|
|
|
2021-04-21 14:29:49 +02:00
|
|
|
SearchResultItem item;
|
|
|
|
|
item.setUserData(int(usageType));
|
2021-08-30 10:58:08 +02:00
|
|
|
item.setStyle(CppEditor::colorStyleForUsageType(usageType));
|
2021-04-21 14:29:49 +02:00
|
|
|
item.setFilePath(file);
|
|
|
|
|
item.setMainRange(SymbolSupport::convertRange(range));
|
|
|
|
|
item.setUseTextEditorFont(true);
|
|
|
|
|
item.setLineText(rangeWithText.second);
|
2022-05-07 00:44:03 +03:00
|
|
|
item.setContainingFunctionName(getContainingFunctionName(astPath, range));
|
|
|
|
|
|
2021-05-18 12:59:15 +02:00
|
|
|
if (refData.search->supportsReplace()) {
|
|
|
|
|
const bool fileInSession = SessionManager::projectForFile(file);
|
|
|
|
|
item.setSelectForReplacement(fileInSession);
|
2021-06-03 12:53:40 +02:00
|
|
|
if (fileInSession && file.baseName().compare(
|
2021-05-18 12:59:15 +02:00
|
|
|
refData.replacementData->oldSymbolName,
|
|
|
|
|
Qt::CaseInsensitive) == 0) {
|
2021-09-24 13:11:31 +02:00
|
|
|
refData.replacementData->fileRenameCandidates << file;
|
2021-05-18 12:59:15 +02:00
|
|
|
}
|
|
|
|
|
}
|
2021-04-21 14:29:49 +02:00
|
|
|
items << item;
|
|
|
|
|
}
|
|
|
|
|
if (isTesting)
|
|
|
|
|
emit q->foundReferences(items);
|
|
|
|
|
else
|
|
|
|
|
refData.search->addResults(items, SearchResult::AddOrdered);
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-18 12:59:15 +02:00
|
|
|
void ClangdClient::Private::reportAllSearchResultsAndFinish(ReferencesData &refData)
|
2021-04-21 14:29:49 +02:00
|
|
|
{
|
|
|
|
|
for (auto it = refData.fileData.begin(); it != refData.fileData.end(); ++it)
|
|
|
|
|
addSearchResultsForFile(refData, it.key().toFilePath(), it.value());
|
2021-05-18 12:59:15 +02:00
|
|
|
finishSearch(refData, refData.canceled);
|
2021-04-21 14:29:49 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ClangdClient::Private::finishSearch(const ReferencesData &refData, bool canceled)
|
|
|
|
|
{
|
|
|
|
|
if (isTesting) {
|
|
|
|
|
emit q->findUsagesDone();
|
|
|
|
|
} else if (refData.search) {
|
|
|
|
|
refData.search->finishSearch(canceled);
|
|
|
|
|
refData.search->disconnect(q);
|
2021-05-18 12:59:15 +02:00
|
|
|
if (refData.replacementData) {
|
|
|
|
|
const auto renameCheckBox = qobject_cast<QCheckBox *>(
|
|
|
|
|
refData.search->additionalReplaceWidget());
|
|
|
|
|
QTC_CHECK(renameCheckBox);
|
|
|
|
|
const QSet<Utils::FilePath> files = refData.replacementData->fileRenameCandidates;
|
|
|
|
|
renameCheckBox->setText(tr("Re&name %n files", nullptr, files.size()));
|
|
|
|
|
const QStringList filesForUser = Utils::transform<QStringList>(files,
|
|
|
|
|
[](const Utils::FilePath &fp) { return fp.toUserOutput(); });
|
|
|
|
|
renameCheckBox->setToolTip(tr("Files:\n%1").arg(filesForUser.join('\n')));
|
|
|
|
|
renameCheckBox->setVisible(true);
|
|
|
|
|
refData.search->setUserData(QVariant::fromValue(*refData.replacementData));
|
|
|
|
|
}
|
2021-04-21 14:29:49 +02:00
|
|
|
}
|
|
|
|
|
runningFindUsages.remove(refData.key);
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
void ClangdClient::followSymbol(TextDocument *document,
|
2021-05-19 15:51:25 +02:00
|
|
|
const QTextCursor &cursor,
|
2021-09-01 18:08:54 +02:00
|
|
|
CppEditor::CppEditorWidget *editorWidget,
|
2022-06-03 15:17:33 +02:00
|
|
|
const Utils::LinkHandler &callback,
|
2021-05-19 15:51:25 +02:00
|
|
|
bool resolveTarget,
|
|
|
|
|
bool openInSplit
|
|
|
|
|
)
|
|
|
|
|
{
|
|
|
|
|
QTC_ASSERT(documentOpen(document), openDocument(document));
|
2022-06-07 11:19:41 +02:00
|
|
|
|
|
|
|
|
delete d->followSymbol;
|
|
|
|
|
d->followSymbol = nullptr;
|
|
|
|
|
|
2021-12-03 12:54:21 +01:00
|
|
|
const QTextCursor adjustedCursor = d->adjustedCursor(cursor, document);
|
2021-05-19 15:51:25 +02:00
|
|
|
if (!resolveTarget) {
|
2022-06-03 15:17:33 +02:00
|
|
|
symbolSupport().findLinkAt(document, adjustedCursor, callback, false);
|
2021-05-19 15:51:25 +02:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-19 13:22:49 +02:00
|
|
|
qCDebug(clangdLog) << "follow symbol requested" << document->filePath()
|
2021-12-02 13:18:02 +01:00
|
|
|
<< adjustedCursor.blockNumber() << adjustedCursor.positionInBlock();
|
2022-06-07 11:19:41 +02:00
|
|
|
d->followSymbol = new ClangdFollowSymbol(this, adjustedCursor, editorWidget, document, callback,
|
|
|
|
|
openInSplit);
|
|
|
|
|
connect(d->followSymbol, &ClangdFollowSymbol::done, this, [this] {
|
|
|
|
|
delete d->followSymbol;
|
|
|
|
|
d->followSymbol = nullptr;
|
|
|
|
|
});
|
2021-05-19 15:51:25 +02:00
|
|
|
}
|
|
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
void ClangdClient::switchDeclDef(TextDocument *document, const QTextCursor &cursor,
|
2021-09-01 18:08:54 +02:00
|
|
|
CppEditor::CppEditorWidget *editorWidget,
|
2022-06-03 15:17:33 +02:00
|
|
|
const Utils::LinkHandler &callback)
|
2021-05-31 15:57:44 +02:00
|
|
|
{
|
|
|
|
|
QTC_ASSERT(documentOpen(document), openDocument(document));
|
|
|
|
|
|
|
|
|
|
qCDebug(clangdLog) << "switch decl/dev requested" << document->filePath()
|
|
|
|
|
<< cursor.blockNumber() << cursor.positionInBlock();
|
2022-06-03 15:17:33 +02:00
|
|
|
d->switchDeclDefData.emplace(++d->nextJobId, document, cursor, editorWidget, callback);
|
2021-05-31 15:57:44 +02:00
|
|
|
|
|
|
|
|
// Retrieve AST and document symbols.
|
2022-05-18 18:15:41 +02:00
|
|
|
const auto astHandler = [this, id = d->switchDeclDefData->id](const ClangdAstNode &ast,
|
2021-09-27 16:24:37 +02:00
|
|
|
const MessageId &) {
|
2021-05-31 15:57:44 +02:00
|
|
|
qCDebug(clangdLog) << "received ast for decl/def switch";
|
|
|
|
|
if (!d->switchDeclDefData || d->switchDeclDefData->id != id
|
|
|
|
|
|| !d->switchDeclDefData->document)
|
|
|
|
|
return;
|
2021-09-27 16:24:37 +02:00
|
|
|
if (!ast.isValid()) {
|
2021-05-31 15:57:44 +02:00
|
|
|
d->switchDeclDefData.reset();
|
|
|
|
|
return;
|
|
|
|
|
}
|
2021-09-27 16:24:37 +02:00
|
|
|
d->switchDeclDefData->ast = ast;
|
2021-05-31 15:57:44 +02:00
|
|
|
if (d->switchDeclDefData->docSymbols)
|
|
|
|
|
d->handleDeclDefSwitchReplies();
|
|
|
|
|
|
2021-09-27 16:24:37 +02:00
|
|
|
};
|
2022-06-07 11:19:41 +02:00
|
|
|
d->getAndHandleAst(document, astHandler, AstCallbackMode::SyncIfPossible);
|
2021-09-14 17:00:16 +02:00
|
|
|
documentSymbolCache()->requestSymbols(d->switchDeclDefData->uri, Schedule::Now);
|
2021-05-31 15:57:44 +02:00
|
|
|
}
|
|
|
|
|
|
2022-05-18 15:16:40 +02:00
|
|
|
void ClangdClient::switchHeaderSource(const Utils::FilePath &filePath, bool inNextSplit)
|
|
|
|
|
{
|
|
|
|
|
class SwitchSourceHeaderRequest : public Request<QJsonValue, std::nullptr_t, TextDocumentIdentifier>
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
using Request::Request;
|
|
|
|
|
explicit SwitchSourceHeaderRequest(const Utils::FilePath &filePath)
|
|
|
|
|
: Request("textDocument/switchSourceHeader",
|
|
|
|
|
TextDocumentIdentifier(DocumentUri::fromFilePath(filePath))) {}
|
|
|
|
|
};
|
|
|
|
|
SwitchSourceHeaderRequest req(filePath);
|
|
|
|
|
req.setResponseCallback([inNextSplit](const SwitchSourceHeaderRequest::Response &response) {
|
|
|
|
|
if (const Utils::optional<QJsonValue> result = response.result()) {
|
|
|
|
|
const DocumentUri uri = DocumentUri::fromProtocol(result->toString());
|
|
|
|
|
const Utils::FilePath filePath = uri.toFilePath();
|
|
|
|
|
if (!filePath.isEmpty())
|
|
|
|
|
CppEditor::openEditor(filePath, inNextSplit);
|
|
|
|
|
}
|
|
|
|
|
});
|
2022-05-12 09:51:39 +02:00
|
|
|
sendMessage(req);
|
2022-05-18 15:16:40 +02:00
|
|
|
}
|
|
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
void ClangdClient::findLocalUsages(TextDocument *document, const QTextCursor &cursor,
|
2022-04-29 16:52:48 +02:00
|
|
|
CppEditor::RenameCallback &&callback)
|
2021-06-01 18:14:12 +02:00
|
|
|
{
|
|
|
|
|
QTC_ASSERT(documentOpen(document), openDocument(document));
|
|
|
|
|
|
|
|
|
|
qCDebug(clangdLog) << "local references requested" << document->filePath()
|
|
|
|
|
<< (cursor.blockNumber() + 1) << (cursor.positionInBlock() + 1);
|
|
|
|
|
|
2021-06-02 16:32:54 +02:00
|
|
|
d->localRefsData.emplace(++d->nextJobId, document, cursor, std::move(callback));
|
2021-06-01 18:14:12 +02:00
|
|
|
const QString searchTerm = d->searchTermFromCursor(cursor);
|
|
|
|
|
if (searchTerm.isEmpty()) {
|
|
|
|
|
d->localRefsData.reset();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Step 1: Go to definition
|
|
|
|
|
const auto gotoDefCallback = [this, id = d->localRefsData->id](const Utils::Link &link) {
|
|
|
|
|
qCDebug(clangdLog) << "received go to definition response" << link.targetFilePath
|
|
|
|
|
<< link.targetLine << (link.targetColumn + 1);
|
|
|
|
|
if (!d->localRefsData || id != d->localRefsData->id)
|
|
|
|
|
return;
|
|
|
|
|
if (!link.hasValidTarget()) {
|
|
|
|
|
d->localRefsData.reset();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Step 2: Get AST and check whether it's a local variable.
|
2022-05-18 18:15:41 +02:00
|
|
|
const auto astHandler = [this, link, id](const ClangdAstNode &ast, const MessageId &) {
|
2021-06-01 18:14:12 +02:00
|
|
|
qCDebug(clangdLog) << "received ast response";
|
|
|
|
|
if (!d->localRefsData || id != d->localRefsData->id)
|
|
|
|
|
return;
|
2021-09-27 16:24:37 +02:00
|
|
|
if (!ast.isValid() || !d->localRefsData->document) {
|
2021-06-01 18:14:12 +02:00
|
|
|
d->localRefsData.reset();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const Position linkPos(link.targetLine - 1, link.targetColumn);
|
2022-05-18 18:15:41 +02:00
|
|
|
const ClangdAstPath astPath = getAstPath(ast, linkPos);
|
2021-06-01 18:14:12 +02:00
|
|
|
bool isVar = false;
|
|
|
|
|
for (auto it = astPath.rbegin(); it != astPath.rend(); ++it) {
|
2022-03-30 17:31:26 +02:00
|
|
|
if (it->role() == "declaration"
|
|
|
|
|
&& (it->kind() == "Function" || it->kind() == "CXXMethod"
|
|
|
|
|
|| it->kind() == "CXXConstructor" || it->kind() == "CXXDestructor"
|
|
|
|
|
|| it->kind() == "Lambda")) {
|
2021-06-01 18:14:12 +02:00
|
|
|
if (!isVar)
|
|
|
|
|
break;
|
|
|
|
|
|
|
|
|
|
// Step 3: Find references.
|
|
|
|
|
qCDebug(clangdLog) << "finding references for local var";
|
|
|
|
|
symbolSupport().findUsages(d->localRefsData->document,
|
|
|
|
|
d->localRefsData->cursor,
|
|
|
|
|
[this, id](const QList<Location> &locations) {
|
|
|
|
|
qCDebug(clangdLog) << "found" << locations.size() << "local references";
|
|
|
|
|
if (!d->localRefsData || id != d->localRefsData->id)
|
|
|
|
|
return;
|
2022-05-02 12:29:57 +02:00
|
|
|
const Utils::Links links = Utils::transform(locations, &Location::toLink);
|
2021-06-01 18:14:12 +02:00
|
|
|
|
|
|
|
|
// The callback only uses the symbol length, so we just create a dummy.
|
|
|
|
|
// Note that the calculation will be wrong for identifiers with
|
|
|
|
|
// embedded newlines, but we've never supported that.
|
|
|
|
|
QString symbol;
|
|
|
|
|
if (!locations.isEmpty()) {
|
|
|
|
|
const Range r = locations.first().range();
|
|
|
|
|
symbol = QString(r.end().character() - r.start().character(), 'x');
|
|
|
|
|
}
|
2022-05-02 12:29:57 +02:00
|
|
|
d->localRefsData->callback(symbol, links, d->localRefsData->revision);
|
2021-06-01 18:14:12 +02:00
|
|
|
d->localRefsData->callback = {};
|
|
|
|
|
d->localRefsData.reset();
|
|
|
|
|
});
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (!isVar && it->role() == "declaration"
|
|
|
|
|
&& (it->kind() == "Var" || it->kind() == "ParmVar")) {
|
|
|
|
|
isVar = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
d->localRefsData.reset();
|
2021-09-27 16:24:37 +02:00
|
|
|
};
|
2021-06-01 18:14:12 +02:00
|
|
|
qCDebug(clangdLog) << "sending ast request for link";
|
2021-09-27 16:24:37 +02:00
|
|
|
d->getAndHandleAst(d->localRefsData->document, astHandler,
|
2022-06-07 11:19:41 +02:00
|
|
|
AstCallbackMode::SyncIfPossible);
|
2021-06-01 18:14:12 +02:00
|
|
|
};
|
|
|
|
|
symbolSupport().findLinkAt(document, cursor, std::move(gotoDefCallback), true);
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-04 12:40:26 +02:00
|
|
|
void ClangdClient::gatherHelpItemForTooltip(const HoverRequest::Response &hoverResponse,
|
|
|
|
|
const DocumentUri &uri)
|
|
|
|
|
{
|
2022-05-16 13:31:10 +02:00
|
|
|
if (const Utils::optional<HoverResult> result = hoverResponse.result()) {
|
|
|
|
|
if (auto hover = Utils::get_if<Hover>(&(*result))) {
|
|
|
|
|
const HoverContent content = hover->content();
|
|
|
|
|
const MarkupContent *const markup = Utils::get_if<MarkupContent>(&content);
|
|
|
|
|
if (markup) {
|
|
|
|
|
const QString markupString = markup->content();
|
|
|
|
|
|
|
|
|
|
// Macros aren't locatable via the AST, so parse the formatted string.
|
|
|
|
|
static const QString magicMacroPrefix = "### macro `";
|
|
|
|
|
if (markupString.startsWith(magicMacroPrefix)) {
|
|
|
|
|
const int nameStart = magicMacroPrefix.length();
|
|
|
|
|
const int closingQuoteIndex = markupString.indexOf('`', nameStart);
|
|
|
|
|
if (closingQuoteIndex != -1) {
|
|
|
|
|
const QString macroName = markupString.mid(nameStart,
|
|
|
|
|
closingQuoteIndex - nameStart);
|
|
|
|
|
d->setHelpItemForTooltip(hoverResponse.id(), macroName, HelpItem::Macro);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2021-06-04 12:40:26 +02:00
|
|
|
}
|
2021-07-29 16:50:55 +02:00
|
|
|
|
2022-05-16 13:31:10 +02:00
|
|
|
// Is it the file path for an include directive?
|
|
|
|
|
QString cleanString = markupString;
|
|
|
|
|
cleanString.remove('`');
|
|
|
|
|
const QStringList lines = cleanString.trimmed().split('\n');
|
|
|
|
|
if (!lines.isEmpty()) {
|
|
|
|
|
const auto filePath = Utils::FilePath::fromUserInput(lines.last().simplified());
|
|
|
|
|
if (filePath.exists()) {
|
|
|
|
|
d->setHelpItemForTooltip(hoverResponse.id(),
|
|
|
|
|
filePath.fileName(),
|
|
|
|
|
HelpItem::Brief);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2021-07-29 16:50:55 +02:00
|
|
|
}
|
|
|
|
|
}
|
2021-06-04 12:40:26 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
const TextDocument * const doc = documentForFilePath(uri.toFilePath());
|
2021-09-27 16:24:37 +02:00
|
|
|
QTC_ASSERT(doc, return);
|
2022-05-18 18:15:41 +02:00
|
|
|
const auto astHandler = [this, uri, hoverResponse](const ClangdAstNode &ast, const MessageId &) {
|
2021-06-04 12:40:26 +02:00
|
|
|
const MessageId id = hoverResponse.id();
|
2022-05-16 13:31:10 +02:00
|
|
|
Range range;
|
|
|
|
|
if (const Utils::optional<HoverResult> result = hoverResponse.result()) {
|
|
|
|
|
if (auto hover = Utils::get_if<Hover>(&(*result)))
|
|
|
|
|
range = hover->range().value_or(Range());
|
|
|
|
|
}
|
2022-05-18 18:15:41 +02:00
|
|
|
const ClangdAstPath path = getAstPath(ast, range);
|
2021-06-04 12:40:26 +02:00
|
|
|
if (path.isEmpty()) {
|
|
|
|
|
d->setHelpItemForTooltip(id);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2022-05-18 18:15:41 +02:00
|
|
|
ClangdAstNode node = path.last();
|
2021-06-04 12:40:26 +02:00
|
|
|
if (node.role() == "expression" && node.kind() == "ImplicitCast") {
|
2022-05-18 18:15:41 +02:00
|
|
|
const Utils::optional<QList<ClangdAstNode>> children = node.children();
|
2021-06-04 12:40:26 +02:00
|
|
|
if (children && !children->isEmpty())
|
|
|
|
|
node = children->first();
|
|
|
|
|
}
|
|
|
|
|
while (node.kind() == "Qualified") {
|
2022-05-18 18:15:41 +02:00
|
|
|
const Utils::optional<QList<ClangdAstNode>> children = node.children();
|
2021-06-04 12:40:26 +02:00
|
|
|
if (children && !children->isEmpty())
|
|
|
|
|
node = children->first();
|
|
|
|
|
}
|
2021-07-15 11:39:56 +02:00
|
|
|
if (clangdLogAst().isDebugEnabled())
|
2021-06-04 12:40:26 +02:00
|
|
|
node.print(0);
|
|
|
|
|
|
|
|
|
|
QString type = node.type();
|
|
|
|
|
const auto stripTemplatePartOffType = [&type] {
|
|
|
|
|
const int angleBracketIndex = type.indexOf('<');
|
|
|
|
|
if (angleBracketIndex != -1)
|
|
|
|
|
type = type.left(angleBracketIndex);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const bool isMemberFunction = node.role() == "expression" && node.kind() == "Member"
|
|
|
|
|
&& (node.arcanaContains("member function") || type.contains('('));
|
|
|
|
|
const bool isFunction = node.role() == "expression" && node.kind() == "DeclRef"
|
|
|
|
|
&& type.contains('(');
|
|
|
|
|
if (isMemberFunction || isFunction) {
|
2022-06-07 11:19:41 +02:00
|
|
|
const auto symbolInfoHandler = [this, id, type, isFunction]
|
|
|
|
|
(const QString &name, const QString &prefix, const MessageId &) {
|
2021-06-04 12:40:26 +02:00
|
|
|
qCDebug(clangdLog) << "handling symbol info reply";
|
2022-06-07 11:19:41 +02:00
|
|
|
const QString fqn = prefix + name;
|
2021-06-04 12:40:26 +02:00
|
|
|
|
|
|
|
|
// Unfortunately, the arcana string contains the signature only for
|
|
|
|
|
// free functions, so we can't distinguish member function overloads.
|
|
|
|
|
// But since HtmlDocExtractor::getFunctionDescription() is always called
|
|
|
|
|
// with mainOverload = true, such information would get ignored anyway.
|
2022-06-07 11:19:41 +02:00
|
|
|
if (!fqn.isEmpty())
|
|
|
|
|
d->setHelpItemForTooltip(id, fqn, HelpItem::Function, isFunction ? type : "()");
|
|
|
|
|
};
|
|
|
|
|
requestSymbolInfo(uri.toFilePath(), range.start(), symbolInfoHandler);
|
2021-06-04 12:40:26 +02:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if ((node.role() == "expression" && node.kind() == "DeclRef")
|
|
|
|
|
|| (node.role() == "declaration"
|
|
|
|
|
&& (node.kind() == "Var" || node.kind() == "ParmVar"
|
|
|
|
|
|| node.kind() == "Field"))) {
|
|
|
|
|
if (node.arcanaContains("EnumConstant")) {
|
|
|
|
|
d->setHelpItemForTooltip(id, node.detail().value_or(QString()),
|
|
|
|
|
HelpItem::Enum, type);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
stripTemplatePartOffType();
|
|
|
|
|
type.remove("&").remove("*").remove("const ").remove(" const")
|
|
|
|
|
.remove("volatile ").remove(" volatile");
|
|
|
|
|
type = type.simplified();
|
|
|
|
|
if (type != "int" && !type.contains(" int")
|
|
|
|
|
&& type != "char" && !type.contains(" char")
|
|
|
|
|
&& type != "double" && !type.contains(" double")
|
|
|
|
|
&& type != "float" && type != "bool") {
|
|
|
|
|
d->setHelpItemForTooltip(id, type, node.qdocCategoryForDeclaration(
|
|
|
|
|
HelpItem::ClassOrNamespace));
|
|
|
|
|
} else {
|
|
|
|
|
d->setHelpItemForTooltip(id);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (node.isNamespace()) {
|
|
|
|
|
QString ns = node.detail().value_or(QString());
|
|
|
|
|
for (auto it = path.rbegin() + 1; it != path.rend(); ++it) {
|
|
|
|
|
if (it->isNamespace()) {
|
|
|
|
|
const QString name = it->detail().value_or(QString());
|
|
|
|
|
if (!name.isEmpty())
|
|
|
|
|
ns.prepend("::").prepend(name);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
d->setHelpItemForTooltip(hoverResponse.id(), ns, HelpItem::ClassOrNamespace);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (node.role() == "type") {
|
|
|
|
|
if (node.kind() == "Enum") {
|
|
|
|
|
d->setHelpItemForTooltip(id, node.detail().value_or(QString()), HelpItem::Enum);
|
|
|
|
|
} else if (node.kind() == "Record" || node.kind() == "TemplateSpecialization") {
|
|
|
|
|
stripTemplatePartOffType();
|
|
|
|
|
d->setHelpItemForTooltip(id, type, HelpItem::ClassOrNamespace);
|
|
|
|
|
} else if (node.kind() == "Typedef") {
|
|
|
|
|
d->setHelpItemForTooltip(id, type, HelpItem::Typedef);
|
|
|
|
|
} else {
|
|
|
|
|
d->setHelpItemForTooltip(id);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (node.role() == "expression" && node.kind() == "CXXConstruct") {
|
|
|
|
|
const QString name = node.detail().value_or(QString());
|
|
|
|
|
if (!name.isEmpty())
|
|
|
|
|
type = name;
|
|
|
|
|
d->setHelpItemForTooltip(id, type, HelpItem::ClassOrNamespace);
|
|
|
|
|
}
|
|
|
|
|
if (node.role() == "specifier" && node.kind() == "NamespaceAlias") {
|
|
|
|
|
d->setHelpItemForTooltip(id, node.detail().value_or(QString()).chopped(2),
|
|
|
|
|
HelpItem::ClassOrNamespace);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
d->setHelpItemForTooltip(id);
|
2021-09-27 16:24:37 +02:00
|
|
|
};
|
2022-06-07 11:19:41 +02:00
|
|
|
d->getAndHandleAst(doc, astHandler, AstCallbackMode::SyncIfPossible);
|
2021-06-04 12:40:26 +02:00
|
|
|
}
|
|
|
|
|
|
2021-10-28 11:59:48 +02:00
|
|
|
void ClangdClient::setVirtualRanges(const Utils::FilePath &filePath, const QList<Range> &ranges,
|
|
|
|
|
int revision)
|
|
|
|
|
{
|
|
|
|
|
TextDocument * const doc = documentForFilePath(filePath);
|
|
|
|
|
if (doc && doc->document()->revision() == revision)
|
2022-04-21 13:02:09 +02:00
|
|
|
d->highlightingData[doc].virtualRanges = {ranges, revision};
|
2021-10-28 11:59:48 +02:00
|
|
|
}
|
|
|
|
|
|
2021-05-31 15:57:44 +02:00
|
|
|
void ClangdClient::Private::handleDeclDefSwitchReplies()
|
|
|
|
|
{
|
|
|
|
|
if (!switchDeclDefData->document) {
|
|
|
|
|
switchDeclDefData.reset();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Find the function declaration or definition associated with the cursor.
|
|
|
|
|
// For instance, the cursor could be somwehere inside a function body or
|
|
|
|
|
// on a function return type, or ...
|
2021-07-15 11:39:56 +02:00
|
|
|
if (clangdLogAst().isDebugEnabled())
|
2021-05-31 15:57:44 +02:00
|
|
|
switchDeclDefData->ast->print(0);
|
2022-05-18 18:15:41 +02:00
|
|
|
const Utils::optional<ClangdAstNode> functionNode = switchDeclDefData->getFunctionNode();
|
2021-05-31 15:57:44 +02:00
|
|
|
if (!functionNode) {
|
|
|
|
|
switchDeclDefData.reset();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Unfortunately, the AST does not contain the location of the actual function name symbol,
|
|
|
|
|
// so we have to look for it in the document symbols.
|
|
|
|
|
const QTextCursor funcNameCursor = switchDeclDefData->cursorForFunctionName(*functionNode);
|
|
|
|
|
if (!funcNameCursor.isNull()) {
|
|
|
|
|
q->followSymbol(switchDeclDefData->document.data(), funcNameCursor,
|
|
|
|
|
switchDeclDefData->editorWidget, std::move(switchDeclDefData->callback),
|
|
|
|
|
true, false);
|
|
|
|
|
}
|
|
|
|
|
switchDeclDefData.reset();
|
|
|
|
|
}
|
|
|
|
|
|
2022-05-07 00:44:03 +03:00
|
|
|
Utils::optional<QString> ClangdClient::Private::getContainingFunctionName(
|
|
|
|
|
const ClangdAstPath &astPath, const Range& range)
|
|
|
|
|
{
|
|
|
|
|
const ClangdAstNode* containingFuncNode{nullptr};
|
|
|
|
|
const ClangdAstNode* lastCompoundStmtNode{nullptr};
|
|
|
|
|
|
|
|
|
|
for (auto it = astPath.crbegin(); it != astPath.crend(); ++it) {
|
|
|
|
|
if (it->arcanaContains("CompoundStmt"))
|
|
|
|
|
lastCompoundStmtNode = &*it;
|
|
|
|
|
|
|
|
|
|
if (it->isFunction()) {
|
|
|
|
|
if (lastCompoundStmtNode && lastCompoundStmtNode->hasRange()
|
|
|
|
|
&& lastCompoundStmtNode->range().contains(range)) {
|
|
|
|
|
containingFuncNode = &*it;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!containingFuncNode || !containingFuncNode->isValid())
|
|
|
|
|
return Utils::nullopt;
|
|
|
|
|
|
|
|
|
|
return containingFuncNode->detail();
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-02 13:18:02 +01:00
|
|
|
CppEditor::CppEditorWidget *ClangdClient::Private::widgetFromDocument(const TextDocument *doc)
|
|
|
|
|
{
|
|
|
|
|
IEditor * const editor = Utils::findOrDefault(EditorManager::visibleEditors(),
|
|
|
|
|
[doc](const IEditor *editor) { return editor->document() == doc; });
|
|
|
|
|
return qobject_cast<CppEditor::CppEditorWidget *>(TextEditorWidget::fromEditor(editor));
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-01 18:14:12 +02:00
|
|
|
QString ClangdClient::Private::searchTermFromCursor(const QTextCursor &cursor) const
|
|
|
|
|
{
|
|
|
|
|
QTextCursor termCursor(cursor);
|
|
|
|
|
termCursor.select(QTextCursor::WordUnderCursor);
|
|
|
|
|
return termCursor.selectedText();
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-02 13:18:02 +01:00
|
|
|
// https://github.com/clangd/clangd/issues/936
|
|
|
|
|
QTextCursor ClangdClient::Private::adjustedCursor(const QTextCursor &cursor,
|
|
|
|
|
const TextDocument *doc)
|
|
|
|
|
{
|
|
|
|
|
CppEditor::CppEditorWidget * const widget = widgetFromDocument(doc);
|
|
|
|
|
if (!widget)
|
|
|
|
|
return cursor;
|
|
|
|
|
const Document::Ptr cppDoc = widget->semanticInfo().doc;
|
|
|
|
|
if (!cppDoc)
|
|
|
|
|
return cursor;
|
2021-12-03 12:54:21 +01:00
|
|
|
const QList<AST *> builtinAstPath = ASTPath(cppDoc)(cursor);
|
2022-06-09 13:21:26 +02:00
|
|
|
if (builtinAstPath.isEmpty())
|
|
|
|
|
return cursor;
|
2021-12-07 11:40:13 +01:00
|
|
|
const TranslationUnit * const tu = cppDoc->translationUnit();
|
|
|
|
|
const auto posForToken = [doc, tu](int tok) {
|
|
|
|
|
int line, column;
|
|
|
|
|
tu->getTokenPosition(tok, &line, &column);
|
|
|
|
|
return Utils::Text::positionInText(doc->document(), line, column);
|
|
|
|
|
};
|
2022-06-09 13:21:26 +02:00
|
|
|
const auto endPosForToken = [doc, tu](int tok) {
|
|
|
|
|
int line, column;
|
|
|
|
|
tu->getTokenEndPosition(tok, &line, &column);
|
|
|
|
|
return Utils::Text::positionInText(doc->document(), line, column);
|
|
|
|
|
};
|
2021-12-07 11:40:13 +01:00
|
|
|
const auto leftMovedCursor = [cursor] {
|
|
|
|
|
QTextCursor c = cursor;
|
|
|
|
|
c.setPosition(cursor.position() - 1);
|
|
|
|
|
return c;
|
|
|
|
|
};
|
2022-06-09 13:21:26 +02:00
|
|
|
|
|
|
|
|
// enum E { v1|, v2 };
|
|
|
|
|
if (const EnumeratorAST * const enumAst = builtinAstPath.last()->asEnumerator()) {
|
|
|
|
|
if (endPosForToken(enumAst->identifier_token) == cursor.position())
|
|
|
|
|
return leftMovedCursor();
|
|
|
|
|
return cursor;
|
|
|
|
|
}
|
|
|
|
|
|
2021-12-03 12:54:21 +01:00
|
|
|
for (auto it = builtinAstPath.rbegin(); it != builtinAstPath.rend(); ++it) {
|
2021-12-07 11:40:13 +01:00
|
|
|
|
|
|
|
|
// s|.x or s|->x
|
|
|
|
|
if (const MemberAccessAST * const memberAccess = (*it)->asMemberAccess()) {
|
|
|
|
|
switch (tu->tokenAt(memberAccess->access_token).kind()) {
|
|
|
|
|
case T_DOT:
|
|
|
|
|
break;
|
|
|
|
|
case T_ARROW: {
|
2022-05-18 18:15:41 +02:00
|
|
|
const Utils::optional<ClangdAstNode> clangdAst = astCache.get(doc);
|
2021-12-07 11:40:13 +01:00
|
|
|
if (!clangdAst)
|
2021-12-03 12:54:21 +01:00
|
|
|
return cursor;
|
2022-05-18 18:15:41 +02:00
|
|
|
const ClangdAstPath clangdAstPath = getAstPath(*clangdAst, Range(cursor));
|
2021-12-07 11:40:13 +01:00
|
|
|
for (auto it = clangdAstPath.rbegin(); it != clangdAstPath.rend(); ++it) {
|
|
|
|
|
if (it->detailIs("operator->") && it->arcanaContains("CXXMethod"))
|
|
|
|
|
return cursor;
|
|
|
|
|
}
|
|
|
|
|
break;
|
2021-12-03 12:54:21 +01:00
|
|
|
}
|
2021-12-07 11:40:13 +01:00
|
|
|
default:
|
|
|
|
|
return cursor;
|
|
|
|
|
}
|
|
|
|
|
if (posForToken(memberAccess->access_token) != cursor.position())
|
|
|
|
|
return cursor;
|
|
|
|
|
return leftMovedCursor();
|
2021-12-03 12:54:21 +01:00
|
|
|
}
|
2021-12-07 11:40:13 +01:00
|
|
|
|
|
|
|
|
// f(arg1|, arg2)
|
|
|
|
|
if (const CallAST *const callAst = (*it)->asCall()) {
|
|
|
|
|
const int tok = builtinAstPath.last()->lastToken();
|
|
|
|
|
if (posForToken(tok) != cursor.position())
|
|
|
|
|
return cursor;
|
|
|
|
|
if (tok == callAst->rparen_token)
|
|
|
|
|
return leftMovedCursor();
|
|
|
|
|
if (tu->tokenKind(tok) != T_COMMA)
|
|
|
|
|
return cursor;
|
|
|
|
|
|
|
|
|
|
// Guard against edge case of overloaded comma operator.
|
|
|
|
|
for (auto list = callAst->expression_list; list; list = list->next) {
|
|
|
|
|
if (list->value->lastToken() == tok)
|
|
|
|
|
return leftMovedCursor();
|
|
|
|
|
}
|
2021-12-02 13:18:02 +01:00
|
|
|
return cursor;
|
2021-12-03 12:54:21 +01:00
|
|
|
}
|
2022-01-26 12:40:12 +01:00
|
|
|
|
|
|
|
|
// ~My|Class
|
|
|
|
|
if (const DestructorNameAST * const destrAst = (*it)->asDestructorName()) {
|
|
|
|
|
QTextCursor c = cursor;
|
|
|
|
|
c.setPosition(posForToken(destrAst->tilde_token));
|
|
|
|
|
return c;
|
|
|
|
|
}
|
2022-05-11 10:54:24 +02:00
|
|
|
|
|
|
|
|
// QVector<QString|>
|
|
|
|
|
if (const TemplateIdAST * const templAst = (*it)->asTemplateId()) {
|
|
|
|
|
if (posForToken(templAst->greater_token) == cursor.position())
|
|
|
|
|
return leftMovedCursor();
|
|
|
|
|
return cursor;
|
|
|
|
|
}
|
2021-12-02 13:18:02 +01:00
|
|
|
}
|
|
|
|
|
return cursor;
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-04 12:40:26 +02:00
|
|
|
void ClangdClient::Private::setHelpItemForTooltip(const MessageId &token, const QString &fqn,
|
|
|
|
|
HelpItem::Category category,
|
|
|
|
|
const QString &type)
|
|
|
|
|
{
|
|
|
|
|
QStringList helpIds;
|
|
|
|
|
QString mark;
|
|
|
|
|
if (!fqn.isEmpty()) {
|
|
|
|
|
helpIds << fqn;
|
|
|
|
|
int sepSearchStart = 0;
|
|
|
|
|
while (true) {
|
|
|
|
|
sepSearchStart = fqn.indexOf("::", sepSearchStart);
|
|
|
|
|
if (sepSearchStart == -1)
|
|
|
|
|
break;
|
|
|
|
|
sepSearchStart += 2;
|
|
|
|
|
helpIds << fqn.mid(sepSearchStart);
|
|
|
|
|
}
|
|
|
|
|
mark = helpIds.last();
|
|
|
|
|
if (category == HelpItem::Function)
|
|
|
|
|
mark += type.mid(type.indexOf('('));
|
|
|
|
|
}
|
|
|
|
|
if (category == HelpItem::Enum && !type.isEmpty())
|
|
|
|
|
mark = type;
|
|
|
|
|
|
|
|
|
|
HelpItem helpItem(helpIds, mark, category);
|
|
|
|
|
if (isTesting)
|
|
|
|
|
emit q->helpItemGathered(helpItem);
|
|
|
|
|
else
|
|
|
|
|
q->hoverHandler()->setHelpItem(token, helpItem);
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-09 09:47:26 +02:00
|
|
|
// Unfortunately, clangd ignores almost everything except symbols when sending
|
|
|
|
|
// semantic token info, so we need to consult the AST for additional information.
|
|
|
|
|
// In particular, we inspect the following constructs:
|
|
|
|
|
// - Raw string literals, because our built-in lexer does not parse them properly.
|
|
|
|
|
// While we're at it, we also handle other types of literals.
|
|
|
|
|
// - Ternary expressions (for the matching of "?" and ":").
|
|
|
|
|
// - Template declarations and instantiations (for the matching of "<" and ">").
|
|
|
|
|
// - Function declarations, to find out whether a declaration is also a definition.
|
|
|
|
|
// - Function arguments, to find out whether they correspond to output parameters.
|
|
|
|
|
// - We consider most other tokens to be simple enough to be handled by the built-in code model.
|
|
|
|
|
// Sometimes we have no choice, as for #include directives, which appear neither
|
|
|
|
|
// in the semantic tokens nor in the AST.
|
2021-09-28 13:21:59 +02:00
|
|
|
void ClangdClient::Private::handleSemanticTokens(TextDocument *doc,
|
2021-10-22 15:06:46 +02:00
|
|
|
const QList<ExpandedSemanticToken> &tokens,
|
2021-11-15 14:58:40 +01:00
|
|
|
int version, bool force)
|
2021-06-09 09:47:26 +02:00
|
|
|
{
|
2021-10-01 12:23:05 +02:00
|
|
|
SubtaskTimer t(highlightingTimer);
|
2022-02-17 15:54:37 +01:00
|
|
|
qCInfo(clangdLogHighlight) << "handling LSP tokens" << doc->filePath()
|
|
|
|
|
<< version << tokens.size();
|
2021-10-22 15:06:46 +02:00
|
|
|
if (version != q->documentVersion(doc->filePath())) {
|
2022-02-17 15:54:37 +01:00
|
|
|
qCInfo(clangdLogHighlight) << "LSP tokens outdated; aborting highlighting procedure"
|
2021-10-22 15:06:46 +02:00
|
|
|
<< version << q->documentVersion(doc->filePath());
|
|
|
|
|
return;
|
|
|
|
|
}
|
2021-12-10 14:34:26 +01:00
|
|
|
force = force || isTesting;
|
2022-04-21 13:02:09 +02:00
|
|
|
const auto data = highlightingData.find(doc);
|
|
|
|
|
if (data != highlightingData.end()) {
|
|
|
|
|
if (!force && data->previousTokens.first == tokens
|
|
|
|
|
&& data->previousTokens.second == version) {
|
2022-02-17 15:54:37 +01:00
|
|
|
qCInfo(clangdLogHighlight) << "tokens and version same as last time; nothing to do";
|
2021-11-03 15:30:57 +01:00
|
|
|
return;
|
|
|
|
|
}
|
2022-04-21 13:02:09 +02:00
|
|
|
data->previousTokens.first = tokens;
|
|
|
|
|
data->previousTokens.second = version;
|
2021-11-03 15:30:57 +01:00
|
|
|
} else {
|
2022-04-21 13:02:09 +02:00
|
|
|
HighlightingData data;
|
|
|
|
|
data.previousTokens = qMakePair(tokens, version);
|
|
|
|
|
highlightingData.insert(doc, data);
|
2021-11-03 15:30:57 +01:00
|
|
|
}
|
2021-06-09 09:47:26 +02:00
|
|
|
for (const ExpandedSemanticToken &t : tokens)
|
2021-07-15 11:39:56 +02:00
|
|
|
qCDebug(clangdLogHighlight()) << '\t' << t.line << t.column << t.length << t.type
|
|
|
|
|
<< t.modifiers;
|
2021-06-09 09:47:26 +02:00
|
|
|
|
2022-05-18 18:15:41 +02:00
|
|
|
const auto astHandler = [this, tokens, doc, version](const ClangdAstNode &ast, const MessageId &) {
|
2021-10-01 12:23:05 +02:00
|
|
|
FinalizingSubtaskTimer t(highlightingTimer);
|
2021-06-09 09:47:26 +02:00
|
|
|
if (!q->documentOpen(doc))
|
|
|
|
|
return;
|
2021-10-22 15:06:46 +02:00
|
|
|
if (version != q->documentVersion(doc->filePath())) {
|
2022-02-17 15:54:37 +01:00
|
|
|
qCInfo(clangdLogHighlight) << "AST not up to date; aborting highlighting procedure"
|
2021-10-22 15:06:46 +02:00
|
|
|
<< version << q->documentVersion(doc->filePath());
|
|
|
|
|
return;
|
|
|
|
|
}
|
2021-09-27 16:24:37 +02:00
|
|
|
if (clangdLogAst().isDebugEnabled())
|
|
|
|
|
ast.print();
|
2021-06-09 09:47:26 +02:00
|
|
|
|
2021-10-14 12:47:24 +02:00
|
|
|
const auto runner = [tokens, filePath = doc->filePath(),
|
|
|
|
|
text = doc->document()->toPlainText(), ast,
|
2021-12-03 11:19:59 +01:00
|
|
|
doc = QPointer(doc), rev = doc->document()->revision(),
|
2022-03-04 19:42:46 +01:00
|
|
|
clangdVersion = q->versionNumber(),
|
|
|
|
|
this] {
|
2022-05-30 13:39:08 +02:00
|
|
|
return Utils::runAsync(doSemanticHighlighting, filePath, tokens, text, ast, doc, rev,
|
2022-03-04 19:42:46 +01:00
|
|
|
clangdVersion, highlightingTimer);
|
2021-06-09 09:47:26 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (isTesting) {
|
2021-09-28 13:21:59 +02:00
|
|
|
const auto watcher = new QFutureWatcher<HighlightingResult>(q);
|
|
|
|
|
connect(watcher, &QFutureWatcher<HighlightingResult>::finished,
|
2021-06-18 16:30:03 +02:00
|
|
|
q, [this, watcher, fp = doc->filePath()] {
|
|
|
|
|
emit q->highlightingResultsReady(watcher->future().results(), fp);
|
2021-06-09 09:47:26 +02:00
|
|
|
watcher->deleteLater();
|
|
|
|
|
});
|
|
|
|
|
watcher->setFuture(runner());
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-21 13:02:09 +02:00
|
|
|
auto &data = highlightingData[doc];
|
|
|
|
|
if (!data.highlighter)
|
|
|
|
|
data.highlighter = new CppEditor::SemanticHighlighter(doc);
|
|
|
|
|
else
|
|
|
|
|
data.highlighter->updateFormatMapFromFontSettings();
|
|
|
|
|
data.highlighter->setHighlightingRunner(runner);
|
|
|
|
|
data.highlighter->run();
|
2021-09-27 16:24:37 +02:00
|
|
|
};
|
|
|
|
|
getAndHandleAst(doc, astHandler, AstCallbackMode::SyncIfPossible);
|
2021-06-09 09:47:26 +02:00
|
|
|
}
|
|
|
|
|
|
2021-09-13 16:09:04 +02:00
|
|
|
Utils::optional<QList<CodeAction> > ClangdDiagnostic::codeActions() const
|
|
|
|
|
{
|
2022-05-13 17:13:02 +02:00
|
|
|
auto actions = optionalArray<LanguageServerProtocol::CodeAction>("codeActions");
|
|
|
|
|
if (!actions)
|
|
|
|
|
return actions;
|
|
|
|
|
static const QStringList badCodeActions{
|
|
|
|
|
"remove constant to silence this warning", // QTCREATORBUG-18593
|
|
|
|
|
};
|
|
|
|
|
for (auto it = actions->begin(); it != actions->end();) {
|
|
|
|
|
if (badCodeActions.contains(it->title()))
|
|
|
|
|
it = actions->erase(it);
|
|
|
|
|
else
|
|
|
|
|
++it;
|
|
|
|
|
}
|
|
|
|
|
return actions;
|
2021-09-13 16:09:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
QString ClangdDiagnostic::category() const
|
|
|
|
|
{
|
|
|
|
|
return typedValue<QString>("category");
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-15 11:35:19 +02:00
|
|
|
class ClangdClient::ClangdFunctionHintProcessor : public FunctionHintProcessor
|
2021-09-13 16:09:04 +02:00
|
|
|
{
|
2021-09-15 11:35:19 +02:00
|
|
|
public:
|
|
|
|
|
ClangdFunctionHintProcessor(ClangdClient *client)
|
|
|
|
|
: FunctionHintProcessor(client)
|
|
|
|
|
, m_client(client)
|
|
|
|
|
{}
|
|
|
|
|
|
|
|
|
|
private:
|
2021-09-28 13:21:59 +02:00
|
|
|
IAssistProposal *perform(const AssistInterface *interface) override
|
2021-09-15 11:35:19 +02:00
|
|
|
{
|
|
|
|
|
if (m_client->d->isTesting) {
|
2021-09-28 13:21:59 +02:00
|
|
|
setAsyncCompletionAvailableHandler([this](IAssistProposal *proposal) {
|
2021-09-15 11:35:19 +02:00
|
|
|
emit m_client->proposalReady(proposal);
|
|
|
|
|
});
|
2021-09-13 16:09:04 +02:00
|
|
|
}
|
2021-09-15 11:35:19 +02:00
|
|
|
return FunctionHintProcessor::perform(interface);
|
|
|
|
|
}
|
2021-09-13 16:09:04 +02:00
|
|
|
|
2021-09-15 11:35:19 +02:00
|
|
|
ClangdClient * const m_client;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
ClangdClient::ClangdCompletionAssistProvider::ClangdCompletionAssistProvider(ClangdClient *client)
|
|
|
|
|
: LanguageClientCompletionAssistProvider(client)
|
|
|
|
|
, m_client(client)
|
|
|
|
|
{}
|
2021-09-13 16:09:04 +02:00
|
|
|
|
2021-09-28 13:21:59 +02:00
|
|
|
IAssistProcessor *ClangdClient::ClangdCompletionAssistProvider::createProcessor(
|
2021-10-08 10:15:51 +02:00
|
|
|
const AssistInterface *interface) const
|
2021-09-15 08:10:30 +02:00
|
|
|
{
|
2021-10-15 11:31:13 +02:00
|
|
|
qCDebug(clangdLogCompletion) << "completion processor requested for" << interface->filePath();
|
|
|
|
|
qCDebug(clangdLogCompletion) << "text before cursor is"
|
|
|
|
|
<< interface->textAt(interface->position(), -10);
|
|
|
|
|
qCDebug(clangdLogCompletion) << "text after cursor is"
|
|
|
|
|
<< interface->textAt(interface->position(), 10);
|
2021-10-08 10:15:51 +02:00
|
|
|
ClangCompletionContextAnalyzer contextAnalyzer(interface->textDocument(),
|
|
|
|
|
interface->position(), false, {});
|
2021-09-15 08:10:30 +02:00
|
|
|
contextAnalyzer.analyze();
|
|
|
|
|
switch (contextAnalyzer.completionAction()) {
|
|
|
|
|
case ClangCompletionContextAnalyzer::PassThroughToLibClangAfterLeftParen:
|
2021-10-15 11:31:13 +02:00
|
|
|
qCDebug(clangdLogCompletion) << "creating function hint processor";
|
2021-09-15 11:35:19 +02:00
|
|
|
return new ClangdFunctionHintProcessor(m_client);
|
2021-09-15 08:10:30 +02:00
|
|
|
case ClangCompletionContextAnalyzer::CompleteDoxygenKeyword:
|
2021-10-15 11:31:13 +02:00
|
|
|
qCDebug(clangdLogCompletion) << "creating doxygen processor";
|
2021-09-28 15:10:47 +02:00
|
|
|
return new CustomAssistProcessor(m_client,
|
|
|
|
|
contextAnalyzer.positionForProposal(),
|
2021-11-10 12:35:06 +01:00
|
|
|
contextAnalyzer.positionEndOfExpression(),
|
2021-09-28 15:10:47 +02:00
|
|
|
contextAnalyzer.completionOperator(),
|
|
|
|
|
CustomAssistMode::Doxygen);
|
|
|
|
|
case ClangCompletionContextAnalyzer::CompletePreprocessorDirective:
|
2021-10-15 11:31:13 +02:00
|
|
|
qCDebug(clangdLogCompletion) << "creating macro processor";
|
2021-09-28 15:10:47 +02:00
|
|
|
return new CustomAssistProcessor(m_client,
|
|
|
|
|
contextAnalyzer.positionForProposal(),
|
2021-11-10 12:35:06 +01:00
|
|
|
contextAnalyzer.positionEndOfExpression(),
|
2021-09-28 15:10:47 +02:00
|
|
|
contextAnalyzer.completionOperator(),
|
|
|
|
|
CustomAssistMode::Preprocessor);
|
2021-09-15 08:10:30 +02:00
|
|
|
default:
|
|
|
|
|
break;
|
|
|
|
|
}
|
2021-10-08 10:15:51 +02:00
|
|
|
const QString snippetsGroup = contextAnalyzer.addSnippets() && !isInCommentOrString(interface)
|
2021-09-15 11:35:19 +02:00
|
|
|
? CppEditor::Constants::CPP_SNIPPETS_GROUP_ID
|
|
|
|
|
: QString();
|
2021-10-15 11:31:13 +02:00
|
|
|
qCDebug(clangdLogCompletion) << "creating proper completion processor"
|
|
|
|
|
<< (snippetsGroup.isEmpty() ? "without" : "with") << "snippets";
|
2021-09-15 11:35:19 +02:00
|
|
|
return new ClangdCompletionAssistProcessor(m_client, snippetsGroup);
|
2021-09-15 08:10:30 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bool ClangdClient::ClangdCompletionAssistProvider::isActivationCharSequence(const QString &sequence) const
|
2021-09-13 16:09:04 +02:00
|
|
|
{
|
|
|
|
|
const QChar &ch = sequence.at(2);
|
|
|
|
|
const QChar &ch2 = sequence.at(1);
|
|
|
|
|
const QChar &ch3 = sequence.at(0);
|
|
|
|
|
unsigned kind = T_EOF_SYMBOL;
|
|
|
|
|
const int pos = CppEditor::CppCompletionAssistProvider::activationSequenceChar(
|
|
|
|
|
ch, ch2, ch3, &kind, false, false);
|
|
|
|
|
if (pos == 0)
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
// We want to minimize unneeded completion requests, as those trigger document updates,
|
|
|
|
|
// which trigger re-highlighting and diagnostics, which we try to delay.
|
|
|
|
|
// Therefore, we do not trigger on syntax elements that often occur in non-applicable
|
|
|
|
|
// contexts, such as '(', '<' or '/'.
|
|
|
|
|
switch (kind) {
|
|
|
|
|
case T_DOT: case T_COLON_COLON: case T_ARROW: case T_DOT_STAR: case T_ARROW_STAR: case T_POUND:
|
2021-10-15 11:31:13 +02:00
|
|
|
qCDebug(clangdLogCompletion) << "detected" << sequence << "as activation char sequence";
|
2021-09-13 16:09:04 +02:00
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-15 08:10:30 +02:00
|
|
|
bool ClangdClient::ClangdCompletionAssistProvider::isContinuationChar(const QChar &c) const
|
2021-09-13 16:09:04 +02:00
|
|
|
{
|
|
|
|
|
return CppEditor::isValidIdentifierChar(c);
|
|
|
|
|
}
|
|
|
|
|
|
2021-10-08 10:15:51 +02:00
|
|
|
bool ClangdClient::ClangdCompletionAssistProvider::isInCommentOrString(
|
|
|
|
|
const AssistInterface *interface) const
|
|
|
|
|
{
|
2021-10-13 17:18:07 +02:00
|
|
|
LanguageFeatures features = LanguageFeatures::defaultFeatures();
|
|
|
|
|
features.objCEnabled = CppEditor::ProjectFile::isObjC(interface->filePath().toString());
|
|
|
|
|
return CppEditor::isInCommentOrString(interface, features);
|
2021-10-08 10:15:51 +02:00
|
|
|
}
|
|
|
|
|
|
2021-09-27 11:08:59 +02:00
|
|
|
void ClangdCompletionItem::apply(TextDocumentManipulatorInterface &manipulator,
|
|
|
|
|
int /*basePosition*/) const
|
2021-06-18 16:30:03 +02:00
|
|
|
{
|
2021-09-27 11:08:59 +02:00
|
|
|
const LanguageServerProtocol::CompletionItem item = this->item();
|
|
|
|
|
QChar typedChar = triggeredCommitCharacter();
|
2021-06-18 16:30:03 +02:00
|
|
|
const auto edit = item.textEdit();
|
|
|
|
|
if (!edit)
|
|
|
|
|
return;
|
|
|
|
|
|
2021-11-23 18:02:41 +01:00
|
|
|
const int labelOpenParenOffset = item.label().indexOf('(');
|
|
|
|
|
const int labelClosingParenOffset = item.label().indexOf(')');
|
2021-11-03 15:08:38 +01:00
|
|
|
const auto kind = static_cast<CompletionItemKind::Kind>(
|
|
|
|
|
item.kind().value_or(CompletionItemKind::Text));
|
2021-11-23 18:02:41 +01:00
|
|
|
const bool isMacroCall = kind == CompletionItemKind::Text && labelOpenParenOffset != -1
|
|
|
|
|
&& labelClosingParenOffset > labelOpenParenOffset; // Heuristic
|
2021-11-03 15:08:38 +01:00
|
|
|
const bool isFunctionLike = kind == CompletionItemKind::Function
|
2021-11-22 13:53:59 +01:00
|
|
|
|| kind == CompletionItemKind::Method || kind == CompletionItemKind::Constructor
|
|
|
|
|
|| isMacroCall;
|
|
|
|
|
|
2021-11-03 15:08:38 +01:00
|
|
|
QString rawInsertText = edit->newText();
|
|
|
|
|
|
|
|
|
|
// Some preparation for our magic involving (non-)insertion of parentheses and
|
|
|
|
|
// cursor placement.
|
|
|
|
|
if (isFunctionLike && !rawInsertText.contains('(')) {
|
2021-11-23 18:02:41 +01:00
|
|
|
if (labelOpenParenOffset != -1) {
|
|
|
|
|
if (labelClosingParenOffset == labelOpenParenOffset + 1) // function takes no arguments
|
|
|
|
|
rawInsertText += "()";
|
|
|
|
|
else // function takes arguments
|
|
|
|
|
rawInsertText += "( )";
|
|
|
|
|
}
|
2021-11-03 15:08:38 +01:00
|
|
|
}
|
|
|
|
|
|
2021-06-18 16:30:03 +02:00
|
|
|
const int firstParenOffset = rawInsertText.indexOf('(');
|
|
|
|
|
const int lastParenOffset = rawInsertText.lastIndexOf(')');
|
|
|
|
|
const QString detail = item.detail().value_or(QString());
|
2021-09-28 13:21:59 +02:00
|
|
|
const CompletionSettings &completionSettings = TextEditorSettings::completionSettings();
|
2021-06-18 16:30:03 +02:00
|
|
|
QString textToBeInserted = rawInsertText.left(firstParenOffset);
|
|
|
|
|
QString extraCharacters;
|
2021-10-12 17:45:26 +02:00
|
|
|
int extraLength = 0;
|
2021-06-18 16:30:03 +02:00
|
|
|
int cursorOffset = 0;
|
|
|
|
|
bool setAutoCompleteSkipPos = false;
|
2021-10-12 17:45:26 +02:00
|
|
|
int currentPos = manipulator.currentPosition();
|
|
|
|
|
const QTextDocument * const doc = manipulator.textCursorAt(currentPos).document();
|
2021-06-18 16:30:03 +02:00
|
|
|
const Range range = edit->range();
|
|
|
|
|
const int rangeStart = range.start().toPositionInDocument(doc);
|
2021-10-12 17:45:26 +02:00
|
|
|
if (isFunctionLike && completionSettings.m_autoInsertBrackets) {
|
2021-06-18 16:30:03 +02:00
|
|
|
// If the user typed the opening parenthesis, they'll likely also type the closing one,
|
|
|
|
|
// in which case it would be annoying if we put the cursor after the already automatically
|
|
|
|
|
// inserted closing parenthesis.
|
|
|
|
|
const bool skipClosingParenthesis = typedChar != '(';
|
|
|
|
|
QTextCursor cursor = manipulator.textCursorAt(rangeStart);
|
|
|
|
|
|
|
|
|
|
bool abandonParen = false;
|
|
|
|
|
if (matchPreviousWord(manipulator, cursor, "&")) {
|
|
|
|
|
moveToPreviousWord(manipulator, cursor);
|
|
|
|
|
moveToPreviousChar(manipulator, cursor);
|
|
|
|
|
const QChar prevChar = manipulator.characterAt(cursor.position());
|
|
|
|
|
cursor.setPosition(rangeStart);
|
|
|
|
|
abandonParen = QString("(;,{}=").contains(prevChar);
|
|
|
|
|
}
|
|
|
|
|
if (!abandonParen)
|
|
|
|
|
abandonParen = isAtUsingDeclaration(manipulator, rangeStart);
|
2021-11-22 13:53:59 +01:00
|
|
|
if (!abandonParen && !isMacroCall && matchPreviousWord(manipulator, cursor, detail))
|
|
|
|
|
abandonParen = true; // function definition
|
2021-06-18 16:30:03 +02:00
|
|
|
if (!abandonParen) {
|
|
|
|
|
if (completionSettings.m_spaceAfterFunctionName)
|
|
|
|
|
extraCharacters += ' ';
|
|
|
|
|
extraCharacters += '(';
|
|
|
|
|
if (typedChar == '(')
|
|
|
|
|
typedChar = {};
|
|
|
|
|
|
|
|
|
|
// If the function doesn't return anything, automatically place the semicolon,
|
|
|
|
|
// unless we're doing a scope completion (then it might be function definition).
|
2021-10-12 17:45:26 +02:00
|
|
|
const QChar characterAtCursor = manipulator.characterAt(currentPos);
|
2021-06-18 16:30:03 +02:00
|
|
|
bool endWithSemicolon = typedChar == ';';
|
|
|
|
|
const QChar semicolon = typedChar.isNull() ? QLatin1Char(';') : typedChar;
|
|
|
|
|
if (endWithSemicolon && characterAtCursor == semicolon) {
|
|
|
|
|
endWithSemicolon = false;
|
|
|
|
|
typedChar = {};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If the function takes no arguments, automatically place the closing parenthesis
|
|
|
|
|
if (firstParenOffset + 1 == lastParenOffset && skipClosingParenthesis) {
|
|
|
|
|
extraCharacters += QLatin1Char(')');
|
|
|
|
|
if (endWithSemicolon) {
|
|
|
|
|
extraCharacters += semicolon;
|
|
|
|
|
typedChar = {};
|
|
|
|
|
}
|
|
|
|
|
} else {
|
2021-10-12 17:45:26 +02:00
|
|
|
const QChar lookAhead = manipulator.characterAt(currentPos + 1);
|
2021-06-18 16:30:03 +02:00
|
|
|
if (MatchingText::shouldInsertMatchingText(lookAhead)) {
|
|
|
|
|
extraCharacters += ')';
|
|
|
|
|
--cursorOffset;
|
|
|
|
|
setAutoCompleteSkipPos = true;
|
|
|
|
|
if (endWithSemicolon) {
|
|
|
|
|
extraCharacters += semicolon;
|
|
|
|
|
--cursorOffset;
|
|
|
|
|
typedChar = {};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Append an unhandled typed character, adjusting cursor offset when it had been adjusted before
|
|
|
|
|
if (!typedChar.isNull()) {
|
|
|
|
|
extraCharacters += typedChar;
|
|
|
|
|
if (cursorOffset != 0)
|
|
|
|
|
--cursorOffset;
|
|
|
|
|
}
|
|
|
|
|
|
2021-10-12 17:45:26 +02:00
|
|
|
// Avoid inserting characters that are already there
|
|
|
|
|
QTextCursor cursor = manipulator.textCursorAt(rangeStart);
|
|
|
|
|
cursor.movePosition(QTextCursor::EndOfWord);
|
|
|
|
|
const QString textAfterCursor = manipulator.textAt(currentPos, cursor.position() - currentPos);
|
2022-02-10 14:01:14 +01:00
|
|
|
if (currentPos < cursor.position()
|
|
|
|
|
&& textToBeInserted != textAfterCursor
|
2021-10-12 17:45:26 +02:00
|
|
|
&& textToBeInserted.indexOf(textAfterCursor, currentPos - rangeStart) >= 0) {
|
|
|
|
|
currentPos = cursor.position();
|
|
|
|
|
}
|
|
|
|
|
for (int i = 0; i < extraCharacters.length(); ++i) {
|
|
|
|
|
const QChar a = extraCharacters.at(i);
|
|
|
|
|
const QChar b = manipulator.characterAt(currentPos + i);
|
|
|
|
|
if (a == b)
|
|
|
|
|
++extraLength;
|
|
|
|
|
else
|
|
|
|
|
break;
|
|
|
|
|
}
|
2021-06-18 16:30:03 +02:00
|
|
|
|
2021-10-12 17:45:26 +02:00
|
|
|
textToBeInserted += extraCharacters;
|
|
|
|
|
const int length = currentPos - rangeStart + extraLength;
|
|
|
|
|
const bool isReplaced = manipulator.replace(rangeStart, length, textToBeInserted);
|
2021-06-18 16:30:03 +02:00
|
|
|
manipulator.setCursorPosition(rangeStart + textToBeInserted.length());
|
|
|
|
|
if (isReplaced) {
|
|
|
|
|
if (cursorOffset)
|
|
|
|
|
manipulator.setCursorPosition(manipulator.currentPosition() + cursorOffset);
|
|
|
|
|
if (setAutoCompleteSkipPos)
|
|
|
|
|
manipulator.setAutoCompleteSkipPosition(manipulator.currentPosition());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (auto additionalEdits = item.additionalTextEdits()) {
|
|
|
|
|
for (const auto &edit : *additionalEdits)
|
|
|
|
|
applyTextEdit(manipulator, edit);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-10 14:44:41 +01:00
|
|
|
ClangdCompletionItem::SpecialQtType ClangdCompletionItem::getQtType(const CompletionItem &item)
|
|
|
|
|
{
|
|
|
|
|
const Utils::optional<MarkupOrString> doc = item.documentation();
|
|
|
|
|
if (!doc)
|
|
|
|
|
return SpecialQtType::None;
|
|
|
|
|
QString docText;
|
|
|
|
|
if (Utils::holds_alternative<QString>(*doc))
|
|
|
|
|
docText = Utils::get<QString>(*doc);
|
|
|
|
|
else if (Utils::holds_alternative<MarkupContent>(*doc))
|
|
|
|
|
docText = Utils::get<MarkupContent>(*doc).content();
|
|
|
|
|
if (docText.contains("Annotation: qt_signal"))
|
|
|
|
|
return SpecialQtType::Signal;
|
|
|
|
|
if (docText.contains("Annotation: qt_slot"))
|
|
|
|
|
return SpecialQtType::Slot;
|
|
|
|
|
return SpecialQtType::None;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
QIcon ClangdCompletionItem::icon() const
|
|
|
|
|
{
|
2022-06-17 09:48:54 +02:00
|
|
|
if (isDeprecated())
|
|
|
|
|
return Utils::Icons::WARNING.icon();
|
2021-11-10 14:44:41 +01:00
|
|
|
const SpecialQtType qtType = getQtType(item());
|
|
|
|
|
switch (qtType) {
|
|
|
|
|
case SpecialQtType::Signal:
|
|
|
|
|
return Utils::CodeModelIcon::iconForType(Utils::CodeModelIcon::Signal);
|
|
|
|
|
case SpecialQtType::Slot:
|
|
|
|
|
// FIXME: Add visibility info to completion item tags in clangd?
|
|
|
|
|
return Utils::CodeModelIcon::iconForType(Utils::CodeModelIcon::SlotPublic);
|
|
|
|
|
case SpecialQtType::None:
|
|
|
|
|
break;
|
|
|
|
|
}
|
2022-04-01 14:58:06 +02:00
|
|
|
if (item().kind().value_or(CompletionItemKind::Text) == CompletionItemKind::Property)
|
|
|
|
|
return Utils::CodeModelIcon::iconForType(Utils::CodeModelIcon::VarPublicStatic);
|
2021-11-10 14:44:41 +01:00
|
|
|
return LanguageClientCompletionItem::icon();
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-17 09:48:54 +02:00
|
|
|
QString ClangdCompletionItem::text() const
|
|
|
|
|
{
|
|
|
|
|
const QString clangdValue = LanguageClientCompletionItem::text();
|
|
|
|
|
if (isDeprecated())
|
|
|
|
|
return "[[deprecated]]" + clangdValue;
|
|
|
|
|
return clangdValue;
|
|
|
|
|
}
|
|
|
|
|
|
2021-09-27 16:24:37 +02:00
|
|
|
MessageId ClangdClient::Private::getAndHandleAst(const TextDocOrFile &doc,
|
|
|
|
|
const AstHandler &astHandler,
|
2021-10-07 10:58:54 +02:00
|
|
|
AstCallbackMode callbackMode, const Range &range)
|
2021-09-27 16:24:37 +02:00
|
|
|
{
|
2021-09-29 09:32:08 +02:00
|
|
|
const auto textDocPtr = Utils::get_if<const TextDocument *>(&doc);
|
2021-09-28 13:21:59 +02:00
|
|
|
const TextDocument * const textDoc = textDocPtr ? *textDocPtr : nullptr;
|
2021-09-29 09:32:08 +02:00
|
|
|
const Utils::FilePath filePath = textDoc ? textDoc->filePath()
|
|
|
|
|
: Utils::get<Utils::FilePath>(doc);
|
2021-09-27 16:24:37 +02:00
|
|
|
|
2021-10-07 10:58:54 +02:00
|
|
|
// If the entire AST is requested and the document's AST is in the cache and it is up to date,
|
|
|
|
|
// call the handler.
|
|
|
|
|
const bool fullAstRequested = !range.isValid();
|
|
|
|
|
if (fullAstRequested) {
|
|
|
|
|
if (const auto ast = textDoc ? astCache.get(textDoc) : externalAstCache.get(filePath)) {
|
|
|
|
|
qCDebug(clangdLog) << "using AST from cache";
|
|
|
|
|
switch (callbackMode) {
|
|
|
|
|
case AstCallbackMode::SyncIfPossible:
|
|
|
|
|
astHandler(*ast, {});
|
|
|
|
|
break;
|
|
|
|
|
case AstCallbackMode::AlwaysAsync:
|
|
|
|
|
QMetaObject::invokeMethod(q, [ast, astHandler] { astHandler(*ast, {}); },
|
2021-09-27 16:24:37 +02:00
|
|
|
Qt::QueuedConnection);
|
2021-10-07 10:58:54 +02:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
return {};
|
2021-09-27 16:24:37 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Otherwise retrieve the AST from clangd.
|
2022-05-18 18:15:41 +02:00
|
|
|
const auto wrapperHandler = [this, filePath, guardedTextDoc = QPointer(textDoc), astHandler,
|
|
|
|
|
fullAstRequested, docRev = textDoc ? getRevision(textDoc) : -1,
|
|
|
|
|
fileRev = getRevision(filePath)](const ClangdAstNode &ast, const MessageId &reqId) {
|
2021-09-27 16:24:37 +02:00
|
|
|
qCDebug(clangdLog) << "retrieved AST from clangd";
|
2021-10-07 10:58:54 +02:00
|
|
|
if (fullAstRequested) {
|
|
|
|
|
if (guardedTextDoc) {
|
|
|
|
|
if (docRev == getRevision(guardedTextDoc))
|
|
|
|
|
astCache.insert(guardedTextDoc, ast);
|
|
|
|
|
} else if (fileRev == getRevision(filePath) && !q->documentForFilePath(filePath)) {
|
|
|
|
|
externalAstCache.insert(filePath, ast);
|
|
|
|
|
}
|
2021-09-27 16:24:37 +02:00
|
|
|
}
|
|
|
|
|
astHandler(ast, reqId);
|
2022-05-18 18:15:41 +02:00
|
|
|
};
|
2021-09-27 16:24:37 +02:00
|
|
|
qCDebug(clangdLog) << "requesting AST for" << filePath;
|
2022-05-18 18:15:41 +02:00
|
|
|
return requestAst(q, filePath, range, wrapperHandler);
|
2021-09-27 16:24:37 +02:00
|
|
|
}
|
|
|
|
|
|
2021-11-16 14:12:41 +01:00
|
|
|
class MemoryTree : public JsonObject
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
using JsonObject::JsonObject;
|
|
|
|
|
|
|
|
|
|
// number of bytes used, including child components
|
|
|
|
|
qint64 total() const { return qint64(typedValue<double>(totalKey())); }
|
|
|
|
|
|
|
|
|
|
// number of bytes used, excluding child components
|
|
|
|
|
qint64 self() const { return qint64(typedValue<double>(selfKey())); }
|
|
|
|
|
|
|
|
|
|
// named child components
|
|
|
|
|
using NamedComponent = std::pair<MemoryTree, QString>;
|
|
|
|
|
QList<NamedComponent> children() const
|
|
|
|
|
{
|
|
|
|
|
QList<NamedComponent> components;
|
|
|
|
|
const auto obj = operator const QJsonObject &();
|
|
|
|
|
for (auto it = obj.begin(); it != obj.end(); ++it) {
|
|
|
|
|
if (it.key() == totalKey() || it.key() == selfKey())
|
|
|
|
|
continue;
|
|
|
|
|
components << std::make_pair(MemoryTree(it.value()), it.key());
|
|
|
|
|
}
|
|
|
|
|
return components;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
static QString totalKey() { return QLatin1String("_total"); }
|
|
|
|
|
static QString selfKey() { return QLatin1String("_self"); }
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
class MemoryTreeItem : public Utils::TreeItem
|
|
|
|
|
{
|
|
|
|
|
Q_DECLARE_TR_FUNCTIONS(MemoryTreeItem)
|
|
|
|
|
public:
|
|
|
|
|
MemoryTreeItem(const QString &displayName, const MemoryTree &tree)
|
|
|
|
|
: m_displayName(displayName), m_bytesUsed(tree.total())
|
|
|
|
|
{
|
|
|
|
|
for (const MemoryTree::NamedComponent &component : tree.children())
|
|
|
|
|
appendChild(new MemoryTreeItem(component.second, component.first));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
|
QVariant data(int column, int role) const override
|
|
|
|
|
{
|
|
|
|
|
switch (role) {
|
|
|
|
|
case Qt::DisplayRole:
|
|
|
|
|
if (column == 0)
|
|
|
|
|
return m_displayName;
|
|
|
|
|
return memString();
|
|
|
|
|
case Qt::TextAlignmentRole:
|
|
|
|
|
if (column == 1)
|
|
|
|
|
return Qt::AlignRight;
|
|
|
|
|
break;
|
|
|
|
|
default:
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
QString memString() const
|
|
|
|
|
{
|
|
|
|
|
static const QList<std::pair<int, QString>> factors{
|
|
|
|
|
std::make_pair(1000000000, QString("GB")),
|
|
|
|
|
std::make_pair(1000000, QString("MB")),
|
|
|
|
|
std::make_pair(1000, QString("KB")),
|
|
|
|
|
};
|
|
|
|
|
for (const auto &factor : factors) {
|
|
|
|
|
if (m_bytesUsed > factor.first)
|
|
|
|
|
return QString::number(qint64(std::round(double(m_bytesUsed) / factor.first)))
|
|
|
|
|
+ ' ' + factor.second;
|
|
|
|
|
}
|
|
|
|
|
return QString::number(m_bytesUsed) + " B";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const QString m_displayName;
|
|
|
|
|
const qint64 m_bytesUsed;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
class MemoryTreeModel : public Utils::BaseTreeModel
|
|
|
|
|
{
|
|
|
|
|
public:
|
|
|
|
|
MemoryTreeModel(QObject *parent) : BaseTreeModel(parent)
|
|
|
|
|
{
|
2022-02-16 14:32:48 +01:00
|
|
|
setHeader({MemoryUsageWidget::tr("Component"), MemoryUsageWidget::tr("Total Memory")});
|
2021-11-16 14:12:41 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void update(const MemoryTree &tree)
|
|
|
|
|
{
|
|
|
|
|
setRootItem(new MemoryTreeItem({}, tree));
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
MemoryUsageWidget::MemoryUsageWidget(ClangdClient *client)
|
|
|
|
|
: m_client(client), m_model(new MemoryTreeModel(this))
|
|
|
|
|
{
|
|
|
|
|
setupUi();
|
|
|
|
|
getMemoryTree();
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-09 09:58:48 +01:00
|
|
|
MemoryUsageWidget::~MemoryUsageWidget()
|
|
|
|
|
{
|
|
|
|
|
if (m_currentRequest.has_value())
|
|
|
|
|
m_client->cancelRequest(m_currentRequest.value());
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-16 14:12:41 +01:00
|
|
|
void MemoryUsageWidget::setupUi()
|
|
|
|
|
{
|
|
|
|
|
const auto layout = new QVBoxLayout(this);
|
|
|
|
|
m_view.setContextMenuPolicy(Qt::CustomContextMenu);
|
|
|
|
|
m_view.header()->setSectionResizeMode(QHeaderView::ResizeToContents);
|
|
|
|
|
m_view.header()->setStretchLastSection(false);
|
|
|
|
|
m_view.setModel(m_model);
|
|
|
|
|
layout->addWidget(&m_view);
|
|
|
|
|
connect(&m_view, &QWidget::customContextMenuRequested, this, [this](const QPoint &pos) {
|
|
|
|
|
QMenu menu;
|
|
|
|
|
menu.addAction(tr("Update"), [this] { getMemoryTree(); });
|
|
|
|
|
menu.exec(m_view.mapToGlobal(pos));
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void MemoryUsageWidget::getMemoryTree()
|
|
|
|
|
{
|
|
|
|
|
Request<MemoryTree, std::nullptr_t, JsonObject> request("$/memoryUsage", {});
|
|
|
|
|
request.setResponseCallback([this](decltype(request)::Response response) {
|
2022-02-09 09:58:48 +01:00
|
|
|
m_currentRequest.reset();
|
2021-11-16 14:12:41 +01:00
|
|
|
qCDebug(clangdLog) << "received memory usage response";
|
|
|
|
|
if (const auto result = response.result())
|
|
|
|
|
m_model->update(*result);
|
|
|
|
|
});
|
|
|
|
|
qCDebug(clangdLog) << "sending memory usage request";
|
2022-02-09 09:58:48 +01:00
|
|
|
m_currentRequest = request.id();
|
2022-05-12 09:51:39 +02:00
|
|
|
m_client->sendMessage(request, ClangdClient::SendDocUpdates::Ignore);
|
2021-11-16 14:12:41 +01:00
|
|
|
}
|
|
|
|
|
|
2021-04-20 14:42:29 +02:00
|
|
|
} // namespace Internal
|
|
|
|
|
} // namespace ClangCodeModel
|
2021-05-18 12:59:15 +02:00
|
|
|
|
|
|
|
|
Q_DECLARE_METATYPE(ClangCodeModel::Internal::ReplacementData)
|