clangbackendipcintegration.cpp 15.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://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 http://www.qt.io/terms-conditions.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

31
#include "clangbackendipcintegration.h"
32

33
#include "clangcompletionassistprocessor.h"
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include "clangmodelmanagersupport.h"
#include "clangutils.h"
#include "pchmanager.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>

#include <cpptools/abstracteditorsupport.h>
#include <cpptools/baseeditordocumentprocessor.h>
#include <cpptools/editordocumenthandle.h>

#include <texteditor/codeassist/functionhintproposal.h>
#include <texteditor/codeassist/iassistprocessor.h>
#include <texteditor/texteditor.h>

#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>

Marco Bubke's avatar
Marco Bubke committed
52 53 54 55 56 57 58 59 60 61
#include <clangbackendipc/cmbcodecompletedmessage.h>
#include <clangbackendipc/cmbcompletecodemessage.h>
#include <clangbackendipc/cmbechomessage.h>
#include <clangbackendipc/cmbregistertranslationunitsforcodecompletionmessage.h>
#include <clangbackendipc/cmbregisterprojectsforcodecompletionmessage.h>
#include <clangbackendipc/cmbunregistertranslationunitsforcodecompletionmessage.h>
#include <clangbackendipc/cmbunregisterprojectsforcodecompletionmessage.h>
#include <clangbackendipc/cmbmessages.h>
#include <clangbackendipc/projectpartsdonotexistmessage.h>
#include <clangbackendipc/translationunitdoesnotexistmessage.h>
62 63 64 65 66 67 68 69 70 71 72 73

#include <cplusplus/Icons.h>

#include <QElapsedTimer>
#include <QLoggingCategory>
#include <QProcess>

static Q_LOGGING_CATEGORY(log, "qtc.clangcodemodel.ipc")

using namespace CPlusPlus;
using namespace ClangCodeModel;
using namespace ClangCodeModel::Internal;
74
using namespace ClangBackEnd;
75 76 77 78 79 80
using namespace TextEditor;

namespace {

QString backendProcessPath()
{
81
    return Core::ICore::libexecPath()
82
            + QStringLiteral("/clangbackend")
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
            + QStringLiteral(QTC_HOST_EXE_SUFFIX);
}

} // anonymous namespace

IpcReceiver::IpcReceiver()
{
}

IpcReceiver::~IpcReceiver()
{
    deleteAndClearWaitingAssistProcessors();
}

void IpcReceiver::setAliveHandler(const IpcReceiver::AliveHandler &handler)
{
    m_aliveHandler = handler;
}

Marco Bubke's avatar
Marco Bubke committed
102
void IpcReceiver::addExpectedCodeCompletedMessage(
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        quint64 ticket,
        ClangCompletionAssistProcessor *processor)
{
    QTC_ASSERT(processor, return);
    QTC_CHECK(!m_assistProcessorsTable.contains(ticket));
    m_assistProcessorsTable.insert(ticket, processor);
}

void IpcReceiver::deleteAndClearWaitingAssistProcessors()
{
    qDeleteAll(m_assistProcessorsTable.begin(), m_assistProcessorsTable.end());
    m_assistProcessorsTable.clear();
}

void IpcReceiver::deleteProcessorsOfEditorWidget(TextEditor::TextEditorWidget *textEditorWidget)
{
    QMutableHashIterator<quint64, ClangCompletionAssistProcessor *> it(m_assistProcessorsTable);
    while (it.hasNext()) {
        it.next();
        ClangCompletionAssistProcessor *assistProcessor = it.value();
        if (assistProcessor->textEditorWidget() == textEditorWidget) {
            delete assistProcessor;
            it.remove();
        }
    }
}

void IpcReceiver::alive()
{
Marco Bubke's avatar
Marco Bubke committed
132
    qCDebug(log) << "<<< AliveMessage";
133 134 135 136
    QTC_ASSERT(m_aliveHandler, return);
    m_aliveHandler();
}

