aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmlls/qlanguageserver.cpp
blob: b65873ef5d08bec459a2efe4acb537a310ce22fd (plain)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qlanguageserver_p_p.h"

#include <QtLanguageServer/private/qlspnotifysignals_p.h>
#include <QtJsonRpc/private/qjsonrpcprotocol_p_p.h>

QT_BEGIN_NAMESPACE

using namespace QLspSpecification;
using namespace Qt::StringLiterals;

Q_LOGGING_CATEGORY(lspServerLog, "qt.languageserver.server")

QLanguageServerPrivate::QLanguageServerPrivate(const QJsonRpcTransport::DataHandler &h)
    : protocol(h)
{
}

/*!
\internal
\class QLanguageServer
\brief Implements a server for the language server protocol

QLanguageServer is a class that uses the QLanguageServerProtocol to
provide a server implementation.
It handles the lifecycle management, and can be extended via
QLanguageServerModule subclasses.

The language server keeps a strictly monotonically increasing runState that can be queried
from any thread (and is thus mutex gated), the normal run state is DidInitialize.

The language server also keeps track of the task canceled by the client (or implicitly when
shutting down, and isRequestCanceled can be called from any thread.
*/

QLanguageServer::QLanguageServer(const QJsonRpcTransport::DataHandler &h, QObject *parent)
    : QObject(*new QLanguageServerPrivate(h), parent)
{
    Q_D(QLanguageServer);
    registerMethods(*d->protocol.typedRpc());
    d->notifySignals.registerHandlers(&d->protocol);
}

QLanguageServerProtocol *QLanguageServer::protocol()
{
    Q_D(QLanguageServer);
    return &d->protocol;
}

QLanguageServer::RunStatus QLanguageServer::runStatus() const
{
    const Q_D(QLanguageServer);
    QMutexLocker l(&d->mutex);
    return d->runStatus;
}

void QLanguageServer::finishSetup()
{
    Q_D(QLanguageServer);
    RunStatus rStatus;
    {
        QMutexLocker l(&d->mutex);
        rStatus = d->runStatus;
        if (rStatus == RunStatus::NotSetup)
            d->runStatus = RunStatus::SettingUp;
    }
    if (rStatus != RunStatus::NotSetup) {
        emit lifecycleError();
        return;
    }
    emit runStatusChanged(RunStatus::SettingUp);

    registerHandlers(&d->protocol);
    for (auto module : d->modules)
        module->registerHandlers(this, &d->protocol);

    {
        QMutexLocker l(&d->mutex);
        rStatus = d->runStatus;
        if (rStatus == RunStatus::SettingUp)
            d->runStatus = RunStatus::DidSetup;
    }
    if (rStatus != RunStatus::SettingUp) {
        emit lifecycleError();
        return;
    }
    emit runStatusChanged(RunStatus::DidSetup);
}

void QLanguageServer::addServerModule(QLanguageServerModule *serverModule)
{
    Q_D(QLanguageServer);
    Q_ASSERT(serverModule);
    RunStatus rStatus;
    {
        QMutexLocker l(&d->mutex);
        rStatus = d->runStatus;
        if (rStatus == RunStatus::NotSetup) {
            if (d->modules.contains(serverModule->name())) {
                d->modules.insert(serverModule->name(), serverModule);
                qCWarning(lspServerLog) << "Duplicate add of QLanguageServerModule named"
                                        << serverModule->name() << ", overwriting.";
            } else {
                d->modules.insert(serverModule->name(), serverModule);
            }
        }
    }
    if (rStatus != RunStatus::NotSetup) {
        qCWarning(lspServerLog) << "Called QLanguageServer::addServerModule after setup";
        emit lifecycleError();
        return;
    }
}

QLanguageServerModule *QLanguageServer::moduleByName(const QString &n) const
{
    const Q_D(QLanguageServer);
    QMutexLocker l(&d->mutex);
    return d->modules.value(n);
}

QLspNotifySignals *QLanguageServer::notifySignals()
{
    Q_D(QLanguageServer);
    return &d->notifySignals;
}

