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
6
9
10#include <QtQmlCompiler/private/qqmljsimporter_p.h>
11#include <QtQmlCompiler/private/qqmljsimportvisitor_p.h>
12#include <QtQmlCompiler/private/qqmljsliteralbindingcheck_p.h>
13
14#include <QtCore/qjsonobject.h>
15#include <QtCore/qfileinfo.h>
16#include <QtCore/qloggingcategory.h>
17#include <QtCore/qpluginloader.h>
18#include <QtCore/qlibraryinfo.h>
19#include <QtCore/qdir.h>
20#include <QtCore/private/qduplicatetracker_p.h>
21#include <QtCore/qscopedpointer.h>
22
23#include <QtQmlCompiler/private/qqmlsa_p.h>
24#include <QtQmlCompiler/private/qqmljsloggingutils_p.h>
25#include <QtQmlCompiler/private/qqmljslintervisitor_p.h>
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 UnreachableVisitor *unreachableVisitor() override { return &m_unreachableVisitor; }
138
139private:
140 QQmlJSLogger *m_logger;
141 UnreachableVisitor m_unreachableVisitor;
142};
143
144QQmlJSLinter::QQmlJSLinter(const QStringList &importPaths, const QStringList &extraPluginPaths,
145 bool useAbsolutePath)
146 : m_useAbsolutePath(useAbsolutePath),
147 m_enablePlugins(true),
148 m_importer(importPaths, nullptr, QQmlJSImporterFlags(UseOptionalImports | TolerateFileSelectors))
149{
150 m_plugins = loadPlugins(extraPluginPaths);
151}
152
153QQmlJSLinter::Plugin::Plugin(QQmlJSLinter::Plugin &&plugin) noexcept
154 : m_name(std::move(plugin.m_name))
155 , m_description(std::move(plugin.m_description))
156 , m_version(std::move(plugin.m_version))
157 , m_author(std::move(plugin.m_author))
158 , m_categories(std::move(plugin.m_categories))
159 , m_instance(std::move(plugin.m_instance))
160 , m_loader(std::move(plugin.m_loader))
161 , m_isInternal(std::move(plugin.m_isInternal))
162 , m_isValid(std::move(plugin.m_isValid))
163{
164 // Mark the old Plugin as invalid and make sure it doesn't delete the loader
165 Q_ASSERT(!plugin.m_loader);
166 plugin.m_instance = nullptr;
167 plugin.m_isValid = false;
168}
169
170#if QT_CONFIG(library)
171QQmlJSLinter::Plugin::Plugin(QString path)
172{
173 m_loader = std::make_unique<QPluginLoader>(path);
174 if (!parseMetaData(m_loader->metaData(), path))
175 return;
176
177 QObject *object = m_loader->instance();
178 if (!object)
179 return;
180
181 m_instance = qobject_cast<QQmlSA::LintPlugin *>(object);
182 if (!m_instance)
183 return;
184
185 m_isValid = true;
186}
187#endif
188
189QQmlJSLinter::Plugin::Plugin(const QStaticPlugin &staticPlugin)
190{
191 if (!parseMetaData(staticPlugin.metaData(), u"built-in"_s))
192 return;
193
194 m_instance = qobject_cast<QQmlSA::LintPlugin *>(staticPlugin.instance());
195 if (!m_instance)
196 return;
197
198 m_isValid = true;
199}
200
201QQmlJSLinter::Plugin::~Plugin()
202{
203#if QT_CONFIG(library)
204 if (m_loader != nullptr) {
205 m_loader->unload();
206 m_loader->deleteLater();
207 }
208#endif
209}
210
211bool QQmlJSLinter::Plugin::parseMetaData(const QJsonObject &metaData, QString pluginName)
212{
213 const QString pluginIID = QStringLiteral(QmlLintPluginInterface_iid);
214
215 if (metaData[u"IID"].toString() != pluginIID)
216 return false;
217
218 QJsonObject pluginMetaData = metaData[u"MetaData"].toObject();
219
220 for (const QString &requiredKey :
221 { u"name"_s, u"version"_s, u"author"_s, u"loggingCategories"_s }) {
222 if (!pluginMetaData.contains(requiredKey)) {
223 qWarning() << pluginName << "is missing the required " << requiredKey
224 << "metadata, skipping";
225 return false;
226 }
227 }
228
229 m_name = pluginMetaData[u"name"].toString();
230 m_author = pluginMetaData[u"author"].toString();
231 m_version = pluginMetaData[u"version"].toString();
232 m_description = pluginMetaData[u"description"].toString(u"-/-"_s);
233 m_isInternal = pluginMetaData[u"isInternal"].toBool(false);
234
235 if (!pluginMetaData[u"loggingCategories"].isArray()) {
236 qWarning() << pluginName << "has loggingCategories which are not an array, skipping";
237 return false;
238 }
239
240 QJsonArray categories = pluginMetaData[u"loggingCategories"].toArray();
241
242 for (const QJsonValue &value : std::as_const(categories)) {
243 if (!value.isObject()) {
244 qWarning() << pluginName << "has invalid loggingCategories entries, skipping";
245 return false;
246 }
247
248 const QJsonObject object = value.toObject();
249
250 for (const QString &requiredKey : { u"name"_s, u"description"_s }) {
251 if (!object.contains(requiredKey)) {
252 qWarning() << pluginName << " logging category is missing the required "
253 << requiredKey << "metadata, skipping";
254 return false;
255 }
256 }
257
258 const auto it = object.find("enabled"_L1);
259 const bool ignored = (it != object.end() && !it->toBool());
260
261 const QString prefix = (m_isInternal ? u""_s : u"Plugin."_s).append(m_name).append(u'.');
262 const QString categoryId =
263 prefix + object[u"name"].toString();
264 const auto settingsNameIt = object.constFind(u"settingsName");
265 const QString settingsName = (settingsNameIt == object.constEnd())
266 ? categoryId
267 : prefix + settingsNameIt->toString(categoryId);
268 m_categories << QQmlJS::LoggerCategory{ categoryId, settingsName,
269 object["description"_L1].toString(), QtWarningMsg,
270 ignored };
271 const auto itLevel = object.find("defaultLevel"_L1);
272 if (itLevel == object.end())
273 continue;
274
275 const QString level = itLevel->toString();
276 if (!QQmlJS::LoggingUtils::applyLevelToCategory(level, m_categories.last())) {
277 qWarning() << "Invalid logging level" << level << "provided for"
278 << m_categories.last().id().name().toString()
279 << "(allowed are: disable, info, warning, error) found in plugin metadata.";
280 }
281 }
282
283 return true;
284}
285
286std::vector<QQmlJSLinter::Plugin> QQmlJSLinter::loadPlugins(QStringList extraPluginPaths)
287{
288 std::vector<Plugin> plugins;
289
290 QDuplicateTracker<QString> seenPlugins;
291
292 const auto &staticPlugins = QPluginLoader::staticPlugins();
293 for (const QStaticPlugin &staticPlugin : staticPlugins) {
294 Plugin plugin(staticPlugin);
295 if (!plugin.isValid())
296 continue;
297
298 if (seenPlugins.hasSeen(plugin.name().toLower())) {
299 qWarning() << "Two plugins named" << plugin.name()
300 << "present, make sure no plugins are duplicated. The second plugin will "
301 "not be loaded.";
302 continue;
303 }
304
305 plugins.push_back(std::move(plugin));
306 }
307
308#if QT_CONFIG(library)
309 const QStringList paths = [&extraPluginPaths]() {
310 QStringList result{ extraPluginPaths };
311 const QStringList libraryPaths = QCoreApplication::libraryPaths();
312 for (const auto &path : libraryPaths) {
313 result.append(path + u"/qmllint"_s);
314 }
315 return result;
316 }();
317 for (const QString &pluginDir : paths) {
318 QDirIterator it{ pluginDir, QDir::Files };
319
320 while (it.hasNext()) {
321 auto potentialPlugin = it.next();
322
323 if (!QLibrary::isLibrary(potentialPlugin))
324 continue;
325
326 Plugin plugin(potentialPlugin);
327
328 if (!plugin.isValid())
329 continue;
330
331 if (seenPlugins.hasSeen(plugin.name().toLower())) {
332 qWarning() << "Two plugins named" << plugin.name()
333 << "present, make sure no plugins are duplicated. The second plugin "
334 "will not be loaded.";
335 continue;
336 }
337
338 plugins.push_back(std::move(plugin));
339 }
340 }
341#endif
342 Q_UNUSED(extraPluginPaths)
343 return plugins;
344}
345
346void QQmlJSLinter::parseComments(QQmlJSLogger *logger,
347 const QList<QQmlJS::SourceLocation> &comments)
348{
349 QHash<int, QSet<QString>> disablesPerLine;
350 QHash<int, QSet<QString>> enablesPerLine;
351 QHash<int, QSet<QString>> oneLineDisablesPerLine;
352
353 const QString code = logger->code();
354 const QStringList lines = code.split(u'\n');
355 const auto loggerCategories = logger->categories();
356
357 for (const auto &loc : comments) {
358 const QString comment = code.mid(loc.offset, loc.length);
359 if (!comment.startsWith(u" qmllint ") && !comment.startsWith(u"qmllint "))
360 continue;
361
362 QStringList words = comment.split(u' ', Qt::SkipEmptyParts);
363 if (words.size() < 2)
364 continue;
365
366 QSet<QString> categories;
367 for (qsizetype i = 2; i < words.size(); i++) {
368 const QString category = words.at(i);
369 const auto categoryExists = std::any_of(
370 loggerCategories.cbegin(), loggerCategories.cend(),
371 [&](const QQmlJS::LoggerCategory &cat) { return cat.id().name() == category; });
372
373 if (categoryExists)
374 categories << category;
375 else
376 logger->log(u"qmllint directive on unknown category \"%1\""_s.arg(category),
377 qmlInvalidLintDirective, loc);
378 }
379
380 if (categories.isEmpty()) {
381 const auto &loggerCategories = logger->categories();
382 for (const auto &option : loggerCategories)
383 categories << option.id().name().toString();
384 }
385
386 const QString command = words.at(1);
387 if (command == u"disable"_s) {
388 if (const qsizetype lineIndex = loc.startLine - 1; lineIndex < lines.size()) {
389 const QString line = lines[lineIndex];
390 const QString preComment = line.left(line.indexOf(comment) - 2);
391
392 bool lineHasContent = false;
393 for (qsizetype i = 0; i < preComment.size(); i++) {
394 if (!preComment[i].isSpace()) {
395 lineHasContent = true;
396 break;
397 }
398 }
399
400 if (lineHasContent)
401 oneLineDisablesPerLine[loc.startLine] |= categories;
402 else
403 disablesPerLine[loc.startLine] |= categories;
404 }
405 } else if (command == u"enable"_s) {
406 enablesPerLine[loc.startLine + 1] |= categories;
407 } else {
408 logger->log(u"Invalid qmllint directive \"%1\" provided"_s.arg(command),
409 qmlInvalidLintDirective, loc);
410 }
411 }
412
413 if (disablesPerLine.isEmpty() && oneLineDisablesPerLine.isEmpty())
414 return;
415
416 QSet<QString> currentlyDisabled;
417 for (qsizetype i = 1; i <= lines.size(); i++) {
418 currentlyDisabled.unite(disablesPerLine[i]).subtract(enablesPerLine[i]);
419
420 currentlyDisabled.unite(oneLineDisablesPerLine[i]);
421
422 if (!currentlyDisabled.isEmpty())
423 logger->ignoreWarnings(i, currentlyDisabled);
424
425 currentlyDisabled.subtract(oneLineDisablesPerLine[i]);
426 }
427}
428
429static void addJsonWarning(QJsonArray &warnings, const QQmlJS::DiagnosticMessage &message,
430 QAnyStringView id, const std::optional<QQmlJSFixSuggestion> &suggestion = {})
431{
432 QJsonObject jsonMessage;
433
434 QString type;
435 switch (message.type) {
436 case QtDebugMsg:
437 type = u"debug"_s;
438 break;
439 case QtWarningMsg:
440 type = u"warning"_s;
441 break;
442 case QtCriticalMsg:
443 type = u"critical"_s;
444 break;
445 case QtFatalMsg:
446 type = u"fatal"_s;
447 break;
448 case QtInfoMsg:
449 type = u"info"_s;
450 break;
451 default:
452 type = u"unknown"_s;
453 break;
454 }
455
456 jsonMessage[u"type"_s] = type;
457 jsonMessage[u"id"_s] = id.toString();
458
459 if (message.loc.isValid()) {
460 jsonMessage[u"line"_s] = static_cast<int>(message.loc.startLine);
461 jsonMessage[u"column"_s] = static_cast<int>(message.loc.startColumn);
462 jsonMessage[u"charOffset"_s] = static_cast<int>(message.loc.offset);
463 jsonMessage[u"length"_s] = static_cast<int>(message.loc.length);
464 }
465
466 jsonMessage[u"message"_s] = message.message;
467
468 QJsonArray suggestions;
469 const auto convertLocation = [](const QQmlJS::SourceLocation &source, QJsonObject *target) {
470 target->insert("line"_L1, int(source.startLine));
471 target->insert("column"_L1, int(source.startColumn));
472 target->insert("charOffset"_L1, int(source.offset));
473 target->insert("length"_L1, int(source.length));
474 };
475 if (suggestion.has_value()) {
476 QJsonObject jsonFix {
477 { "message"_L1, suggestion->fixDescription() },
478 { "replacement"_L1, suggestion->replacement() },
479 { "isAutoApplicable"_L1, suggestion->isAutoApplicable() },
480 { "hint"_L1, suggestion->hint() },
481 };
482 convertLocation(suggestion->location(), &jsonFix);
483 const QString filename = suggestion->filename();
484 if (!filename.isEmpty())
485 jsonFix.insert("fileName"_L1, filename);
486 suggestions << jsonFix;
487 }
488 jsonMessage[u"suggestions"] = suggestions;
489
490 warnings << jsonMessage;
491}
492
493void QQmlJSLinter::processMessages(QJsonArray &warnings)
494{
495 m_logger->iterateAllMessages([&](const Message &message) {
496 addJsonWarning(warnings, message, message.id, message.fixSuggestion);
497 });
498}
499
500ContextPropertyInfo QQmlJSLinter::contextPropertiesFor(
501 const QString &filename, QQmlJSResourceFileMapper *mapper,
502 const QQmlJS::HeuristicContextProperties &heuristicContextProperties)
503{
504 ContextPropertyInfo result;
505 if (m_userContextPropertySettings.search(filename).isValid()) {
506 result.userContextProperties =
507 QQmlJS::UserContextProperties{ m_userContextPropertySettings };
508 }
509
510 if (heuristicContextProperties.isValid()) {
511 result.heuristicContextProperties = heuristicContextProperties;
512 return result;
513 }
514
515#if QT_CONFIG(qmlcontextpropertydump)
516 const QString buildPath = QQmlJSUtils::qmlBuildPathFromSourcePath(mapper, filename);
517 if (const auto searchResult = m_heuristicContextPropertySearcher.search(buildPath);
518 searchResult.isValid()) {
519 QSettings settings(searchResult.iniFilePath, QSettings::IniFormat);
520 result.heuristicContextProperties =
521 QQmlJS::HeuristicContextProperties::collectFrom(&settings);
522 }
523#else
524 Q_UNUSED(mapper);
525#endif
526 return result;
527}
528
529QQmlJSLinter::LintResult
530QQmlJSLinter::lintFile(const QString &filename, const QString *fileContents, const bool silent,
531 QJsonArray *json, const QStringList &qmlImportPaths,
532 const QStringList &qmldirFiles, const QStringList &resourceFiles,
533 const QList<QQmlJS::LoggerCategory> &categories,
534 const QQmlJS::HeuristicContextProperties &heuristicContextProperties)
535{
536 // Make sure that we don't expose an old logger if we return before a new one is created.
537 m_logger.reset();
538
539 QJsonArray warnings;
540 QJsonObject result;
541
542 LintResult success = LintSuccess;
543
544 QScopeGuard jsonOutput([&] {
545 if (!json)
546 return;
547
548 result[u"filename"_s] = QFileInfo(filename).absoluteFilePath();
549 result[u"warnings"] = warnings;
550 result[u"success"] = success == LintSuccess;
551
552 json->append(result);
553 });
554
555 QString code;
556
557 if (fileContents == nullptr) {
558 QFile file(filename);
559 if (!file.open(QFile::ReadOnly)) {
560 if (json) {
561 addJsonWarning(
562 warnings,
563 QQmlJS::DiagnosticMessage { QStringLiteral("Failed to open file %1: %2")
564 .arg(filename, file.errorString()),
565 QtCriticalMsg, QQmlJS::SourceLocation() },
566 qmlImport.name());
567 } else if (!silent) {
568 qWarning() << "Failed to open file" << filename << file.error();
569 }
570 success = FailedToOpen;
571 return success;
572 }
573
574 code = QString::fromUtf8(file.readAll());
575 file.close();
576 } else {
577 code = *fileContents;
578 }
579
580 m_fileContents = code;
581
582 QQmlJS::Engine engine;
583 QQmlJS::Lexer lexer(&engine);
584
585 QFileInfo info(filename);
586 const QString lowerSuffix = info.suffix().toLower();
587 const bool isESModule = lowerSuffix == QLatin1String("mjs");
588 const bool isJavaScript = isESModule || lowerSuffix == QLatin1String("js");
589
590 m_logger.reset(new QQmlJSLogger);
591 m_logger->setFilePath(m_useAbsolutePath ? info.absoluteFilePath() : filename);
592 m_logger->setCode(code);
593 m_logger->setSilent(silent || json);
594
595 lexer.setCode(code, /*lineno = */ 1, /*qmlMode=*/!isJavaScript);
596 QQmlJS::Parser parser(&engine);
597
598 if (!(isJavaScript ? (isESModule ? parser.parseModule() : parser.parseProgram())
599 : parser.parse())) {
600 success = FailedToParse;
601 const auto diagnosticMessages = parser.diagnosticMessages();
602 for (const QQmlJS::DiagnosticMessage &m : diagnosticMessages) {
603 if (json)
604 addJsonWarning(warnings, m, qmlSyntax.name());
605 m_logger->log(m.message, qmlSyntax, m.loc);
606 }
607 return success;
608 }
609
610 if (isJavaScript)
611 return success;
612
613 if (m_importer.importPaths() != qmlImportPaths)
614 m_importer.setImportPaths(qmlImportPaths);
615
616 std::optional<QQmlJSResourceFileMapper> mapper;
617 if (!resourceFiles.isEmpty())
618 mapper.emplace(resourceFiles);
619 m_importer.setResourceFileMapper(mapper.has_value() ? &*mapper : nullptr);
620
621 QQmlJS::LinterVisitor v{ &m_importer, m_logger.get(),
622 QQmlJSImportVisitor::implicitImportDirectory(
623 m_logger->filePath(), m_importer.resourceFileMapper()),
624 qmldirFiles, &engine };
625
626 if (m_enablePlugins) {
627 for (const Plugin &plugin : m_plugins) {
628 for (const QQmlJS::LoggerCategory &category : plugin.categories())
629 m_logger->registerCategory(category);
630 }
631 }
632
633 for (auto it = categories.cbegin(); it != categories.cend(); ++it) {
634 if (auto logger = *it; !QQmlJS::LoggerCategoryPrivate::get(&logger)->hasChanged())
635 continue;
636
637 m_logger->setCategoryIgnored(it->id(), it->isIgnored());
638 m_logger->setCategoryLevel(it->id(), it->level());
639 }
640
641 parseComments(m_logger.get(), engine.comments());
642
643 QQmlJSTypeResolver typeResolver(&m_importer);
644
645 // Type resolving is using document parent mode here so that it produces fewer false
646 // positives on the "parent" property of QQuickItem. It does produce a few false
647 // negatives this way because items can be reparented. Furthermore, even if items
648 // are not reparented, the document parent may indeed not be their visual parent.
649 // See QTBUG-95530. Eventually, we'll need cleverer logic to deal with this.
650 typeResolver.setParentMode(QQmlJSTypeResolver::UseDocumentParent);
651 // We don't need to create tracked types and such as we are just linting the code
652 // here and not actually compiling it. The duplicated scopes would cause issues
653 // during linting.
654 typeResolver.setCloneMode(QQmlJSTypeResolver::DoNotCloneTypes);
655
656 typeResolver.init(&v, parser.rootNode());
657
658 const QStringList resourcePaths = mapper
659 ? mapper->resourcePaths(QQmlJSResourceFileMapper::localFileFilter(filename))
660 : QStringList();
661 const QString resolvedPath =
662 (resourcePaths.size() == 1) ? u':' + resourcePaths.first() : filename;
663
664 QQmlJSLinterCodegen codegen{ &m_importer, resolvedPath, qmldirFiles, m_logger.get(),
665 contextPropertiesFor(filename, mapper ? &*mapper : nullptr,
666 heuristicContextProperties) };
667 codegen.setTypeResolver(std::move(typeResolver));
668
669 using PassManagerPtr =
670 std::unique_ptr<QQmlSA::PassManager,
671 decltype(&QQmlSA::PassManagerPrivate::deletePassManager)>;
672 PassManagerPtr passMan(
673 QQmlSA::PassManagerPrivate::createPassManager(&v, codegen.typeResolver()),
674 &QQmlSA::PassManagerPrivate::deletePassManager);
675 passMan->registerPropertyPass(std::make_unique<QQmlJSLiteralBindingCheck>(passMan.get()),
676 QString(), QString(), QString());
677
678 QQmlSA::PropertyPassBuilder(passMan.get())
679 .withOnCall([](QQmlSA::PropertyPass *self, const QQmlSA::Element &, const QString &,
680 const QQmlSA::Element &, QQmlSA::SourceLocation location) {
681 self->emitWarning("Do not use 'eval'", qmlEval, location);
682 })
683 .registerOnBuiltin("GlobalObject", "eval");
684
685 QQmlSA::PropertyPassBuilder(passMan.get())
686 .withOnRead([](QQmlSA::PropertyPass *self, const QQmlSA::Element &element,
687 const QString &propName, const QQmlSA::Element &readScope_,
688 QQmlSA::SourceLocation location) {
689
690 const auto &elementScope = QQmlJSScope::scope(element);
691 const auto &owner = QQmlJSScope::ownerOfProperty(elementScope, propName).scope;
692 if (!owner || owner->isComposite() || owner->isValueType())
693 return;
694 const auto &prop = QQmlSA::PropertyPrivate::property(element.property(propName));
695 if (prop.index() != -1 && !prop.isPropertyConstant()
696 && prop.notify().isEmpty() && prop.bindable().isEmpty()) {
697 const QQmlJSScope::ConstPtr &readScope = QQmlJSScope::scope(readScope_);
698 // FIXME: we currently get the closest QML Scope as readScope, instead of
699 // the innermost scope. We try locate it here via source location
700 Q_ASSERT(readScope->scopeType() == QQmlJSScope::ScopeType::QMLScope);
701 for (auto it = readScope->childScopesBegin(); it != readScope->childScopesEnd(); ++it) {
702 QQmlJS::SourceLocation childLocation = (*it)->sourceLocation();
703 if ( childLocation.offset <= location.offset() &&
704 (childLocation.offset + childLocation.length <= location.offset() + location.length()) ) {
705 if ((*it)->scopeType() != QQmlSA::ScopeType::BindingFunctionScope)
706 return;
707 }
708 }
709 const QString msg =
710 "Reading non-constant and non-notifiable property %1. "_L1
711 "Binding might not update when the property changes."_L1.arg(propName);
712 self->emitWarning(msg, qmlStalePropertyRead, location);
713 }
714 }).registerOn({}, {}, {});
715
716 if (m_enablePlugins) {
717 for (const Plugin &plugin : m_plugins) {
718 if (!plugin.isValid() || !plugin.isEnabled())
719 continue;
720
721 QQmlSA::LintPlugin *instance = plugin.m_instance;
722 Q_ASSERT(instance);
723 instance->registerPasses(passMan.get(), QQmlJSScope::createQQmlSAElement(v.result()));
724 }
725 }
726 passMan->analyze(QQmlJSScope::createQQmlSAElement(v.result()));
727
728 if (m_logger->hasErrors()) {
729 success = HasErrors;
730 if (json)
731 processMessages(warnings);
732 return success;
733 } else if (m_logger->hasWarnings())
734 success = HasWarnings;
735
736 // passMan now has a pointer to the moved from type resolver
737 // we fix this in setPassManager
738 codegen.setPassManager(passMan.get());
739
740 QQmlJSSaveFunction saveFunction = [](const QV4::CompiledData::SaveableUnitPointer &,
741 const QQmlJSAotFunctionMap &, QString *) { return true; };
742
743 QQmlJSCompileError error;
744
745 QLoggingCategory::setFilterRules(u"qt.qml.compiler=false"_s);
746
747 CodegenWarningInterface warningInterface(m_logger.get());
748 qCompileQmlFile(filename, saveFunction, &codegen, &error, true, &warningInterface,
749 fileContents);
750
751 QList<QQmlJS::DiagnosticMessage> globalWarnings = m_importer.takeGlobalWarnings();
752
753 if (!globalWarnings.isEmpty()) {
754 m_logger->log(QStringLiteral("Type warnings occurred while evaluating file:"), qmlImport,
755 QQmlJS::SourceLocation());
756 m_logger->processMessages(globalWarnings, qmlImport);
757 }
758
759 if (m_logger->hasErrors())
760 success = HasErrors;
761 else if (m_logger->hasWarnings())
762 success = HasWarnings;
763
764 if (json)
765 processMessages(warnings);
766 return success;
767}
768
769QQmlJSLinter::LintResult QQmlJSLinter::lintModule(
770 const QString &module, const bool silent, QJsonArray *json,
771 const QStringList &qmlImportPaths, const QStringList &resourceFiles)
772{
773 // Make sure that we don't expose an old logger if we return before a new one is created.
774 m_logger.reset();
775
776 // We can't lint properly if a module has already been pre-cached
777 m_importer.clearCache();
778
779 if (m_importer.importPaths() != qmlImportPaths)
780 m_importer.setImportPaths(qmlImportPaths);
781
782 QQmlJSResourceFileMapper mapper(resourceFiles);
783 if (!resourceFiles.isEmpty())
784 m_importer.setResourceFileMapper(&mapper);
785 else
786 m_importer.setResourceFileMapper(nullptr);
787
788 QJsonArray warnings;
789 QJsonObject result;
790
791 bool success = true;
792
793 QScopeGuard jsonOutput([&] {
794 if (!json)
795 return;
796
797 result[u"module"_s] = module;
798
799 result[u"warnings"] = warnings;
800 result[u"success"] = success;
801
802 json->append(result);
803 });
804
805 m_logger.reset(new QQmlJSLogger);
806 m_logger->setFilePath(module);
807 m_logger->setCode(u""_s);
808 m_logger->setSilent(silent || json);
809
810 const QQmlJSImporter::ImportedTypes types = m_importer.importModule(module);
811
812 QList<QQmlJS::DiagnosticMessage> importWarnings =
813 m_importer.takeGlobalWarnings() + types.warnings();
814
815 if (!importWarnings.isEmpty()) {
816 m_logger->log(QStringLiteral("Warnings occurred while importing module:"), qmlImport,
817 QQmlJS::SourceLocation());
818 m_logger->processMessages(importWarnings, qmlImport);
819 }
820
821 QMap<QString, QSet<QString>> missingTypes;
822 QMap<QString, QSet<QString>> partiallyResolvedTypes;
823
824 const QString modulePrefix = u"$module$."_s;
825 const QString internalPrefix = u"$internal$."_s;
826
827 for (auto &&[typeName, importedScope] : types.types().asKeyValueRange()) {
828 QString name = typeName;
829 const QQmlJSScope::ConstPtr scope = importedScope.scope;
830
831 if (name.startsWith(modulePrefix))
832 continue;
833
834 if (name.startsWith(internalPrefix)) {
835 name = name.mid(internalPrefix.size());
836 }
837
838 if (scope.isNull()) {
839 if (!missingTypes.contains(name))
840 missingTypes[name] = {};
841 continue;
842 }
843
844 if (!scope->isFullyResolved()) {
845 if (!partiallyResolvedTypes.contains(name))
846 partiallyResolvedTypes[name] = {};
847 }
848 const auto &ownProperties = scope->ownProperties();
849 for (const auto &property : ownProperties) {
850 if (property.typeName().isEmpty()) {
851 // If the type name is empty, then it's an intentional vaguery i.e. for some
852 // builtins
853 continue;
854 }
855 if (property.type().isNull()) {
856 missingTypes[property.typeName()]
857 << scope->internalName() + u'.' + property.propertyName();
858 continue;
859 }
860 if (!property.type()->isFullyResolved()) {
861 partiallyResolvedTypes[property.typeName()]
862 << scope->internalName() + u'.' + property.propertyName();
863 }
864 }
865 if (scope->attachedType() && !scope->attachedType()->isFullyResolved()) {
866 m_logger->log(u"Attached type of \"%1\" not fully resolved"_s.arg(name),
867 qmlUnresolvedType, scope->sourceLocation());
868 }
869
870 const auto &ownMethods = scope->ownMethods();
871 for (const auto &method : ownMethods) {
872 if (method.returnTypeName().isEmpty())
873 continue;
874 if (method.returnType().isNull()) {
875 missingTypes[method.returnTypeName()] << u"return type of "_s
876 + scope->internalName() + u'.' + method.methodName() + u"()"_s;
877 } else if (!method.returnType()->isFullyResolved()) {
878 partiallyResolvedTypes[method.returnTypeName()] << u"return type of "_s
879 + scope->internalName() + u'.' + method.methodName() + u"()"_s;
880 }
881
882 const auto parameters = method.parameters();
883 for (qsizetype i = 0; i < parameters.size(); i++) {
884 auto &parameter = parameters[i];
885 const QString typeName = parameter.typeName();
886 const QSharedPointer<const QQmlJSScope> type = parameter.type();
887 if (typeName.isEmpty())
888 continue;
889 if (type.isNull()) {
890 missingTypes[typeName] << u"parameter %1 of "_s.arg(i + 1)
891 + scope->internalName() + u'.' + method.methodName() + u"()"_s;
892 continue;
893 }
894 if (!type->isFullyResolved()) {
895 partiallyResolvedTypes[typeName] << u"parameter %1 of "_s.arg(i + 1)
896 + scope->internalName() + u'.' + method.methodName() + u"()"_s;
897 continue;
898 }
899 }
900 }
901 }
902
903 for (auto &&[name, uses] : missingTypes.asKeyValueRange()) {
904 QString message = u"Type \"%1\" not found"_s.arg(name);
905
906 if (!uses.isEmpty()) {
907 const QStringList usesList = QStringList(uses.begin(), uses.end());
908 message += u". Used in %1"_s.arg(usesList.join(u", "_s));
909 }
910
911 m_logger->log(message, qmlUnresolvedType, QQmlJS::SourceLocation());
912 }
913
914 for (auto &&[name, uses] : partiallyResolvedTypes.asKeyValueRange()) {
915 QString message = u"Type \"%1\" is not fully resolved"_s.arg(name);
916
917 if (!uses.isEmpty()) {
918 const QStringList usesList = QStringList(uses.begin(), uses.end());
919 message += u". Used in %1"_s.arg(usesList.join(u", "_s));
920 }
921
922 m_logger->log(message, qmlUnresolvedType, QQmlJS::SourceLocation());
923 }
924
925 if (json)
926 processMessages(warnings);
927
928 success &= !m_logger->hasWarnings() && !m_logger->hasErrors();
929
930 return success ? LintSuccess : HasWarnings;
931}
932
933QQmlJSLinter::FixResult QQmlJSLinter::applyFixes(QString *fixedCode, bool silent)
934{
935 Q_ASSERT(fixedCode != nullptr);
936
937 // This means that the necessary analysis for applying fixes hasn't run for some reason
938 // (because it was JS file, a syntax error etc.). We can't procede without it and if an error
939 // has occurred that has to be handled by the caller of lintFile(). Just say that there is
940 // nothing to fix.
941 if (m_logger == nullptr)
942 return NothingToFix;
943
944 QString code = m_fileContents;
945
946 QList<QQmlJSFixSuggestion> fixesToApply;
947
948 QFileInfo info(m_logger->filePath());
949 const QString currentFileAbsolutePath = info.absoluteFilePath();
950
951 const QString lowerSuffix = info.suffix().toLower();
952 const bool isESModule = lowerSuffix == QLatin1String("mjs");
953 const bool isJavaScript = isESModule || lowerSuffix == QLatin1String("js");
954
955 if (isESModule || isJavaScript)
956 return NothingToFix;
957
958 m_logger->iterateAllMessages([&](const Message &msg) {
959 if (!msg.fixSuggestion.has_value() || !msg.fixSuggestion->isAutoApplicable())
960 return;
961
962 // Ignore fix suggestions for other files
963 const QString filename = msg.fixSuggestion->filename();
964 if (!filename.isEmpty()
965 && QFileInfo(filename).absoluteFilePath() != currentFileAbsolutePath) {
966 return;
967 }
968
969 fixesToApply << msg.fixSuggestion.value();
970 });
971
972 if (fixesToApply.isEmpty())
973 return NothingToFix;
974
975 std::sort(fixesToApply.begin(), fixesToApply.end(),
976 [](const QQmlJSFixSuggestion &a, const QQmlJSFixSuggestion &b) {
977 return a.location().offset < b.location().offset;
978 });
979
980 const auto dupes = std::unique(fixesToApply.begin(), fixesToApply.end());
981 fixesToApply.erase(dupes, fixesToApply.end());
982
983 for (auto it = fixesToApply.begin(); it + 1 != fixesToApply.end(); it++) {
984 const QQmlJS::SourceLocation srcLocA = it->location();
985 const QQmlJS::SourceLocation srcLocB = (it + 1)->location();
986 if (srcLocA.offset + srcLocA.length > srcLocB.offset) {
987 if (!silent)
988 qWarning() << "Fixes for two warnings are overlapping, aborting. Please file a bug "
989 "report.";
990 return FixError;
991 }
992 }
993
994 int offsetChange = 0;
995
996 for (const auto &fix : std::as_const(fixesToApply)) {
997 const QQmlJS::SourceLocation fixLocation = fix.location();
998 qsizetype cutLocation = fixLocation.offset + offsetChange;
999 const QString before = code.left(cutLocation);
1000 const QString after = code.mid(cutLocation + fixLocation.length);
1001
1002 const QString replacement = fix.replacement();
1003 code = before + replacement + after;
1004 offsetChange += replacement.size() - fixLocation.length;
1005 }
1006
1007 QQmlJS::Engine engine;
1008 QQmlJS::Lexer lexer(&engine);
1009
1010 lexer.setCode(code, /*lineno = */ 1, /*qmlMode=*/!isJavaScript);
1011 QQmlJS::Parser parser(&engine);
1012
1013 bool success = parser.parse();
1014
1015 if (!success) {
1016 const auto diagnosticMessages = parser.diagnosticMessages();
1017
1018 if (!silent) {
1019 qDebug() << "File became unparseable after suggestions were applied. Please file a bug "
1020 "report.";
1021 } else {
1022 return FixError;
1023 }
1024
1025 for (const QQmlJS::DiagnosticMessage &m : diagnosticMessages) {
1026 qWarning().noquote() << QString::fromLatin1("%1:%2:%3: %4")
1027 .arg(m_logger->filePath())
1028 .arg(m.loc.startLine)
1029 .arg(m.loc.startColumn)
1030 .arg(m.message);
1031 }
1032 return FixError;
1033 }
1034
1035 *fixedCode = code;
1036 return FixSuccess;
1037}
1038
1039QT_END_NAMESPACE
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
virtual QString location() const
UnreachableVisitor(QQmlJSLogger *logger)
void throwRecursionDepthError() override
bool containsFunctionDeclaration(QQmlJS::AST::Node *node)
bool visit(QQmlJS::AST::StatementList *unreachable) override
Combined button and popup list for selecting options.
static void addJsonWarning(QJsonArray &warnings, const QQmlJS::DiagnosticMessage &message, QAnyStringView id, const std::optional< QQmlJSFixSuggestion > &suggestion={})
#define QmlLintPluginInterface_iid
Definition qqmlsa.h:440