Marco Bubke's avatar
Marco Bubke committed
137
void IpcReceiver::echo(const EchoMessage &message)
138
{
Marco Bubke's avatar
Marco Bubke committed
139
    qCDebug(log) << "<<<" << message;
140 141
}

Marco Bubke's avatar
Marco Bubke committed
142
void IpcReceiver::codeCompleted(const CodeCompletedMessage &message)
143
{
Marco Bubke's avatar
Marco Bubke committed
144
    qCDebug(log) << "<<< CodeCompletedMessage with" << message.codeCompletions().size() << "items";
145

Marco Bubke's avatar
Marco Bubke committed
146
    const quint64 ticket = message.ticketNumber();
147
    QScopedPointer<ClangCompletionAssistProcessor> processor(m_assistProcessorsTable.take(ticket));
148
    if (processor) {
Marco Bubke's avatar
Marco Bubke committed
149
        const bool finished = processor->handleAvailableAsyncCompletions(message.codeCompletions());
150 151 152
        if (!finished)
            processor.take();
    }
153 154
}

Marco Bubke's avatar
Marco Bubke committed
155
void IpcReceiver::translationUnitDoesNotExist(const TranslationUnitDoesNotExistMessage &message)
156
{
Marco Bubke's avatar
Marco Bubke committed
157 158
    QTC_CHECK(!"Got TranslationUnitDoesNotExistMessage");
    qCDebug(log) << "<<< ERROR:" << message;
159 160
}

Marco Bubke's avatar
Marco Bubke committed
161
void IpcReceiver::projectPartsDoNotExist(const ProjectPartsDoNotExistMessage &message)
162
{
Marco Bubke's avatar
Marco Bubke committed
163 164
    QTC_CHECK(!"Got ProjectPartsDoNotExistMessage");
    qCDebug(log) << "<<< ERROR:" << message;
165 166 167 168 169
}

class IpcSender : public IpcSenderInterface
{
public:
170
    IpcSender(ClangBackEnd::ConnectionClient &connectionClient)
171 172 173 174
        : m_connection(connectionClient)
    {}

    void end() override;
Marco Bubke's avatar
Marco Bubke committed
175 176 177 178 179
    void registerTranslationUnitsForCodeCompletion(const ClangBackEnd::RegisterTranslationUnitForCodeCompletionMessage &message) override;
    void unregisterTranslationUnitsForCodeCompletion(const ClangBackEnd::UnregisterTranslationUnitsForCodeCompletionMessage &message) override;
    void registerProjectPartsForCodeCompletion(const ClangBackEnd::RegisterProjectPartsForCodeCompletionMessage &message) override;
    void unregisterProjectPartsForCodeCompletion(const ClangBackEnd::UnregisterProjectPartsForCodeCompletionMessage &message) override;
    void completeCode(const ClangBackEnd::CompleteCodeMessage &message) override;
180 181

private:
182
    ClangBackEnd::ConnectionClient &m_connection;
183 184 185 186 187
};

void IpcSender::end()
{
     QTC_CHECK(m_connection.isConnected());
Marco Bubke's avatar
Marco Bubke committed
188
     m_connection.sendEndMessage();
189 190
}

Marco Bubke's avatar
Marco Bubke committed
191
void IpcSender::registerTranslationUnitsForCodeCompletion(const RegisterTranslationUnitForCodeCompletionMessage &message)
192 193
{
     QTC_CHECK(m_connection.isConnected());
Marco Bubke's avatar
Marco Bubke committed
194
     m_connection.serverProxy().registerTranslationUnitsForCodeCompletion(message);
195 196
}

Marco Bubke's avatar
Marco Bubke committed
197
void IpcSender::unregisterTranslationUnitsForCodeCompletion(const UnregisterTranslationUnitsForCodeCompletionMessage &message)
198 199
{
     QTC_CHECK(m_connection.isConnected());
Marco Bubke's avatar
Marco Bubke committed
200
     m_connection.serverProxy().unregisterTranslationUnitsForCodeCompletion(message);
201 202
}

