1// Copyright (C) 2016 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 "qqmljsloadergenerator_p.h"
5
6#include <QByteArray>
7#include <QRegularExpression>
8#include <QString>
9#include <QStringList>
10#include <QTextStream>
11#include <QVector>
12#include <QtEndian>
13#include <QStack>
14#include <QFileInfo>
15#include <QSaveFile>
16
17QT_BEGIN_NAMESPACE
18
19/*!
20 * \internal
21 * Mangles \a str to be a unique C++ identifier. Characters that are invalid for C++ identifiers
22 * are replaced by the pattern \c _0x<hex>_ where <hex> is the hexadecimal unicode
23 * representation of the character. As identifiers with leading underscores followed by either
24 * another underscore or a capital letter are reserved in C++, we also escape those, by escaping
25 * the first underscore, using the above method.
26 *
27 * \note
28 * Although C++11 allows for non-ascii (unicode) characters to be used in identifiers,
29 * many compilers forgot to read the spec and do not implement this. Some also do not
30 * implement C99 identifiers, because that is \e {at the implementation's discretion}. So,
31 * we are stuck with plain old boring identifiers.
32 */
33QString mangledIdentifier(const QString &str)
34{
35 Q_ASSERT(!str.isEmpty());
36
37 QString mangled;
38 mangled.reserve(asize: str.size());
39
40 int i = 0;
41 if (str.startsWith(c: QLatin1Char('_')) && str.size() > 1) {
42 QChar ch = str.at(i: 1);
43 if (ch == QLatin1Char('_')
44 || (ch >= QLatin1Char('A') && ch <= QLatin1Char('Z'))) {
45 mangled += QLatin1String("_0x5f_");
46 ++i;
47 }
48 }
49
50 for (int ei = str.size(); i != ei; ++i) {
51 auto c = str.at(i).unicode();
52 if ((c >= QLatin1Char('0') && c <= QLatin1Char('9'))
53 || (c >= QLatin1Char('a') && c <= QLatin1Char('z'))
54 || (c >= QLatin1Char('A') && c <= QLatin1Char('Z'))
55 || c == QLatin1Char('_')) {
56 mangled += QChar(c);
57 } else {
58 mangled += QLatin1String("_0x") + QString::number(c, base: 16) + QLatin1Char('_');
59 }
60 }
61
62 return mangled;
63}
64
65QString qQmlJSSymbolNamespaceForPath(const QString &relativePath)
66{
67 QFileInfo fi(relativePath);
68 QString symbol = fi.path();
69 if (symbol.size() == 1 && symbol.startsWith(c: QLatin1Char('.'))) {
70 symbol.clear();
71 } else {
72 symbol.replace(before: QLatin1Char('/'), after: QLatin1Char('_'));
73 symbol += QLatin1Char('_');
74 }
75 symbol += fi.baseName();
76 symbol += QLatin1Char('_');
77 symbol += fi.completeSuffix();
78 return mangledIdentifier(str: symbol);
79}
80
81static QString qtResourceNameForFile(const QString &fileName)
82{
83 QFileInfo fi(fileName);
84 QString name = fi.completeBaseName();
85 if (name.isEmpty())
86 name = fi.fileName();
87 name.replace(re: QRegularExpression(QLatin1String("[^a-zA-Z0-9_]")), after: QLatin1String("_"));
88 return name;
89}
90
91bool qQmlJSGenerateLoader(const QStringList &compiledFiles, const QString &outputFileName,
92 const QStringList &resourceFileMappings, QString *errorString)
93{
94 QByteArray generatedLoaderCode;
95
96 {
97 QTextStream stream(&generatedLoaderCode);
98 stream << "#include <QtQml/qqmlprivate.h>\n";
99 stream << "#include <QtCore/qdir.h>\n";
100 stream << "#include <QtCore/qurl.h>\n";
101 stream << "#include <QtCore/qhash.h>\n";
102 stream << "#include <QtCore/qstring.h>\n";
103 stream << "\n";
104
105 stream << "namespace QmlCacheGeneratedCode {\n";
106 for (int i = 0; i < compiledFiles.size(); ++i) {
107 const QString compiledFile = compiledFiles.at(i);
108 const QString ns = qQmlJSSymbolNamespaceForPath(relativePath: compiledFile);
109 stream << "namespace " << ns << " { \n";
110 stream << " extern const unsigned char qmlData[];\n";
111 stream << " extern const QQmlPrivate::AOTCompiledFunction aotBuiltFunctions[];\n";
112 stream << " const QQmlPrivate::CachedQmlUnit unit = {\n";
113 stream << " reinterpret_cast<const QV4::CompiledData::Unit*>(&qmlData), &aotBuiltFunctions[0], nullptr\n";
114 stream << " };\n";
115 stream << "}\n";
116 }
117
118 stream << "\n}\n";
119 stream << "namespace {\n";
120
121 stream << "struct Registry {\n";
122 stream << " Registry();\n";
123 stream << " ~Registry();\n";
124 stream << " QHash<QString, const QQmlPrivate::CachedQmlUnit*> resourcePathToCachedUnit;\n";
125 stream << " static const QQmlPrivate::CachedQmlUnit *lookupCachedUnit(const QUrl &url);\n";
126 stream << "};\n\n";
127 stream << "Q_GLOBAL_STATIC(Registry, unitRegistry)\n";
128 stream << "\n\n";
129
130 stream << "Registry::Registry() {\n";
131
132 for (int i = 0; i < compiledFiles.size(); ++i) {
133 const QString qrcFile = compiledFiles.at(i);
134 const QString ns = qQmlJSSymbolNamespaceForPath(relativePath: qrcFile);
135 stream << " resourcePathToCachedUnit.insert(QStringLiteral(\"" << qrcFile << "\"), &QmlCacheGeneratedCode::" << ns << "::unit);\n";
136 }
137
138 stream << " QQmlPrivate::RegisterQmlUnitCacheHook registration;\n";
139 stream << " registration.structVersion = 0;\n";
140 stream << " registration.lookupCachedQmlUnit = &lookupCachedUnit;\n";
141 stream << " QQmlPrivate::qmlregister(QQmlPrivate::QmlUnitCacheHookRegistration, &registration);\n";
142
143 stream << "}\n\n";
144 stream << "Registry::~Registry() {\n";
145 stream << " QQmlPrivate::qmlunregister(QQmlPrivate::QmlUnitCacheHookRegistration, quintptr(&lookupCachedUnit));\n";
146 stream << "}\n\n";
147
148 stream << "const QQmlPrivate::CachedQmlUnit *Registry::lookupCachedUnit(const QUrl &url) {\n";
149 stream << " if (url.scheme() != QLatin1String(\"qrc\"))\n";
150 stream << " return nullptr;\n";
151 stream << " QString resourcePath = QDir::cleanPath(url.path());\n";
152 stream << " if (resourcePath.isEmpty())\n";
153 stream << " return nullptr;\n";
154 stream << " if (!resourcePath.startsWith(QLatin1Char('/')))\n";
155 stream << " resourcePath.prepend(QLatin1Char('/'));\n";
156 stream << " return unitRegistry()->resourcePathToCachedUnit.value(resourcePath, nullptr);\n";
157 stream << "}\n";
158 stream << "}\n";
159
160 for (const QString &mapping: resourceFileMappings) {
161 QString originalResourceFile = mapping;
162 QString newResourceFile;
163 const int mappingSplit = originalResourceFile.indexOf(ch: QLatin1Char('='));
164 if (mappingSplit != -1) {
165 newResourceFile = originalResourceFile.mid(position: mappingSplit + 1);
166 originalResourceFile.truncate(pos: mappingSplit);
167 }
168
169 const QString suffix = qtResourceNameForFile(fileName: originalResourceFile);
170 const QString initFunction = QLatin1String("qInitResources_") + suffix;
171
172 stream << QStringLiteral("int QT_MANGLE_NAMESPACE(%1)() {\n").arg(a: initFunction);
173 stream << " ::unitRegistry();\n";
174 if (!newResourceFile.isEmpty())
175 stream << " Q_INIT_RESOURCE(" << qtResourceNameForFile(fileName: newResourceFile) << ");\n";
176 stream << " return 1;\n";
177 stream << "}\n";
178 stream << "Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(" << initFunction << "))\n";
179
180 const QString cleanupFunction = QLatin1String("qCleanupResources_") + suffix;
181 stream << QStringLiteral("int QT_MANGLE_NAMESPACE(%1)() {\n").arg(a: cleanupFunction);
182 if (!newResourceFile.isEmpty())
183 stream << " Q_CLEANUP_RESOURCE(" << qtResourceNameForFile(fileName: newResourceFile) << ");\n";
184 stream << " return 1;\n";
185 stream << "}\n";
186 }
187 }
188
189#if QT_CONFIG(temporaryfile)
190 QSaveFile f(outputFileName);
191#else
192 QFile f(outputFileName);
193#endif
194 if (!f.open(flags: QIODevice::WriteOnly | QIODevice::Truncate)) {
195 *errorString = f.errorString();
196 return false;
197 }
198
199 if (f.write(data: generatedLoaderCode) != generatedLoaderCode.size()) {
200 *errorString = f.errorString();
201 return false;
202 }
203
204#if QT_CONFIG(temporaryfile)
205 if (!f.commit()) {
206 *errorString = f.errorString();
207 return false;
208 }
209#endif
210
211 return true;
212}
213
214QT_END_NAMESPACE
215

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