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 QtQml module 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
40 #include "qv4script_p.h"
41 #include <private/qv4mm_p.h>
42 #include "qv4functionobject_p.h"
43 #include "qv4function_p.h"
44 #include "qv4context_p.h"
45 #include "qv4debugging_p.h"
46 #include "qv4profiling_p.h"
47 #include "qv4scopedvalue_p.h"
48 #include "qv4jscall_p.h"
49
50 #include <private/qqmljsengine_p.h>
51 #include <private/qqmljslexer_p.h>
52 #include <private/qqmljsparser_p.h>
53 #include <private/qqmljsast_p.h>
54 #include <private/qqmlengine_p.h>
55 #include <private/qqmlsourcecoordinate_p.h>
56 #include <private/qv4profiling_p.h>
57 #include <qv4runtimecodegen_p.h>
58
59 #include <QtCore/QDebug>
60 #include <QtCore/QString>
61 #include <QScopedValueRollback>
62
63 using namespace QV4;
64 using namespace QQmlJS;
65
Script(ExecutionEngine * v4,QmlContext * qml,const QQmlRefPointer<ExecutableCompilationUnit> & compilationUnit)66 Script::Script(ExecutionEngine *v4, QmlContext *qml, const QQmlRefPointer<ExecutableCompilationUnit> &compilationUnit)
67 : line(1), column(0), context(v4->rootContext()), strictMode(false), inheritContext(true), parsed(false)
68 , compilationUnit(compilationUnit), vmFunction(nullptr), parseAsBinding(true)
69 {
70 if (qml)
71 qmlContext.set(v4, *qml);
72
73 parsed = true;
74
75 vmFunction = compilationUnit ? compilationUnit->linkToEngine(v4) : nullptr;
76 }
77
~Script()78 Script::~Script()
79 {
80 }
81
parse()82 void Script::parse()
83 {
84 if (parsed)
85 return;
86
87 using namespace QV4::Compiler;
88
89 parsed = true;
90
91 ExecutionEngine *v4 = context->engine();
92 Scope valueScope(v4);
93
94 Module module(v4->debugger() != nullptr);
95
96 if (sourceCode.startsWith(QLatin1String("function("))) {
97 static const int snippetLength = 70;
98 qWarning() << "Warning: Using function expressions as statements in scripts is not compliant with the ECMAScript specification:\n"
99 << (sourceCode.leftRef(snippetLength) + QLatin1String("..."))
100 << "\nThis will throw a syntax error in Qt 5.12. If you want a function expression, surround it by parentheses.";
101 }
102
103 Engine ee, *engine = ⅇ
104 Lexer lexer(engine);
105 lexer.setCode(sourceCode, line, parseAsBinding);
106 Parser parser(engine);
107
108 const bool parsed = parser.parseProgram();
109
110 const auto diagnosticMessages = parser.diagnosticMessages();
111 for (const DiagnosticMessage &m : diagnosticMessages) {
112 if (m.isError()) {
113 valueScope.engine->throwSyntaxError(m.message, sourceFile, m.loc.startLine, m.loc.startColumn);
114 return;
115 } else {
116 qWarning() << sourceFile << ':' << m.loc.startLine << ':' << m.loc.startColumn
117 << ": warning: " << m.message;
118 }
119 }
120
121 if (parsed) {
122 using namespace AST;
123 Program *program = AST::cast<Program *>(parser.rootNode());
124 if (!program) {
125 // if parsing was successful, and we have no program, then
126 // we're done...:
127 return;
128 }
129
130 QV4::Compiler::JSUnitGenerator jsGenerator(&module);
131 RuntimeCodegen cg(v4, &jsGenerator, strictMode);
132 if (inheritContext)
133 cg.setUseFastLookups(false);
134 cg.generateFromProgram(sourceFile, sourceFile, sourceCode, program, &module, contextType);
135 if (v4->hasException)
136 return;
137
138 compilationUnit = QV4::ExecutableCompilationUnit::create(cg.generateCompilationUnit());
139 vmFunction = compilationUnit->linkToEngine(v4);
140 }
141
142 if (!vmFunction) {
143 // ### FIX file/line number
144 ScopedObject error(valueScope, v4->newSyntaxErrorObject(QStringLiteral("Syntax error")));
145 v4->throwError(error);
146 }
147 }
148
run(const QV4::Value * thisObject)149 ReturnedValue Script::run(const QV4::Value *thisObject)
150 {
151 if (!parsed)
152 parse();
153 if (!vmFunction)
154 return Encode::undefined();
155
156 QV4::ExecutionEngine *engine = context->engine();
157 QV4::Scope valueScope(engine);
158
159 if (qmlContext.isUndefined()) {
160 QScopedValueRollback<Function*> savedGlobalCode(engine->globalCode, vmFunction);
161
162 return vmFunction->call(thisObject ? thisObject : engine->globalObject, nullptr, 0,
163 context);
164 } else {
165 Scoped<QmlContext> qml(valueScope, qmlContext.value());
166 return vmFunction->call(thisObject, nullptr, 0, qml);
167 }
168 }
169
function()170 Function *Script::function()
171 {
172 if (!parsed)
173 parse();
174 return vmFunction;
175 }
176
precompile(QV4::Compiler::Module * module,QQmlJS::Engine * jsEngine,Compiler::JSUnitGenerator * unitGenerator,const QString & fileName,const QString & finalUrl,const QString & source,QList<QQmlError> * reportedErrors,QV4::Compiler::ContextType contextType)177 QV4::CompiledData::CompilationUnit Script::precompile(
178 QV4::Compiler::Module *module, QQmlJS::Engine *jsEngine,
179 Compiler::JSUnitGenerator *unitGenerator, const QString &fileName, const QString &finalUrl,
180 const QString &source, QList<QQmlError> *reportedErrors,
181 QV4::Compiler::ContextType contextType)
182 {
183 using namespace QV4::Compiler;
184 using namespace QQmlJS::AST;
185
186 Lexer lexer(jsEngine);
187 lexer.setCode(source, /*line*/1, /*qml mode*/false);
188 Parser parser(jsEngine);
189
190 parser.parseProgram();
191
192 QList<QQmlError> errors = QQmlEnginePrivate::qmlErrorFromDiagnostics(fileName, parser.diagnosticMessages());
193 if (!errors.isEmpty()) {
194 if (reportedErrors)
195 *reportedErrors << errors;
196 return nullptr;
197 }
198
199 Program *program = AST::cast<Program *>(parser.rootNode());
200 if (!program) {
201 // if parsing was successful, and we have no program, then
202 // we're done...:
203 return nullptr;
204 }
205
206 Codegen cg(unitGenerator, /*strict mode*/false);
207 cg.generateFromProgram(fileName, finalUrl, source, program, module, contextType);
208 if (cg.hasError()) {
209 if (reportedErrors) {
210 const auto v4Error = cg.error();
211 QQmlError error;
212 error.setUrl(cg.url());
213 error.setLine(qmlConvertSourceCoordinate<quint32, int>(v4Error.loc.startLine));
214 error.setColumn(qmlConvertSourceCoordinate<quint32, int>(v4Error.loc.startColumn));
215 error.setDescription(v4Error.message);
216 reportedErrors->append(error);
217 }
218 return nullptr;
219 }
220
221 return cg.generateCompilationUnit(/*generate unit data*/false);
222 }
223
createFromFileOrCache(ExecutionEngine * engine,QmlContext * qmlContext,const QString & fileName,const QUrl & originalUrl,QString * error)224 Script *Script::createFromFileOrCache(ExecutionEngine *engine, QmlContext *qmlContext, const QString &fileName, const QUrl &originalUrl, QString *error)
225 {
226 if (error)
227 error->clear();
228
229 QQmlMetaType::CachedUnitLookupError cacheError = QQmlMetaType::CachedUnitLookupError::NoError;
230 if (const QV4::CompiledData::Unit *cachedUnit = QQmlMetaType::findCachedCompilationUnit(originalUrl, &cacheError)) {
231 QQmlRefPointer<QV4::ExecutableCompilationUnit> jsUnit
232 = QV4::ExecutableCompilationUnit::create(
233 QV4::CompiledData::CompilationUnit(cachedUnit));
234 return new QV4::Script(engine, qmlContext, jsUnit);
235 }
236
237 QFile f(fileName);
238 if (!f.open(QIODevice::ReadOnly)) {
239 if (error) {
240 if (cacheError == QQmlMetaType::CachedUnitLookupError::VersionMismatch)
241 *error = originalUrl.toString() + QString::fromUtf8(" was compiled ahead of time with an incompatible version of Qt and the original source code cannot be found. Please recompile");
242 else
243 *error = QString::fromUtf8("Error opening source file %1: %2").arg(originalUrl.toString()).arg(f.errorString());
244 }
245 return nullptr;
246 }
247
248 QByteArray data = f.readAll();
249 QString sourceCode = QString::fromUtf8(data);
250
251 auto result = new QV4::Script(engine, qmlContext, /*parseAsBinding*/false, sourceCode, originalUrl.toString());
252 result->contextType = QV4::Compiler::ContextType::ScriptImportedByQML;
253 result->parse();
254 return result;
255 }
256