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
qqmljsfunctioninitializer.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
7#include <private/qqmljsmemorypool_p.h>
8
9#include <QtCore/qloggingcategory.h>
10#include <QtCore/qfileinfo.h>
11
12#include <QtQml/private/qqmlsignalnames_p.h>
13
15
16using namespace Qt::StringLiterals;
17
18/*!
19 * \internal
20 * \class QQmlJSFunctionInitializer
21 *
22 * QQmlJSFunctionInitializer analyzes the IR to produce an initial
23 * QQmlJSCompilePass::Function for further analysis. It only looks for the
24 * signature and the QML scope and doesn't visit the byte code.
25 */
26
27static QString bindingTypeDescription(QmlIR::Binding::Type type)
28{
29 switch (type) {
30 case QmlIR::Binding::Type_Invalid:
31 return u"invalid"_s;
32 case QmlIR::Binding::Type_Boolean:
33 return u"a boolean"_s;
34 case QmlIR::Binding::Type_Number:
35 return u"a number"_s;
36 case QmlIR::Binding::Type_String:
37 return u"a string"_s;
38 case QmlIR::Binding::Type_Null:
39 return u"null"_s;
40 case QmlIR::Binding::Type_Translation:
41 return u"a translation"_s;
42 case QmlIR::Binding::Type_TranslationById:
43 return u"a translation by id"_s;
44 case QmlIR::Binding::Type_Script:
45 return u"a script"_s;
46 case QmlIR::Binding::Type_Object:
47 return u"an object"_s;
48 case QmlIR::Binding::Type_AttachedProperty:
49 return u"an attached property"_s;
50 case QmlIR::Binding::Type_GroupProperty:
51 return u"a grouped property"_s;
52 }
53
54 return u"nothing"_s;
55}
56
57void QQmlJSFunctionInitializer::populateSignature(
58 const QV4::Compiler::Context *context, QQmlJS::AST::FunctionExpression *ast,
59 QQmlJSCompilePass::Function *function)
60{
61 const auto signatureError = [&](const QString &message) {
62 m_logger->logCompileError(message, ast->firstSourceLocation());
63 function->isFullyTyped = false;
64 };
65
66 QQmlJS::AST::BoundNames arguments;
67 if (ast->formals)
68 arguments = ast->formals->formals();
69
70 // If the function has no arguments and no return type annotation we assume it's untyped.
71 // You can annotate it to return void to make it typed.
72 // Otherwise we first assume it's typed and reset the flag if we detect a problem.
73 function->isFullyTyped = m_typeResolver->canCallJSFunctions()
74 && (!arguments.isEmpty() || ast->typeAnnotation);
75
76 if (function->argumentTypes.isEmpty()) {
77 bool alreadyWarnedAboutMissingAnnotations = false;
78 for (const QQmlJS::AST::BoundName &argument : std::as_const(arguments)) {
79 if (argument.typeAnnotation) {
80 if (const auto type = m_typeResolver->typeFromAST(argument.typeAnnotation->type)) {
81 function->argumentTypes.append(m_typeResolver->namedType(type));
82 } else {
83 function->argumentTypes.append(
84 m_typeResolver->namedType(m_typeResolver->varType()));
85 signatureError(u"Cannot resolve the argument type %1."_s
86 .arg(argument.typeAnnotation->type->toString()));
87 }
88 } else {
89 if (!alreadyWarnedAboutMissingAnnotations) {
90 alreadyWarnedAboutMissingAnnotations = true;
91 signatureError(u"Functions without type annotations won't be compiled"_s);
92 }
93 function->argumentTypes.append(
94 m_typeResolver->namedType(m_typeResolver->varType()));
95 }
96 }
97 } else {
98 for (qsizetype i = 0, end = arguments.size(); i != end; ++i) {
99 const QQmlJS::AST::BoundName &argument = arguments[i];
100 if (argument.typeAnnotation) {
101 if (const auto type = m_typeResolver->typeFromAST(argument.typeAnnotation->type)) {
102 if (!function->argumentTypes[i].contains(type)) {
103 signatureError(u"Type annotation %1 on signal handler "
104 "contradicts signal argument type %2"_s
105 .arg(argument.typeAnnotation->type->toString(),
106 function->argumentTypes[i].descriptiveName()));
107 }
108 }
109 }
110 }
111 }
112
113 if (!function->returnType.isValid()) {
114 if (ast->typeAnnotation) {
115 function->returnType = m_typeResolver->namedType(
116 m_typeResolver->typeFromAST(ast->typeAnnotation->type));
117 if (!function->returnType.isValid())
118 signatureError(u"Cannot resolve return type %1"_s.arg(
119 QmlIR::IRBuilder::asString(ast->typeAnnotation->type->typeId)));
120 }
121 }
122
123 for (int i = QQmlJSCompilePass::FirstArgument + function->argumentTypes.size();
124 i < context->registerCountInFunction; ++i) {
125 function->registerTypes.append(m_typeResolver->namedType(m_typeResolver->voidType()));
126 }
127
128 function->addressableScopes = m_typeResolver->objectsById();
129 function->code = context->code;
130 function->sourceLocations = context->sourceLocationTable.get();
131}
132
133static void diagnose(
134 const QString &message, const QQmlJS::SourceLocation &location, QQmlJSLogger *logger)
135{
136 logger->logCompileError(message, location);
137}
138
139QQmlJSCompilePass::Function QQmlJSFunctionInitializer::run(
140 const QV4::Compiler::Context *context, const QString &propertyName,
141 QQmlJS::AST::Node *astNode, const QmlIR::Binding &irBinding)
142{
143 QQmlJS::SourceLocation bindingLocation;
144 bindingLocation.startLine = irBinding.location.line();
145 bindingLocation.startColumn = irBinding.location.column();
146
147 QQmlJSCompilePass::Function function;
148 function.qmlScope = m_typeResolver->registerContentPool()->createType(
149 m_scopeType, QQmlJSRegisterContent::InvalidLookupIndex,
150 QQmlJSRegisterContent::ScopeObject);
151
152 // If we find a problem before we can determine whether it's a signal handler,
153 // that's bad and warrants a warning, even if it then turns out to be a signal handler.
154 const auto setIsSignalHandler = [&]() {
155 function.isSignalHandler = true;
156
157 // If the function is a signal handler and just returns a closure, it's harmless.
158 // Otherwise it's a warning.
159 m_logger->setCompileErrorSeverity(context->returnsClosure
160 ? QQmlJS::WarningSeverity::Info
161 : QQmlJS::WarningSeverity::Warning);
162 };
163
164 if (irBinding.type() != QmlIR::Binding::Type_Script) {
165 diagnose(u"Binding is not a script binding, but %1."_s.arg(
166 bindingTypeDescription(QmlIR::Binding::Type(quint32(irBinding.type())))),
167 bindingLocation, m_logger);
168 }
169
170 function.isProperty = m_objectType->hasProperty(propertyName);
171 if (function.isProperty) {
172 const auto property = m_objectType->property(propertyName);
173 if (const QQmlJSScope::ConstPtr propertyType = property.type()) {
174 function.returnType = m_typeResolver->namedType(propertyType->isListProperty()
175 ? m_typeResolver->qObjectListType()
176 : QQmlJSScope::ConstPtr(property.type()));
177 } else {
178 diagnose(u"Cannot resolve property type %1 for binding on %2."_s
179 .arg(property.typeName(), propertyName),
180 bindingLocation, m_logger);
181 }
182
183 if (!property.bindable().isEmpty() && !property.isPrivate())
184 function.isQPropertyBinding = true;
185 } else if (QQmlSignalNames::isHandlerName(propertyName)) {
186 if (auto actualPropertyName =
187 QQmlSignalNames::changedHandlerNameToPropertyName(propertyName);
188 actualPropertyName && m_objectType->hasProperty(*actualPropertyName)) {
189 setIsSignalHandler();
190 } else {
191 auto signalName = QQmlSignalNames::handlerNameToSignalName(propertyName);
192 const auto methods = m_objectType->methods(*signalName);
193 for (const auto &method : methods) {
194 if (method.isCloned())
195 continue;
196 if (method.methodType() == QQmlJSMetaMethodType::Signal) {
197 setIsSignalHandler();
198 const auto arguments = method.parameters();
199 for (qsizetype i = 0, end = arguments.size(); i < end; ++i) {
200 const auto &type = arguments[i].type();
201 if (type.isNull()) {
202 diagnose(u"Cannot resolve the argument type %1."_s.arg(
203 arguments[i].typeName()),
204 bindingLocation, m_logger);
205 function.argumentTypes.append(
206 m_typeResolver->namedType(m_typeResolver->varType()));
207 } else {
208 function.argumentTypes.append(m_typeResolver->namedType(type));
209 }
210 }
211 break;
212 }
213 }
214 if (!function.isSignalHandler) {
215 diagnose(u"Could not find signal \"%1\"."_s.arg(*signalName),
216 bindingLocation, m_logger);
217 }
218 }
219 } else {
220 QString message = u"Could not find property \"%1\"."_s.arg(propertyName);
221 if (m_objectType->isNameDeferred(propertyName)) {
222 // If the property doesn't exist but the name is deferred, then
223 // it's deferred via the presence of immediate names. Those are
224 // most commonly used to enable generalized grouped properties.
225 message += u" You may want use ID-based grouped properties here.";
226 }
227
228 diagnose(message, bindingLocation, m_logger);
229 }
230
231 QQmlJS::MemoryPool pool;
232 auto ast = astNode->asFunctionDefinition();
233 if (!ast) {
234 QQmlJS::AST::Statement *stmt = astNode->statementCast();
235 if (!stmt) {
236 Q_ASSERT(astNode->expressionCast());
237 QQmlJS::AST::ExpressionNode *expr = astNode->expressionCast();
238 stmt = new (&pool) QQmlJS::AST::ExpressionStatement(expr);
239 }
240 auto body = new (&pool) QQmlJS::AST::StatementList(stmt);
241 body = body->finish();
242
243 QString name = u"binding for "_s; // ####
244 ast = new (&pool) QQmlJS::AST::FunctionDeclaration(
245 pool.newString(std::move(name)), /*formals*/ nullptr, body);
246 ast->lbraceToken = astNode->firstSourceLocation();
247 ast->functionToken = ast->lbraceToken;
248 ast->rbraceToken = astNode->lastSourceLocation();
249 }
250
251 populateSignature(context, ast, &function);
252 return function;
253}
254
255QQmlJSCompilePass::Function QQmlJSFunctionInitializer::run(
256 const QV4::Compiler::Context *context, const QString &functionName,
257 QQmlJS::AST::Node *astNode)
258{
259 Q_UNUSED(functionName);
260
261 QQmlJSCompilePass::Function function;
262 function.qmlScope = m_typeResolver->registerContentPool()->createType(
263 m_scopeType, QQmlJSRegisterContent::InvalidLookupIndex,
264 QQmlJSRegisterContent::ScopeObject);
265
266 auto ast = astNode->asFunctionDefinition();
267 Q_ASSERT(ast);
268
269 populateSignature(context, ast, &function);
270 return function;
271}
272
273QT_END_NAMESPACE
Combined button and popup list for selecting options.
static QString bindingTypeDescription(QmlIR::Binding::Type type)
static void diagnose(const QString &message, const QQmlJS::SourceLocation &location, QQmlJSLogger *logger)