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