Marco Bubke's avatar
Marco Bubke committed
203
void IpcSender::registerProjectPartsForCodeCompletion(const RegisterProjectPartsForCodeCompletionMessage &message)
204 205
{
     QTC_CHECK(m_connection.isConnected());
Marco Bubke's avatar
Marco Bubke committed
206
     m_connection.serverProxy().registerProjectPartsForCodeCompletion(message);
207 208
}

Marco Bubke's avatar
Marco Bubke committed
209
void IpcSender::unregisterProjectPartsForCodeCompletion(const UnregisterProjectPartsForCodeCompletionMessage &message)
210 211
{
     QTC_CHECK(m_connection.isConnected());
Marco Bubke's avatar
Marco Bubke committed
212
     m_connection.serverProxy().unregisterProjectPartsForCodeCompletion(message);
213 214
}

Marco Bubke's avatar
Marco Bubke committed
215
void IpcSender::completeCode(const CompleteCodeMessage &message)
216 217
{
     QTC_CHECK(m_connection.isConnected());
Marco Bubke's avatar
Marco Bubke committed
218
     m_connection.serverProxy().completeCode(message);
219 220 221 222 223 224 225 226 227 228
}

IpcCommunicator::IpcCommunicator()
    : m_connection(&m_ipcReceiver)
    , m_ipcSender(new IpcSender(m_connection))
{
    m_ipcReceiver.setAliveHandler([this]() { m_connection.resetProcessAliveTimer(); });

    connect(Core::EditorManager::instance(), &Core::EditorManager::editorAboutToClose,
            this, &IpcCommunicator::onEditorAboutToClose);
229 230
    connect(Core::ICore::instance(), &Core::ICore::coreAboutToClose,
            this, &IpcCommunicator::onCoreAboutToClose);
231 232 233 234

    initializeBackend();
}

Marco Bubke's avatar
Marco Bubke committed
235
static bool areMessagesRegistered = false;
236 237 238

void IpcCommunicator::initializeBackend()
{
Marco Bubke's avatar
Marco Bubke committed
239 240 241
    if (!areMessagesRegistered) {
        areMessagesRegistered = true;
        Messages::registerMessages();
242 243
    }

244 245 246
    const QString clangBackEndProcessPath = backendProcessPath();
    qCDebug(log) << "Starting" << clangBackEndProcessPath;
    QTC_ASSERT(QFileInfo(clangBackEndProcessPath).exists(), return);
247

248
    m_connection.setProcessAliveTimerInterval(30 * 1000);
249
    m_connection.setProcessPath(clangBackEndProcessPath);
250 251 252 253

    connect(&m_connection, &ConnectionClient::processRestarted,
            this, &IpcCommunicator::onBackendRestarted);

254 255
    // TODO: Add a asynchron API to ConnectionClient, otherwise we might hang here
    if (m_connection.connectToServer())
256 257 258 259 260 261
        initializeBackendWithCurrentData();
}

void IpcCommunicator::registerEmptyProjectForProjectLessFiles()
{
    QTC_CHECK(m_connection.isConnected());
262
    registerProjectPartsForCodeCompletion({ClangBackEnd::ProjectPartContainer(
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
                                           Utf8String(),
                                           Utf8StringVector())});
}

void IpcCommunicator::registerCurrentProjectParts()
{
    using namespace CppTools;

    const QList<ProjectInfo> projectInfos = CppModelManager::instance()->projectInfos();
    foreach (const ProjectInfo &projectInfo, projectInfos)
        registerProjectsParts(projectInfo.projectParts());
}

