1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QCoreApplication>
#include <QStringList>
#include <QCommandLineParser>
#include <QFile>
#include <QFileInfo>
#include <QDateTime>
#include <QHashFunctions>
#include <QSaveFile>
#include <private/qqmlirbuilder_p.h>
#include <private/qqmljsparser_p.h>
#include "resourcefilemapper.h"
int filterResourceFile(const QString &input, const QString &output);
bool generateLoader(const QStringList &compiledFiles, const QString &output, const QStringList &resourceFileMappings, QString *errorString);
QString symbolNamespaceForPath(const QString &relativePath);
QSet<QString> illegalNames;
void setupIllegalNames()
{
// #### this in incomplete
illegalNames.insert(QStringLiteral("Math"));
illegalNames.insert(QStringLiteral("Array"));
illegalNames.insert(QStringLiteral("String"));
illegalNames.insert(QStringLiteral("Function"));
illegalNames.insert(QStringLiteral("Boolean"));
illegalNames.insert(QStringLiteral("Number"));
illegalNames.insert(QStringLiteral("Date"));
illegalNames.insert(QStringLiteral("RegExp"));
illegalNames.insert(QStringLiteral("Error"));
illegalNames.insert(QStringLiteral("Object"));
}
struct Error
{
QString message;
void print();
Error augment(const QString &contextErrorMessage) const;
};
void Error::print()
{
fprintf(stderr, "%s\n", qPrintable(message));
}
Error Error::augment(const QString &contextErrorMessage) const
{
Error augmented;
augmented.message = contextErrorMessage + message;
return augmented;
}
QString diagnosticErrorMessage(const QString &fileName, const QQmlJS::DiagnosticMessage &m)
{
QString message;
message = fileName + QLatin1Char(':') + QString::number(m.loc.startLine) + QLatin1Char(':');
if (m.loc.startColumn > 0)
message += QString::number(m.loc.startColumn) + QLatin1Char(':');
if (m.isError())
message += QLatin1String(" error: ");
else
message += QLatin1String(" warning: ");
message += m.message;
return message;
}
// Ensure that ListElement objects keep all property assignments in their string form
static void annotateListElements(QmlIR::Document *document)
{
QStringList listElementNames;
foreach (const QV4::CompiledData::Import *import, document->imports) {
const QString uri = document->stringAt(import->uriIndex);
if (uri != QStringLiteral("QtQml.Models") && uri != QStringLiteral("QtQuick"))
continue;
QString listElementName = QStringLiteral("ListElement");
const QString qualifier = document->stringAt(import->qualifierIndex);
if (!qualifier.isEmpty()) {
listElementName.prepend(QLatin1Char('.'));
listElementName.prepend(qualifier);
}
listElementNames.append(listElementName);
}
if (listElementNames.isEmpty())
return;
foreach (QmlIR::Object *object, document->objects) {
if (!listElementNames.contains(document->stringAt(object->inheritedTypeNameIndex)))
continue;
for (QmlIR::Binding *binding = object->firstBinding(); binding; binding = binding->next) {
if (binding->type != QV4::CompiledData::Binding::Type_Script)
continue;
binding->stringIndex = document->registerString(object->bindingAsString(document, binding->value.compiledScriptIndex));
}
}
}
static bool checkArgumentsObjectUseInSignalHandlers(const QmlIR::Document &doc, Error *error)
{
for (QmlIR::Object *object: qAsConst(doc.objects)) {
for (auto binding = object->bindingsBegin(); binding != object->bindingsEnd(); ++binding) {
if (binding->type != QV4::CompiledData::Binding::Type_Script)
continue;
const QString propName = doc.stringAt(binding->propertyNameIndex);
if (!propName.startsWith(QLatin1String("on"))
|| propName.length() < 3
|| !propName.at(2).isUpper())
continue;
auto compiledFunction = doc.jsModule.functions.value(object->runtimeFunctionIndices.at(binding->value.compiledScriptIndex));
if (!compiledFunction)
continue;
if (compiledFunction->usesArgumentsObject == QV4::Compiler::Context::ArgumentsObjectUsed) {
error->message = QLatin1Char(':') + QString::number(compiledFunction->line) + QLatin1Char(':');
if (compiledFunction->column > 0)
error->message += QString::number(compiledFunction->column) + QLatin1Char(':');
error->message += QLatin1String(" error: The use of the arguments object in signal handlers is\n"
"not supported when compiling qml files ahead of time, because it may be ambiguous if\n"
"any signal parameter is called \"arguments\". Unfortunately we cannot distinguish\n"
"between it being a parameter or the JavaScript arguments object at this point.\n"
"Consider renaming the parameter of the signal if applicable.");
return false;
}
}
}
return true;
}
using SaveFunction = std::function<bool (QV4::CompiledData::CompilationUnit *, QString *)>;
static bool compileQmlFile(const QString &inputFileName, SaveFunction saveFunction, Error *error)
{
QmlIR::Document irDocument(/*debugMode*/false);
QString sourceCode;
{
QFile f(inputFileName);
if (!f.open(QIODevice::ReadOnly)) {
error->message = QLatin1String("Error opening ") + inputFileName + QLatin1Char(':') + f.errorString();
return false;
}
sourceCode = QString::fromUtf8(f.readAll());
if (f.error() != QFileDevice::NoError) {
error->message = QLatin1String("Error reading from ") + inputFileName + QLatin1Char(':') + f.errorString();
return false;
}
}
{
QmlIR::IRBuilder irBuilder(illegalNames);
if (!irBuilder.generateFromQml(sourceCode, inputFileName, &irDocument)) {
for (const QQmlJS::DiagnosticMessage &parseError: qAsConst(irBuilder.errors)) {
if (!error->message.isEmpty())
error->message += QLatin1Char('\n');
error->message += diagnosticErrorMessage(inputFileName, parseError);
}
return false;
}
}
annotateListElements(&irDocument);
{
QmlIR::JSCodeGen v4CodeGen(irDocument.code,
&irDocument.jsGenerator, &irDocument.jsModule,
&irDocument.jsParserEngine, irDocument.program,
/*import cache*/nullptr, &irDocument.jsGenerator.stringTable, illegalNames);
v4CodeGen.setUseFastLookups(false); // Disable lookups in non-standalone (aka QML) mode
for (QmlIR::Object *object: qAsConst(irDocument.objects)) {
if (object->functionsAndExpressions->count == 0)
continue;
QList<QmlIR::CompiledFunctionOrExpression> functionsToCompile;
for (QmlIR::CompiledFunctionOrExpression *foe = object->functionsAndExpressions->first; foe; foe = foe->next) {
foe->disableAcceleratedLookups = true;
functionsToCompile << *foe;
}
const QVector<int> runtimeFunctionIndices = v4CodeGen.generateJSCodeForFunctionsAndBindings(functionsToCompile);
QList<QQmlJS::DiagnosticMessage> jsErrors = v4CodeGen.errors();
if (!jsErrors.isEmpty()) {
for (const QQmlJS::DiagnosticMessage &e: qAsConst(jsErrors)) {
if (!error->message.isEmpty())
error->message += QLatin1Char('\n');
error->message += diagnosticErrorMessage(inputFileName, e);
}
return false;
}
QQmlJS::MemoryPool *pool = irDocument.jsParserEngine.pool();
object->runtimeFunctionIndices.allocate(pool, runtimeFunctionIndices);
}
if (!checkArgumentsObjectUseInSignalHandlers(irDocument, error)) {
*error = error->augment(inputFileName);
return false;
}
QmlIR::QmlUnitGenerator generator;
irDocument.javaScriptCompilationUnit = v4CodeGen.generateCompilationUnit(/*generate unit*/false);
QV4::CompiledData::Unit *unit = generator.generate(irDocument);
unit->flags |= QV4::CompiledData::Unit::StaticData;
unit->flags |= QV4::CompiledData::Unit::PendingTypeCompilation;
irDocument.javaScriptCompilationUnit->data = unit;
if (!saveFunction(irDocument.javaScriptCompilationUnit, &error->message))
return false;
free(unit);
}
return true;
}
static bool compileJSFile(const QString &inputFileName, const QString &inputFileUrl, SaveFunction saveFunction, Error *error)
{
QmlIR::Document irDocument(/*debugMode*/false);
QString sourceCode;
{
QFile f(inputFileName);
if (!f.open(QIODevice::ReadOnly)) {
error->message = QLatin1String("Error opening ") + inputFileName + QLatin1Char(':') + f.errorString();
return false;
}
sourceCode = QString::fromUtf8(f.readAll());
if (f.error() != QFileDevice::NoError) {
error->message = QLatin1String("Error reading from ") + inputFileName + QLatin1Char(':') + f.errorString();
return false;
}
}
QQmlJS::Engine *engine = &irDocument.jsParserEngine;
QmlIR::ScriptDirectivesCollector directivesCollector(engine, &irDocument.jsGenerator);
QQmlJS::Directives *oldDirs = engine->directives();
engine->setDirectives(&directivesCollector);
QQmlJS::AST::Program *program = nullptr;
{
QQmlJS::Lexer lexer(engine);
lexer.setCode(sourceCode, /*line*/1, /*parseAsBinding*/false);
QQmlJS::Parser parser(engine);
bool parsed = parser.parseProgram();
for (const QQmlJS::DiagnosticMessage &parseError: parser.diagnosticMessages()) {
if (!error->message.isEmpty())
error->message += QLatin1Char('\n');
error->message += diagnosticErrorMessage(inputFileName, parseError);
}
if (!parsed) {
engine->setDirectives(oldDirs);
return false;
}
program = QQmlJS::AST::cast<QQmlJS::AST::Program*>(parser.rootNode());
if (!program) {
lexer.setCode(QStringLiteral("undefined;"), 1, false);
parsed = parser.parseProgram();
Q_ASSERT(parsed);
program = QQmlJS::AST::cast<QQmlJS::AST::Program*>(parser.rootNode());
Q_ASSERT(program);
}
}
{
QmlIR::JSCodeGen v4CodeGen(irDocument.code, &irDocument.jsGenerator,
&irDocument.jsModule, &irDocument.jsParserEngine,
irDocument.program, /*import cache*/nullptr,
&irDocument.jsGenerator.stringTable, illegalNames);
v4CodeGen.setUseFastLookups(false); // Disable lookups in non-standalone (aka QML) mode
v4CodeGen.generateFromProgram(inputFileName, inputFileUrl, sourceCode, program,
&irDocument.jsModule, QV4::Compiler::GlobalCode);
QList<QQmlJS::DiagnosticMessage> jsErrors = v4CodeGen.errors();
if (!jsErrors.isEmpty()) {
for (const QQmlJS::DiagnosticMessage &e: qAsConst(jsErrors)) {
if (!error->message.isEmpty())
error->message += QLatin1Char('\n');
error->message += diagnosticErrorMessage(inputFileName, e);
}
engine->setDirectives(oldDirs);
return false;
}
QmlIR::QmlUnitGenerator generator;
irDocument.javaScriptCompilationUnit = v4CodeGen.generateCompilationUnit(/*generate unit*/false);
QV4::CompiledData::Unit *unit = generator.generate(irDocument);
unit->flags |= QV4::CompiledData::Unit::StaticData;
irDocument.javaScriptCompilationUnit->data = unit;
if (!saveFunction(irDocument.javaScriptCompilationUnit, &error->message)) {
engine->setDirectives(oldDirs);
return false;
}
free(unit);
}
engine->setDirectives(oldDirs);
return true;
}
static bool saveUnitAsCpp(const QString &inputFileName, const QString &outputFileName, QV4::CompiledData::CompilationUnit *unit, QString *errorString)
{
QSaveFile f(outputFileName);
if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
*errorString = f.errorString();
return false;
}
auto writeStr = [&f, errorString](const QByteArray &data) {
if (f.write(data) != data.size()) {
*errorString = f.errorString();
return false;
}
return true;
};
if (!writeStr("// "))
return false;
if (!writeStr(inputFileName.toUtf8()))
return false;
if (!writeStr("\n"))
return false;
if (!writeStr(QByteArrayLiteral("namespace QmlCacheGeneratedCode {\nnamespace ")))
return false;
if (!writeStr(symbolNamespaceForPath(inputFileName).toUtf8()))
return false;
if (!writeStr(QByteArrayLiteral(" {\nextern const unsigned char qmlData alignas(16) [] = {\n")))
return false;
QByteArray hexifiedData;
{
QByteArray modifiedUnit;
modifiedUnit.resize(unit->data->unitSize);
memcpy(modifiedUnit.data(), unit->data, unit->data->unitSize);
const char *dataPtr = modifiedUnit.data();
QV4::CompiledData::Unit *unitPtr;
memcpy(&unitPtr, &dataPtr, sizeof(unitPtr));
unitPtr->flags |= QV4::CompiledData::Unit::StaticData;
QTextStream stream(&hexifiedData);
const uchar *begin = reinterpret_cast<const uchar *>(modifiedUnit.constData());
const uchar *end = begin + unit->data->unitSize;
stream << hex;
int col = 0;
for (const uchar *data = begin; data < end; ++data, ++col) {
if (data > begin)
stream << ',';
if (col % 8 == 0) {
stream << '\n';
col = 0;
}
stream << "0x" << *data;
}
stream << '\n';
};
if (!writeStr(hexifiedData))
return false;
if (!writeStr("};\n}\n}\n"))
return false;
if (!f.commit()) {
*errorString = f.errorString();
return false;
}
return true;
}
int main(int argc, char **argv)
{
// Produce reliably the same output for the same input by disabling QHash's random seeding.
qSetGlobalQHashSeed(0);
QCoreApplication app(argc, argv);
QCoreApplication::setApplicationName(QStringLiteral("qmlcachegen"));
QCoreApplication::setApplicationVersion(QLatin1String(QT_VERSION_STR));
QCommandLineParser parser;
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption filterResourceFileOption(QStringLiteral("filter-resource-file"), QCoreApplication::translate("main", "Filter out QML/JS files from a resource file that can be cached ahead of time instead"));
parser.addOption(filterResourceFileOption);
QCommandLineOption resourceFileMappingOption(QStringLiteral("resource-file-mapping"), QCoreApplication::translate("main", "Path from original resource file to new one"), QCoreApplication::translate("main", "old-name:new-name"));
parser.addOption(resourceFileMappingOption);
QCommandLineOption resourceOption(QStringLiteral("resource"), QCoreApplication::translate("main", "Qt resource file that might later contain one of the compiled files"), QCoreApplication::translate("main", "resource-file-name"));
parser.addOption(resourceOption);
QCommandLineOption resourcePathOption(QStringLiteral("resource-path"), QCoreApplication::translate("main", "Qt resource file path corresponding to the file being compiled"), QCoreApplication::translate("main", "resource-path"));
parser.addOption(resourcePathOption);
QCommandLineOption outputFileOption(QStringLiteral("o"), QCoreApplication::translate("main", "Output file name"), QCoreApplication::translate("main", "file name"));
parser.addOption(outputFileOption);
QCommandLineOption checkIfSupportedOption(QStringLiteral("check-if-supported"), QCoreApplication::translate("main", "Check if cache generate is supported on the specified target architecture"));
parser.addOption(checkIfSupportedOption);
parser.addPositionalArgument(QStringLiteral("[qml file]"),
QStringLiteral("QML source file to generate cache for."));
parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
parser.process(app);
enum Output {
GenerateCpp,
GenerateCacheFile,
GenerateLoader
} target = GenerateCacheFile;
QString outputFileName;
if (parser.isSet(outputFileOption))
outputFileName = parser.value(outputFileOption);
if (outputFileName.endsWith(QLatin1String(".cpp"))) {
target = GenerateCpp;
if (outputFileName.endsWith(QLatin1String("qmlcache_loader.cpp")))
target = GenerateLoader;
}
const QStringList sources = parser.positionalArguments();
if (sources.isEmpty()){
parser.showHelp();
} else if (sources.count() > 1 && target != GenerateLoader) {
fprintf(stderr, "%s\n", qPrintable(QStringLiteral("Too many input files specified: '") + sources.join(QStringLiteral("' '")) + QLatin1Char('\'')));
return EXIT_FAILURE;
}
const QString inputFile = sources.first();
if (outputFileName.isEmpty())
outputFileName = inputFile + QLatin1Char('c');
if (parser.isSet(filterResourceFileOption)) {
return filterResourceFile(inputFile, outputFileName);
}
if (target == GenerateLoader) {
ResourceFileMapper mapper(sources);
Error error;
if (!generateLoader(mapper.qmlCompilerFiles(), outputFileName, parser.values(resourceFileMappingOption), &error.message)) {
error.augment(QLatin1String("Error generating loader stub: ")).print();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
QString inputFileUrl = inputFile;
SaveFunction saveFunction;
if (target == GenerateCpp) {
ResourceFileMapper fileMapper(parser.values(resourceOption));
QString inputResourcePath = parser.value(resourcePathOption);
if (!inputResourcePath.isEmpty() && !fileMapper.isEmpty()) {
fprintf(stderr, "--%s and --%s are mutually exclusive.\n",
qPrintable(resourcePathOption.names().first()),
qPrintable(resourceOption.names().first()));
return EXIT_FAILURE;
}
// If the user didn't specify the resource path corresponding to the file on disk being
// compiled, try to determine it from the resource file, if one was supplied.
if (inputResourcePath.isEmpty()) {
const QStringList resourcePaths = fileMapper.resourcePaths(inputFile);
if (resourcePaths.isEmpty()) {
fprintf(stderr, "No resource path for file: %s\n", qPrintable(inputFile));
return EXIT_FAILURE;
}
if (resourcePaths.size() != 1) {
fprintf(stderr, "Multiple resource paths for file %s. "
"Use the --%s option to disambiguate:\n",
qPrintable(inputFile),
qPrintable(resourcePathOption.names().first()));
for (const QString &resourcePath: resourcePaths)
fprintf(stderr, "\t%s\n", qPrintable(resourcePath));
return EXIT_FAILURE;
}
inputResourcePath = resourcePaths.first();
}
inputFileUrl = QStringLiteral("qrc://") + inputResourcePath;
saveFunction = [inputResourcePath, outputFileName](QV4::CompiledData::CompilationUnit *unit, QString *errorString) {
return saveUnitAsCpp(inputResourcePath, outputFileName, unit, errorString);
};
} else {
saveFunction = [outputFileName](QV4::CompiledData::CompilationUnit *unit, QString *errorString) {
return unit->saveToDisk(outputFileName, errorString);
};
}
setupIllegalNames();
if (inputFile.endsWith(QLatin1String(".qml"))) {
Error error;
if (!compileQmlFile(inputFile, saveFunction, &error)) {
error.augment(QLatin1String("Error compiling qml file: ")).print();
return EXIT_FAILURE;
}
} else if (inputFile.endsWith(QLatin1String(".js"))) {
Error error;
if (!compileJSFile(inputFile, inputFileUrl, saveFunction, &error)) {
error.augment(QLatin1String("Error compiling js file: ")).print();
return EXIT_FAILURE;
}
} else {
fprintf(stderr, "Ignoring %s input file as it is not QML source code - maybe remove from QML_FILES?\n", qPrintable(inputFile));
}
return EXIT_SUCCESS;
}
|