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
qqmljslinter.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3// Qt-Security score:significant
4
7
8#include <private/qqmljsimporter_p.h>
9#include <private/qqmljsimportvisitor_p.h>
10#include <private/qqmljslinterpasses_p.h>
11#include <private/qqmljslintervisitor_p.h>
12#include <private/qqmljsliteralbindingcheck_p.h>
13#include <private/qqmljsloggingutils_p.h>
14#include <private/qqmljsutils_p.h>
15#include <private/qqmlsa_p.h>
16
17#include <QtCore/qjsonobject.h>
18#include <QtCore/qfileinfo.h>
19#include <QtCore/qloggingcategory.h>
20#include <QtCore/qpluginloader.h>
21#include <QtCore/qlibraryinfo.h>
22#include <QtCore/qdir.h>
23#include <QtCore/private/qduplicatetracker_p.h>
24#include <QtCore/qscopedpointer.h>
25
26
27#if QT_CONFIG(library)
28# include <QtCore/qdiriterator.h>
29# include <QtCore/qlibrary.h>
30#endif
31
32#if QT_CONFIG(qmlcontextpropertydump)
33# include <QtCore/qsettings.h>
34#endif
35
36#include <QtQml/private/qqmljslexer_p.h>
37#include <QtQml/private/qqmljsparser_p.h>
38#include <QtQml/private/qqmljsengine_p.h>
39#include <QtQml/private/qqmljsastvisitor_p.h>
40#include <QtQml/private/qqmljsast_p.h>
41#include <QtQml/private/qqmljsdiagnosticmessage_p.h>
42
43
45
46using namespace Qt::StringLiterals;
47
48class HasFunctionDefinitionVisitor final : public QQmlJS::AST::Visitor
49{
50public:
51 bool visit(QQmlJS::AST::FunctionDeclaration *functionDeclaration) override
52 {
53 m_result = !functionDeclaration->name.isEmpty();
54 return false;
55 }
56
58 bool result() const { return m_result; }
59 void reset() { m_result = false; }
60
61private:
62 bool m_result = false;
63};
64
65class UnreachableVisitor final : public QQmlJS::AST::Visitor
66{
67public:
68 UnreachableVisitor(QQmlJSLogger *logger) : m_logger(logger) { }
69
70 bool containsFunctionDeclaration(QQmlJS::AST::Node *node)
71 {
72 m_hasFunctionDefinition.reset();
73 node->accept(&m_hasFunctionDefinition);
74 return m_hasFunctionDefinition.result();
75 }
76
77 bool visit(QQmlJS::AST::StatementList *unreachable) override
78 {
79 QQmlJS::SourceLocation location;
80 auto report = [this, &location]() {
81 if (location.isValid()) {
82 m_logger->log(u"Unreachable code"_s, qmlUnreachableCode, location);
83 }
84 location = QQmlJS::SourceLocation{};
85 };
86
87 for (auto it = unreachable; it && it->statement; it = it->next) {
88 if (containsFunctionDeclaration(it->statement)) {
89 report();
90 continue; // don't warn about the location of the function declaration
91 }
92 location = combine(location,
93 combine(it->statement->firstSourceLocation(),
94 it->statement->lastSourceLocation()));
95 }
96 report();
97 return false;
98 }
100
101private:
102 QQmlJSLogger *m_logger = nullptr;
103 HasFunctionDefinitionVisitor m_hasFunctionDefinition;
104};
105
106class CodegenWarningInterface final : public QV4::Compiler::CodegenWarningInterface
107{
108public:
110 {
111 }
112
113 void reportVarUsedBeforeDeclaration(const QString &name, const QString &fileName,
114 QQmlJS::SourceLocation declarationLocation,
115 QQmlJS::SourceLocation accessLocation) override
116 {
117 Q_UNUSED(fileName)
118
119 m_logger->log("Identifier '%1' is used here before its declaration."_L1.arg(name),
120 qmlVarUsedBeforeDeclaration, accessLocation);
121 m_logger->log("Note: declaration of '%1' here"_L1.arg(name), qmlVarUsedBeforeDeclaration,
122 declarationLocation, true, true, {}, accessLocation.startLine);
123 }
124
125 void reportFunctionUsedBeforeDeclaration(const QString &name, const QString &fileName,
126 QQmlJS::SourceLocation declarationLocation,
127 QQmlJS::SourceLocation accessLocation) override
128 {
129 Q_UNUSED(fileName)
130
131 m_logger->log("Function '%1' is used here before its declaration."_L1.arg(name),
132 qmlFunctionUsedBeforeDeclaration, accessLocation);
133 m_logger->log("Note: declaration of '%1' here"_L1.arg(name),
134 qmlFunctionUsedBeforeDeclaration, declarationLocation);
135 }
136
137 void reportParserWarnings(const QString &, QQmlJS::SourceLocation, const QString &) override
138 {
139 // Note: we already reported parser warnings in QQmlJSLinter::typeReader(), so we don't
140 // need to report them again here.
141 }
142
143 UnreachableVisitor *unreachableVisitor() override { return &m_unreachableVisitor; }
144
145private:
146 QQmlJSLogger *m_logger;
147 UnreachableVisitor m_unreachableVisitor;
148};
149
150QQmlJSLinter::QQmlJSLinter(const QStringList &importPaths, const QStringList &extraPluginPaths,
151 bool useAbsolutePath)
152 : m_useAbsolutePath(useAbsolutePath),
153 m_enablePlugins(true),
154 m_importer(importPaths, nullptr,
157{
158 m_plugins = loadPlugins(extraPluginPaths);
159}
160
167 , m_instance(std::move(plugin.m_instance))
169 , m_isInternal(std::move(plugin.m_isInternal))
170 , m_isValid(std::move(plugin.m_isValid))
171{
172 // Mark the old Plugin as invalid and make sure it doesn't delete the loader
173 Q_ASSERT(!plugin.m_loader);
174 plugin.m_instance = nullptr;
175 plugin.m_isValid = false;
176}
177
178#if QT_CONFIG(library)
179QQmlJSLinter::Plugin::Plugin(QString path)
180{
181 m_loader = std::make_unique<QPluginLoader>(path);
182 if (!parseMetaData(m_loader->metaData(), path))
183 return;
184
185 QObject *object = m_loader->instance();
186 if (!object)
187 return;
188
189 m_instance = qobject_cast<QQmlSA::LintPlugin *>(object);
190 if (!m_instance)
191 return;
192
193 m_isValid = true;
194}
195#endif
196
197QQmlJSLinter::Plugin::Plugin(const QStaticPlugin &staticPlugin)
198{
199 if (!parseMetaData(staticPlugin.metaData(), u"built-in"_s))
200 return;
201
202 m_instance = qobject_cast<QQmlSA::LintPlugin *>(staticPlugin.instance());
203 if (!m_instance)
204 return;
205
206 m_isValid = true;
207}
208
210{
211#if QT_CONFIG(library)
212 if (m_loader != nullptr) {
213 m_loader->unload();
214 m_loader->deleteLater();
215 }
216#endif
217}
218
219bool QQmlJSLinter::Plugin::parseMetaData(const QJsonObject &metaData, QString pluginName)
220{
221 const QString pluginIID = QStringLiteral(QmlLintPluginInterface_iid);
222
223 if (metaData[u"IID"].toString() != pluginIID)
224 return false;
225
226 QJsonObject pluginMetaData = metaData[u"MetaData"].toObject();
227
228 for (const QString &requiredKey :
229 { u"name"_s, u"version"_s, u"author"_s, u"loggingCategories"_s }) {
230 if (!pluginMetaData.contains(requiredKey)) {
231 qWarning() << pluginName << "is missing the required " << requiredKey
232 << "metadata, skipping";
233 return false;
234 }
235 }
236
237 m_name = pluginMetaData[u"name"].toString();
238 m_author = pluginMetaData[u"author"].toString();
239 m_version = pluginMetaData[u"version"].toString();
240 m_description = pluginMetaData[u"description"].toString(u"-/-"_s);
241 m_isInternal = pluginMetaData[u"isInternal"].toBool(false);
242
243 if (!pluginMetaData[u"loggingCategories"].isArray()) {
244 qWarning() << pluginName << "has loggingCategories which are not an array, skipping";
245 return false;
246 }
247
248 const QJsonArray categories = pluginMetaData[u"loggingCategories"].toArray();
249 for (const QJsonValue &value : categories) {
250 if (!value.isObject()) {
251 qWarning() << pluginName << "has invalid loggingCategories entries, skipping";
252 return false;
253 }
254
255 const QJsonObject object = value.toObject();
256
257 for (const QString &requiredKey : { u"name"_s, u"description"_s }) {
258 if (!object.contains(requiredKey)) {
259 qWarning() << pluginName << " logging category is missing the required "
260 << requiredKey << "metadata, skipping";
261 return false;
262 }
263 }
264
265 const QString prefix = (m_isInternal ? u""_s : u"Plugin."_s).append(m_name).append(u'.');
266 const QString categoryId =
267 prefix + object[u"name"].toString();
268 const auto settingsNameIt = object.constFind(u"settingsName");
269 const QString settingsName = (settingsNameIt == object.constEnd())
270 ? categoryId
271 : prefix + settingsNameIt->toString(categoryId);
272 m_categories << QQmlJS::LoggerCategory{ categoryId, settingsName,
273 object["description"_L1].toString(),
274 QQmlJS::WarningSeverity::Warning };
275 const auto itSeverity = object.find("defaultSeverity"_L1);
276 if (itSeverity == object.end())
277 continue;
278
279 const QString severityName = itSeverity->toString();
280 const auto severity = QQmlJS::LoggingUtils::severityFromString(severityName);
281 if (!severity.has_value()) {
282 qWarning() << "Invalid logging severity" << severityName << "provided for"
283 << m_categories.last().id().name().toString()
284 << "(allowed are: disable, info, warning, error) found in plugin metadata.";
285 continue;
286 }
287
288 m_categories.last().setSeverity(severity.value());
289 }
290
291 return true;
292}
293
294std::vector<QQmlJSLinter::Plugin> QQmlJSLinter::loadPlugins(QStringList extraPluginPaths)
295{
296 std::vector<Plugin> plugins;
297
298 QDuplicateTracker<QString> seenPlugins;
299
300 const auto &staticPlugins = QPluginLoader::staticPlugins();
301 for (const QStaticPlugin &staticPlugin : staticPlugins) {
302 Plugin plugin(staticPlugin);
303 if (!plugin.isValid())
304 continue;
305
306 if (seenPlugins.hasSeen(plugin.name().toLower())) {
307 qWarning() << "Two plugins named" << plugin.name()
308 << "present, make sure no plugins are duplicated. The second plugin will "
309 "not be loaded.";
310 continue;
311 }
312
313 plugins.push_back(std::move(plugin));
314 }
315
316#if QT_CONFIG(library)
317 const QStringList paths = [&extraPluginPaths]() {
318 QStringList result{ extraPluginPaths };
319 const QStringList libraryPaths = QCoreApplication::libraryPaths();
320 for (const auto &path : libraryPaths) {
321 result.append(path + u"/qmllint"_s);
322 }
323 return result;
324 }();
325 for (const QString &pluginDir : paths) {
326 QDirIterator it{ pluginDir, QDir::Files };
327
328 while (it.hasNext()) {
329 auto potentialPlugin = it.next();
330
331 if (!QLibrary::isLibrary(potentialPlugin))
332 continue;
333
334 Plugin plugin(potentialPlugin);
335
336 if (!plugin.isValid())
337 continue;
338
339 if (seenPlugins.hasSeen(plugin.name().toLower())) {
340 qWarning() << "Two plugins named" << plugin.name()
341 << "present, make sure no plugins are duplicated. The second plugin "
342 "will not be loaded.";
343 continue;
344 }
345
346 plugins.push_back(std::move(plugin));
347 }
348 }
349#endif
350 Q_UNUSED(extraPluginPaths)
351 return plugins;
352}
353
354void QQmlJSLinter::parseComments(QQmlJSLogger *logger,
355 const QList<QQmlJS::SourceLocation> &comments)
356{
357 QHash<int, QSet<QString>> disablesPerLine;
358 QHash<int, QSet<QString>> enablesPerLine;
359 QHash<int, QSet<QString>> oneLineDisablesPerLine;
360
361 struct PostponedWarning
362 {
363 QString message;
364 QQmlSA::LoggerWarningId category;
365 QQmlJS::SourceLocation location;
366 };
367
368 std::vector<PostponedWarning> postponedWarnings;
369 auto guard = qScopeGuard([&postponedWarnings, &logger]() {
370 // only log messages after processing the logger->ignoreWarnings() calls, so that the
371 // qmlInvalidLintDirective warnings can be disabled if needed.
372 for (const auto &warning : postponedWarnings)
373 logger->log(warning.message, warning.category, warning.location);
374 });
375
376 const QString code = logger->code();
377 const QStringList lines = code.split(u'\n');
378 const auto loggerCategories = logger->categories();
379
380 for (const auto &loc : comments) {
381 const QString comment = code.mid(loc.offset, loc.length);
382 if (!comment.startsWith(u" qmllint ") && !comment.startsWith(u"qmllint "))
383 continue;
384
385 QStringList words = comment.split(u' ', Qt::SkipEmptyParts);
386 if (words.size() < 2)
387 continue;
388
389 QSet<QString> categories;
390 for (qsizetype i = 2; i < words.size(); i++) {
391 const QString category = words.at(i);
392 const auto categoryExists = std::any_of(
393 loggerCategories.cbegin(), loggerCategories.cend(),
394 [&](const QQmlJS::LoggerCategory &cat) { return cat.id().name() == category; });
395
396 if (categoryExists)
397 categories << category;
398 else {
399 postponedWarnings.push_back(
400 { u"qmllint directive on unknown category \"%1\""_s.arg(category),
401 qmlInvalidLintDirective, loc });
402 }
403 }
404
405 if (words.size() == 2) {
406 const auto &loggerCategories = logger->categories();
407 for (const auto &option : loggerCategories)
408 categories << option.id().name().toString();
409 }
410
411 const QString command = words.at(1);
412 if (command == u"disable"_s) {
413 if (const qsizetype lineIndex = loc.startLine - 1; lineIndex < lines.size()) {
414 const QString line = lines[lineIndex];
415 const QString preComment = line.left(line.indexOf(comment) - 2);
416
417 bool lineHasContent = false;
418 for (qsizetype i = 0; i < preComment.size(); i++) {
419 if (!preComment[i].isSpace()) {
420 lineHasContent = true;
421 break;
422 }
423 }
424
425 if (lineHasContent)
426 oneLineDisablesPerLine[loc.startLine] |= categories;
427 else
428 disablesPerLine[loc.startLine] |= categories;
429 }
430 } else if (command == u"enable"_s) {
431 enablesPerLine[loc.startLine + 1] |= categories;
432 } else {
433 postponedWarnings.push_back(
434 { u"Invalid qmllint directive \"%1\" provided"_s.arg(command),
435 qmlInvalidLintDirective, loc });
436 }
437 }
438
439 if (disablesPerLine.isEmpty() && oneLineDisablesPerLine.isEmpty())
440 return;
441
442 QSet<QString> currentlyDisabled;
443 for (qsizetype i = 1; i <= lines.size(); i++) {
444 currentlyDisabled.unite(disablesPerLine[i]).subtract(enablesPerLine[i]);
445
446 currentlyDisabled.unite(oneLineDisablesPerLine[i]);
447
448 if (!currentlyDisabled.isEmpty())
449 logger->ignoreWarnings(i, currentlyDisabled);
450
451 currentlyDisabled.subtract(oneLineDisablesPerLine[i]);
452 }
453}
454
455static void addJsonWarning(QJsonArray &warnings, const QQmlJS::DiagnosticMessage &message,
456 QAnyStringView id, const std::optional<QQmlJSFixSuggestion> &suggestion = {})
457{
458 QJsonObject jsonMessage;
459
460 QString type;
461 switch (message.type) {
462 case QtDebugMsg:
463 type = u"debug"_s;
464 break;
465 case QtWarningMsg:
466 type = u"warning"_s;
467 break;
468 case QtCriticalMsg:
469 type = u"critical"_s;
470 break;
471 case QtFatalMsg:
472 type = u"fatal"_s;
473 break;
474 case QtInfoMsg:
475 type = u"info"_s;
476 break;
477 default:
478 type = u"unknown"_s;
479 break;
480 }
481
482 jsonMessage[u"type"_s] = type;
483 jsonMessage[u"id"_s] = id.toString();
484
485 const auto convertLocation = [](const QQmlJS::SourceLocation &source, QJsonObject *target) {
486 target->insert("line"_L1, int(source.startLine));
487 target->insert("column"_L1, int(source.startColumn));
488 target->insert("charOffset"_L1, int(source.offset));
489 target->insert("length"_L1, int(source.length));
490 };
491
492 if (message.loc.isValid())
493 convertLocation(message.loc, &jsonMessage);
494
495 jsonMessage[u"message"_s] = message.message;
496
497 QJsonArray suggestions;
498 if (suggestion.has_value()) {
499 QJsonArray documentEdits;
500 for (const auto &documentEdit : suggestion->documentEdits()) {
501 QJsonObject location;
502 convertLocation(documentEdit.m_location, &location);
503 QJsonObject edit {
504 { "filename"_L1, documentEdit.m_filename },
505 { "location"_L1, location },
506 { "replacement"_L1, documentEdit.m_replacement }
507 };
508 documentEdits.append(edit);
509 }
510
511 QJsonObject jsonFix {
512 { "message"_L1, suggestion->description() },
513 { "documentEdits"_L1, documentEdits },
514 { "isAutoApplicable"_L1, suggestion->isAutoApplicable() },
515 };
516 convertLocation(suggestion->location(), &jsonFix);
517 const QString filename = suggestion->filename();
518 if (!filename.isEmpty())
519 jsonFix.insert("fileName"_L1, filename);
520 suggestions << jsonFix;
521 }
522 jsonMessage[u"suggestions"] = suggestions;
523
524 warnings << jsonMessage;
525}
526
527static void processMessages(const QQmlJSLogger &logger, QJsonArray &warnings)
528{
529 logger.iterateAllMessages([&](const Message &message) {
530 addJsonWarning(warnings, message, message.id, message.fixSuggestion);
531 });
532}
533
534/*!
535\internal
536Returns false on already-populated files.
537
538Set up the scope of a file to lazy-load via LinterVisitor.
539Returns true on success and false if the scope already was populated.
540Retrieve lint results via QQmlJSLinter::lintFileInBatch().
541*/
542bool QQmlJSLinter::prepareFileForBatchLinting(const QString &dirtyFilename,
543 const QString *fileContents, LintOptions options,
544 const QStringList &qmlImportPaths,
545 const QStringList &qmldirFiles,
546 const QStringList &resourceFiles,
547 const QList<QQmlJS::LoggerCategory> &categories)
548{
549 QFileInfo info(dirtyFilename);
550 const QString filenameFromUser =
551 QDir::cleanPath(m_useAbsolutePath ? info.absoluteFilePath() : dirtyFilename);
552
553 LintInfo &lintInfo = m_lintInfo[filenameFromUser];
554 lintInfo.fileContents = fileContents;
555 lintInfo.options = options;
556 lintInfo.qmlImportPaths = qmlImportPaths;
557 lintInfo.qmldirFiles = qmldirFiles;
558 lintInfo.categories = categories;
559
560 const QString lowerSuffix = info.suffix().toLower();
561 lintInfo.isESModule = lowerSuffix == QLatin1String("mjs");
562 lintInfo.isJavaScript = lintInfo.isESModule || lowerSuffix == QLatin1String("js");
563
564 lintInfo.resourceMapper = { resourceFiles };
565 m_importer.setResourceFileMapper(lintInfo.resourceMapper ? &*lintInfo.resourceMapper : nullptr);
566 lintInfo.handle = m_importer.importFile(filenameFromUser);
567 auto guard = qScopeGuard([this]() { m_importer.setResourceFileMapper(nullptr); });
568
569 if (!lintInfo.handle.factory()) {
570 // File was already linted or populated once: resetting its factory might break things, like
571 // weakpointers in QQmlJSMetaProperty pointing to children QQmlJSScope of lintInfo.handle.
572 m_lintInfo.erase(filenameFromUser);
573 return false;
574 }
575
576 resetFactory(lintInfo.handle, &m_importer,
577 [this, filenameFromUser](QQmlJSImporter *, const QString &,
578 const QSharedPointer<QQmlJSScope> &) {
579 return typeReader(filenameFromUser);
580 });
581 return true;
582}
583
585{
586 json[u"filename"_s] = logger->filePath();
587
588 QJsonArray warnings;
589 processMessages(*logger.get(), warnings);
590 json[u"warnings"] = warnings;
591 json[u"success"] = status == LintSuccess;
592}
593
595{
596 if (logger->hasErrors()) {
598 return;
599 }
600 if (logger->hasWarnings()) {
602 return;
603 }
604
606}
607
608QQmlJSLinter::Result QQmlJSLinter::lintFileInBatch(const QString &dirtyFilename)
609{
610 QFileInfo info(dirtyFilename);
611 const QString filename =
612 QDir::cleanPath(m_useAbsolutePath ? info.absoluteFilePath() : dirtyFilename);
613 auto it = m_lintInfo.find(filename);
614 if (it == m_lintInfo.end() || !it->second.handle.data())
615 return { LintResult::FailedToOpen, { }, { } };
616
617 auto &lintInfo = it->second;
618 if (lintInfo.result.status != FailedToOpen && lintInfo.result.status != FailedToParse && !lintInfo.isJavaScript)
619 lintFileImpl(filename);
620
621 // emit all (possibly pre-recorded) warnings now
622 if (const auto &logger = lintInfo.result.logger) {
623 logger->manualFlush();
624 if (lintInfo.options.testAnyFlag(QQmlJSLinter::GenerateJson))
625 lintInfo.result.generateJson();
626 }
627
628 Result result = std::move(it->second.result);
629 m_lintInfo.erase(it);
630 return result;
631}
632
633void QQmlJSLinter::setupLoggingCategoriesInLogger(QQmlJSLogger *logger,
634 const QList<QQmlJS::LoggerCategory> &categories)
635{
636 if (m_enablePlugins) {
637 for (const Plugin &plugin : m_plugins) {
638 for (const QQmlJS::LoggerCategory &category : plugin.categories())
639 logger->registerCategory(category);
640 }
641 }
642
643 for (auto it = categories.cbegin(); it != categories.cend(); ++it) {
644 if (auto logger = *it; !QQmlJS::LoggerCategoryPrivate::get(&logger)->hasChanged())
645 continue;
646
647 logger->setCategorySeverity(it->id(), it->severity());
648 }
649}
650
651void QQmlJSLinter::updateUserContextProperties(const QString &fileName)
652{
653 const QString cachedSettingsPath = m_userContextPropertySettings.currentSettingsPath();
654 auto searchResult = m_userContextPropertySettings.search(fileName);
655 if (searchResult.iniFilePath == cachedSettingsPath)
656 return;
657 if (!searchResult.isValid()) {
658 m_cachedUserContextProperties = { };
659 return;
660 }
661 m_cachedUserContextProperties = QQmlJS::UserContextProperties{ m_userContextPropertySettings };
662}
663
664void QQmlJSLinter::updateHeuristicContextProperties(const QString &fileName)
665{
666#if QT_CONFIG(qmlcontextpropertydump)
667 const QString buildPath =
668 QQmlJSUtils::qmlBuildPathFromSourcePath(m_importer.resourceFileMapper(), fileName);
669
670 const QString cachedSettingsPath = m_userContextPropertySettings.currentSettingsPath();
671 const auto searchResult = m_heuristicContextPropertySearcher.search(buildPath);
672 if (searchResult.iniFilePath == cachedSettingsPath)
673 return;
674 if (!searchResult.isValid()) {
675 m_cachedHeuristicContextProperties = { };
676 return;
677 }
678 QSettings settings(searchResult.iniFilePath, QSettings::IniFormat);
679 m_cachedHeuristicContextProperties = QQmlJS::HeuristicContextProperties::collectFrom(&settings);
680#endif
681}
682
683void QQmlJSLinter::typeReader(const QString &filename)
684{
685 QString code;
686
687 auto &lintInfo = m_lintInfo[filename];
688 auto &result = lintInfo.result;
689
690 result.logger = std::make_unique<QQmlJSLogger>();
691 result.logger->setManualFlush(true);
692 QFileInfo info(filename);
693 result.logger->setFilePath(useAbsolutePath() ? info.absoluteFilePath() : filename);
694 result.logger->setSilent(lintInfo.options.testFlag(QQmlJSLinter::Silent)
695 || lintInfo.options.testFlag(QQmlJSLinter::GenerateJson));
696 setupLoggingCategoriesInLogger(result.logger.get(), lintInfo.categories);
697
698 if (lintInfo.fileContents == nullptr) {
699 QFile file(filename);
700 if (!file.open(QFile::ReadOnly)) {
701 result.logger->log("Failed to open file %1: %2"_L1.arg(filename, file.errorString()),
702 qmlImport, QQmlJS::SourceLocation());
703 result.status = FailedToOpen;
704 return;
705 }
706
707 code = QString::fromUtf8(file.readAll());
708 file.close();
709 } else {
710 code = *lintInfo.fileContents;
711 }
712
713 result.logger->setCode(code);
714
715 QQmlJS::Lexer lexer(&lintInfo.engine);
716
717 lexer.setCode(code, /*lineno = */ 1, /*qmlMode=*/!lintInfo.isJavaScript);
718 QQmlJS::Parser parser(&lintInfo.engine);
719
720 const bool parseSuccess = lintInfo.isJavaScript
721 ? (lintInfo.isESModule ? parser.parseModule() : parser.parseProgram())
722 : parser.parse();
723 const auto diagnosticMessages = parser.diagnosticMessages();
724 for (const QQmlJS::DiagnosticMessage &m : diagnosticMessages)
725 result.logger->log(m.message, qmlSyntax, m.loc);
726
727 if (!parseSuccess) {
728 result.status = FailedToParse;
729 return;
730 }
731
732 m_importer.setImportPaths(lintInfo.qmlImportPaths);
733
734 const QQmlJSResourceFileMapper *mapperPtr =
735 lintInfo.resourceMapper ? &*lintInfo.resourceMapper : nullptr;
736 m_importer.setResourceFileMapper(mapperPtr);
737 // make sure the temporary mapper iscleared from m_importer when it goes out of scope
738 auto guard = qScopeGuard([this]() { m_importer.setResourceFileMapper(nullptr); });
739
740 const QString implicitImportDirectory =
741 QQmlJSImportVisitor::implicitImportDirectory(result.logger->filePath(), mapperPtr);
742 if (lintInfo.isJavaScript) {
743 m_importer.runImportVisitor(parser.rootNode(),
744 {
745 lintInfo.handle,
746 lintInfo.result.logger.get(),
747 implicitImportDirectory,
748 });
749 result.status = LintSuccess;
750 return;
751 }
752
753 lintInfo.visitor.emplace(&m_importer, result.logger.get(), implicitImportDirectory,
754 lintInfo.qmldirFiles, &lintInfo.engine);
755
756 parseComments(result.logger.get(), lintInfo.engine.comments());
757 parser.rootNode()->accept(&*lintInfo.visitor);
758}
759
760void QQmlJSLinter::lintFileImpl(const QString &filename)
761{
762 Q_ASSERT(m_lintInfo.count(filename) == 1);
763 LintInfo &lintInfo = m_lintInfo[filename];
764
765 Q_ASSERT(!lintInfo.isJavaScript);
766
767 QQmlJSTypeResolver typeResolver(&m_importer);
768
769 // Type resolving is using document parent mode here so that it produces fewer false
770 // positives on the "parent" property of QQuickItem. It does produce a few false
771 // negatives this way because items can be reparented. Furthermore, even if items
772 // are not reparented, the document parent may indeed not be their visual parent.
773 // See QTBUG-95530. Eventually, we'll need cleverer logic to deal with this.
774 typeResolver.setParentMode(QQmlJSTypeResolver::UseDocumentParent);
775 // We don't need to create tracked types and such as we are just linting the code
776 // here and not actually compiling it. The duplicated scopes would cause issues
777 // during linting.
778 typeResolver.setCloneMode(QQmlJSTypeResolver::DoNotCloneTypes);
779
780 Q_ASSERT(lintInfo.visitor);
781 auto &v = *lintInfo.visitor;
782 typeResolver.init(&v, nullptr);
783
784 QStringList resourcePaths;
785 if (auto &mapper = lintInfo.resourceMapper)
786 resourcePaths = mapper->resourcePaths(QQmlJSResourceFileMapper::localFileFilter(filename));
787
788 m_importer.setResourceFileMapper(lintInfo.resourceMapper ? &*lintInfo.resourceMapper : nullptr);
789 auto guard = qScopeGuard([this]() { m_importer.setResourceFileMapper(nullptr); });
790
791 const QString resolvedPath =
792 (resourcePaths.size() == 1) ? u':' + resourcePaths.first() : filename;
793
794 updateHeuristicContextProperties(filename);
795 updateUserContextProperties(filename);
796
797 QQmlJS::LinterContext context{
798 v.addressableScopes(), *v.knownUnresolvedTypes(),
799 v.renamedComponents(), m_importer,
800 m_cachedUserContextProperties, m_cachedHeuristicContextProperties
801 };
802
803 QQmlJSLinterCodegen codegen{
804 &m_importer, resolvedPath, lintInfo.qmldirFiles, lintInfo.result.logger.get(), context,
805 };
806 codegen.setTypeResolver(std::move(typeResolver));
807
808 using PassManagerPtr =
809 std::unique_ptr<QQmlSA::PassManager,
810 decltype(&QQmlSA::PassManagerPrivate::deletePassManager)>;
811 PassManagerPtr passMan(
812 QQmlSA::PassManagerPrivate::createPassManager(&v, codegen.typeResolver()),
813 &QQmlSA::PassManagerPrivate::deletePassManager);
814 QQmlJSLinterPasses::registerDefaultPasses(passMan.get());
815
816 if (m_enablePlugins) {
817 for (const Plugin &plugin : m_plugins) {
818 if (!plugin.isValid() || !plugin.isEnabled())
819 continue;
820
821 QQmlSA::LintPlugin *instance = plugin.m_instance;
822 Q_ASSERT(instance);
823 instance->registerPasses(passMan.get(), QQmlJSScope::createQQmlSAElement(v.result()));
824 }
825 }
826 passMan->analyze(QQmlJSScope::createQQmlSAElement(v.result()));
827
828 if (lintInfo.result.logger->hasErrors()) {
829 lintInfo.result.status = HasErrors;
830 return;
831 }
832
833 // passMan now has a pointer to the moved from type resolver
834 // we fix this in setPassManager
835 codegen.setPassManager(passMan.get());
836
837 QQmlJSSaveFunction saveFunction = [](const QV4::CompiledData::SaveableUnitPointer &,
838 const QQmlJSAotFunctionMap &,
839 const LookupSignatures &,
840 const QString *) { return true; };
841
842 QQmlJSCompileError error;
843
844 QLoggingCategory::setFilterRules(u"qt.qml.compiler=false"_s);
845
846 CodegenWarningInterface warningInterface(lintInfo.result.logger.get());
847 qCompileQmlFile(filename, saveFunction, &codegen, &error, true, &warningInterface,
848 lintInfo.fileContents);
849
850 QList<QQmlJS::DiagnosticMessage> globalWarnings = m_importer.takeGlobalWarnings();
851
852 if (!globalWarnings.isEmpty()) {
853 lintInfo.result.logger->log(QStringLiteral("Type warnings occurred while evaluating file:"),
854 qmlImport, QQmlJS::SourceLocation());
855 lintInfo.result.logger->processMessages(globalWarnings, qmlImport);
856 }
857
858 lintInfo.result.setStatusFromLogger();
859}
860
861QQmlJSLinter::Result QQmlJSLinter::lintModule(const QString &module, LintOptions options,
862 const QStringList &qmlImportPaths,
863 const QStringList &resourceFiles)
864{
865 Result lintResult = lintModuleImpl(module, options, qmlImportPaths, resourceFiles);
866 if (!options.testFlag(GenerateJson))
867 return lintResult;
868
869 QJsonArray warnings;
870 processMessages(*lintResult.logger, warnings);
871
872 lintResult.json[u"module"_s] = module;
873 lintResult.json[u"warnings"] = warnings;
874 lintResult.json[u"success"] = lintResult.status == LintSuccess;
875
876 return lintResult;
877}
878
879QQmlJSLinter::Result QQmlJSLinter::lintModuleImpl(const QString &module, LintOptions options,
880 const QStringList &qmlImportPaths,
881 const QStringList &resourceFiles)
882{
883 Result result;
884 result.logger = std::make_unique<QQmlJSLogger>();
885
886 // We can't lint properly if a module has already been pre-cached
887 m_importer.clearCache();
888
889 // We don't support file selectors during module linting currently
890 const QQmlJSImporterFlags oldFlags = m_importer.flags();
891 QQmlJSImporterFlags newFlags = oldFlags;
892 newFlags.setFlag(TolerateFileSelectors, false);
893 m_importer.setFlags(newFlags);
894 auto flagGuard = qScopeGuard([this, oldFlags]() { m_importer.setFlags(oldFlags); });
895 m_importer.setImportPaths(qmlImportPaths);
896
897 QQmlJSResourceFileMapper mapper(resourceFiles);
898 if (!resourceFiles.isEmpty())
899 m_importer.setResourceFileMapper(&mapper);
900 else
901 m_importer.setResourceFileMapper(nullptr);
902 auto guard = qScopeGuard([this]() { m_importer.setResourceFileMapper(nullptr); });
903
904 result.logger->setFilePath(module);
905 result.logger->setCode(u""_s);
906 result.logger->setSilent(options.testFlag(Silent) || options.testFlag(GenerateJson));
907
908 const QQmlJSImporter::ImportedTypes types =
909 m_importer.importModule(module, quint8(QQmlJS::PrecedenceValues::Default));
910
911 QList<QQmlJS::DiagnosticMessage> importWarnings =
912 m_importer.takeGlobalWarnings() + types.warnings();
913
914 if (!importWarnings.isEmpty()) {
915 result.logger->log(QStringLiteral("Warnings occurred while importing module:"), qmlImport,
916 QQmlJS::SourceLocation());
917 result.logger->processMessages(importWarnings, qmlImport);
918 }
919
920 QMap<QString, QSet<QString>> missingTypes;
921 QMap<QString, QSet<QString>> partiallyResolvedTypes;
922
923 const QString modulePrefix = u"$module$."_s;
924 const QString internalPrefix = u"$internal$."_s;
925
926 for (auto &&[typeName, importedScope] : types.types().asKeyValueRange()) {
927 QString name = typeName;
928 const QQmlJSScope::ConstPtr scope = importedScope.scope;
929
930 if (name.startsWith(modulePrefix))
931 continue;
932
933 if (name.startsWith(internalPrefix)) {
934 name = name.mid(internalPrefix.size());
935 }
936
937 if (scope.isNull()) {
938 if (!missingTypes.contains(name))
939 missingTypes[name] = {};
940 continue;
941 }
942
943 if (!scope->isFullyResolved()) {
944 if (!partiallyResolvedTypes.contains(name))
945 partiallyResolvedTypes[name] = {};
946 }
947 const auto &ownProperties = scope->ownProperties();
948 for (const auto &property : ownProperties) {
949 if (property.typeName().isEmpty()) {
950 // If the type name is empty, then it's an intentional vaguery i.e. for some
951 // builtins
952 continue;
953 }
954 if (property.type().isNull()) {
955 missingTypes[property.typeName()]
956 << scope->internalName() + u'.' + property.propertyName();
957 continue;
958 }
959 if (!property.type()->isFullyResolved()) {
960 partiallyResolvedTypes[property.typeName()]
961 << scope->internalName() + u'.' + property.propertyName();
962 }
963 }
964 if (scope->attachedType() && !scope->attachedType()->isFullyResolved()) {
965 result.logger->log(u"Attached type of \"%1\" not fully resolved"_s.arg(name),
966 qmlUnresolvedType, scope->sourceLocation());
967 }
968
969 const auto &ownMethods = scope->ownMethods();
970 for (const auto &method : ownMethods) {
971 if (method.returnTypeName().isEmpty())
972 continue;
973 if (method.returnType().isNull()) {
974 missingTypes[method.returnTypeName()] << u"return type of "_s
975 + scope->internalName() + u'.' + method.methodName() + u"()"_s;
976 } else if (!method.returnType()->isFullyResolved()) {
977 partiallyResolvedTypes[method.returnTypeName()] << u"return type of "_s
978 + scope->internalName() + u'.' + method.methodName() + u"()"_s;
979 }
980
981 const auto parameters = method.parameters();
982 for (qsizetype i = 0; i < parameters.size(); i++) {
983 auto &parameter = parameters[i];
984 const QString typeName = parameter.typeName();
985 const QSharedPointer<const QQmlJSScope> type = parameter.type();
986 if (typeName.isEmpty())
987 continue;
988 if (type.isNull()) {
989 missingTypes[typeName] << u"parameter %1 of "_s.arg(i + 1)
990 + scope->internalName() + u'.' + method.methodName() + u"()"_s;
991 continue;
992 }
993 if (!type->isFullyResolved()) {
994 partiallyResolvedTypes[typeName] << u"parameter %1 of "_s.arg(i + 1)
995 + scope->internalName() + u'.' + method.methodName() + u"()"_s;
996 continue;
997 }
998 }
999 }
1000 }
1001
1002 for (auto &&[name, uses] : missingTypes.asKeyValueRange()) {
1003 QString message = u"Type \"%1\" not found"_s.arg(name);
1004
1005 if (!uses.isEmpty()) {
1006 const QStringList usesList = QStringList(uses.begin(), uses.end());
1007 message += u". Used in %1"_s.arg(usesList.join(u", "_s));
1008 }
1009
1010 result.logger->log(message, qmlUnresolvedType, QQmlJS::SourceLocation());
1011 }
1012
1013 for (auto &&[name, uses] : partiallyResolvedTypes.asKeyValueRange()) {
1014 QString message = u"Type \"%1\" is not fully resolved"_s.arg(name);
1015
1016 if (!uses.isEmpty()) {
1017 const QStringList usesList = QStringList(uses.begin(), uses.end());
1018 message += u". Used in %1"_s.arg(usesList.join(u", "_s));
1019 }
1020
1021 result.logger->log(message, qmlUnresolvedType, QQmlJS::SourceLocation());
1022 }
1023
1024 result.status = (result.logger->hasWarnings() || result.logger->hasErrors()) ? HasWarnings
1025 : LintSuccess;
1026 return result;
1027}
1028
1029QQmlJSLinter::FixResult QQmlJSLinter::applyFixes(const QQmlJSLogger *logger, QString *fixedCode,
1030 bool silent)
1031{
1032 Q_ASSERT(fixedCode != nullptr);
1033
1034 // This means that the necessary analysis for applying fixes hasn't run for some reason
1035 // (because it was JS file, a syntax error etc.). We can't procede without it and if an error
1036 // has occurred that has to be handled by the caller. Just say that there is
1037 // nothing to fix.
1038 if (logger == nullptr)
1039 return NothingToFix;
1040
1041 QString code = logger->code();
1042
1043 QList<QQmlJSFixSuggestion> fixesToApply;
1044
1045 QFileInfo info(logger->filePath());
1046 const QString currentFileAbsolutePath = info.absoluteFilePath();
1047
1048 const QString lowerSuffix = info.suffix().toLower();
1049 const bool isESModule = lowerSuffix == QLatin1String("mjs");
1050 const bool isJavaScript = isESModule || lowerSuffix == QLatin1String("js");
1051
1052 if (isESModule || isJavaScript)
1053 return NothingToFix;
1054
1055 logger->iterateAllMessages([&](const Message &msg) {
1056 if (!msg.fixSuggestion.has_value() || !msg.fixSuggestion->isAutoApplicable())
1057 return;
1058
1059 // Ignore fix suggestions for other files
1060 const QString filename = msg.fixSuggestion->filename();
1061 if (!filename.isEmpty()
1062 && QFileInfo(filename).absoluteFilePath() != currentFileAbsolutePath) {
1063 return;
1064 }
1065
1066 fixesToApply << msg.fixSuggestion.value();
1067 });
1068
1069 if (fixesToApply.isEmpty())
1070 return NothingToFix;
1071
1072 QList<QQmlJSDocumentEdit> documentEdits;
1073 for (const auto &fixToApply : std::as_const(fixesToApply)) {
1074 const auto &fixDocumentEdits = fixToApply.documentEdits();
1075 for (const auto &documentEdit : fixDocumentEdits) {
1076 // TODO also apply documentEdits in other files
1077 if (documentEdit.m_filename == logger->filePath())
1078 documentEdits << documentEdit;
1079 }
1080 }
1081
1082 std::sort(documentEdits.begin(), documentEdits.end(),
1083 [](const QQmlJSDocumentEdit &a, const QQmlJSDocumentEdit &b) {
1084 return a.m_location.offset < b.m_location.offset;
1085 });
1086
1087 const auto dupes = std::unique(documentEdits.begin(), documentEdits.end());
1088 documentEdits.erase(dupes, documentEdits.end());
1089
1090 for (auto it = documentEdits.begin(); it + 1 != documentEdits.end(); it++) {
1091 const QQmlJS::SourceLocation srcLocA = it->m_location;
1092 const QQmlJS::SourceLocation srcLocB = (it + 1)->m_location;
1093 if (srcLocA.offset + srcLocA.length > srcLocB.offset) {
1094 if (!silent)
1095 qWarning() << "Document edits for warning fixes are overlapping, aborting. "
1096 "Please file a bug report if this is a Qt warning";
1097 return FixError;
1098 }
1099 }
1100
1101 int offsetEdit = 0;
1102
1103 for (const auto &edit : std::as_const(documentEdits)) {
1104 const QQmlJS::SourceLocation fixLocation = edit.m_location;
1105 qsizetype cutLocation = fixLocation.offset + offsetEdit;
1106 const QString before = code.left(cutLocation);
1107 const QString after = code.mid(cutLocation + fixLocation.length);
1108
1109 const QString replacement = edit.m_replacement;
1110 code = before + replacement + after;
1111 offsetEdit += replacement.size() - fixLocation.length;
1112 }
1113
1114 QQmlJS::Engine engine;
1115 QQmlJS::Lexer lexer(&engine);
1116
1117 lexer.setCode(code, /*lineno = */ 1, /*qmlMode=*/!isJavaScript);
1118 QQmlJS::Parser parser(&engine);
1119
1120 bool success = parser.parse();
1121
1122 if (!success) {
1123 const auto diagnosticMessages = parser.diagnosticMessages();
1124
1125 if (!silent) {
1126 qDebug() << "File became unparseable after suggestions were applied. Please file a bug "
1127 "report.";
1128 } else {
1129 return FixError;
1130 }
1131
1132 for (const QQmlJS::DiagnosticMessage &m : diagnosticMessages) {
1133 qWarning().noquote() << QString::fromLatin1("%1:%2:%3: %4")
1134 .arg(logger->filePath())
1135 .arg(m.loc.startLine)
1136 .arg(m.loc.startColumn)
1137 .arg(m.message);
1138 }
1139 return FixError;
1140 }
1141
1142 *fixedCode = code;
1143 return FixSuccess;
1144}
1145
1146QT_END_NAMESPACE
void reportParserWarnings(const QString &, QQmlJS::SourceLocation, const QString &) override
void reportVarUsedBeforeDeclaration(const QString &name, const QString &fileName, QQmlJS::SourceLocation declarationLocation, QQmlJS::SourceLocation accessLocation) override
void reportFunctionUsedBeforeDeclaration(const QString &name, const QString &fileName, QQmlJS::SourceLocation declarationLocation, QQmlJS::SourceLocation accessLocation) override
UnreachableVisitor * unreachableVisitor() override
CodegenWarningInterface(QQmlJSLogger *logger)
bool visit(QQmlJS::AST::FunctionDeclaration *functionDeclaration) override
void throwRecursionDepthError() override
void setPassManager(QQmlSA::PassManager *passManager)
Plugin(Plugin &&plugin) noexcept
Plugin(const QStaticPlugin &plugin)
Result lintModule(const QString &uri, LintOptions options, const QStringList &qmlImportPaths, const QStringList &resourceFiles)
bool useAbsolutePath() const
Result lintFileInBatch(const QString &filename)
QQmlJSLinter(const QStringList &importPaths, const QStringList &extraPluginPaths={}, bool useAbsolutePath=false)
bool prepareFileForBatchLinting(const QString &filename, const QString *fileContents, LintOptions options, const QStringList &qmlImportPaths, const QStringList &qmldirFiles, const QStringList &resourceFiles, const QList< QQmlJS::LoggerCategory > &categories)
UnreachableVisitor(QQmlJSLogger *logger)
void throwRecursionDepthError() override
bool containsFunctionDeclaration(QQmlJS::AST::Node *node)
bool visit(QQmlJS::AST::StatementList *unreachable) override
\inmodule QtQmlCompiler
Combined button and popup list for selecting options.
static void addJsonWarning(QJsonArray &warnings, const QQmlJS::DiagnosticMessage &message, QAnyStringView id, const std::optional< QQmlJSFixSuggestion > &suggestion={})
static void processMessages(const QQmlJSLogger &logger, QJsonArray &warnings)