void IpcCommunicator::registerCurrentUnsavedFiles()
{
    using namespace CppTools;

    const auto cppEditorDocuments = CppModelManager::instance()->cppEditorDocuments();
    foreach (const CppEditorDocumentHandle *cppEditorDocument, cppEditorDocuments) {
        if (cppEditorDocument->processor()->baseTextDocument()->isModified())
            updateUnsavedFileFromCppEditorDocument(cppEditorDocument->filePath());
    }

}

void IpcCommunicator::registerCurrrentCodeModelUiHeaders()
{
    using namespace CppTools;

    const auto editorSupports = CppModelManager::instance()->abstractEditorSupports();
    foreach (const AbstractEditorSupport *es, editorSupports)
        updateUnsavedFile(es->fileName(), es->contents());
}

Marco Bubke's avatar
Marco Bubke committed
297
static QStringList projectPartMessageLine(const CppTools::ProjectPart::Ptr &projectPart)
298 299 300 301 302 303 304 305
{
    QStringList options = ClangCodeModel::Utils::createClangOptions(projectPart,
        CppTools::ProjectFile::Unclassified); // No language option
    if (PchInfo::Ptr pchInfo = PchManager::instance()->pchInfo(projectPart))
        options += ClangCodeModel::Utils::createPCHInclusionOptions(pchInfo->fileName());
    return options;
}

306
static ClangBackEnd::ProjectPartContainer toProjectPartContainer(
307 308
        const CppTools::ProjectPart::Ptr &projectPart)
{
Marco Bubke's avatar
Marco Bubke committed
309
    const QStringList arguments = projectPartMessageLine(projectPart);
310
    return ClangBackEnd::ProjectPartContainer(projectPart->id(), Utf8StringVector(arguments));
311 312
}

313
static QVector<ClangBackEnd::ProjectPartContainer> toProjectPartContainers(
314 315
        const QList<CppTools::ProjectPart::Ptr> projectParts)
{
316
    QVector<ClangBackEnd::ProjectPartContainer> projectPartContainers;
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
    projectPartContainers.reserve(projectParts.size());
    foreach (const CppTools::ProjectPart::Ptr &projectPart, projectParts)
        projectPartContainers << toProjectPartContainer(projectPart);
    return projectPartContainers;
}

void IpcCommunicator::registerProjectsParts(const QList<CppTools::ProjectPart::Ptr> projectParts)
{
    const auto projectPartContainers = toProjectPartContainers(projectParts);
    registerProjectPartsForCodeCompletion(projectPartContainers);
}

void IpcCommunicator::updateUnsavedFileFromCppEditorDocument(const QString &filePath)
{
    const QByteArray unsavedContent = CppTools::CppModelManager::instance()
            ->cppEditorDocument(filePath)->contents();
    updateUnsavedFile(filePath, unsavedContent);
}

void IpcCommunicator::updateUnsavedFile(const QString &filePath, const QByteArray &contents)
{
338
    const QString projectPartId = Utils::projectPartIdForFile(filePath);
339 340 341 342
    const bool hasUnsavedContent = true;

    // TODO: Send new only if changed
    registerFilesForCodeCompletion({
343
        ClangBackEnd::FileContainer(filePath,
344
            projectPartId,
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
            Utf8String::fromByteArray(contents),
            hasUnsavedContent)
    });
}

void IpcCommunicator::updateUnsavedFileIfNotCurrentDocument(Core::IDocument *document)
{
    QTC_ASSERT(document, return);

    if (Core::EditorManager::currentDocument() != document)
        updateUnsavedFileFromCppEditorDocument(document->filePath().toString());
}

void IpcCommunicator::onBackendRestarted()
{
360
    qWarning("Clang back end finished unexpectedly, restarted.");
361 362 363 364 365 366 367 368 369 370 371 372
    qCDebug(log) << "Backend restarted, re-initializing with project data and unsaved files.";

    m_ipcReceiver.deleteAndClearWaitingAssistProcessors();
    initializeBackendWithCurrentData();
}

