aboutsummaryrefslogtreecommitdiffstats
path: root/tools/qmlls/qmllanguageservertool.cpp
blob: 896e0c049c1eb3e10140e4658995877d9e00b967 (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
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "qqmllanguageserver.h"
#include <QtCore/qdebug.h>
#include <QtCore/qfile.h>
#include <QtCore/qdir.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qcoreapplication.h>
#include "../shared/qqmltoolingsettings.h"
#include <QtCore/qdiriterator.h>
#include <QtCore/qjsonobject.h>
#include <QtCore/qjsonarray.h>
#include <QtCore/qjsondocument.h>
#include <QtCore/qmutex.h>
#include <QtCore/QMutexLocker>
#include <QtCore/qscopedpointer.h>
#include <QtCore/qrunnable.h>
#include <QtCore/qthreadpool.h>
#include <QtCore/qtimer.h>

#include <QtJsonRpc/private/qhttpmessagestreamparser_p.h>

#include <QtQmlCompiler/private/qqmljsresourcefilemapper_p.h>
#include <QtQmlCompiler/private/qqmljscompiler_p.h>
#include <QtQmlCompiler/private/qqmljslogger_p.h>
#include <QtQmlCompiler/private/qqmljsscope_p.h>
#include <QtQmlCompiler/private/qqmljsimporter_p.h>
#if QT_CONFIG(commandlineparser)
#    include <QtCore/qcommandlineparser.h>
#endif

#ifndef QT_BOOTSTRAPPED
#    include <QtCore/qlibraryinfo.h>
#endif

#include <iostream>
#ifdef Q_OS_WIN32
#    include <fcntl.h>
#    include <io.h>
#endif

using namespace QmlLsp;

QFile *logFile = nullptr;
QBasicMutex *logFileLock = nullptr;

class StdinReader : public QObject
{
    Q_OBJECT
public:
    void run()
    {
        auto guard = qScopeGuard([this]() { emit eof(); });
        const constexpr qsizetype bufSize = 1024;
        qsizetype bytesInBuf = 0;
        char bufferData[2 * bufSize];
        char *buffer = static_cast<char *>(bufferData);

        auto trySend = [this, &bytesInBuf, buffer]() {
            if (bytesInBuf == 0)
                return;
            qsizetype toSend = bytesInBuf;
            bytesInBuf = 0;
            QByteArray dataToSend(buffer, toSend);
            emit receivedData(dataToSend);
        };
        QHttpMessageStreamParser streamParser(
                [](const QByteArray &, const QByteArray &) { /* just a header, do nothing */ },
                [&trySend](const QByteArray &) {
                    // message body
                    trySend();
                },
                [&trySend](QtMsgType, QString) {
                    // there was an error
                    trySend();
                },
                QHttpMessageStreamParser::UNBUFFERED);

        while (std::cin.get(buffer[bytesInBuf])) { // should poll/select and process events
            qsizetype readNow = std::cin.readsome(buffer + bytesInBuf + 1, bufSize) + 1;
            QByteArray toAdd(buffer + bytesInBuf, readNow);
            bytesInBuf += readNow;
            if (bytesInBuf >= bufSize)
                trySend();
            streamParser.receiveData(toAdd);
        }
        trySend();
    }
signals:
    void receivedData(const QByteArray &data);
    void eof();
};

// To debug:
//
// * simple logging can be redirected to a file
//   passing -l <file> to the qmlls command
//
// * more complex debugging can use named pipes:
//
//     mkfifo qmllsIn
//     mkfifo qmllsOut
//
// this together with a qmllsEcho script that can be defined as
//
//     #!/bin/sh
//     cat -u < ~/qmllsOut &
//     cat -u > ~/qmllsIn
//
// allows to use qmllsEcho as lsp server, and still easily start
// it in a terminal
//
//     qmlls < ~/qmllsIn > ~/qmllsOut
//
// * statup can be slowed down to have the time to attach via the
//   -w <nSeconds> flag.

int main(int argv, char *argc[])
{
#ifdef Q_OS_WIN32
    // windows does not open stdin/stdout in binary mode by default
    int err = _setmode(_fileno(stdout), _O_BINARY);
    if (err == -1)
        perror("Cannot set mode for stdout");
    err = _setmode(_fileno(stdin), _O_BINARY);
    if (err == -1)
        perror("Cannot set mode for stdin");
#endif

    QHashSeed::setDeterministicGlobalSeed();
    QCoreApplication app(argv, argc);
    QCoreApplication::setApplicationName("qmlls");
    QCoreApplication::setApplicationVersion(QT_VERSION_STR);
#if QT_CONFIG(commandlineparser)
    QCommandLineParser parser;
    QQmlToolingSettings settings(QLatin1String("qmlls"));
    parser.setApplicationDescription(QLatin1String(R"(QML languageserver)"));

    parser.addHelpOption();
    QCommandLineOption waitOption(QStringList() << "w"
                                                << "wait",
                                  QLatin1String("Waits the given number of seconds before startup"),
                                  QLatin1String("waitSeconds"));
    parser.addOption(waitOption);

    QCommandLineOption verboseOption(
            QStringList() << "v"
                          << "verbose",
            QLatin1String("Outputs extra information on the operations being performed"));
    parser.addOption(verboseOption);

    QCommandLineOption logFileOption(QStringList() << "l"
                                                   << "log-file",
                                     QLatin1String("Writes logging to the given file"),
                                     QLatin1String("logFile"));
    parser.addOption(logFileOption);

    QString buildDir = QStringLiteral(u"buildDir");
    QCommandLineOption buildDirOption(
            QStringList() << "b"
                          << "build-dir",
            QLatin1String("Adds a build dir to look up for qml information"), buildDir);
    parser.addOption(buildDirOption);
    settings.addOption(buildDir);

    QCommandLineOption writeDefaultsOption(
            QStringList() << "write-defaults",
            QLatin1String("Writes defaults settings to .qmlls.ini and exits (Warning: This "
                          "will overwrite any existing settings and comments!)"));
    parser.addOption(writeDefaultsOption);

    QCommandLineOption ignoreSettings(QStringList() << "ignore-settings",
                                      QLatin1String("Ignores all settings files and only takes "
                                                    "command line options into consideration"));
    parser.addOption(ignoreSettings);

    parser.process(app);

    if (parser.isSet(writeDefaultsOption)) {
        return settings.writeDefaults() ? 0 : 1;
    }
    if (parser.isSet(logFileOption)) {
        QString fileName = parser.value(logFileOption);
        qInfo() << "will log to" << fileName;
        logFile = new QFile(fileName);
        logFileLock = new QMutex;
        logFile->open(QFile::WriteOnly | QFile::Truncate | QFile::Text);
        qInstallMessageHandler([](QtMsgType t, const QMessageLogContext &, const QString &msg) {
            QMutexLocker l(logFileLock);
            logFile->write(QString::number(int(t)).toUtf8());
            logFile->write(" ");
            logFile->write(msg.toUtf8());
            logFile->write("\n");
            logFile->flush();
        });
    }
    if (parser.isSet(verboseOption))
        QLoggingCategory::setFilterRules("qt.languageserver*.debug=true\n");
    if (parser.isSet(waitOption)) {
        int waitSeconds = parser.value(waitOption).toInt();
        if (waitSeconds > 0)
            qDebug() << "waiting";
        QThread::sleep(waitSeconds);
        qDebug() << "starting";
    }
#endif
    QMutex writeMutex;
    QQmlLanguageServer qmlServer(
            [&writeMutex](const QByteArray &data) {
                QMutexLocker l(&writeMutex);
                std::cout.write(data.constData(), data.size());
                std::cout.flush();
            },
            (parser.isSet(ignoreSettings) ? nullptr : &settings));
    if (parser.isSet(buildDirOption))
        qmlServer.codeModel()->setBuildPathsForRootUrl(QByteArray(), parser.values(buildDirOption));
    StdinReader r;
    QObject::connect(&r, &StdinReader::receivedData,
                     qmlServer.server(), &QLanguageServer::receiveData);
    QObject::connect(&r, &StdinReader::eof, &app, [&app]() {
        QTimer::singleShot(100, &app, []() {
            QCoreApplication::processEvents();
            QCoreApplication::exit();
        });
    });
    QThreadPool::globalInstance()->start([&r]() { r.run(); });
    app.exec();
    return qmlServer.returnValue();
}

#include "qmllanguageservertool.moc"