1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the tools applications of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39#ifndef QQMLIRBUILDER_P_H
40#define QQMLIRBUILDER_P_H
41
42//
43// W A R N I N G
44// -------------
45//
46// This file is not part of the Qt API. It exists purely as an
47// implementation detail. This header file may change from version to
48// version without notice, or even be removed.
49//
50// We mean it.
51//
52
53#include <private/qqmljsast_p.h>
54#include <private/qqmljsengine_p.h>
55#include <private/qv4compiler_p.h>
56#include <private/qv4compileddata_p.h>
57#include <private/qqmljsmemorypool_p.h>
58#include <private/qqmljsfixedpoolarray_p.h>
59#include <private/qv4codegen_p.h>
60#include <private/qv4compiler_p.h>
61#include <QTextStream>
62#include <QCoreApplication>
63
64QT_BEGIN_NAMESPACE
65
66class QQmlPropertyCache;
67class QQmlContextData;
68class QQmlTypeNameCache;
69struct QQmlIRLoader;
70
71namespace QmlIR {
72
73struct Document;
74
75template <typename T>
76struct PoolList
77{
78 PoolList()
79 : first(nullptr)
80 , last(nullptr)
81 {}
82
83 T *first;
84 T *last;
85 int count = 0;
86
87 int append(T *item) {
88 item->next = nullptr;
89 if (last)
90 last->next = item;
91 else
92 first = item;
93 last = item;
94 return count++;
95 }
96
97 void prepend(T *item) {
98 item->next = first;
99 first = item;
100 if (!last)
101 last = first;
102 ++count;
103 }
104
105 template <typename Sortable, typename Base, Sortable Base::*sortMember>
106 T *findSortedInsertionPoint(T *item) const
107 {
108 T *insertPos = nullptr;
109
110 for (T *it = first; it; it = it->next) {
111 if (!(it->*sortMember <= item->*sortMember))
112 break;
113 insertPos = it;
114 }
115
116 return insertPos;
117 }
118
119 void insertAfter(T *insertionPoint, T *item) {
120 if (!insertionPoint) {
121 prepend(item);
122 } else if (insertionPoint == last) {
123 append(item);
124 } else {
125 item->next = insertionPoint->next;
126 insertionPoint->next = item;
127 ++count;
128 }
129 }
130
131 T *unlink(T *before, T *item) {
132 T * const newNext = item->next;
133
134 if (before)
135 before->next = newNext;
136 else
137 first = newNext;
138
139 if (item == last) {
140 if (newNext)
141 last = newNext;
142 else
143 last = first;
144 }
145
146 --count;
147 return newNext;
148 }
149
150 T *slowAt(int index) const
151 {
152 T *result = first;
153 while (index > 0 && result) {
154 result = result->next;
155 --index;
156 }
157 return result;
158 }
159
160 struct Iterator {
161 T *ptr;
162
163 explicit Iterator(T *p) : ptr(p) {}
164
165 T *operator->() {
166 return ptr;
167 }
168
169 const T *operator->() const {
170 return ptr;
171 }
172
173 T &operator*() {
174 return *ptr;
175 }
176
177 const T &operator*() const {
178 return *ptr;
179 }
180
181 void operator++() {
182 ptr = ptr->next;
183 }
184
185 bool operator==(const Iterator &rhs) const {
186 return ptr == rhs.ptr;
187 }
188
189 bool operator!=(const Iterator &rhs) const {
190 return ptr != rhs.ptr;
191 }
192 };
193
194 Iterator begin() { return Iterator(first); }
195 Iterator end() { return Iterator(nullptr); }
196};
197
198struct Object;
199
200struct EnumValue : public QV4::CompiledData::EnumValue
201{
202 EnumValue *next;
203};
204
205struct Enum
206{
207 int nameIndex;
208 QV4::CompiledData::Location location;
209 PoolList<EnumValue> *enumValues;
210
211 int enumValueCount() const { return enumValues->count; }
212 PoolList<EnumValue>::Iterator enumValuesBegin() const { return enumValues->begin(); }
213 PoolList<EnumValue>::Iterator enumValuesEnd() const { return enumValues->end(); }
214
215 Enum *next;
216};
217
218
219struct Parameter : public QV4::CompiledData::Parameter
220{
221 Parameter *next;
222
223 bool init(QV4::Compiler::JSUnitGenerator *stringGenerator, const QString &parameterName, const QString &typeName);
224 static bool init(QV4::CompiledData::Parameter *param, const QV4::Compiler::JSUnitGenerator *stringGenerator,
225 int parameterNameIndex, int typeNameIndex);
226 static bool initType(QV4::CompiledData::ParameterType *paramType,
227 const QV4::Compiler::JSUnitGenerator *stringGenerator, int typeNameIndex);
228
229 static QV4::CompiledData::BuiltinType stringToBuiltinType(const QString &typeName);
230};
231
232struct Signal
233{
234 int nameIndex;
235 QV4::CompiledData::Location location;
236 PoolList<Parameter> *parameters;
237
238 QStringList parameterStringList(const QV4::Compiler::StringTableGenerator *stringPool) const;
239
240 int parameterCount() const { return parameters->count; }
241 PoolList<Parameter>::Iterator parametersBegin() const { return parameters->begin(); }
242 PoolList<Parameter>::Iterator parametersEnd() const { return parameters->end(); }
243
244 Signal *next;
245};
246
247struct Property : public QV4::CompiledData::Property
248{
249 Property *next;
250};
251
252struct Binding : public QV4::CompiledData::Binding
253{
254 // The offset in the source file where the binding appeared. This is used for sorting to ensure
255 // that assignments to list properties are done in the correct order. We use the offset here instead
256 // of Binding::location as the latter has limited precision.
257 quint32 offset;
258 // Binding's compiledScriptIndex is index in object's functionsAndExpressions
259 Binding *next;
260};
261
262struct Alias : public QV4::CompiledData::Alias
263{
264 Alias *next;
265};
266
267struct Function
268{
269 QV4::CompiledData::Location location;
270 int nameIndex;
271 quint32 index; // index in parsedQML::functions
272 QQmlJS::FixedPoolArray<Parameter> formals;
273 QV4::CompiledData::ParameterType returnType;
274
275 // --- QQmlPropertyCacheCreator interface
276 const Parameter *formalsBegin() const { return formals.begin(); }
277 const Parameter *formalsEnd() const { return formals.end(); }
278 // ---
279
280 Function *next;
281};
282
283struct Q_QMLCOMPILER_PRIVATE_EXPORT CompiledFunctionOrExpression
284{
285 CompiledFunctionOrExpression()
286 {}
287
288 QQmlJS::AST::Node *parentNode = nullptr; // FunctionDeclaration, Statement or Expression
289 QQmlJS::AST::Node *node = nullptr; // FunctionDeclaration, Statement or Expression
290 quint32 nameIndex = 0;
291 CompiledFunctionOrExpression *next = nullptr;
292};
293
294struct Q_QMLCOMPILER_PRIVATE_EXPORT Object
295{
296 Q_DECLARE_TR_FUNCTIONS(Object)
297public:
298 quint32 inheritedTypeNameIndex;
299 quint32 idNameIndex;
300 int id;
301 int indexOfDefaultPropertyOrAlias;
302 bool defaultPropertyIsAlias;
303 quint32 flags;
304
305 QV4::CompiledData::Location location;
306 QV4::CompiledData::Location locationOfIdProperty;
307
308 const Property *firstProperty() const { return properties->first; }
309 int propertyCount() const { return properties->count; }
310 Alias *firstAlias() const { return aliases->first; }
311 int aliasCount() const { return aliases->count; }
312 const Enum *firstEnum() const { return qmlEnums->first; }
313 int enumCount() const { return qmlEnums->count; }
314 const Signal *firstSignal() const { return qmlSignals->first; }
315 int signalCount() const { return qmlSignals->count; }
316 Binding *firstBinding() const { return bindings->first; }
317 int bindingCount() const { return bindings->count; }
318 const Function *firstFunction() const { return functions->first; }
319 int functionCount() const { return functions->count; }
320
321 PoolList<Binding>::Iterator bindingsBegin() const { return bindings->begin(); }
322 PoolList<Binding>::Iterator bindingsEnd() const { return bindings->end(); }
323 PoolList<Property>::Iterator propertiesBegin() const { return properties->begin(); }
324 PoolList<Property>::Iterator propertiesEnd() const { return properties->end(); }
325 PoolList<Alias>::Iterator aliasesBegin() const { return aliases->begin(); }
326 PoolList<Alias>::Iterator aliasesEnd() const { return aliases->end(); }
327 PoolList<Enum>::Iterator enumsBegin() const { return qmlEnums->begin(); }
328 PoolList<Enum>::Iterator enumsEnd() const { return qmlEnums->end(); }
329 PoolList<Signal>::Iterator signalsBegin() const { return qmlSignals->begin(); }
330 PoolList<Signal>::Iterator signalsEnd() const { return qmlSignals->end(); }
331 PoolList<Function>::Iterator functionsBegin() const { return functions->begin(); }
332 PoolList<Function>::Iterator functionsEnd() const { return functions->end(); }
333
334 // If set, then declarations for this object (and init bindings for these) should go into the
335 // specified object. Used for declarations inside group properties.
336 Object *declarationsOverride;
337
338 void init(QQmlJS::MemoryPool *pool, int typeNameIndex, int idIndex, const QQmlJS::AST::SourceLocation &location = QQmlJS::AST::SourceLocation());
339
340 QString appendEnum(Enum *enumeration);
341 QString appendSignal(Signal *signal);
342 QString appendProperty(Property *prop, const QString &propertyName, bool isDefaultProperty, const QQmlJS::AST::SourceLocation &defaultToken, QQmlJS::AST::SourceLocation *errorLocation);
343 QString appendAlias(Alias *prop, const QString &aliasName, bool isDefaultProperty, const QQmlJS::AST::SourceLocation &defaultToken, QQmlJS::AST::SourceLocation *errorLocation);
344 void appendFunction(QmlIR::Function *f);
345
346 QString appendBinding(Binding *b, bool isListBinding);
347 Binding *findBinding(quint32 nameIndex) const;
348 Binding *unlinkBinding(Binding *before, Binding *binding) { return bindings->unlink(before, binding); }
349 void insertSorted(Binding *b);
350 QString bindingAsString(Document *doc, int scriptIndex) const;
351
352 PoolList<CompiledFunctionOrExpression> *functionsAndExpressions;
353 QQmlJS::FixedPoolArray<int> runtimeFunctionIndices;
354
355 QQmlJS::FixedPoolArray<quint32> namedObjectsInComponent;
356 int namedObjectsInComponentCount() const { return namedObjectsInComponent.size(); }
357 const quint32 *namedObjectsInComponentTable() const { return namedObjectsInComponent.begin(); }
358
359private:
360 friend struct ::QQmlIRLoader;
361
362 PoolList<Property> *properties;
363 PoolList<Alias> *aliases;
364 PoolList<Enum> *qmlEnums;
365 PoolList<Signal> *qmlSignals;
366 PoolList<Binding> *bindings;
367 PoolList<Function> *functions;
368};
369
370struct Q_QMLCOMPILER_PRIVATE_EXPORT Pragma
371{
372 enum PragmaType {
373 PragmaSingleton = 0x1
374 };
375 quint32 type;
376
377 QV4::CompiledData::Location location;
378};
379
380struct Q_QMLCOMPILER_PRIVATE_EXPORT Document
381{
382 Document(bool debugMode);
383 QString code;
384 QQmlJS::Engine jsParserEngine;
385 QV4::Compiler::Module jsModule;
386 QList<const QV4::CompiledData::Import *> imports;
387 QList<Pragma*> pragmas;
388 QQmlJS::AST::UiProgram *program;
389 QVector<Object*> objects;
390 QV4::Compiler::JSUnitGenerator jsGenerator;
391
392 QV4::CompiledData::CompilationUnit javaScriptCompilationUnit;
393
394 int registerString(const QString &str) { return jsGenerator.registerString(str); }
395 QString stringAt(int index) const { return jsGenerator.stringForIndex(index); }
396};
397
398class Q_QMLCOMPILER_PRIVATE_EXPORT ScriptDirectivesCollector : public QQmlJS::Directives
399{
400 QmlIR::Document *document;
401 QQmlJS::Engine *engine;
402 QV4::Compiler::JSUnitGenerator *jsGenerator;
403
404public:
405 ScriptDirectivesCollector(QmlIR::Document *doc);
406
407 void pragmaLibrary() override;
408 void importFile(const QString &jsfile, const QString &module, int lineNumber, int column) override;
409 void importModule(const QString &uri, const QString &version, const QString &module, int lineNumber, int column) override;
410};
411
412struct Q_QMLCOMPILER_PRIVATE_EXPORT IRBuilder : public QQmlJS::AST::Visitor
413{
414 Q_DECLARE_TR_FUNCTIONS(QQmlCodeGenerator)
415public:
416 IRBuilder(const QSet<QString> &illegalNames);
417 bool generateFromQml(const QString &code, const QString &url, Document *output);
418
419 static bool isSignalPropertyName(const QString &name);
420
421 using QQmlJS::AST::Visitor::visit;
422 using QQmlJS::AST::Visitor::endVisit;
423
424 bool visit(QQmlJS::AST::UiArrayMemberList *ast) override;
425 bool visit(QQmlJS::AST::UiImport *ast) override;
426 bool visit(QQmlJS::AST::UiPragma *ast) override;
427 bool visit(QQmlJS::AST::UiHeaderItemList *ast) override;
428 bool visit(QQmlJS::AST::UiObjectInitializer *ast) override;
429 bool visit(QQmlJS::AST::UiObjectMemberList *ast) override;
430 bool visit(QQmlJS::AST::UiParameterList *ast) override;
431 bool visit(QQmlJS::AST::UiProgram *) override;
432 bool visit(QQmlJS::AST::UiQualifiedId *ast) override;
433 bool visit(QQmlJS::AST::UiArrayBinding *ast) override;
434 bool visit(QQmlJS::AST::UiObjectBinding *ast) override;
435 bool visit(QQmlJS::AST::UiObjectDefinition *ast) override;
436 bool visit(QQmlJS::AST::UiEnumDeclaration *ast) override;
437 bool visit(QQmlJS::AST::UiPublicMember *ast) override;
438 bool visit(QQmlJS::AST::UiScriptBinding *ast) override;
439 bool visit(QQmlJS::AST::UiSourceElement *ast) override;
440
441 void throwRecursionDepthError() override
442 {
443 recordError(QQmlJS::AST::SourceLocation(),
444 QStringLiteral("Maximum statement or expression depth exceeded"));
445 }
446
447 void accept(QQmlJS::AST::Node *node);
448
449 // returns index in _objects
450 bool defineQMLObject(int *objectIndex, QQmlJS::AST::UiQualifiedId *qualifiedTypeNameId, const QQmlJS::AST::SourceLocation &location, QQmlJS::AST::UiObjectInitializer *initializer, Object *declarationsOverride = nullptr);
451 bool defineQMLObject(int *objectIndex, QQmlJS::AST::UiObjectDefinition *node, Object *declarationsOverride = nullptr)
452 { return defineQMLObject(objectIndex, node->qualifiedTypeNameId, node->qualifiedTypeNameId->firstSourceLocation(), node->initializer, declarationsOverride); }
453
454 static QString asString(QQmlJS::AST::UiQualifiedId *node);
455 QStringRef asStringRef(QQmlJS::AST::Node *node);
456 static void extractVersion(QStringRef string, int *maj, int *min);
457 QStringRef textRefAt(const QQmlJS::AST::SourceLocation &loc) const
458 { return QStringRef(&sourceCode, loc.offset, loc.length); }
459 QStringRef textRefAt(const QQmlJS::AST::SourceLocation &first,
460 const QQmlJS::AST::SourceLocation &last) const;
461
462 void setBindingValue(QV4::CompiledData::Binding *binding, QQmlJS::AST::Statement *statement,
463 QQmlJS::AST::Node *parentNode);
464 void tryGeneratingTranslationBinding(const QStringRef &base, QQmlJS::AST::ArgumentList *args, QV4::CompiledData::Binding *binding);
465
466 void appendBinding(QQmlJS::AST::UiQualifiedId *name, QQmlJS::AST::Statement *value,
467 QQmlJS::AST::Node *parentNode);
468 void appendBinding(QQmlJS::AST::UiQualifiedId *name, int objectIndex, bool isOnAssignment = false);
469 void appendBinding(const QQmlJS::AST::SourceLocation &qualifiedNameLocation,
470 const QQmlJS::AST::SourceLocation &nameLocation, quint32 propertyNameIndex,
471 QQmlJS::AST::Statement *value, QQmlJS::AST::Node *parentNode);
472 void appendBinding(const QQmlJS::AST::SourceLocation &qualifiedNameLocation,
473 const QQmlJS::AST::SourceLocation &nameLocation, quint32 propertyNameIndex,
474 int objectIndex, bool isListItem = false, bool isOnAssignment = false);
475
476 bool appendAlias(QQmlJS::AST::UiPublicMember *node);
477
478 Object *bindingsTarget() const;
479
480 bool setId(const QQmlJS::AST::SourceLocation &idLocation, QQmlJS::AST::Statement *value);
481
482 // resolves qualified name (font.pixelSize for example) and returns the last name along
483 // with the object any right-hand-side of a binding should apply to.
484 bool resolveQualifiedId(QQmlJS::AST::UiQualifiedId **nameToResolve, Object **object, bool onAssignment = false);
485
486 void recordError(const QQmlJS::AST::SourceLocation &location, const QString &description);
487
488 quint32 registerString(const QString &str) const { return jsGenerator->registerString(str); }
489 template <typename _Tp> _Tp *New() { return pool->New<_Tp>(); }
490
491 QString stringAt(int index) const { return jsGenerator->stringForIndex(index); }
492
493 static bool isStatementNodeScript(QQmlJS::AST::Statement *statement);
494 static bool isRedundantNullInitializerForPropertyDeclaration(Property *property, QQmlJS::AST::Statement *statement);
495
496 QString sanityCheckFunctionNames(Object *obj, const QSet<QString> &illegalNames, QQmlJS::AST::SourceLocation *errorLocation);
497
498 QList<QQmlJS::DiagnosticMessage> errors;
499
500 QSet<QString> illegalNames;
501
502 QList<const QV4::CompiledData::Import *> _imports;
503 QList<Pragma*> _pragmas;
504 QVector<Object*> _objects;
505
506 QV4::CompiledData::TypeReferenceMap _typeReferences;
507
508 Object *_object;
509 Property *_propertyDeclaration;
510
511 QQmlJS::MemoryPool *pool;
512 QString sourceCode;
513 QV4::Compiler::JSUnitGenerator *jsGenerator;
514};
515
516struct Q_QMLCOMPILER_PRIVATE_EXPORT QmlUnitGenerator
517{
518 void generate(Document &output, const QV4::CompiledData::DependentTypesHasher &dependencyHasher = QV4::CompiledData::DependentTypesHasher());
519
520private:
521 typedef bool (Binding::*BindingFilter)() const;
522 char *writeBindings(char *bindingPtr, const Object *o, BindingFilter filter) const;
523};
524
525struct Q_QMLCOMPILER_PRIVATE_EXPORT JSCodeGen : public QV4::Compiler::Codegen
526{
527 JSCodeGen(Document *document, const QSet<QString> &globalNames);
528
529 // Returns mapping from input functions to index in IR::Module::functions / compiledData->runtimeFunctions
530 QVector<int> generateJSCodeForFunctionsAndBindings(const QList<CompiledFunctionOrExpression> &functions);
531
532 bool generateCodeForComponents(const QVector<quint32> &componentRoots);
533 bool compileComponent(int contextObject);
534 bool compileJavaScriptCodeInObjectsRecursively(int objectIndex, int scopeObjectIndex);
535
536private:
537 Document *document;
538};
539
540} // namespace QmlIR
541
542QT_END_NAMESPACE
543
544#endif // QQMLIRBUILDER_P_H
545