void IpcCommunicator::onEditorAboutToClose(Core::IEditor *editor)
{
    if (auto *textEditor = qobject_cast<TextEditor::BaseTextEditor *>(editor))
        m_ipcReceiver.deleteProcessorsOfEditorWidget(textEditor->editorWidget());
}

373 374 375 376 377
void IpcCommunicator::onCoreAboutToClose()
{
    m_sendMode = IgnoreSendRequests;
}

378 379 380 381 382 383 384 385 386 387 388 389
void IpcCommunicator::initializeBackendWithCurrentData()
{
    registerEmptyProjectForProjectLessFiles();
    registerCurrentProjectParts();
    registerCurrentUnsavedFiles();
    registerCurrrentCodeModelUiHeaders();

    emit backendReinitialized();
}

IpcSenderInterface *IpcCommunicator::setIpcSender(IpcSenderInterface *ipcSender)
{
Marco Bubke's avatar
Marco Bubke committed
390
    IpcSenderInterface *previousMessageSender = m_ipcSender.take();
391
    m_ipcSender.reset(ipcSender);
Marco Bubke's avatar
Marco Bubke committed
392
    return previousMessageSender;
393 394 395 396 397 398 399 400 401 402 403 404
}

void IpcCommunicator::killBackendProcess()
{
    m_connection.processForTestOnly()->kill();
}

void IpcCommunicator::registerFilesForCodeCompletion(const FileContainers &fileContainers)
{
    if (m_sendMode == IgnoreSendRequests)
        return;

Marco Bubke's avatar
Marco Bubke committed
405 406 407
    const RegisterTranslationUnitForCodeCompletionMessage message(fileContainers);
    qCDebug(log) << ">>>" << message;
    m_ipcSender->registerTranslationUnitsForCodeCompletion(message);
408 409 410 411 412 413 414
}

void IpcCommunicator::unregisterFilesForCodeCompletion(const FileContainers &fileContainers)
{
    if (m_sendMode == IgnoreSendRequests)
        return;

Marco Bubke's avatar
Marco Bubke committed
415 416 417
    const UnregisterTranslationUnitsForCodeCompletionMessage message(fileContainers);
    qCDebug(log) << ">>>" << message;
    m_ipcSender->unregisterTranslationUnitsForCodeCompletion(message);
418 419 420 421 422 423 424 425
}

void IpcCommunicator::registerProjectPartsForCodeCompletion(
        const ProjectPartContainers &projectPartContainers)
{
    if (m_sendMode == IgnoreSendRequests)
        return;

Marco Bubke's avatar
Marco Bubke committed
426 427 428
    const RegisterProjectPartsForCodeCompletionMessage message(projectPartContainers);
    qCDebug(log) << ">>>" << message;
    m_ipcSender->registerProjectPartsForCodeCompletion(message);
429 430
}

431
void IpcCommunicator::unregisterProjectPartsForCodeCompletion(const QStringList &projectPartIds)
432 433 434 435
{
    if (m_sendMode == IgnoreSendRequests)
        return;

Marco Bubke's avatar
Marco Bubke committed
436 437 438
    const UnregisterProjectPartsForCodeCompletionMessage message((Utf8StringVector(projectPartIds)));
    qCDebug(log) << ">>>" << message;
    m_ipcSender->unregisterProjectPartsForCodeCompletion(message);
439 440 441 442 443 444 445 446 447 448 449
}

void IpcCommunicator::completeCode(ClangCompletionAssistProcessor *assistProcessor,
                              const QString &filePath,
                              quint32 line,
                              quint32 column,
                              const QString &projectFilePath)
{
    if (m_sendMode == IgnoreSendRequests)
        return;

Marco Bubke's avatar
Marco Bubke committed
450 451 452 453
    const CompleteCodeMessage message(filePath, line, column, projectFilePath);
    qCDebug(log) << ">>>" << message;
    m_ipcSender->completeCode(message);
    m_ipcReceiver.addExpectedCodeCompletedMessage(message.ticketNumber(), assistProcessor);
454
}