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
4#include "qqmljsliteralbindingcheck_p.h"
5
6#include <private/qqmljsimportvisitor_p.h>
7#include <private/qqmljstyperesolver_p.h>
8#include <private/qqmljsmetatypes_p.h>
9
10QT_BEGIN_NAMESPACE
11
12using namespace Qt::StringLiterals;
13
14// This makes no sense, but we want to warn about things QQmlPropertyResolver complains about.
15static bool canConvertForLiteralBinding(
16 QQmlJSTypeResolver *resolver, const QQmlJSScope::ConstPtr &from,
17 const QQmlJSScope::ConstPtr &to) {
18 if (resolver->equals(a: from, b: to))
19 return true;
20
21 if (!resolver->canConvertFromTo(from, to))
22 return false;
23
24 const bool fromIsString = resolver->equals(a: from, b: resolver->stringType());
25
26 if (resolver->equals(a: to, b: resolver->stringType())
27 || resolver->equals(a: to, b: resolver->stringListType())
28 || resolver->equals(a: to, b: resolver->byteArrayType())
29 || resolver->equals(a: to, b: resolver->urlType())) {
30 return fromIsString;
31 }
32
33 if (resolver->isNumeric(type: to))
34 return resolver->isNumeric(type: from);
35
36 if (resolver->equals(a: to, b: resolver->boolType()))
37 return resolver->equals(a: from, b: resolver->boolType());
38
39 return true;
40}
41
42void QQmlJSLiteralBindingCheck::run(QQmlJSImportVisitor *visitor, QQmlJSTypeResolver *resolver)
43{
44 QQmlJSLogger *logger = visitor->logger();
45 const auto literalScopes = visitor->literalScopesToCheck();
46 for (const auto &scope : literalScopes) {
47 const auto bindings = scope->ownPropertyBindings();
48 for (const auto &binding : bindings) {
49 if (!binding.hasLiteral())
50 continue;
51
52 const QString propertyName = binding.propertyName();
53 const QQmlJSMetaProperty property = scope->property(name: propertyName);
54 if (!property.isValid())
55 continue;
56
57 // If the property is defined in the same scope where it is set,
58 // we are in fact allowed to set it, even if it's not writable.
59 if (!property.isWritable() && !scope->hasOwnProperty(name: propertyName)) {
60 logger->log(message: u"Cannot assign to read-only property %1"_s.arg(a: propertyName),
61 id: qmlReadOnlyProperty, srcLocation: binding.sourceLocation());
62 continue;
63 }
64
65 if (!canConvertForLiteralBinding(
66 resolver, from: binding.literalType(resolver), to: property.type())) {
67 logger->log(message: u"Cannot assign literal of type %1 to %2"_s.arg(
68 args: QQmlJSScope::prettyName(name: binding.literalTypeName()),
69 args: QQmlJSScope::prettyName(name: property.typeName())),
70 id: qmlIncompatibleType, srcLocation: binding.sourceLocation());
71 continue;
72 }
73 }
74 }
75}
76
77QT_END_NAMESPACE
78

source code of qtdeclarative/src/qmlcompiler/qqmljsliteralbindingcheck.cpp