5#include <QtCore/qcompilerdetection.h>
10QT_WARNING_DISABLE_GCC(
"-Wuninitialized")
11QT_WARNING_DISABLE_GCC(
"-Wmaybe-uninitialized")
12#include <QtCore/qlist.h>
15#include <private/qqmljslogger_p.h>
16#include <private/qqmlsa_p.h>
18#include <QtQmlCompiler/qqmljsloggingutils.h>
20#include <QtCore/qglobal.h>
21#include <QtCore/qfile.h>
26using namespace Qt::StringLiterals;
29
30
31
32
33
34
37
38
39
40
41
42
43
44
48#define QMLLINT_BUILTIN_CATEGORIES
49 X(qmlAccessSingleton, "access-singleton-via-object", "AccessSingletonViaObject",
50 "Warn if a singleton is accessed via an object", Warning, NonEssential)
51 X(qmlAliasCycle, "alias-cycle", "AliasCycle", "Warn about alias cycles", Warning, NonEssential)
52 X(qmlAssignmentInCondition, "assignment-in-condition", "AssignmentInCondition",
53 "Warn about using assignment in conditions.", Warning, NonEssential)
54 X(qmlAttachedPropertyReuse, "attached-property-reuse", "AttachedPropertyReuse",
55 "Warn if attached types from parent components aren't reused. This is handled by the "
56 "QtQuick lint plugin. Use Quick.AttachedPropertyReuse instead.",
57 Disable, NonEssential)
58 X(qmlBlockScopeVarDeclaration, "block-scope-var-declaration", "BlockScopeVarDeclaration",
59 "Warn if a variable is declared with var inside a block scope", Warning, NonEssential)
60 X(qmlComma, "comma", "Comma", "Warn about using comma expressions.", Warning, NonEssential)
61 X(qmlCompiler, "compiler", "CompilerWarnings", "Warn about compiler issues", Disable,
63 X(qmlComponentChildrenCount, "component-children-count", "ComponentChildrenCount",
64 "Warn about Components that don't have exactly one child", Warning, NonEssential)
65 X(qmlConfusingExpressionStatement, "confusing-expression-statement",
66 "ConfusingExpressionStatement",
67 "Warn about expression statement that has no obvious effect.", Warning, NonEssential)
68 X(qmlConfusingMinuses, "confusing-minuses", "ConfusingMinuses",
69 "Warn about confusing minuses.", Warning, NonEssential)
70 X(qmlConfusingPluses, "confusing-pluses", "ConfusingPluses",
71 "Warn about confusing pluses.", Warning, NonEssential)
72 X(qmlContextProperties, "context-properties", "ContextProperties",
73 "Warn about using context properties.", Warning, NonEssential)
74 X(qmlDeferredPropertyId, "deferred-property-id", "DeferredPropertyId",
75 "Warn about making deferred properties immediate by giving them an id.", Disable,
77 X(qmlEnumsAreNotTypes, "enums-are-not-types", "EnumsAreNotTypes",
78 "Warn about the use of enumerations as types.", Warning, NonEssential)
79 X(qmlEqualityTypeCoercion, "equality-type-coercion", "EqualityTypeCoercion",
80 "Warn about coercions due to usages of '==' and '!='", Warning, NonEssential)
81 X(qmlDeprecated, "deprecated", "Deprecated", "Warn about deprecated properties and types",
82 Warning, NonEssential)
83 X(qmlDuplicateEnumEntries, "duplicate-enum-entries", "DuplicateEnumEntries",
84 "Warn about duplicate enum entries", Warning, NonEssential)
85 X(qmlDuplicateImport, "duplicate-import", "DuplicateImport", "Warn about duplicate imports",
86 Warning, NonEssential)
87 X(qmlDuplicateInlineComponent, "duplicate-inline-component", "DuplicateInlineComponent",
88 "Warn about duplicate inline components", Warning, NonEssential)
89 X(qmlDuplicatePropertyBinding, "duplicate-property-binding", "DuplicatePropertyBinding",
90 "Warn about duplicate property bindings", Warning, NonEssential)
91 X(qmlDuplicatedName, "duplicated-name", "DuplicatedName",
92 "Warn about duplicated property/signal names", Warning, NonEssential)
93 X(qmlEnumEntryMatchesEnum, "enum-entry-matches-enum", "EnumEntryMatchesEnum",
94 "Warn about enum entries named the same as the enum itself", Warning, NonEssential)
95 X(qmlEnumKeyCase, "enum-key-case", "EnumKeyCase", "Warn about lowercase enum keys", Warning,
97 X(qmlEval, "eval", "Eval", "Warn about uses of eval()", Warning, NonEssential)
98 X(qmlFunctionUsedBeforeDeclaration, "function-used-before-declaration",
99 "FunctionUsedBeforeDeclaration", "Warn if a function is used before declaration",
100 Disable, NonEssential)
101 X(qmlIdShadowsMember, "id-shadows-member", "IdShadowsMember",
102 "Warn about ids potentially shadowing members", Warning, NonEssential)
103 X(qmlImport, "import", "ImportFailure", "Warn about failing imports and deprecated qmltypes",
104 Warning, NonEssential)
105 X(qmlImportFileSelector, "import-file-selector", "ImportFileSelector",
106 "Warn about encountered file selectors during import", Disable, NonEssential)
107 X(qmlIncompatibleType, "incompatible-type", "IncompatibleType",
108 "Warn about incompatible types", Warning, NonEssential)
109 X(qmlInheritanceCycle, "inheritance-cycle", "InheritanceCycle",
110 "Warn about inheritance cycles", Warning, NonEssential)
111 X(qmlInlineComponentEnums, "inline-component-enums", "InlineComponentEnums",
112 "Warn about enum declarations inside inline components", Warning, NonEssential)
113 X(qmlInvalidLintDirective, "invalid-lint-directive", "InvalidLintDirective",
114 "Warn if an invalid qmllint comment is found", Warning, NonEssential)
115 X(qmlLiteralConstructor, "literal-constructor", "LiteralConstructor",
116 "Warn about using literal constructors, like Boolean or String for example.", Warning,
118 X(qmlMaxWarningsExceeded, "max-warnings-exceeded", "MaxWarningsExceeded",
119 "Warn when exceeding the allowed maximum number of warnings.", Error, Essential)
120 X(qmlMissingEnumEntry, "missing-enum-entry", "MissingEnumEntry",
121 "Warn about using missing enum values.", Warning, NonEssential)
122 X(qmlMissingProperty, "missing-property", "MissingProperty", "Warn about missing properties",
123 Warning, NonEssential)
124 X(qmlMissingType, "missing-type", "MissingType", "Warn about missing types", Warning,
126 X(qmlMultilineStrings, "multiline-strings", "MultilineStrings",
127 "Warn about multiline strings", Info, NonEssential)
128 X(qmlNonListProperty, "non-list-property", "NonListProperty",
129 "Warn about non-list properties", Warning, NonEssential)
130 X(qmlNonRootEnums, "non-root-enum", "NonRootEnum",
131 "Warn about enums defined outside the root component", Warning, NonEssential)
132 X(qmlPropertyOverride, "property-override", "PropertyOverride",
133 "Warn about wrongly overriding properties from a base class", Warning, NonEssential)
134 X(qmlUnterminatedCase, "unterminated-case", "UnterminatedCase", "Warn about non-empty case "
135 "blocks that are not terminated by control flow or by a fallthrough comment", Warning,
137 X(qmlPreferNonVarProperties, "prefer-non-var-properties", "PreferNonVarProperties",
138 "Warn about var properties that could use a more specific type", Warning, NonEssential)
139 X(qmlPrefixedImportType, "prefixed-import-type", "PrefixedImportType",
140 "Warn about prefixed import types", Warning, NonEssential)
141 X(qmlReadOnlyProperty, "read-only-property", "ReadOnlyProperty",
142 "Warn about writing to read-only properties", Warning, NonEssential)
143 X(qmlRecursionDepthErrors, "recursion-depth-errors", "", "", Warning, NonEssential)
144 X(qmlRedundantOptionalChaining, "redundant-optional-chaining", "RedundantOptionalChaining",
145 "Warn about optional chaining on non-voidable and non-nullable base", Warning, NonEssential)
146 X(qmlRenamedType, "renamed-type", "RenamedType",
147 "Warn when renamed types refer to themselves using their unrenamed name", Warning,
149 X(qmlRequired, "required", "RequiredProperty", "Warn about required properties", Warning,
151 X(qmlShadowableMember, "shadowable-member", "ShadowableMember",
152 "Warn about members that the compiler has to treat as var because a derived type might "
153 "shadow them. Reported under the compiler category unless set explicitly.",
154 Disable, NonEssential)
155 X(qmlShadow, "shadow", "Shadow", "Warn about shadowing attributes from a base class", Disable,
157 X(qmlSignalHandlerNameClash, "signal-handler-name-clash", "SignalHandlerNameClash",
158 "Warn about property names that clash with signal handler names", Warning, NonEssential)
159 X(qmlSignalParameters, "signal-handler-parameters", "BadSignalHandlerParameters",
160 "Warn about bad signal handler parameters", Warning, NonEssential)
161 X(qmlStalePropertyRead, "stale-property-read", "StalePropertyRead",
162 "Warn about bindings reading non-constant and non-notifiable properties", Warning,
164 X(qmlSyntax, "syntax", "Syntax", "Syntax errors", Warning, Essential)
165 X(qmlSyntaxDuplicateIds, "syntax.duplicate-ids", "", "ID duplication", Error, NonEssential)
166 X(qmlSyntaxIdQuotation, "syntax.id-quotation", "", "ID quotation", Warning, NonEssential)
167 X(qmlTypeInstantiatedRecursively, "type-instantiated-recursively",
168 "TypeInstantiatedRecursively", "Warn when types are instantiated recursively", Warning,
170 X(qmlTopLevelComponent, "top-level-component", "TopLevelComponent",
171 "Warn if a top level Component is encountered", Warning, NonEssential)
172 X(qmlUncreatableType, "uncreatable-type", "UncreatableType",
173 "Warn if uncreatable types are created", Warning, NonEssential)
174 X(qmlUnintentionalEmptyBlock, "unintentional-empty-block", "UnintentionalEmptyBlock",
175 "Warn about bindings that contain only an empty block", Warning, NonEssential)
176 X(qmlUnqualified, "unqualified", "UnqualifiedAccess",
177 "Warn about unqualified identifiers and how to fix them", Warning, NonEssential)
178 X(qmlUnreachableCode, "unreachable-code", "UnreachableCode", "Warn about unreachable code.",
179 Warning, NonEssential)
180 X(qmlUnresolvedAlias, "unresolved-alias", "UnresolvedAlias", "Warn about unresolved aliases",
181 Warning, NonEssential)
182 X(qmlUnresolvedType, "unresolved-type", "UnresolvedType", "Warn about unresolved types",
183 Warning, NonEssential)
184 X(qmlUnusedImports, "unused-imports", "UnusedImports", "Warn about unused imports", Info,
186 X(qmlUseProperFunction, "use-proper-function", "UseProperFunction",
187 "Warn if var is used for storing functions", Disable, NonEssential)
188 X(qmlVarUsedBeforeDeclaration, "var-used-before-declaration", "VarUsedBeforeDeclaration",
189 "Warn if a variable is used before declaration", Warning, NonEssential)
190 X(qmlVoid, "void", "Void", "Warn about void expressions.", Disable, NonEssential)
191 X(qmlWith, "with", "WithStatement",
192 "Warn about with statements as they can cause NonEssential "
193 "positives when checking for unqualified access", Warning, NonEssential)
197#define X(category, name, setting, description, severity, essential)
198 const QQmlSA::LoggerWarningId category{ name };
203#define X(category, name, setting, description, severity, essential) ++i;
207constexpr bool isUnique(
const std::array<std::string_view, numCategories>& fields) {
208 for (std::size_t i = 0; i < fields.size(); ++i) {
209 for (std::size_t j = i + 1; j < fields.size(); ++j) {
210 if (!fields[i].empty() && fields[i] == fields[j]) {
218#define X(category, name, setting, description, severity, essential) std::string_view(name),
222#define X(category, name, setting, description, severity, essential) std::string_view(setting),
226#define X(category, name, setting, description, severity, essential) std::string_view(description),
231QQmlJSLogger::QQmlJSLogger()
233 static const QList<QQmlJS::LoggerCategory> cats = builtinCategories();
235 for (
const QQmlJS::LoggerCategory &category : cats)
236 registerCategory(category);
239 m_output.insertMapping(QtCriticalMsg, QColorOutput::RedForeground);
240 m_output.insertMapping(QtWarningMsg, QColorOutput::PurpleForeground);
241 m_output.insertMapping(QtInfoMsg, QColorOutput::BlueForeground);
242 m_output.insertMapping(QtDebugMsg, QColorOutput::GreenForeground);
245const QList<QQmlJS::LoggerCategory> &QQmlJSLogger::builtinCategories()
247 static const QList<QQmlJS::LoggerCategory> cats = {
248#define X(category, name, setting, description, severity, essential)
249 QQmlJS::LoggerCategory{ name##_L1, setting##_L1, description##_L1, QQmlJS::WarningSeverity::severity, QQmlJS::LoggerCategory::essential },
257bool QQmlJSFixSuggestion::operator==(
const QQmlJSFixSuggestion &other)
const
259 return m_location == other.m_location && m_description == other.m_description
260 && m_documentEdits == other.m_documentEdits && m_filename == other.m_filename
261 && m_autoApplicable == other.m_autoApplicable;
264bool QQmlJSFixSuggestion::operator!=(
const QQmlJSFixSuggestion &other)
const
266 return !(*
this == other);
269QList<QQmlJS::LoggerCategory> QQmlJSLogger::categories()
const
271 return m_categories.values();
274void QQmlJSLogger::registerCategory(
const QQmlJS::LoggerCategory &category)
276 if (m_categories.contains(category.name())) {
277 qWarning() <<
"Trying to re-register existing logger category" << category.name();
281 m_categorySeverities[category.name()] = category.severity();
282 m_categories.insert(category.name(), category);
287 static QHash<QtMsgType,
int> level = { { QtDebugMsg, 0 },
290 { QtCriticalMsg, 3 },
292 return level[a] < level[b];
295void QQmlJSLogger::log(Message &&diagMsg,
bool showContext,
bool showFileName)
297 Q_ASSERT(m_categorySeverities.contains(diagMsg.id.toString()));
299 if (categorySeverity(diagMsg.id) == QQmlJS::WarningSeverity::Disable || isDisabled())
304 if (diagMsg.loc.isValid()
305 && m_ignoredWarnings[diagMsg.lineForDisabling()].contains(diagMsg.id.toString())) {
310 if (!m_filePath.isEmpty() && showFileName)
311 prefix = m_filePath + QStringLiteral(
":");
313 if (diagMsg.loc.isValid())
314 prefix += QStringLiteral(
"%1:%2: ").arg(diagMsg.loc.startLine).arg(diagMsg.loc.startColumn);
315 else if (!prefix.isEmpty())
316 prefix += QStringLiteral(
": ");
320 diagMsg.type = std::clamp(diagMsg.msgType(), QtInfoMsg, QtCriticalMsg, isMsgTypeLess);
324 const QString categoryName = diagMsg.id.toString();
325 const QString categoryLink = m_output.linkify(
326 "https://doc.qt.io/qt-6/qmllint-warnings-and-errors-%1.html"_L1.arg(categoryName),
327 "[%1]"_L1.arg(categoryName));
328 m_output.writePrefixedMessage(u"%1%2 %3"_s.arg(prefix, diagMsg.message, categoryLink),
331 if (diagMsg.loc.length > 0 && !m_code.isEmpty() && showContext)
332 printContext(diagMsg.loc);
334 if (diagMsg.fixSuggestion.has_value())
335 printFix(diagMsg.fixSuggestion.value());
337 if (m_inTransaction) {
338 m_pendingMessages.push_back(std::move(diagMsg));
340 countMessage(diagMsg);
341 m_currentFunctionMessages.push_back(std::move(diagMsg));
344 if (!m_inTransaction && !m_manualFlush)
345 m_output.flushBuffer();
348void QQmlJSLogger::countMessage(
const Message &message)
350 switch (message.msgType()) {
362void QQmlJSLogger::processMessages(QSpan<
const QQmlJS::DiagnosticMessage> messages,
363 QQmlJS::LoggerWarningId id,
364 const QQmlJS::SourceLocation &sourceLocation)
366 if (messages.isEmpty() || categorySeverity(id) == QQmlJS::WarningSeverity::Disable || isDisabled())
369 m_output.write(QStringLiteral(
"---\n"));
373 for (
const QQmlJS::DiagnosticMessage &message : messages)
374 log(message.message, id, sourceLocation,
false,
false);
376 m_output.write(QStringLiteral(
"---\n\n"));
379void QQmlJSLogger::finalizeFunction()
381 Q_ASSERT(!m_inTransaction);
382 m_archivedMessages.append(std::exchange(m_currentFunctionMessages, {}));
383 m_hasCompileError =
false;
387
388
389
390
391
392
393
394
395
396
397void QQmlJSLogger::startTransaction()
399 Q_ASSERT(!m_inTransaction);
400 m_transactionOutputMark = m_output.bufferSize();
401 m_inTransaction =
true;
405
406
407
408
409void QQmlJSLogger::commit()
411 Q_ASSERT(m_inTransaction);
412 for (
const Message &message : std::as_const(m_pendingMessages))
413 countMessage(message);
415 m_currentFunctionMessages.append(std::exchange(m_pendingMessages, {}));
416 m_hasCompileError = m_hasCompileError || std::exchange(m_hasPendingCompileError,
false);
418 m_output.flushBuffer();
419 m_inTransaction =
false;
423
424
425
426
427void QQmlJSLogger::rollback()
429 Q_ASSERT(m_inTransaction);
430 m_pendingMessages.clear();
431 m_hasPendingCompileError =
false;
432 m_output.truncateBuffer(m_transactionOutputMark);
433 m_inTransaction =
false;
436void QQmlJSLogger::printContext(
const QQmlJS::SourceLocation &location)
438 QString code = m_code;
440 IssueLocationWithContext issueLocationWithContext { code, location };
441 if (
const QStringView beforeText = issueLocationWithContext.beforeText(); !beforeText.isEmpty())
442 m_output.write(beforeText);
444 bool locationMultiline = issueLocationWithContext.issueText().contains(QLatin1Char(
'\n'));
446 if (!issueLocationWithContext.issueText().isEmpty())
447 m_output.write(issueLocationWithContext.issueText().toString(), QtCriticalMsg);
448 m_output.write(issueLocationWithContext.afterText().toString() + QLatin1Char(
'\n'));
451 if (locationMultiline)
454 int tabCount = issueLocationWithContext.beforeText().count(QLatin1Char(
'\t'));
455 int locationLength = location.length == 0 ? 1 : location.length;
456 m_output.write(QString::fromLatin1(
" ").repeated(issueLocationWithContext.beforeText().size()
458 + QString::fromLatin1(
"\t").repeated(tabCount)
459 + QString::fromLatin1(
"^").repeated(locationLength) + QLatin1Char(
'\n'));
462void QQmlJSLogger::printFix(
const QQmlJSFixSuggestion &fixItem)
464 const QString currentFileAbsPath = m_filePath;
465 QString code = m_code;
467 m_output.writePrefixedMessage(fixItem.description(), QtInfoMsg);
469 if (!fixItem.location().isValid())
472 const QString filename = fixItem.filename();
473 if (filename == currentFile) {
475 }
else if (filename.isEmpty() || filename == currentFileAbsPath) {
478 QFile file(filename);
479 const bool success = file.open(QFile::ReadOnly);
481 code = QString::fromUtf8(file.readAll());
482 currentFile = filename;
485 const auto &documentEdits = fixItem.documentEdits();
486 if (!documentEdits.empty()) {
487 m_output.write(documentEdits.size() == 1 ?
"Suggested change:\n"_L1
488 :
"Suggested changes:\n"_L1);
489 for (
const auto &documentEdit: documentEdits) {
490 if (!documentEdit.m_location.isValid())
493 IssueLocationWithContext issueLocationWithContext { code, documentEdit.m_location };
495 if (
const QStringView beforeText = issueLocationWithContext.beforeText();
496 !beforeText.isEmpty()) {
497 m_output.write(beforeText);
501 const QString replacement = documentEdit.m_replacement;
502 QStringView replacementString = replacement.isEmpty()
503 ? issueLocationWithContext.issueText()
507 Q_ASSERT(!replacement.isEmpty() || !fixItem.isAutoApplicable());
509 if (!replacementString.isEmpty())
510 m_output.write(replacementString, QtDebugMsg);
511 m_output.write(issueLocationWithContext.afterText().toString() + u'\n');
513 int tabCount = issueLocationWithContext.beforeText().count(u'\t');
516 if (!replacementString.contains(u'\n')) {
517 m_output.write(u" "_s.repeated(
518 issueLocationWithContext.beforeText().size() - tabCount)
519 + u"\t"_s.repeated(tabCount)
520 + u"^"_s.repeated(replacement.size()) + u'\n');
526QQmlJSFixSuggestion::QQmlJSFixSuggestion(
const QString &description,
527 const QQmlJS::SourceLocation &location,
528 const QQmlJSDocumentEdit &documentEdit)
529 : QQmlJSFixSuggestion(description, location, QList{ documentEdit })
533QQmlJSFixSuggestion::QQmlJSFixSuggestion(
const QString &description,
534 const QQmlJS::SourceLocation &location,
535 const QList<QQmlJSDocumentEdit> &documentEdits)
536 : m_description{ description }, m_location{ location }, m_documentEdits(documentEdits)
540void QQmlJSFixSuggestion::addDocumentEdit(
const QQmlJSDocumentEdit &documentEdit)
542 m_documentEdits.append(documentEdit);
545void QQmlJSFixSuggestion::setDocumentEdits(
const QList<QQmlJSDocumentEdit> &documentEdits)
547 m_documentEdits = documentEdits;
constexpr bool isUnique(const std::array< std::string_view, numCategories > &fields)
constexpr size_t numCategories
#define QMLLINT_BUILTIN_CATEGORIES
static bool isMsgTypeLess(QtMsgType a, QtMsgType b)