void QLanguageServer::registerMethods(QJsonRpc::TypedRpc &typedRpc)
{
    typedRpc.installMessagePreprocessor(
            [this](const QJsonDocument &doc, const QJsonParseError &err,
                   const QJsonRpcProtocol::Handler<QJsonRpcProtocol::Response> &responder) {
                Q_D(QLanguageServer);
                if (!doc.isObject()) {
                    qCWarning(lspServerLog)
                            << "non object jsonrpc message" << doc << err.errorString();
                    return QJsonRpcProtocol::Processing::Stop;
                }
                bool sendErrorResponse = false;
                RunStatus rState;
                QJsonValue id = doc.object()[u"id"];
                {
                    QMutexLocker l(&d->mutex);
                    // the normal case is d->runStatus == RunStatus::DidInitialize
                    if (d->runStatus != RunStatus::DidInitialize) {
                        if (d->runStatus == RunStatus::DidSetup && !doc.isNull()
                            && doc.object()[u"method"].toString()
                                    == QString::fromUtf8(
                                            QLspSpecification::Requests::InitializeMethod)) {
                            return QJsonRpcProtocol::Processing::Continue;
                        } else if (!doc.isNull()
                                   && doc.object()[u"method"].toString()
                                           == QString::fromUtf8(
                                                   QLspSpecification::Notifications::ExitMethod)) {
                            return QJsonRpcProtocol::Processing::Continue;
                        }
                        if (id.isString() || id.isDouble()) {
                            sendErrorResponse = true;
                            rState = d->runStatus;
                        } else {
                            return QJsonRpcProtocol::Processing::Stop;
                        }
                    }
                }
                if (!sendErrorResponse) {
                    if (id.isString() || id.isDouble()) {
                        QMutexLocker l(&d->mutex);
                        d->requestsInProgress.insert(id, QRequestInProgress {});
                    }
                    return QJsonRpcProtocol::Processing::Continue;
                }
                if (rState == RunStatus::NotSetup || rState == RunStatus::DidSetup)
                    responder(QJsonRpcProtocol::MessageHandler::error(
                            int(QLspSpecification::ErrorCodes::ServerNotInitialized),
                            u"Request on non initialized Language Server (runStatus %1): %2"_s
                                    .arg(int(rState))
                                    .arg(QString::fromUtf8(doc.toJson()))));
                else
                    responder(QJsonRpcProtocol::MessageHandler::error(
                            int(QLspSpecification::ErrorCodes::InvalidRequest),
                            u"Method called on stopping Language Server (runStatus %1)"_s.arg(
                                    int(rState))));
                return QJsonRpcProtocol::Processing::Stop;
            });
    typedRpc.installOnCloseAction([this](QJsonRpc::TypedResponse::Status,
                                         const QJsonRpc::IdType &id, QJsonRpc::TypedRpc &) {
        Q_D(QLanguageServer);
        QJsonValue idValue = QTypedJson::toJsonValue(id);
        bool lastReq;
        {
            QMutexLocker l(&d->mutex);
            d->requestsInProgress.remove(idValue);
            lastReq = d->runStatus == RunStatus::WaitPending && d->requestsInProgress.size() <= 1;
            if (lastReq)
                d->runStatus = RunStatus::Stopping;
        }
        if (lastReq)
            executeShutdown();
    });
}

void QLanguageServer::setupCapabilities(const QLspSpecification::InitializeParams &clientInfo,
                                        QLspSpecification::InitializeResult &serverInfo)
{
    Q_D(QLanguageServer);
    for (auto module : std::as_const(d->modules))
        module->setupCapabilities(clientInfo, serverInfo);
}

const QLspSpecification::InitializeParams &QLanguageServer::clientInfo() const
{
    const Q_D(QLanguageServer);

    if (int(runStatus()) < int(RunStatus::DidInitialize))
        qCWarning(lspServerLog) << "asked for Language Server clientInfo before initialization";
    return d->clientInfo;
}

const QLspSpecification::InitializeResult &QLanguageServer::serverInfo() const
{
    const Q_D(QLanguageServer);
    if (int(runStatus()) < int(RunStatus::DidInitialize))
        qCWarning(lspServerLog) << "asked for Language Server serverInfo before initialization";
    return d->serverInfo;
}

void QLanguageServer::receiveData(const QByteArray &d)
{
    protocol()->receiveData(d);
}

