Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qqmllintsuggestions.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6
7#include <QtLanguageServer/private/qlanguageserverspec_p.h>
8#include <QtQmlCompiler/private/qqmljslogger_p.h>
9#include <QtQmlCompiler/private/qqmljsutils_p.h>
10#include <QtQmlDom/private/qqmldom_utils_p.h>
11#include <QtQmlDom/private/qqmldomtop_p.h>
12#include <QtQmlLint/private/qqmljslinter_p.h>
13#include <QtQmlLint/private/qqmllintsettings_p.h>
14#include <QtCore/qdebug.h>
15#include <QtCore/qdir.h>
16#include <QtCore/qfileinfo.h>
17#include <QtCore/qlibraryinfo.h>
18#include <QtCore/qtimer.h>
19#include <QtCore/qxpfunctional.h>
20#include <chrono>
21
23
24Q_STATIC_LOGGING_CATEGORY(lintLog, "qt.languageserver.lint")
25
26using namespace QLspSpecification;
27using namespace QQmlJS::Dom;
28using namespace Qt::StringLiterals;
29
30namespace QmlLsp {
31
33{
34 switch (t) {
35 case QtDebugMsg:
36 return DiagnosticSeverity::Hint;
37 case QtInfoMsg:
38 return DiagnosticSeverity::Information;
39 case QtWarningMsg:
40 return DiagnosticSeverity::Warning;
41 case QtCriticalMsg:
42 case QtFatalMsg:
43 break;
44 }
45 return DiagnosticSeverity::Error;
46}
47
48QmlLintSuggestions::QmlLintSuggestions(QLanguageServer *server,
49 QmlLsp::QQmlCodeModelManager *codeModelManager)
50 : m_server(server), m_codeModelManager(codeModelManager)
51{
52 QObject::connect(m_codeModelManager, &QmlLsp::QQmlCodeModelManager::updatedSnapshot, this,
53 &QmlLintSuggestions::diagnose, Qt::DirectConnection);
54}
55
57{
58 Diagnostic diagnostic;
59 diagnostic.severity = DiagnosticSeverity::Warning;
60 Range &range = diagnostic.range;
61 Position &position = range.start;
62 position.line = 0;
63 position.character = 0;
64 Position &positionEnd = range.end;
65 positionEnd.line = 1;
66 diagnostic.message =
67 "qmlls couldn't find a build directory. Pass the \"--build-dir <buildDir>\" option to "
68 "qmlls, set the environment variable \"QMLLS_BUILD_DIRS\", or create a .qmlls.ini "
69 "configuration file with a \"buildDir\" value in your project's source folder to avoid "
70 "spurious warnings";
71 diagnostic.source = QByteArray("qmllint");
72 return diagnostic;
73}
74
76QJsonArray suggestionToJson(AdvanceFunc advancePositionPastLocation, const Message &message)
77{
78 const auto addLocationToJsonObject = [&](const auto &location, QJsonObject &object) {
79 const unsigned line = location.isValid() ? location.startLine - 1 : 0;
80 const unsigned column = location.isValid() ? location.startColumn - 1 : 0;
81 Position end = { line, column };
82 if (location.isValid())
83 advancePositionPastLocation(location, end);
84 object["lspBeginLine"_L1] = double(line);
85 object["lspBeginCharacter"_L1] = double(column);
86 object["lspEndLine"_L1] = double(end.line);
87 object["lspEndCharacter"_L1] = double(end.character);
88 };
89
90 if (!message.fixSuggestion.has_value())
91 return QJsonArray();
92
93 const QQmlJSFixSuggestion &suggestion = message.fixSuggestion.value();
94 QJsonArray documentEditsJson;
95 const auto &documentEdits = suggestion.documentEdits();
96 for (const auto &documentEdit : documentEdits) {
97 // We need to interject the information about where the fix suggestions end
98 // here since we don't have access to the textDocument to calculate it later.
99 const QQmlJS::SourceLocation cut = suggestion.location();
100 const unsigned line = cut.isValid() ? cut.startLine - 1 : 0;
101 const unsigned column = cut.isValid() ? cut.startColumn - 1 : 0;
102
103 Position end = { line, column };
104 if (cut.isValid())
105 advancePositionPastLocation(cut, end);
106
107 QJsonObject documentEditJson{
108 { "filename"_L1, QUrl::fromLocalFile(documentEdit.m_filename).toString() },
109 { "replacement"_L1, documentEdit.m_replacement }
110 };
111 addLocationToJsonObject(documentEdit.m_location, documentEditJson);
112 documentEditsJson.append(documentEditJson);
113 }
114
115 QJsonObject fixSuggestionJson;
116 fixSuggestionJson["message"_L1] = message.fixSuggestion->description();
117 addLocationToJsonObject(message.fixSuggestion->location(), fixSuggestionJson);
118 fixSuggestionJson["documentEdits"_L1] = documentEditsJson;
119 fixSuggestionJson["autoApplicable"_L1] = message.fixSuggestion->isAutoApplicable();
120
121 QJsonArray fixSuggestionsJson;
122 fixSuggestionsJson.append(fixSuggestionJson);
123 return fixSuggestionsJson;
124}
125
126static Diagnostic messageToDiagnostic_helper(AdvanceFunc advancePositionPastLocation,
127 std::optional<int> version, const Message &message)
128{
129 Diagnostic diagnostic;
130 diagnostic.severity = severityFromMsgType(message.msgType());
131 Range &range = diagnostic.range;
132 Position &position = range.start;
133
134 QQmlJS::SourceLocation srcLoc = message.loc;
135
136 if (srcLoc.isValid()) {
137 position.line = srcLoc.startLine - 1;
138 position.character = srcLoc.startColumn - 1;
139 range.end = position;
140 advancePositionPastLocation(message.loc, range.end);
141 }
142
143 if (message.fixSuggestion && !message.fixSuggestion->description().isEmpty()) {
144 diagnostic.message = u"%1%2 [%3]"_s.arg(message.message, message.fixSuggestion->description(), message.id.toString())
145 .simplified()
146 .toUtf8();
147 } else {
148 diagnostic.message = u"%1 [%2]"_s.arg(message.message, message.id.toString()).toUtf8();
149 }
150
151 diagnostic.source = QByteArray("qmllint");
152
153 auto suggestion = message.fixSuggestion;
154 if (!suggestion.has_value())
155 return diagnostic;
156
157 QJsonObject data;
158 data[u"suggestions"] = suggestionToJson(advancePositionPastLocation, message);
159 Q_ASSERT(version.has_value());
160 data[u"version"] = version.value();
161
162 diagnostic.data = data;
163 return diagnostic;
164};
165
166static bool isSnapshotNew(std::optional<int> snapshotVersion, std::optional<int> processedVersion,
167 QmlLsp::UpdatePolicy policy)
168{
169 if (!snapshotVersion)
170 return false;
171 if (policy == ForceUpdate)
172 return true;
173 if (!processedVersion || *snapshotVersion > *processedVersion)
174 return true;
175 return false;
176}
177
178using namespace std::chrono_literals;
179
180QmlLintSuggestions::VersionToDiagnose
181QmlLintSuggestions::chooseVersionToDiagnoseHelper(const QByteArray &url,
182 QmlLsp::UpdatePolicy policy)
183{
184 const std::chrono::milliseconds maxInvalidTime = 400ms;
185 QmlLsp::OpenDocumentSnapshot snapshot = m_codeModelManager->snapshotByUrl(url);
186
187 LastLintUpdate &lastUpdate = m_lastUpdate[url];
188
189 // ignore updates when already processed
190 if (policy != ForceUpdate && lastUpdate.version && *lastUpdate.version == snapshot.docVersion) {
191 qCDebug(lspServerLog) << "skipped update of " << url << "unchanged valid doc";
192 return NoDocumentAvailable{};
193 }
194
195 // try out a valid version, if there is one
196 if (isSnapshotNew(snapshot.validDocVersion, lastUpdate.version, policy))
197 return VersionedDocument{ snapshot.validDocVersion, snapshot.validDoc };
198
199 // try out an invalid version, if there is one
200 if (isSnapshotNew(snapshot.docVersion, lastUpdate.version, policy)) {
201 if (auto since = lastUpdate.invalidUpdatesSince) {
202 // did we wait enough to get a valid document?
203 if (std::chrono::steady_clock::now() - *since > maxInvalidTime) {
204 return VersionedDocument{ snapshot.docVersion, snapshot.doc };
205 }
206 } else {
207 // first time hitting the invalid document:
208 lastUpdate.invalidUpdatesSince = std::chrono::steady_clock::now();
209 }
210
211 // wait some time for extra keystrokes before diagnose
212 return TryAgainLater{ maxInvalidTime };
213 }
214 return NoDocumentAvailable{};
215}
216
217QmlLintSuggestions::VersionToDiagnose
218QmlLintSuggestions::chooseVersionToDiagnose(const QByteArray &url, QmlLsp::UpdatePolicy policy)
219{
220 QMutexLocker l(&m_mutex);
221 auto versionToDiagnose = chooseVersionToDiagnoseHelper(url, policy);
222 if (auto versionedDocument = std::get_if<VersionedDocument>(&versionToDiagnose)) {
223 // update immediately, and do not keep track of sent version, thus in extreme cases sent
224 // updates could be out of sync
225 LastLintUpdate &lastUpdate = m_lastUpdate[url];
226 lastUpdate.version = versionedDocument->version;
227 lastUpdate.invalidUpdatesSince.reset();
228 }
229 return versionToDiagnose;
230}
231
232void QmlLintSuggestions::diagnose(const QByteArray &url, QmlLsp::UpdatePolicy policy)
233{
234 auto versionedDocument = chooseVersionToDiagnose(url, policy);
235
236 std::visit(qOverloadedVisitor{
237 [](NoDocumentAvailable) {},
238 [this, &url, &policy](const TryAgainLater &tryAgainLater) {
239 QTimer::singleShot(tryAgainLater.time, Qt::VeryCoarseTimer, this,
240 [this, url, policy]() { diagnose(url, policy); });
241 },
242 [this, &url](const VersionedDocument &versionedDocument) {
243 diagnoseHelper(url, versionedDocument);
244 },
245
246 },
247 versionedDocument);
248}
249
250void QmlLintSuggestions::diagnoseHelper(const QByteArray &url,
251 const VersionedDocument &versionedDocument)
252{
253 auto [version, doc] = versionedDocument;
254
255 PublishDiagnosticsParams diagnosticParams;
256 diagnosticParams.uri = url;
257 diagnosticParams.version = version;
258
259 qCDebug(lintLog) << "has doc, do real lint";
260 QStringList imports = m_codeModelManager->importPathsForUrl(url);
261 const QString filename = doc.canonicalFilePath();
262 // add source directory as last import as fallback in case there is no qmldir in the build
263 // folder this mimics qmllint behaviors
264 imports.append(QFileInfo(filename).dir().absolutePath());
265 // add m_server->clientInfo().rootUri & co?
266 const QString fileContents = doc.field(Fields::code).value().toString();
267 const QStringList qmltypesFiles;
268 const QStringList resourceFiles = m_codeModelManager->resourceFilesForFileUrl(url);
269
270 QList<QQmlJS::LoggerCategory> categories = QQmlJSLogger::builtinCategories();
271
272 QQmlJSLinter linter(imports);
273
274 for (const QQmlJSLinter::Plugin &plugin : linter.plugins()) {
275 for (const QQmlJS::LoggerCategory &category : plugin.categories())
276 categories.append(category);
277 }
278
279 QQmlLintSettings settings;
280 if (settings.search(filename).isValid()) {
281 QQmlJS::LoggingUtils::updateLogSeverities(categories, settings, nullptr);
282 }
283
284 // TODO: pass the workspace folders to QQmlJSLinter
285 QQmlJSLinter::LintOptions lintOptions;
286 lintOptions.setFlag(QQmlJSLinter::Silent);
287
288 const bool wasPrepared = linter.prepareFileForBatchLinting(
289 filename, &fileContents, lintOptions, imports, qmltypesFiles, resourceFiles, categories,
290 settings.maxWarnings());
291 Q_ASSERT(wasPrepared);
292 QQmlJSLinter::Result result = linter.lintFileInBatch(filename);
293
294 auto advancePositionPastLocation = [&fileContents](const QQmlJS::SourceLocation &location,
295 Position &position) {
296 const auto [row, column] =
297 QQmlJS::SourceLocation::rowAndColumnFrom(fileContents, location.end(), location);
298 // positions are 0-based in the LSP, and 1-based in QQmlJS::SourceLocation.
299 position.line = row - 1;
300 position.character = column - 1;
301 };
302 auto messageToDiagnostic = [&advancePositionPastLocation,
303 versionedDocument](const Message &message) {
304 return messageToDiagnostic_helper(advancePositionPastLocation, versionedDocument.version,
305 message);
306 };
307
308 QList<Diagnostic> diagnostics;
309 doc.iterateErrors(
310 [&diagnostics, &advancePositionPastLocation](const DomItem &, const ErrorMessage &msg) {
311 Diagnostic diagnostic;
312 diagnostic.severity = severityFromMsgType(QtMsgType(int(msg.level)));
313 // do something with msg.errorGroups ?
314 auto &location = msg.location;
315 Range &range = diagnostic.range;
316 range.start.line = location.startLine - 1;
317 range.start.character = location.startColumn - 1;
318 range.end = range.start;
319 advancePositionPastLocation(location, range.end);
320 diagnostic.code = QByteArray(msg.errorId.data(), msg.errorId.size());
321 diagnostic.source = "domParsing";
322 diagnostic.message = msg.message.toUtf8();
323 diagnostics.append(diagnostic);
324 return true;
325 },
326 true);
327
328 if (const QQmlJSLogger *logger = result.logger.get()) {
329 qsizetype nDiagnostics = diagnostics.size();
330 logger->iterateAllMessages([&](const Message &message) {
331 if (!message.message.contains(u"Failed to import")) {
332 diagnostics.append(messageToDiagnostic(message));
333 return;
334 }
335
336 Message modified {message};
337 modified.message.append(u" Did you build your project?");
338
339 diagnostics.append(messageToDiagnostic(modified));
340 });
341 if (diagnostics.size() != nDiagnostics && imports.size() == 1)
342 diagnostics.append(createMissingBuildDirDiagnostic());
343 }
344
345 diagnosticParams.diagnostics = diagnostics;
346
347 m_server->protocol()->notifyPublishDiagnostics(diagnosticParams);
348 qCDebug(lintLog) << "lint" << QString::fromUtf8(url) << "found"
349 << diagnosticParams.diagnostics.size() << "issues"
350 << QTypedJson::toJsonValue(diagnosticParams);
351}
352
353} // namespace QmlLsp
354QT_END_NAMESPACE
Combined button and popup list for selecting options.
static Diagnostic messageToDiagnostic_helper(AdvanceFunc advancePositionPastLocation, std::optional< int > version, const Message &message)
static Diagnostic createMissingBuildDirDiagnostic()
static bool isSnapshotNew(std::optional< int > snapshotVersion, std::optional< int > processedVersion, QmlLsp::UpdatePolicy policy)
QJsonArray suggestionToJson(AdvanceFunc advancePositionPastLocation, const Message &message)
static DiagnosticSeverity severityFromMsgType(QtMsgType t)