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
qqmljslogger.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 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
5#include <QtCore/qcompilerdetection.h>
6// GCC 11 thinks diagMsg.fixSuggestion.fixes.d.ptr is somehow uninitialized in
7// QList::emplaceBack(), probably called from QQmlJsLogger::log()
8// Ditto for GCC 12, but it emits a different warning
9QT_WARNING_PUSH
10QT_WARNING_DISABLE_GCC("-Wuninitialized")
11QT_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
12#include <QtCore/qlist.h>
13QT_WARNING_POP
14
15#include <private/qqmljslogger_p.h>
16#include <private/qqmlsa_p.h>
17
18#include <QtQmlCompiler/qqmljsloggingutils.h>
19
20#include <QtCore/qglobal.h>
21#include <QtCore/qfile.h>
22
23
24QT_BEGIN_NAMESPACE
25
26using namespace Qt::StringLiterals;
27
28/*
29Note: users are in full control of the severity level of a category. It is not possible to
30have a single category and use it as a warning in one context, and as an info message in
31another context.
32For that use case, create two distinct categories instead, and give them appropriate default
33warning levels.
34 */
35
36/* The X macro provides (in order):
37 category, name, setting, description, severity, essentiality
38 - category is the C++ variable name of the category
39 - name is the user visible category name, i.e. what what qmllint put in bewteen "[" and "]"
40 - setting name is the name that is used in the qmllint.ini file to configure the category
41 - description is a _short_ description of the category's use
42 - severity is the default warning level of the category (can be overriden by the user though)
43 - essentiality marks essential categories that are required for the proper function of qmllint and can't be disabled by the user
44 */
45
46// clang-format off
47// don't forget to forward-declare your logging category ID in qqmljsloggingutils.h!
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,
62 NonEssential)
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,
76 NonEssential)
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,
96 NonEssential)
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,
117 NonEssential)
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,
125 NonEssential)
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,
136 NonEssential)
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,
148 NonEssential)
149 X(qmlRequired, "required", "RequiredProperty", "Warn about required properties", Warning,
150 NonEssential)
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,
156 NonEssential)
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,
163 NonEssential)
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,
169 NonEssential)
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,
185 NonEssential)
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)
194
195// clang-format on
196
197#define X(category, name, setting, description, severity, essential)
198 const QQmlSA::LoggerWarningId category{ name };
200#undef X
201
202
203#define X(category, name, setting, description, severity, essential) ++i;
204constexpr size_t numCategories = [] { size_t i = 0; QMLLINT_BUILTIN_CATEGORIES return i; }();
205#undef X
206
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]) {
211 return false;
212 }
213 }
214 }
215 return true;
216}
217
218#define X(category, name, setting, description, severity, essential) std::string_view(name),
219static_assert(isUnique(std::array{ QMLLINT_BUILTIN_CATEGORIES }), "Duplicate names found!");
220#undef X
221
222#define X(category, name, setting, description, severity, essential) std::string_view(setting),
223static_assert(isUnique(std::array{ QMLLINT_BUILTIN_CATEGORIES }), "Duplicate settings found!");
224#undef X
225
226#define X(category, name, setting, description, severity, essential) std::string_view(description),
227static_assert(isUnique(std::array{ QMLLINT_BUILTIN_CATEGORIES }), "Duplicate description found!");
228#undef X
229
230
231QQmlJSLogger::QQmlJSLogger()
232{
233 static const QList<QQmlJS::LoggerCategory> cats = builtinCategories();
234
235 for (const QQmlJS::LoggerCategory &category : cats)
236 registerCategory(category);
237
238 // setup color output
239 m_output.insertMapping(QtCriticalMsg, QColorOutput::RedForeground);
240 m_output.insertMapping(QtWarningMsg, QColorOutput::PurpleForeground); // Yellow?
241 m_output.insertMapping(QtInfoMsg, QColorOutput::BlueForeground);
242 m_output.insertMapping(QtDebugMsg, QColorOutput::GreenForeground); // None?
243}
244
245const QList<QQmlJS::LoggerCategory> &QQmlJSLogger::builtinCategories()
246{
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 },
251#undef X
252 };
253
254 return cats;
255}
256
257bool QQmlJSFixSuggestion::operator==(const QQmlJSFixSuggestion &other) const
258{
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;
262}
263
264bool QQmlJSFixSuggestion::operator!=(const QQmlJSFixSuggestion &other) const
265{
266 return !(*this == other);
267}
268
269QList<QQmlJS::LoggerCategory> QQmlJSLogger::categories() const
270{
271 return m_categories.values();
272}
273
274void QQmlJSLogger::registerCategory(const QQmlJS::LoggerCategory &category)
275{
276 if (m_categories.contains(category.name())) {
277 qWarning() << "Trying to re-register existing logger category" << category.name();
278 return;
279 }
280
281 m_categorySeverities[category.name()] = category.severity();
282 m_categories.insert(category.name(), category);
283}
284
285static bool isMsgTypeLess(QtMsgType a, QtMsgType b)
286{
287 static QHash<QtMsgType, int> level = { { QtDebugMsg, 0 },
288 { QtInfoMsg, 1 },
289 { QtWarningMsg, 2 },
290 { QtCriticalMsg, 3 },
291 { QtFatalMsg, 4 } };
292 return level[a] < level[b];
293}
294
295void QQmlJSLogger::log(Message &&diagMsg, bool showContext, bool showFileName)
296{
297 Q_ASSERT(m_categorySeverities.contains(diagMsg.id.toString()));
298
299 if (categorySeverity(diagMsg.id) == QQmlJS::WarningSeverity::Disable || isDisabled())
300 return;
301
302 // Note: assume \a type is the type we should prefer for logging
303
304 if (diagMsg.loc.isValid()
305 && m_ignoredWarnings[diagMsg.lineForDisabling()].contains(diagMsg.id.toString())) {
306 return;
307 }
308
309 QString prefix;
310 if (!m_filePath.isEmpty() && showFileName)
311 prefix = m_filePath + QStringLiteral(":");
312
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(": "); // produce double colon for Qt Creator's issues pane
317
318 // Note: we do the clamping to [Info, Critical] range since our logger only
319 // supports 3 categories
320 diagMsg.type = std::clamp(diagMsg.msgType(), QtInfoMsg, QtCriticalMsg, isMsgTypeLess);
321
322 // Note: since we clamped our \a type, the output message is not printed
323 // exactly like it was requested, bear with us
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),
329 diagMsg.msgType());
330
331 if (diagMsg.loc.length > 0 && !m_code.isEmpty() && showContext)
332 printContext(diagMsg.loc);
333
334 if (diagMsg.fixSuggestion.has_value())
335 printFix(diagMsg.fixSuggestion.value());
336
337 if (m_inTransaction) {
338 m_pendingMessages.push_back(std::move(diagMsg));
339 } else {
340 countMessage(diagMsg);
341 m_currentFunctionMessages.push_back(std::move(diagMsg));
342 }
343
344 if (!m_inTransaction && !m_manualFlush)
345 m_output.flushBuffer();
346}
347
348void QQmlJSLogger::countMessage(const Message &message)
349{
350 switch (message.msgType()) {
351 case QtWarningMsg:
352 ++m_numWarnings;
353 break;
354 case QtCriticalMsg:
355 ++m_numErrors;
356 break;
357 default:
358 break;
359 }
360}
361
362void QQmlJSLogger::processMessages(QSpan<const QQmlJS::DiagnosticMessage> messages,
363 QQmlJS::LoggerWarningId id,
364 const QQmlJS::SourceLocation &sourceLocation)
365{
366 if (messages.isEmpty() || categorySeverity(id) == QQmlJS::WarningSeverity::Disable || isDisabled())
367 return;
368
369 m_output.write(QStringLiteral("---\n"));
370
371 // TODO: we should instead respect message's category here (potentially, it
372 // should hold a category instead of type)
373 for (const QQmlJS::DiagnosticMessage &message : messages)
374 log(message.message, id, sourceLocation, false, false);
375
376 m_output.write(QStringLiteral("---\n\n"));
377}
378
379void QQmlJSLogger::finalizeFunction()
380{
381 Q_ASSERT(!m_inTransaction);
382 m_archivedMessages.append(std::exchange(m_currentFunctionMessages, {}));
383 m_hasCompileError = false;
384}
385
386/*!
387 \internal
388 Starts a transaction for a compile pass. This buffers all messages until the
389 transaction completes. If you commit the transaction, the messages are printed
390 and added to the list of committed messages. If you roll it back, the logger
391 reverts to the state before the start of the transaction.
392
393 This is useful for compile passes that potentially have to be repeated, such
394 as the type propagator. We don't want to see the same messages logged multiple
395 times.
396 */
397void QQmlJSLogger::startTransaction()
398{
399 Q_ASSERT(!m_inTransaction);
400 m_transactionOutputMark = m_output.bufferSize();
401 m_inTransaction = true;
402}
403
404/*!
405 \internal
406 Commit the current transaction. Print all pending messages, and add them to
407 the list of committed messages. Then, clear the transaction flag.
408 */
409void QQmlJSLogger::commit()
410{
411 Q_ASSERT(m_inTransaction);
412 for (const Message &message : std::as_const(m_pendingMessages))
413 countMessage(message);
414
415 m_currentFunctionMessages.append(std::exchange(m_pendingMessages, {}));
416 m_hasCompileError = m_hasCompileError || std::exchange(m_hasPendingCompileError, false);
417 if (!m_manualFlush)
418 m_output.flushBuffer();
419 m_inTransaction = false;
420}
421
422/*!
423 \internal
424 Roll back the current transaction and revert the logger to the state before
425 it was started.
426 */
427void QQmlJSLogger::rollback()
428{
429 Q_ASSERT(m_inTransaction);
430 m_pendingMessages.clear();
431 m_hasPendingCompileError = false;
432 m_output.truncateBuffer(m_transactionOutputMark);
433 m_inTransaction = false;
434}
435
436void QQmlJSLogger::printContext(const QQmlJS::SourceLocation &location)
437{
438 QString code = m_code;
439
440 IssueLocationWithContext issueLocationWithContext { code, location };
441 if (const QStringView beforeText = issueLocationWithContext.beforeText(); !beforeText.isEmpty())
442 m_output.write(beforeText);
443
444 bool locationMultiline = issueLocationWithContext.issueText().contains(QLatin1Char('\n'));
445
446 if (!issueLocationWithContext.issueText().isEmpty())
447 m_output.write(issueLocationWithContext.issueText().toString(), QtCriticalMsg);
448 m_output.write(issueLocationWithContext.afterText().toString() + QLatin1Char('\n'));
449
450 // Do not draw location indicator for multiline locations
451 if (locationMultiline)
452 return;
453
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()
457 - tabCount)
458 + QString::fromLatin1("\t").repeated(tabCount)
459 + QString::fromLatin1("^").repeated(locationLength) + QLatin1Char('\n'));
460}
461
462void QQmlJSLogger::printFix(const QQmlJSFixSuggestion &fixItem)
463{
464 const QString currentFileAbsPath = m_filePath;
465 QString code = m_code;
466 QString currentFile;
467 m_output.writePrefixedMessage(fixItem.description(), QtInfoMsg);
468
469 if (!fixItem.location().isValid())
470 return;
471
472 const QString filename = fixItem.filename();
473 if (filename == currentFile) {
474 // Nothing to do in this case, we've already read the code
475 } else if (filename.isEmpty() || filename == currentFileAbsPath) {
476 code = m_code;
477 } else {
478 QFile file(filename);
479 const bool success = file.open(QFile::ReadOnly);
480 Q_ASSERT(success);
481 code = QString::fromUtf8(file.readAll());
482 currentFile = filename;
483 }
484
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())
491 continue;
492
493 IssueLocationWithContext issueLocationWithContext { code, documentEdit.m_location };
494
495 if (const QStringView beforeText = issueLocationWithContext.beforeText();
496 !beforeText.isEmpty()) {
497 m_output.write(beforeText);
498 }
499
500 // The replacement string can be empty if we're only pointing something out to the user
501 const QString replacement = documentEdit.m_replacement;
502 QStringView replacementString = replacement.isEmpty()
503 ? issueLocationWithContext.issueText()
504 : replacement;
505
506 // But if there's nothing to change it cannot be auto-applied
507 Q_ASSERT(!replacement.isEmpty() || !fixItem.isAutoApplicable());
508
509 if (!replacementString.isEmpty())
510 m_output.write(replacementString, QtDebugMsg);
511 m_output.write(issueLocationWithContext.afterText().toString() + u'\n');
512
513 int tabCount = issueLocationWithContext.beforeText().count(u'\t');
514
515 // Do not draw location indicator for multiline replacement strings
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');
521 }
522 }
523 }
524}
525
526QQmlJSFixSuggestion::QQmlJSFixSuggestion(const QString &description,
527 const QQmlJS::SourceLocation &location,
528 const QQmlJSDocumentEdit &documentEdit)
529 : QQmlJSFixSuggestion(description, location, QList{ documentEdit })
530{
531}
532
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)
537{
538}
539
540void QQmlJSFixSuggestion::addDocumentEdit(const QQmlJSDocumentEdit &documentEdit)
541{
542 m_documentEdits.append(documentEdit);
543}
544
545void QQmlJSFixSuggestion::setDocumentEdits(const QList<QQmlJSDocumentEdit> &documentEdits)
546{
547 m_documentEdits = documentEdits;
548}
549
550QT_END_NAMESPACE
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)