void QLanguageServer::registerHandlers(QLanguageServerProtocol *protocol)
{
    QObject::connect(notifySignals(), &QLspNotifySignals::receivedCancelNotification, this,
                     [this](const QLspSpecification::Notifications::CancelParamsType &params) {
                         Q_D(QLanguageServer);
                         QJsonValue id = QTypedJson::toJsonValue(params.id);
                         QMutexLocker l(&d->mutex);
                         if (d->requestsInProgress.contains(id))
                             d->requestsInProgress[id].canceled = true;
                         else
                             qCWarning(lspServerLog)
                                     << "Ignoring cancellation of non in progress request" << id;
                     });

    protocol->registerInitializeRequestHandler(
            [this](const QByteArray &,
                   const QLspSpecification::Requests::InitializeParamsType &params,
                   QLspSpecification::Responses::InitializeResponseType &&response) {
                qCDebug(lspServerLog) << "init";
                Q_D(QLanguageServer);
                RunStatus rStatus;
                {
                    QMutexLocker l(&d->mutex);
                    rStatus = d->runStatus;
                    if (rStatus == RunStatus::DidSetup)
                        d->runStatus = RunStatus::Initializing;
                }
                if (rStatus != RunStatus::DidSetup) {
                    if (rStatus == RunStatus::NotSetup || rStatus == RunStatus::SettingUp)
                        response.sendErrorResponse(
                                int(QLspSpecification::ErrorCodes::InvalidRequest),
                                u"Initialization request received on non setup language server"_s
                                        .toUtf8());
                    else
                        response.sendErrorResponse(
                                int(QLspSpecification::ErrorCodes::InvalidRequest),
                                u"Received multiple initialization requests"_s.toUtf8());
                    emit lifecycleError();
                    return;
                }
                emit runStatusChanged(RunStatus::Initializing);
                d->clientInfo = params;
                setupCapabilities(d->clientInfo, d->serverInfo);
                {
                    QMutexLocker l(&d->mutex);
                    d->runStatus = RunStatus::DidInitialize;
                }
                emit runStatusChanged(RunStatus::DidInitialize);
                response.sendResponse(d->serverInfo);
            });

    QObject::connect(notifySignals(), &QLspNotifySignals::receivedInitializedNotification, this,
                     [this](const QLspSpecification::Notifications::InitializedParamsType &) {
                         Q_D(QLanguageServer);
                         {
                             QMutexLocker l(&d->mutex);
                             d->clientInitialized = true;
                         }
                         emit clientInitialized(this);
                     });

    protocol->registerShutdownRequestHandler(
            [this](const QByteArray &, const QLspSpecification::Requests::ShutdownParamsType &,
                   QLspSpecification::Responses::ShutdownResponseType &&response) {
                Q_D(QLanguageServer);
                RunStatus rStatus;
                bool shouldExecuteShutdown = false;
                {
                    QMutexLocker l(&d->mutex);
                    rStatus = d->runStatus;
                    if (rStatus == RunStatus::DidInitialize) {
                        d->shutdownResponse = std::move(response);
                        if (d->requestsInProgress.size() <= 1) {
                            d->runStatus = RunStatus::Stopping;
                            shouldExecuteShutdown = true;
                        } else {
                            d->runStatus = RunStatus::WaitPending;
                        }
                    }
                }
                if (rStatus != RunStatus::DidInitialize)
                    emit lifecycleError();
                else if (shouldExecuteShutdown)
                    executeShutdown();
            });

    QObject::connect(notifySignals(), &QLspNotifySignals::receivedExitNotification, this,
                     [this](const QLspSpecification::Notifications::ExitParamsType &) {
                         if (runStatus() != RunStatus::Stopped)
                             emit lifecycleError();
                         else
                             emit exit();
                     });
}

void QLanguageServer::executeShutdown()
{
    RunStatus rStatus = runStatus();
    if (rStatus != RunStatus::Stopping) {
        emit lifecycleError();
        return;
    }
    emit shutdown();
    QLspSpecification::Responses::ShutdownResponseType shutdownResponse;
    {
        Q_D(QLanguageServer);
        QMutexLocker l(&d->mutex);
        rStatus = d->runStatus;
        if (rStatus == RunStatus::Stopping) {
            shutdownResponse = std::move(d->shutdownResponse);
            d->runStatus = RunStatus::Stopped;
        }
    }
    if (rStatus != RunStatus::Stopping)
        emit lifecycleError();
    else
        shutdownResponse.sendResponse(nullptr);
}

bool QLanguageServer::isRequestCanceled(const QJsonRpc::IdType &id) const
{
    const Q_D(QLanguageServer);
    QJsonValue idVal = QTypedJson::toJsonValue(id);
    QMutexLocker l(&d->mutex);
    return d->requestsInProgress.value(idVal).canceled || d->runStatus != RunStatus::DidInitialize;
}

bool QLanguageServer::isInitialized() const
{
    switch (runStatus()) {
    case RunStatus::NotSetup:
    case RunStatus::SettingUp:
    case RunStatus::DidSetup:
    case RunStatus::Initializing:
        return false;
    case RunStatus::DidInitialize:
    case RunStatus::WaitPending:
    case RunStatus::Stopping:
    case RunStatus::Stopped:
        break;
    }
    return true;
}

QT_END_NAMESPACE