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
qv4codegen.cpp
Go to the documentation of this file.
1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
5#include "qv4codegen_p.h"
6
7#include <private/qqmljsast_p.h>
8#include <private/qqmljsdiagnosticmessage_p.h>
9#include <private/qqmljslexer_p.h>
10#include <private/qqmljsparser_p.h>
11#include <private/qv4bytecodegenerator_p.h>
12#include <private/qv4compilercontext_p.h>
13#include <private/qv4compilercontrolflow_p.h>
14#include <private/qv4compilerscanfunctions_p.h>
15#include <private/qv4object_p.h>
16#include <private/qv4objectiterator_p.h>
17#include <private/qv4staticvalue_p.h>
18#include <private/qv4stringtoarrayindex_p.h>
19
20#include <QtCore/qcoreapplication.h>
21#include <QtCore/qloggingcategory.h>
22#include <QtCore/qscopeguard.h>
23#include <QtCore/qstack.h>
24#include <QtCore/qstringlist.h>
25#include <QtCore/qurl.h>
26
27#include <cmath>
28
29#ifdef CONST
30#undef CONST
31#endif
32
33QT_BEGIN_NAMESPACE
34
35using namespace Qt::StringLiterals;
36
37Q_STATIC_LOGGING_CATEGORY(lcQmlUsedBeforeDeclared, "qt.qml.usedbeforedeclared");
38Q_STATIC_LOGGING_CATEGORY(lcQmlInjectedParameter, "qt.qml.injectedparameter");
39
40using namespace QV4;
41using namespace QV4::Compiler;
42using namespace QQmlJS;
43using namespace QQmlJS::AST;
44
45void CodegenWarningInterface::reportVarUsedBeforeDeclaration(
46 const QString &name, const QString &fileName, QQmlJS::SourceLocation declarationLocation,
47 QQmlJS::SourceLocation accessLocation)
48{
49 qCWarning(lcQmlUsedBeforeDeclared).nospace().noquote()
50 << fileName << ":" << accessLocation.startLine << ":" << accessLocation.startColumn
51 << " Variable \"" << name << "\" is used before its declaration at "
52 << declarationLocation.startLine << ":" << declarationLocation.startColumn << ".";
53}
54
55void CodegenWarningInterface::reportFunctionUsedBeforeDeclaration(const QString &, const QString &,
56 QQmlJS::SourceLocation,
57 QQmlJS::SourceLocation)
58{
59 // we don't report this by default, only when using qmllint.
60}
61
62static inline void setJumpOutLocation(QV4::Moth::BytecodeGenerator *bytecodeGenerator,
63 const Statement *body, const SourceLocation &fallback)
64{
65 switch (body->kind) {
66 // Statements where we might never execute the last line.
67 // Use the fallback.
68 case Statement::Kind_ConditionalExpression:
69 case Statement::Kind_ForEachStatement:
70 case Statement::Kind_ForStatement:
71 case Statement::Kind_IfStatement:
72 case Statement::Kind_WhileStatement:
73 bytecodeGenerator->setLocation(fallback);
74 break;
75 default:
76 bytecodeGenerator->setLocation(body->lastSourceLocation());
77 break;
78 }
79}
80
81void Codegen::generateThrowException(const QString &type, const QString &text)
82{
83 RegisterScope scope(this);
84 Instruction::Construct construct;
85 if (text.isEmpty()) {
86 construct.argc = 0;
87 construct.argv = 0;
88 } else {
89 construct.argc = 1;
90 Instruction::LoadRuntimeString load;
91 load.stringId = registerString(text);
92 bytecodeGenerator->addInstruction(load);
93 construct.argv = Reference::fromAccumulator(this).storeOnStack().stackSlot();
94 }
95 Reference r = referenceForName(type, false);
96 r = r.storeOnStack();
97 construct.func = r.stackSlot();
98 bytecodeGenerator->addInstruction(construct);
99 Instruction::ThrowException throwException;
100 bytecodeGenerator->addInstruction(throwException);
101}
102
103Codegen::Codegen(QV4::Compiler::JSUnitGenerator *jsUnitGenerator, bool strict,
104 CodegenWarningInterface *iface, bool storeSourceLocations)
105 : _module(nullptr),
106 _returnAddress(-1),
107 _context(nullptr),
108 _labelledStatement(nullptr),
109 jsUnitGenerator(jsUnitGenerator),
110 _strictMode(strict),
111 storeSourceLocations(storeSourceLocations),
112 _fileNameIsUrl(false),
113 _interface(iface)
114{
115 jsUnitGenerator->codeGeneratorName = QStringLiteral("moth");
116 pushExpr();
117}
118
119static constexpr const QLatin1StringView s_globalNames[] = {
120 QLatin1StringView("Array"),
121 QLatin1StringView("ArrayBuffer"),
122 QLatin1StringView("Atomics"),
123 QLatin1StringView("Boolean"),
124 QLatin1StringView("DOMException"),
125 QLatin1StringView("DataView"),
126 QLatin1StringView("Date"),
127 QLatin1StringView("Error"),
128 QLatin1StringView("EvalError"),
129 QLatin1StringView("Float32Array"),
130 QLatin1StringView("Float64Array"),
131 QLatin1StringView("Function"),
132 QLatin1StringView("Infinity"),
133 QLatin1StringView("Int16Array"),
134 QLatin1StringView("Int32Array"),
135 QLatin1StringView("Int8Array"),
136 QLatin1StringView("JSON"),
137 QLatin1StringView("Map"),
138 QLatin1StringView("Math"),
139 QLatin1StringView("NaN"),
140 QLatin1StringView("Number"),
141 QLatin1StringView("Object"),
142 QLatin1StringView("Promise"),
143 QLatin1StringView("Proxy"),
144 QLatin1StringView("QT_TRANSLATE_NOOP"),
145 QLatin1StringView("QT_TRID_NOOP"),
146 QLatin1StringView("QT_TR_NOOP"),
147 QLatin1StringView("Qt"),
148 QLatin1StringView("RangeError"),
149 QLatin1StringView("ReferenceError"),
150 QLatin1StringView("Reflect"),
151 QLatin1StringView("RegExp"),
152 QLatin1StringView("SQLException"),
153 QLatin1StringView("Set"),
154 QLatin1StringView("SharedArrayBuffer"),
155 QLatin1StringView("String"),
156 QLatin1StringView("Symbol"),
157 QLatin1StringView("SyntaxError"),
158 QLatin1StringView("TypeError"),
159 QLatin1StringView("URIError"),
160 QLatin1StringView("URL"),
161 QLatin1StringView("URLSearchParams"),
162 QLatin1StringView("Uint16Array"),
163 QLatin1StringView("Uint32Array"),
164 QLatin1StringView("Uint8Array"),
165 QLatin1StringView("Uint8ClampedArray"),
166 QLatin1StringView("WeakMap"),
167 QLatin1StringView("WeakSet"),
168 QLatin1StringView("XMLHttpRequest"),
169 QLatin1StringView("console"),
170 QLatin1StringView("decodeURI"),
171 QLatin1StringView("decodeURIComponent"),
172 QLatin1StringView("encodeURI"),
173 QLatin1StringView("encodeURIComponent"),
174 QLatin1StringView("escape"),
175 QLatin1StringView("eval"),
176 QLatin1StringView("gc"),
177 QLatin1StringView("isFinite"),
178 QLatin1StringView("isNaN"),
179 QLatin1StringView("parseFloat"),
180 QLatin1StringView("parseInt"),
181 QLatin1StringView("print"),
182 QLatin1StringView("qsTr"),
183 QLatin1StringView("qsTrId"),
184 QLatin1StringView("qsTranslate"),
185 QLatin1StringView("undefined"),
186 QLatin1StringView("unescape"),
187};
188
189bool Codegen::isNameGlobal(QAnyStringView name)
190{
191 return std::binary_search(std::begin(s_globalNames), std::end(s_globalNames), name);
192}
193
194/*!
195 * \internal
196 * Returns true if \a name is one of the global names that are resolved before anything else,
197 * including the context object. These are the names the engine provides as keywords.
198 */
199bool Codegen::isNameKeyword(QAnyStringView name)
200{
201 static constexpr QLatin1StringView s_keywordNames[] = {
202 QLatin1StringView("Infinity"),
203 QLatin1StringView("NaN"),
204 QLatin1StringView("QT_TRANSLATE_NOOP"),
205 QLatin1StringView("QT_TRID_NOOP"),
206 QLatin1StringView("QT_TR_NOOP"),
207 QLatin1StringView("qsTr"),
208 QLatin1StringView("qsTrId"),
209 QLatin1StringView("qsTranslate"),
210 QLatin1StringView("undefined"),
211 };
212 return std::binary_search(std::begin(s_keywordNames), std::end(s_keywordNames), name);
213}
214
215void Codegen::forEachGlobalName(qxp::function_ref<void (QLatin1StringView)> &&handler)
216{
217 for (QLatin1StringView name : s_globalNames)
218 handler(name);
219}
220
221void Codegen::generateFromProgram(
222 const QString &sourceCode, Program *node, Module *module, ContextType contextType)
223{
224 Q_ASSERT(node);
225
226 _module = module;
227 _context = nullptr;
228
229 ScanFunctions scan(this, sourceCode, contextType);
230 scan(node);
231
232 if (hasError())
233 return;
234
235 defineFunction(QStringLiteral("%entry"), node, nullptr, node->statements);
236}
237
238void Codegen::generateFromModule(const QString &sourceCode, ESModule *node, Module *module)
239{
240 Q_ASSERT(node);
241
242 _module = module;
243 _context = nullptr;
244
245 ScanFunctions scan(this, sourceCode, ContextType::ESModule);
246 scan(node);
247
248 if (hasError())
249 return;
250
251 {
252 Compiler::Context *moduleContext = _module->contextMap.value(node);
253 for (const auto &entry: std::as_const(moduleContext->exportEntries)) {
254 if (entry.moduleRequest.isEmpty()) {
255 // ### check against imported bound names
256 _module->localExportEntries << entry;
257 } else if (entry.importName == QLatin1Char('*')) {
258 _module->starExportEntries << entry;
259 } else {
260 _module->indirectExportEntries << entry;
261 }
262 }
263 _module->importEntries = moduleContext->importEntries;
264
265 _module->moduleRequests = std::move(moduleContext->moduleRequests);
266 _module->moduleRequests.removeDuplicates();
267 }
268
269 std::sort(_module->localExportEntries.begin(), _module->localExportEntries.end(), ExportEntry::lessThan);
270 std::sort(_module->starExportEntries.begin(), _module->starExportEntries.end(), ExportEntry::lessThan);
271 std::sort(_module->indirectExportEntries.begin(), _module->indirectExportEntries.end(), ExportEntry::lessThan);
272
273 defineFunction(QStringLiteral("%entry"), node, nullptr, node->body);
274}
275
276void Codegen::generateFromModule(const Value &value, Module *module)
277{
278 _module = module;
279 _context = nullptr;
280
281 _module->newContext(nullptr, nullptr, ContextType::ESModule);
282 enterContext(nullptr);
283
284 _context->name = QStringLiteral("%entry");
285 _module->functions.append(_context);
286 _context->functionIndex = _module->functions.size() - 1;
287
288 ExportEntry entry;
289 entry.localName = entry.exportName = QLatin1String("default");
290 _module->localExportEntries << entry;
291
292 if (Object *o = value.objectValue()) {
293 QV4::Scope scope(o);
294 QV4::ObjectIterator it(scope, o, QV4::ObjectIterator::EnumerableOnly);
295 QV4::PropertyAttributes attrs;
296 QV4::ScopedPropertyKey name(scope);
297 while (true) {
298 name = it.next(nullptr, &attrs);
299 if (!name->isValid())
300 break;
301
302 ExportEntry entry;
303 entry.localName = entry.exportName = name->toQString();
304 _module->localExportEntries << entry;
305 }
306 }
307
308 std::sort(_module->localExportEntries.begin(), _module->localExportEntries.end(),
309 ExportEntry::lessThan);
310
311 for (auto it = _module->localExportEntries.cbegin(), end = _module->localExportEntries.cend();
312 it != end; ++it) {
313 Context::Member member;
314 member.index = _context->locals.size();
315 _context->locals.append(it->exportName);
316 _context->members.insert(it->exportName, member);
317 }
318
319 leaveContext();
320}
321
322void Codegen::enterContext(Node *node)
323{
324 _context = _module->contextMap.value(node);
325 Q_ASSERT(_context);
326}
327
328int Codegen::leaveContext()
329{
330 Q_ASSERT(_context);
331 int functionIndex = _context->functionIndex;
332 _context = _context->parent;
333 return functionIndex;
334}
335
336Context *Codegen::enterBlock(Node *node)
337{
338 enterContext(node);
339 return _context;
340}
341
342Codegen::Reference Codegen::unop(UnaryOperation op, const Reference &expr)
343{
344 if (hasError())
345 return exprResult();
346
347 if (expr.isConstant()) {
348 auto v = StaticValue::fromReturnedValue(expr.constant);
349 if (v.isNumber()) {
350 switch (op) {
351 case Not:
352 return Reference::fromConst(this, Encode(!v.toBoolean()));
353 case UMinus:
354 // This duplicates some of the logic from Runtime::UMinus::call()
355 ReturnedValue r;
356 if (v.isInteger()) {
357 int intVal = v.integerValue();
358 if (intVal && intVal != std::numeric_limits<int>::min())
359 r = QV4::Encode(-intVal);
360 else
361 r = QV4::Encode(-double(intVal));
362 } else if (v.isDouble()) {
363 r = QV4::Encode(-v.doubleValue());
364 } else {
365 r = QV4::Encode(-v.int_32());
366 }
367 return Reference::fromConst(this, r);
368 case UPlus:
369 return expr;
370 case Compl:
371 return Reference::fromConst(this, Encode((int)~v.toInt32()));
372 default:
373 break;
374 }
375 }
376 }
377
378 switch (op) {
379 case UMinus: {
380 expr.loadInAccumulator();
381 Instruction::UMinus uminus = {};
382 bytecodeGenerator->addInstruction(uminus);
383 return Reference::fromAccumulator(this);
384 }
385 case UPlus: {
386 expr.loadInAccumulator();
387 Instruction::UPlus uplus = {};
388 bytecodeGenerator->addInstruction(uplus);
389 return Reference::fromAccumulator(this);
390 }
391 case Not: {
392 expr.loadInAccumulator();
393 Instruction::UNot unot;
394 bytecodeGenerator->addInstruction(unot);
395 return Reference::fromAccumulator(this);
396 }
397 case Compl: {
398 expr.loadInAccumulator();
399 Instruction::UCompl ucompl;
400 bytecodeGenerator->addInstruction(ucompl);
401 return Reference::fromAccumulator(this);
402 }
403 case PostIncrement:
404 if (!exprAccept(nx) || requiresReturnValue) {
405 Reference e = expr.asLValue();
406 e.loadInAccumulator();
407 Instruction::UPlus uplus = {};
408 bytecodeGenerator->addInstruction(uplus);
409 Reference originalValue = Reference::fromStackSlot(this).storeRetainAccumulator();
410 Instruction::Increment inc = {};
411 bytecodeGenerator->addInstruction(inc);
412 e.storeConsumeAccumulator();
413 return originalValue;
414 } else {
415 // intentionally fall-through: the result is never used, so it's equivalent to
416 // "expr += 1", which is what a pre-increment does as well.
417 Q_FALLTHROUGH();
418 }
419 case PreIncrement: {
420 Reference e = expr.asLValue();
421 e.loadInAccumulator();
422 e.isReadonly = true;
423 Instruction::Increment inc = {};
424 bytecodeGenerator->addInstruction(inc);
425 if (exprAccept(nx))
426 return e.storeConsumeAccumulator();
427 else
428 return e.storeRetainAccumulator();
429 }
430 case PostDecrement:
431 if (!exprAccept(nx) || requiresReturnValue) {
432 Reference e = expr.asLValue();
433 e.loadInAccumulator();
434 Instruction::UPlus uplus = {};
435 bytecodeGenerator->addInstruction(uplus);
436 Reference originalValue = Reference::fromStackSlot(this).storeRetainAccumulator();
437 Instruction::Decrement dec = {};
438 bytecodeGenerator->addInstruction(dec);
439 e.storeConsumeAccumulator();
440 return originalValue;
441 } else {
442 // intentionally fall-through: the result is never used, so it's equivalent to
443 // "expr -= 1", which is what a pre-decrement does as well.
444 Q_FALLTHROUGH();
445 }
446 case PreDecrement: {
447 Reference e = expr.asLValue();
448 e.loadInAccumulator();
449 e.isReadonly = true;
450 Instruction::Decrement dec = {};
451 bytecodeGenerator->addInstruction(dec);
452 if (exprAccept(nx))
453 return e.storeConsumeAccumulator();
454 else
455 return e.storeRetainAccumulator();
456 }
457 }
458
459 Q_UNREACHABLE();
460}
461
462void Codegen::addCJump()
463{
464 const Result &expression = currentExpr();
465 bytecodeGenerator->addCJumpInstruction(expression.trueBlockFollowsCondition(),
466 expression.iftrue(), expression.iffalse());
467}
468
469void Codegen::statement(Statement *ast)
470{
471 RegisterScope scope(this);
472
473 bytecodeGenerator->incrementStatement();
474 bytecodeGenerator->setLocation(ast->firstSourceLocation());
475
476 VolatileMemoryLocations vLocs = scanVolatileMemoryLocations(ast);
477 qSwap(_volatileMemoryLocations, vLocs);
478 accept(ast);
479 qSwap(_volatileMemoryLocations, vLocs);
480}
481
482void Codegen::statement(ExpressionNode *ast)
483{
484 if (! ast) {
485 return;
486 } else {
487 RegisterScope scope(this);
488
489 bytecodeGenerator->incrementStatement();
490 pushExpr(Result(nx));
491 VolatileMemoryLocations vLocs = scanVolatileMemoryLocations(ast);
492 qSwap(_volatileMemoryLocations, vLocs);
493
494 accept(ast);
495
496 qSwap(_volatileMemoryLocations, vLocs);
497 Reference result = popResult();
498
499 if (hasError())
500 return;
501 if (result.loadTriggersSideEffect())
502 result.loadInAccumulator(); // triggers side effects
503 }
504}
505
506void Codegen::condition(ExpressionNode *ast, const BytecodeGenerator::Label *iftrue,
507 const BytecodeGenerator::Label *iffalse, bool trueBlockFollowsCondition)
508{
509 if (hasError())
510 return;
511
512 if (!ast)
513 return;
514
515 pushExpr(Result(iftrue, iffalse, trueBlockFollowsCondition));
516 accept(ast);
517 Result r = popExpr();
518
519 if (hasError())
520 return;
521
522 if (r.format() == ex) {
523 Q_ASSERT(iftrue == r.iftrue());
524 Q_ASSERT(iffalse == r.iffalse());
525 Q_ASSERT(r.result().isValid());
526 bytecodeGenerator->setLocation(ast->firstSourceLocation());
527 r.result().loadInAccumulator();
528 if (r.trueBlockFollowsCondition())
529 bytecodeGenerator->jumpFalse().link(*r.iffalse());
530 else
531 bytecodeGenerator->jumpTrue().link(*r.iftrue());
532 }
533}
534
535void Codegen::program(Program *ast)
536{
537 if (ast) {
538 statementList(ast->statements);
539 }
540}
541
547
548static CompletionState completionState(StatementList *list)
549{
550 for (StatementList *it = list; it; it = it->next) {
551 if (it->statement->kind == Statement::Kind_BreakStatement ||
552 it->statement->kind == Statement::Kind_ContinueStatement)
554 if (it->statement->kind == Statement::Kind_EmptyStatement ||
555 it->statement->kind == Statement::Kind_VariableDeclaration ||
556 it->statement->kind == Statement::Kind_FunctionDeclaration)
557 continue;
558 if (it->statement->kind == Statement::Kind_Block) {
559 CompletionState subState = completionState(static_cast<Block *>(it->statement)->statements);
560 if (subState != CompletionState::Empty)
561 return subState;
562 continue;
563 }
565 }
567}
568
569static Node *completionStatement(StatementList *list)
570{
571 Node *completionStatement = nullptr;
572 for (StatementList *it = list; it; it = it->next) {
573 if (it->statement->kind == Statement::Kind_BreakStatement ||
574 it->statement->kind == Statement::Kind_ContinueStatement)
575 return completionStatement;
576 if (it->statement->kind == Statement::Kind_ThrowStatement ||
577 it->statement->kind == Statement::Kind_ReturnStatement)
578 return it->statement;
579 if (it->statement->kind == Statement::Kind_EmptyStatement ||
580 it->statement->kind == Statement::Kind_VariableStatement ||
581 it->statement->kind == Statement::Kind_FunctionDeclaration)
582 continue;
583 if (it->statement->kind == Statement::Kind_Block) {
584 CompletionState state = completionState(static_cast<Block *>(it->statement)->statements);
585 switch (state) {
587 continue;
589 return it->statement;
591 break;
592 }
593 }
594 completionStatement = it->statement;
595 }
596 return completionStatement;
597}
598
599void Codegen::statementList(StatementList *ast)
600{
601 if (!ast)
602 return;
603
604 bool _requiresReturnValue = requiresReturnValue;
605 // ### the next line is pessimizing a bit too much, as there are many cases, where the complietion from the break
606 // statement will not be used, but it's at least spec compliant
607 if (!controlFlow || !controlFlow->hasLoop())
608 requiresReturnValue = false;
609
610 Node *needsCompletion = nullptr;
611
612 if (_requiresReturnValue && !requiresReturnValue)
613 needsCompletion = completionStatement(ast);
614
615 if (requiresReturnValue && !needsCompletion && !insideSwitch) {
616 // break or continue is the first real statement, set the return value to undefined
617 Reference::fromConst(this, Encode::undefined()).storeOnStack(_returnAddress);
618 }
619
620 bool _insideSwitch = insideSwitch;
621 insideSwitch = false;
622
623 for (StatementList *it = ast; it; it = it->next) {
624 if (it->statement == needsCompletion)
625 requiresReturnValue = true;
626 if (Statement *s = it->statement->statementCast())
627 statement(s);
628 else
629 statement(static_cast<ExpressionNode *>(it->statement));
630 if (it->statement == needsCompletion)
631 requiresReturnValue = false;
632 if (it->statement->kind == Statement::Kind_ThrowStatement
633 || it->statement->kind == Statement::Kind_BreakStatement
634 || it->statement->kind == Statement::Kind_ContinueStatement
635 || it->statement->kind == Statement::Kind_ReturnStatement) {
636
637 if (Visitor *visitor = _interface->unreachableVisitor())
638 Node::accept(it->next, visitor);
639 break;
640 }
641 }
642 requiresReturnValue = _requiresReturnValue;
643 insideSwitch = _insideSwitch;
644}
645
646void Codegen::variableDeclaration(PatternElement *ast)
647{
648 TailCallBlocker blockTailCalls(this);
649 RegisterScope scope(this);
650
651 if (!ast->initializer) {
652 if (ast->isLexicallyScoped()) {
653 Reference::fromConst(this, Encode::undefined()).loadInAccumulator();
654 Reference varToStore = targetForPatternElement(ast);
655 varToStore.storeConsumeAccumulator();
656 }
657 return;
658 }
659 initializeAndDestructureBindingElement(ast, Reference(), /*isDefinition*/ true);
660}
661
662void Codegen::variableDeclarationList(VariableDeclarationList *ast)
663{
664 for (VariableDeclarationList *it = ast; it; it = it->next) {
665 variableDeclaration(it->declaration);
666 }
667}
668
669Codegen::Reference Codegen::targetForPatternElement(AST::PatternElement *p)
670{
671 if (!p->bindingIdentifier.isNull())
672 return referenceForName(p->bindingIdentifier.toString(), true, p->firstSourceLocation());
673 if (!p->bindingTarget || p->destructuringPattern())
674 return Codegen::Reference::fromStackSlot(this);
675 Reference lhs = expression(p->bindingTarget);
676 if (hasError())
677 return lhs;
678 if (!lhs.isLValue()) {
679 throwReferenceError(p->bindingTarget->firstSourceLocation(), QStringLiteral("Binding target is not a reference."));
680 return lhs;
681 }
682 lhs = lhs.asLValue();
683 return lhs;
684}
685
686// Returns a reference to the raw value passed positionally for the argIndex'th
687// formal parameter, independent of whatever the parameter's own name currently
688// resolves to. This is needed when a parameter is promoted to a real member for
689// TDZ tracking. See Context::promoteFormalParameterForTDZ.
690Codegen::Reference Codegen::referenceForFormalParameter(int argIndex)
691{
692 if (_context->argumentsCanEscape)
693 return Reference::fromScopedLocal(this, argIndex + _context->locals.size(), 0);
694 const int index = argIndex + int(sizeof(CallData) / sizeof(StaticValue)) - 1;
695 return Reference::fromStackSlot(this, index, true);
696}
697
698void Codegen::initializeAndDestructureBindingElement(AST::PatternElement *e, const Reference &base, bool isDefinition)
699{
700 Q_ASSERT(e->type == AST::PatternElement::Binding || e->type == AST::PatternElement::RestElement);
701 RegisterScope scope(this);
702 Reference baseRef = (base.isAccumulator()) ? base.storeOnStack() : base;
703 Reference varToStore = targetForPatternElement(e);
704 if (isDefinition)
705 varToStore.isReferenceToConst = false;
706 if (hasError())
707 return;
708
709 if (e->typeAnnotation) {
710 throwSyntaxError(e->firstSourceLocation(),
711 QLatin1String("Type annotations on default parameters are not supported."));
712 }
713
714 const auto loadValueForStore = [&](const Reference &value) {
715 if (isDefinition || !varToStore.requiresTDZCheck) {
716 value.loadInAccumulator();
717 return;
718 }
719 Reference stashed = value.storeOnStack();
720 varToStore.checkTDZBeforeAssignment();
721 stashed.loadInAccumulator();
722 };
723
724 if (e->initializer) {
725 if (!baseRef.isValid()) {
726 // assignment
727 Reference expr = expression(e->initializer);
728 if (hasError())
729 return;
730 loadValueForStore(expr);
731 varToStore.storeConsumeAccumulator();
732 } else if (baseRef == varToStore) {
733 baseRef.loadInAccumulator();
734 BytecodeGenerator::Jump jump = bytecodeGenerator->jumpNotUndefined();
735 Reference expr = expression(e->initializer);
736 if (hasError()) {
737 jump.link();
738 return;
739 }
740 loadValueForStore(expr);
741 varToStore.storeConsumeAccumulator();
742 jump.link();
743 } else {
744 baseRef.loadInAccumulator();
745 BytecodeGenerator::Jump jump = bytecodeGenerator->jumpNotUndefined();
746 Reference expr = expression(e->initializer);
747 if (hasError()) {
748 jump.link();
749 return;
750 }
751 expr.loadInAccumulator();
752 jump.link();
753 loadValueForStore(Reference::fromAccumulator(this));
754 varToStore.storeConsumeAccumulator();
755 }
756 } else if (baseRef != varToStore && baseRef.isValid()) {
757 loadValueForStore(baseRef);
758 varToStore.storeConsumeAccumulator();
759 }
760 Pattern *p = e->destructuringPattern();
761 if (!p)
762 return;
763
764 if (!varToStore.isStackSlot())
765 varToStore = varToStore.storeOnStack();
766 if (PatternElementList *l = e->elementList()) {
767 destructureElementList(varToStore, l, isDefinition);
768 } else if (PatternPropertyList *p = e->propertyList()) {
769 destructurePropertyList(varToStore, p, isDefinition);
770 } else if (e->bindingTarget) {
771 // empty binding pattern. For spec compatibility, try to coerce the argument to an object
772 varToStore.loadInAccumulator();
773 Instruction::ToObject toObject;
774 bytecodeGenerator->addInstruction(toObject);
775 return;
776 }
777}
778
779Codegen::Reference Codegen::referenceForPropertyName(const Codegen::Reference &object, AST::PropertyName *name)
780{
781 AST::ComputedPropertyName *cname = AST::cast<AST::ComputedPropertyName *>(name);
782 Reference property;
783 if (cname) {
784 Reference computedName = expression(cname->expression);
785 if (hasError())
786 return Reference();
787 computedName = computedName.storeOnStack();
788 property = Reference::fromSubscript(object, computedName).asLValue();
789 } else {
790 QString propertyName = name->asString();
791 property = Reference::fromMember(object, propertyName);
792 }
793 return property;
794}
795
796void Codegen::destructurePropertyList(const Codegen::Reference &object, PatternPropertyList *bindingList, bool isDefinition)
797{
798 RegisterScope scope(this);
799
800 object.loadInAccumulator();
801 Instruction::ThrowOnNullOrUndefined t;
802 bytecodeGenerator->addInstruction(t);
803
804 for (PatternPropertyList *it = bindingList; it; it = it->next) {
805 PatternProperty *p = it->property;
806 RegisterScope scope(this);
807 Reference property = referenceForPropertyName(object, p->name);
808 if (hasError())
809 return;
810 initializeAndDestructureBindingElement(p, property, isDefinition);
811 if (hasError())
812 return;
813 }
814}
815
816void Codegen::destructureElementList(const Codegen::Reference &array, PatternElementList *bindingList, bool isDefinition)
817{
818 RegisterScope scope(this);
819
820 Reference iterator = Reference::fromStackSlot(this);
821 QVarLengthArray<Reference, 32> iteratorValues;
822 Reference ignored;
823
824 array.loadInAccumulator();
825 Instruction::GetIterator iteratorObjInstr;
826 iteratorObjInstr.iterator = static_cast<int>(AST::ForEachType::Of);
827 bytecodeGenerator->addInstruction(iteratorObjInstr);
828 iterator.storeConsumeAccumulator();
829
830 BytecodeGenerator::Label done = bytecodeGenerator->newLabel();
831 Reference needsClose = Reference::storeConstOnStack(this, Encode(false));
832
833 for (PatternElementList *p = bindingList; p; p = p->next) {
834 PatternElement *e = p->element;
835 for (Elision *elision = p->elision; elision; elision = elision->next) {
836 iterator.loadInAccumulator();
837 Instruction::IteratorNext next;
838 if (!ignored.isValid())
839 ignored = Reference::fromStackSlot(this);
840 next.value = ignored.stackSlot();
841 bytecodeGenerator->addJumpInstruction(next).link(done);
842 }
843
844 if (!e)
845 continue;
846
847 if (e->type != PatternElement::RestElement) {
848 iterator.loadInAccumulator();
849 Instruction::IteratorNext next;
850 iteratorValues.push_back(Reference::fromStackSlot(this));
851 next.value = iteratorValues.back().stackSlot();
852 bytecodeGenerator->addJumpInstruction(next).link(done);
853 }
854 }
855
856 // If we've iterated through all the patterns without exhausing the iterator, it needs
857 // to be closed. But we don't close it here because:
858 // a, closing might throw an exception and we want to assign the values before we handle that
859 // b, there might be a rest element that could still continue iterating
860 Reference::fromConst(this, Encode(true)).storeOnStack(needsClose.stackSlot());
861
862 done.link();
863 bytecodeGenerator->checkException();
864
865 {
866 ControlFlowUnwindCleanup flow(this, [&]() {
867 BytecodeGenerator::Label skipClose = bytecodeGenerator->newLabel();
868 needsClose.loadInAccumulator();
869 bytecodeGenerator->jumpFalse().link(skipClose);
870 iterator.loadInAccumulator();
871 Instruction::IteratorClose close;
872 bytecodeGenerator->addInstruction(close);
873 skipClose.link();
874 });
875
876 auto it = iteratorValues.constBegin();
877 for (PatternElementList *p = bindingList; p; p = p->next) {
878 PatternElement *e = p->element;
879
880 if (!e)
881 continue;
882
883 if (e->type == PatternElement::RestElement) {
884 Q_ASSERT(it == iteratorValues.constEnd());
885
886 // The rest element is guaranteed to exhaust the iterator
887 Reference::fromConst(this, Encode(false)).storeOnStack(needsClose.stackSlot());
888
889 iterator.loadInAccumulator();
890 bytecodeGenerator->addInstruction(Instruction::DestructureRestElement());
891 initializeAndDestructureBindingElement(
892 e, Reference::fromAccumulator(this), isDefinition);
893 } else {
894 Q_ASSERT(it != iteratorValues.constEnd());
895 initializeAndDestructureBindingElement(e, *it++, isDefinition);
896 }
897
898 if (hasError())
899 return;
900 }
901 }
902}
903
904void Codegen::destructurePattern(Pattern *p, const Reference &rhs)
905{
906 RegisterScope scope(this);
907 if (auto *o = AST::cast<ObjectPattern *>(p))
908 destructurePropertyList(rhs, o->properties);
909 else if (auto *a = AST::cast<ArrayPattern *>(p))
910 destructureElementList(rhs, a->elements);
911 else
912 Q_UNREACHABLE();
913}
914
915
916bool Codegen::visit(ArgumentList *)
917{
918 Q_UNREACHABLE_RETURN(false);
919}
920
921bool Codegen::visit(CaseBlock *)
922{
923 Q_UNREACHABLE_RETURN(false);
924}
925
926bool Codegen::visit(CaseClause *)
927{
928 Q_UNREACHABLE_RETURN(false);
929}
930
931bool Codegen::visit(CaseClauses *)
932{
933 Q_UNREACHABLE_RETURN(false);
934}
935
936bool Codegen::visit(Catch *)
937{
938 Q_UNREACHABLE_RETURN(false);
939}
940
941bool Codegen::visit(DefaultClause *)
942{
943 Q_UNREACHABLE_RETURN(false);
944}
945
946bool Codegen::visit(Elision *)
947{
948 Q_UNREACHABLE_RETURN(false);
949}
950
951bool Codegen::visit(Finally *)
952{
953 Q_UNREACHABLE_RETURN(false);
954}
955
956bool Codegen::visit(FormalParameterList *)
957{
958 Q_UNREACHABLE_RETURN(false);
959}
960
961bool Codegen::visit(Program *)
962{
963 Q_UNREACHABLE_RETURN(false);
964}
965
966bool Codegen::visit(PatternElement *)
967{
968 Q_UNREACHABLE_RETURN(false);
969}
970
971bool Codegen::visit(PatternElementList *)
972{
973 Q_UNREACHABLE_RETURN(false);
974}
975
976bool Codegen::visit(PatternProperty *)
977{
978 Q_UNREACHABLE_RETURN(false);
979}
980
981bool Codegen::visit(PatternPropertyList *)
982{
983 Q_UNREACHABLE_RETURN(false);
984}
985
986bool Codegen::visit(ExportDeclaration *ast)
987{
988 if (!ast->exportDefault)
989 return true;
990
991 TailCallBlocker blockTailCalls(this);
992 Reference exportedValue;
993
994 if (auto *fdecl = AST::cast<FunctionDeclaration*>(ast->variableStatementOrDeclaration)) {
995 pushExpr();
996 visit(static_cast<FunctionExpression*>(fdecl));
997 exportedValue = popResult();
998 } else if (auto *classDecl = AST::cast<ClassDeclaration*>(ast->variableStatementOrDeclaration)) {
999 pushExpr();
1000 visit(static_cast<ClassExpression*>(classDecl));
1001 exportedValue = popResult();
1002 } else if (ExpressionNode *expr = ast->variableStatementOrDeclaration->expressionCast()) {
1003 exportedValue = expression(expr);
1004 if (hasError())
1005 return false;
1006 }
1007
1008 exportedValue.loadInAccumulator();
1009
1010 const int defaultExportIndex = _context->locals.indexOf(_context->localNameForDefaultExport);
1011 Q_ASSERT(defaultExportIndex != -1);
1012 Reference defaultExportSlot = Reference::fromScopedLocal(this, defaultExportIndex, /*scope*/0);
1013 defaultExportSlot.storeConsumeAccumulator();
1014
1015 return false;
1016}
1017
1018bool Codegen::visit(TypeAnnotation *ast)
1019{
1020 throwSyntaxError(ast->firstSourceLocation(), QLatin1String("Type annotations are not supported (yet)."));
1021 return false;
1022}
1023
1024bool Codegen::visit(StatementList *)
1025{
1026 Q_UNREACHABLE_RETURN(false);
1027}
1028
1029bool Codegen::visit(UiArrayMemberList *)
1030{
1031 Q_UNREACHABLE_RETURN(false);
1032}
1033
1034bool Codegen::visit(UiImport *)
1035{
1036 Q_UNREACHABLE_RETURN(false);
1037}
1038
1039bool Codegen::visit(UiHeaderItemList *)
1040{
1041 Q_UNREACHABLE_RETURN(false);
1042}
1043
1044bool Codegen::visit(UiPragmaValueList *)
1045{
1046 Q_UNREACHABLE_RETURN(false);
1047}
1048
1049bool Codegen::visit(UiPragma *)
1050{
1051 Q_UNREACHABLE_RETURN(false);
1052}
1053
1054bool Codegen::visit(UiObjectInitializer *)
1055{
1056 Q_UNREACHABLE_RETURN(false);
1057}
1058
1059bool Codegen::visit(UiObjectMemberList *)
1060{
1061 Q_UNREACHABLE_RETURN(false);
1062}
1063
1064bool Codegen::visit(UiParameterList *)
1065{
1066 Q_UNREACHABLE_RETURN(false);
1067}
1068
1069bool Codegen::visit(UiProgram *)
1070{
1071 Q_UNREACHABLE_RETURN(false);
1072}
1073
1074bool Codegen::visit(UiQualifiedId *)
1075{
1076 Q_UNREACHABLE_RETURN(false);
1077}
1078
1079bool Codegen::visit(VariableDeclarationList *)
1080{
1081 Q_UNREACHABLE_RETURN(false);
1082}
1083
1084bool Codegen::visit(ClassExpression *ast)
1085{
1086 TailCallBlocker blockTailCalls(this);
1087
1088 Compiler::Class jsClass;
1089 jsClass.nameIndex = registerString(ast->name.toString());
1090
1091 ClassElementList *constructor = nullptr;
1092 int nComputedNames = 0;
1093 int nStaticComputedNames = 0;
1094
1095 RegisterScope scope(this);
1096 ControlFlowBlock controlFlow(this, ast);
1097
1098 for (auto *member = ast->elements; member; member = member->next) {
1099 PatternProperty *p = member->property;
1100 FunctionExpression *f = p->initializer->asFunctionDefinition();
1101 Q_ASSERT(f);
1102 AST::ComputedPropertyName *cname = AST::cast<ComputedPropertyName *>(p->name);
1103 if (cname) {
1104 ++nComputedNames;
1105 if (member->isStatic)
1106 ++nStaticComputedNames;
1107 }
1108 QString name = p->name->asString();
1109 uint nameIndex = cname ? UINT_MAX : registerString(name);
1110 Compiler::Class::Method::Type type = Compiler::Class::Method::Regular;
1111 if (p->type == PatternProperty::Getter)
1112 type = Compiler::Class::Method::Getter;
1113 else if (p->type == PatternProperty::Setter)
1114 type = Compiler::Class::Method::Setter;
1115 Compiler::Class::Method m{ nameIndex, type, static_cast<uint>(defineFunction(name, f, f->formals, f->body)) };
1116
1117 if (member->isStatic) {
1118 if (name == QStringLiteral("prototype")) {
1119 throwSyntaxError(ast->firstSourceLocation(), QLatin1String("Cannot declare a static method named 'prototype'."));
1120 return false;
1121 }
1122 jsClass.staticMethods << m;
1123 } else {
1124 if (name == QStringLiteral("constructor")) {
1125 if (constructor) {
1126 throwSyntaxError(ast->firstSourceLocation(), QLatin1String("Cannot declare a multiple constructors in a class."));
1127 return false;
1128 }
1129 if (m.type != Compiler::Class::Method::Regular) {
1130 throwSyntaxError(ast->firstSourceLocation(), QLatin1String("Cannot declare a getter or setter named 'constructor'."));
1131 return false;
1132 }
1133 constructor = member;
1134 jsClass.constructorIndex = m.functionIndex;
1135 continue;
1136 }
1137
1138 jsClass.methods << m;
1139 }
1140 }
1141
1142 int classIndex = _module->classes.size();
1143 _module->classes.append(jsClass);
1144
1145 Reference heritage = Reference::fromStackSlot(this);
1146 if (ast->heritage) {
1147 bytecodeGenerator->setLocation(ast->heritage->firstSourceLocation());
1148 Reference r = expression(ast->heritage);
1149 if (hasError())
1150 return false;
1151 r.storeOnStack(heritage.stackSlot());
1152 } else {
1153 Reference::fromConst(this, StaticValue::emptyValue().asReturnedValue()).loadInAccumulator();
1154 heritage.storeConsumeAccumulator();
1155 }
1156
1157 int computedNames = nComputedNames ? bytecodeGenerator->newRegisterArray(nComputedNames) : 0;
1158 int currentStaticName = computedNames;
1159 int currentNonStaticName = computedNames + nStaticComputedNames;
1160
1161 for (auto *member = ast->elements; member; member = member->next) {
1162 AST::ComputedPropertyName *cname = AST::cast<AST::ComputedPropertyName *>(member->property->name);
1163 if (!cname)
1164 continue;
1165 RegisterScope scope(this);
1166 bytecodeGenerator->setLocation(cname->firstSourceLocation());
1167 Reference computedName = expression(cname->expression);
1168 if (hasError())
1169 return false;
1170 computedName.storeOnStack(member->isStatic ? currentStaticName++ : currentNonStaticName++);
1171 }
1172
1173 Instruction::CreateClass createClass;
1174 createClass.classIndex = classIndex;
1175 createClass.heritage = heritage.stackSlot();
1176 createClass.computedNames = computedNames;
1177
1178 bytecodeGenerator->addInstruction(createClass);
1179
1180 if (!ast->name.isEmpty()) {
1181 Reference ctor = referenceForName(ast->name.toString(), true);
1182 ctor.isReferenceToConst = false; // this is the definition
1183 (void) ctor.storeRetainAccumulator();
1184 }
1185
1186 setExprResult(Reference::fromAccumulator(this));
1187 return false;
1188}
1189
1190bool Codegen::visit(ClassDeclaration *ast)
1191{
1192 TailCallBlocker blockTailCalls(this);
1193 Reference outerVar = referenceForName(ast->name.toString(), true);
1194 visit(static_cast<ClassExpression *>(ast));
1195 (void) outerVar.storeRetainAccumulator();
1196 return false;
1197}
1198
1199bool Codegen::visit(CommaExpression *ast)
1200{
1201 if (hasError())
1202 return false;
1203
1204 TailCallBlocker blockTailCalls(this);
1205 statement(ast->left);
1206 blockTailCalls.unblock();
1207 clearExprResultName(); // The name only holds for the left part
1208 accept(ast->right);
1209 return false;
1210}
1211
1212bool Codegen::visit(ArrayPattern *ast)
1213{
1214 if (hasError())
1215 return false;
1216
1217 TailCallBlocker blockTailCalls(this);
1218
1219 PatternElementList *it = ast->elements;
1220
1221 int argc = 0;
1222 {
1223 RegisterScope scope(this);
1224
1225 int args = -1;
1226 auto push = [this, &argc, &args](AST::ExpressionNode *arg) {
1227 int temp = bytecodeGenerator->newRegister();
1228 if (args == -1)
1229 args = temp;
1230 if (!arg) {
1231 auto c = Reference::fromConst(this, StaticValue::emptyValue().asReturnedValue());
1232 (void) c.storeOnStack(temp);
1233 } else {
1234 RegisterScope scope(this);
1235 Reference r = expression(arg);
1236 if (hasError())
1237 return;
1238 (void) r.storeOnStack(temp);
1239 }
1240 ++argc;
1241 };
1242
1243 for (; it; it = it->next) {
1244 PatternElement *e = it->element;
1245 if (e && e->type == PatternElement::SpreadElement)
1246 break;
1247 for (Elision *elision = it->elision; elision; elision = elision->next)
1248 push(nullptr);
1249
1250 if (!e)
1251 continue;
1252
1253 push(e->initializer);
1254 if (hasError())
1255 return false;
1256 }
1257
1258 if (args == -1) {
1259 Q_ASSERT(argc == 0);
1260 args = 0;
1261 }
1262
1263 Instruction::DefineArray call;
1264 call.argc = argc;
1265 call.args = Moth::StackSlot::createRegister(args);
1266 bytecodeGenerator->addInstruction(call);
1267 }
1268
1269 if (!it) {
1270 setExprResult(Reference::fromAccumulator(this));
1271 return false;
1272 }
1273 Q_ASSERT(it->element && it->element->type == PatternElement::SpreadElement);
1274
1275 RegisterScope scope(this);
1276 Reference array = Reference::fromStackSlot(this);
1277 array.storeConsumeAccumulator();
1278 Reference index = Reference::storeConstOnStack(this, Encode(argc));
1279
1280 auto pushAccumulator = [&]() {
1281 Reference slot = Reference::fromSubscript(array, index);
1282 slot.storeConsumeAccumulator();
1283
1284 index.loadInAccumulator();
1285 Instruction::Increment inc = {};
1286 bytecodeGenerator->addInstruction(inc);
1287 index.storeConsumeAccumulator();
1288 };
1289
1290 while (it) {
1291 for (Elision *elision = it->elision; elision; elision = elision->next) {
1292 Reference::fromConst(
1293 this, StaticValue::emptyValue().asReturnedValue()).loadInAccumulator();
1294 pushAccumulator();
1295 }
1296
1297 if (!it->element) {
1298 it = it->next;
1299 continue;
1300 }
1301
1302 // handle spread element
1303 if (it->element->type == PatternElement::SpreadElement) {
1304 RegisterScope scope(this);
1305
1306 Reference iterator = Reference::fromStackSlot(this);
1307 Reference lhsValue = Reference::fromStackSlot(this);
1308
1309 // There should be a temporal block, so that variables declared in lhs shadow outside vars.
1310 // This block should define a temporal dead zone for those variables, which is not yet implemented.
1311 {
1312 RegisterScope innerScope(this);
1313 Reference expr = expression(it->element->initializer);
1314 if (hasError())
1315 return false;
1316
1317 expr.loadInAccumulator();
1318 Instruction::GetIterator iteratorObjInstr;
1319 iteratorObjInstr.iterator = static_cast<int>(AST::ForEachType::Of);
1320 bytecodeGenerator->addInstruction(iteratorObjInstr);
1321 iterator.storeConsumeAccumulator();
1322 }
1323
1324 BytecodeGenerator::Label in = bytecodeGenerator->newLabel();
1325 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
1326 BytecodeGenerator::Label done = bytecodeGenerator->newLabel();
1327
1328 {
1329 auto cleanup = [this, iterator, done]() {
1330 iterator.loadInAccumulator();
1331 Instruction::IteratorClose close;
1332 bytecodeGenerator->addInstruction(close);
1333 done.link();
1334 };
1335 ControlFlowLoop flow(this, &end, &in, std::move(cleanup));
1336
1337 in.link();
1338 bytecodeGenerator->addLoopStart(in);
1339 iterator.loadInAccumulator();
1340 Instruction::IteratorNext next;
1341 next.value = lhsValue.stackSlot();
1342 bytecodeGenerator->addJumpInstruction(next).link(done);
1343
1344 lhsValue.loadInAccumulator();
1345 pushAccumulator();
1346
1347 bytecodeGenerator->checkException();
1348 bytecodeGenerator->jump().link(in);
1349 end.link();
1350 }
1351 } else {
1352 RegisterScope innerScope(this);
1353 Reference expr = expression(it->element->initializer);
1354 if (hasError())
1355 return false;
1356
1357 expr.loadInAccumulator();
1358 pushAccumulator();
1359 }
1360
1361 it = it->next;
1362 }
1363
1364 array.loadInAccumulator();
1365 setExprResult(Reference::fromAccumulator(this));
1366
1367 return false;
1368}
1369
1370bool Codegen::visit(ArrayMemberExpression *ast)
1371{
1372 if (hasError())
1373 return false;
1374
1375 const bool isTailOfChain = traverseOptionalChain(ast);
1376
1377 TailCallBlocker blockTailCalls(this);
1378 Reference base = expression(ast->base);
1379 if (hasError())
1380 return false;
1381
1382 auto writeSkip = [&]() {
1383 base.loadInAccumulator();
1384 bytecodeGenerator->addInstruction(Instruction::CmpEqNull());
1385 auto jumpToUndefined = bytecodeGenerator->jumpTrue();
1386 m_optionalChainsStates->top().jumpsToPatch.emplace_back(std::move(jumpToUndefined));
1387 };
1388
1389 if (base.isSuper()) {
1390 auto e = expression(ast->expression);
1391 if (hasError())
1392 return false;
1393 Reference index = e.storeOnStack();
1394 optionalChainFinalizer(Reference::fromSuperProperty(index), isTailOfChain);
1395 return false;
1396 }
1397 base = base.storeOnStack();
1398 if (hasError())
1399 return false;
1400 if (AST::StringLiteral *str = AST::cast<AST::StringLiteral *>(ast->expression)) {
1401 QString s = str->value.toString();
1402 uint arrayIndex = stringToArrayIndex(s);
1403 if (arrayIndex == UINT_MAX) {
1404 auto ref = Reference::fromMember(base, s, ast->expression->firstSourceLocation(),
1405 ast->isOptional,
1406 &m_optionalChainsStates->top().jumpsToPatch);
1407 setExprResult(ref);
1408 optionalChainFinalizer(ref, isTailOfChain);
1409 return false;
1410 }
1411
1412 if (ast->isOptional)
1413 writeSkip();
1414
1415 Reference index = Reference::fromConst(this, QV4::Encode(arrayIndex));
1416 optionalChainFinalizer(Reference::fromSubscript(base, index), isTailOfChain);
1417 return false;
1418 }
1419
1420
1421 if (ast->isOptional)
1422 writeSkip();
1423
1424 Reference index = expression(ast->expression);
1425
1426 if (hasError())
1427 return false;
1428
1429 optionalChainFinalizer(Reference::fromSubscript(base, index), isTailOfChain);
1430 return false;
1431}
1432
1433static QSOperator::Op baseOp(int op)
1434{
1435 switch ((QSOperator::Op) op) {
1436 case QSOperator::InplaceAnd: return QSOperator::BitAnd;
1437 case QSOperator::InplaceSub: return QSOperator::Sub;
1438 case QSOperator::InplaceDiv: return QSOperator::Div;
1439 case QSOperator::InplaceAdd: return QSOperator::Add;
1440 case QSOperator::InplaceLeftShift: return QSOperator::LShift;
1441 case QSOperator::InplaceMod: return QSOperator::Mod;
1442 case QSOperator::InplaceExp: return QSOperator::Exp;
1443 case QSOperator::InplaceMul: return QSOperator::Mul;
1444 case QSOperator::InplaceOr: return QSOperator::BitOr;
1445 case QSOperator::InplaceRightShift: return QSOperator::RShift;
1446 case QSOperator::InplaceURightShift: return QSOperator::URShift;
1447 case QSOperator::InplaceXor: return QSOperator::BitXor;
1448 default: return QSOperator::Invalid;
1449 }
1450}
1451
1452bool Codegen::visit(BinaryExpression *ast)
1453{
1454 if (hasError())
1455 return false;
1456
1457 TailCallBlocker blockTailCalls(this);
1458
1459 if (ast->op == QSOperator::And) {
1460 if (exprAccept(cx)) {
1461 auto iftrue = bytecodeGenerator->newLabel();
1462 condition(ast->left, &iftrue, currentExpr().iffalse(), true);
1463 iftrue.link();
1464 blockTailCalls.unblock();
1465 const Result &expr = currentExpr();
1466 condition(ast->right, expr.iftrue(), expr.iffalse(), expr.trueBlockFollowsCondition());
1467 } else {
1468 auto iftrue = bytecodeGenerator->newLabel();
1469 auto endif = bytecodeGenerator->newLabel();
1470
1471 Reference left = expression(ast->left);
1472 if (hasError())
1473 return false;
1474 left.loadInAccumulator();
1475
1476 bytecodeGenerator->setLocation(ast->operatorToken);
1477 bytecodeGenerator->jumpFalse().link(endif);
1478 iftrue.link();
1479
1480 blockTailCalls.unblock();
1481 Reference right = expression(ast->right);
1482 if (hasError())
1483 return false;
1484 right.loadInAccumulator();
1485
1486 endif.link();
1487
1488 setExprResult(Reference::fromAccumulator(this));
1489 }
1490 return false;
1491 } else if (ast->op == QSOperator::Or) {
1492 if (exprAccept(cx)) {
1493 auto iffalse = bytecodeGenerator->newLabel();
1494 condition(ast->left, currentExpr().iftrue(), &iffalse, false);
1495 iffalse.link();
1496 const Result &expr = currentExpr();
1497 condition(ast->right, expr.iftrue(), expr.iffalse(), expr.trueBlockFollowsCondition());
1498 } else {
1499 auto iffalse = bytecodeGenerator->newLabel();
1500 auto endif = bytecodeGenerator->newLabel();
1501
1502 Reference left = expression(ast->left);
1503 if (hasError())
1504 return false;
1505 left.loadInAccumulator();
1506
1507 bytecodeGenerator->setLocation(ast->operatorToken);
1508 bytecodeGenerator->jumpTrue().link(endif);
1509 iffalse.link();
1510
1511 blockTailCalls.unblock();
1512 Reference right = expression(ast->right);
1513 if (hasError())
1514 return false;
1515 right.loadInAccumulator();
1516
1517 endif.link();
1518
1519 setExprResult(Reference::fromAccumulator(this));
1520 }
1521 return false;
1522 } else if (ast->op == QSOperator::Coalesce) {
1523
1524 Reference left = expression(ast->left);
1525 if (hasError())
1526 return false;
1527
1528 BytecodeGenerator::Label iftrue = bytecodeGenerator->newLabel();
1529
1530 Instruction::CmpEqNull cmp;
1531
1532 left = left.storeOnStack();
1533 left.loadInAccumulator();
1534 bytecodeGenerator->addInstruction(cmp);
1535
1536 bytecodeGenerator->jumpTrue().link(iftrue);
1537
1538 blockTailCalls.unblock();
1539
1540 left.loadInAccumulator();
1541 BytecodeGenerator::Jump jump_endif = bytecodeGenerator->jump();
1542 iftrue.link();
1543
1544 Reference right = expression(ast->right);
1545 if (hasError()) {
1546 jump_endif.link();
1547 return false;
1548 }
1549
1550 right.loadInAccumulator();
1551 jump_endif.link();
1552 setExprResult(Reference::fromAccumulator(this));
1553
1554 return false;
1555 } else if (ast->op == QSOperator::Assign) {
1556 bytecodeGenerator->setLocation(ast->left->firstSourceLocation());
1557 if (AST::Pattern *p = ast->left->patternCast()) {
1558 RegisterScope scope(this);
1559 Reference right = expression(ast->right);
1560 if (hasError())
1561 return false;
1562 right = right.storeOnStack();
1563 destructurePattern(p, right);
1564 if (!exprAccept(nx)) {
1565 right.loadInAccumulator();
1566 setExprResult(Reference::fromAccumulator(this));
1567 }
1568 return false;
1569 }
1570 Reference left = expression(ast->left);
1571 if (hasError())
1572 return false;
1573
1574 if (!left.isLValue()) {
1575 throwReferenceError(ast->operatorToken, QStringLiteral("left-hand side of assignment operator is not an lvalue"));
1576 return false;
1577 }
1578 left = left.asLValue();
1579 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(left, ast->left->lastSourceLocation()))
1580 return false;
1581 blockTailCalls.unblock();
1582 Reference r = expression(ast->right);
1583 if (hasError())
1584 return false;
1585 if (left.requiresTDZCheck) {
1586 r = r.storeOnStack();
1587 left.checkTDZBeforeAssignment();
1588 }
1589 r.loadInAccumulator();
1590 // The location saved above may have been overwritten when evaluating the rhs expression
1591 bytecodeGenerator->setLocation(ast->left->firstSourceLocation());
1592 if (exprAccept(nx))
1593 setExprResult(left.storeConsumeAccumulator());
1594 else
1595 setExprResult(left.storeRetainAccumulator());
1596 return false;
1597 }
1598
1599 Reference left = expression(ast->left);
1600 if (hasError())
1601 return false;
1602
1603 switch (ast->op) {
1604 case QSOperator::Or:
1605 case QSOperator::And:
1606 case QSOperator::Assign:
1607 Q_UNREACHABLE(); // handled separately above
1608 break;
1609
1610 case QSOperator::InplaceAnd:
1611 case QSOperator::InplaceSub:
1612 case QSOperator::InplaceDiv:
1613 case QSOperator::InplaceAdd:
1614 case QSOperator::InplaceLeftShift:
1615 case QSOperator::InplaceMod:
1616 case QSOperator::InplaceExp:
1617 case QSOperator::InplaceMul:
1618 case QSOperator::InplaceOr:
1619 case QSOperator::InplaceRightShift:
1620 case QSOperator::InplaceURightShift:
1621 case QSOperator::InplaceXor: {
1622 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(left, ast->left->lastSourceLocation()))
1623 return false;
1624
1625 if (!left.isLValue()) {
1626 throwSyntaxError(ast->operatorToken, QStringLiteral("left-hand side of inplace operator is not an lvalue"));
1627 return false;
1628 }
1629 left = left.asLValue();
1630
1631 Reference tempLeft = left.storeOnStack();
1632 Reference right = expression(ast->right);
1633
1634 if (hasError())
1635 return false;
1636
1637 binopHelper(ast, baseOp(ast->op), tempLeft, right).loadInAccumulator();
1638 setExprResult(left.storeRetainAccumulator());
1639
1640 break;
1641 }
1642
1643 case QSOperator::BitAnd:
1644 case QSOperator::BitOr:
1645 case QSOperator::BitXor:
1646 if (left.isConstant()) {
1647 Reference right = expression(ast->right);
1648 if (hasError())
1649 return false;
1650 setExprResult(binopHelper(ast, static_cast<QSOperator::Op>(ast->op), right, left));
1651 break;
1652 }
1653 Q_FALLTHROUGH();
1654 case QSOperator::In:
1655 case QSOperator::InstanceOf:
1656 case QSOperator::As:
1657 case QSOperator::Equal:
1658 case QSOperator::NotEqual:
1659 case QSOperator::Ge:
1660 case QSOperator::Gt:
1661 case QSOperator::Le:
1662 case QSOperator::Lt:
1663 case QSOperator::StrictEqual:
1664 case QSOperator::StrictNotEqual:
1665 case QSOperator::Add:
1666 case QSOperator::Div:
1667 case QSOperator::Exp:
1668 case QSOperator::Mod:
1669 case QSOperator::Mul:
1670 case QSOperator::Sub:
1671 case QSOperator::LShift:
1672 case QSOperator::RShift:
1673 case QSOperator::URShift: {
1674 Reference right;
1675 if (AST::NumericLiteral *rhs = AST::cast<AST::NumericLiteral *>(ast->right)) {
1676 visit(rhs);
1677 right = exprResult();
1678 } else {
1679 left = left.storeOnStack(); // force any loads of the lhs, so the rhs won't clobber it
1680 right = expression(ast->right);
1681 }
1682 if (hasError())
1683 return false;
1684
1685 setExprResult(binopHelper(ast, static_cast<QSOperator::Op>(ast->op), left, right));
1686
1687 break;
1688 }
1689 } // switch
1690
1691 return false;
1692}
1693
1694Codegen::Reference Codegen::binopHelper(BinaryExpression *ast, QSOperator::Op oper, Reference &left,
1695 Reference &right)
1696{
1697 auto loc = combine(ast->left->firstSourceLocation(), ast->right->lastSourceLocation());
1698 bytecodeGenerator->setLocation(loc);
1699 switch (oper) {
1700 case QSOperator::Add: {
1701 left = left.storeOnStack();
1702 right.loadInAccumulator();
1703 Instruction::Add add;
1704 add.lhs = left.stackSlot();
1705 bytecodeGenerator->addInstruction(add);
1706 break;
1707 }
1708 case QSOperator::Sub: {
1709 if (right.isConstant() && right.constant == Encode(int(1))) {
1710 left.loadInAccumulator();
1711 Instruction::Decrement dec = {};
1712 bytecodeGenerator->addInstruction(dec);
1713 } else {
1714 left = left.storeOnStack();
1715 right.loadInAccumulator();
1716 Instruction::Sub sub;
1717 sub.lhs = left.stackSlot();
1718 bytecodeGenerator->addInstruction(sub);
1719 }
1720 break;
1721 }
1722 case QSOperator::Exp: {
1723 left = left.storeOnStack();
1724 right.loadInAccumulator();
1725 Instruction::Exp exp;
1726 exp.lhs = left.stackSlot();
1727 bytecodeGenerator->addInstruction(exp);
1728 break;
1729 }
1730 case QSOperator::Mul: {
1731 left = left.storeOnStack();
1732 right.loadInAccumulator();
1733 Instruction::Mul mul;
1734 mul.lhs = left.stackSlot();
1735 bytecodeGenerator->addInstruction(mul);
1736 break;
1737 }
1738 case QSOperator::Div: {
1739 left = left.storeOnStack();
1740 right.loadInAccumulator();
1741 Instruction::Div div;
1742 div.lhs = left.stackSlot();
1743 bytecodeGenerator->addInstruction(div);
1744 break;
1745 }
1746 case QSOperator::Mod: {
1747 left = left.storeOnStack();
1748 right.loadInAccumulator();
1749 Instruction::Mod mod;
1750 mod.lhs = left.stackSlot();
1751 bytecodeGenerator->addInstruction(mod);
1752 break;
1753 }
1754 case QSOperator::BitAnd:
1755 if (right.isConstant()) {
1756 int rightAsInt = StaticValue::fromReturnedValue(right.constant).toInt32();
1757 if (left.isConstant()) {
1758 int result = StaticValue::fromReturnedValue(left.constant).toInt32() & rightAsInt;
1759 return Reference::fromConst(this, Encode(result));
1760 }
1761 left.loadInAccumulator();
1762 Instruction::BitAndConst bitAnd;
1763 bitAnd.rhs = rightAsInt;
1764 bytecodeGenerator->addInstruction(bitAnd);
1765 } else {
1766 right.loadInAccumulator();
1767 Instruction::BitAnd bitAnd;
1768 bitAnd.lhs = left.stackSlot();
1769 bytecodeGenerator->addInstruction(bitAnd);
1770 }
1771 break;
1772 case QSOperator::BitOr:
1773 if (right.isConstant()) {
1774 int rightAsInt = StaticValue::fromReturnedValue(right.constant).toInt32();
1775 if (left.isConstant()) {
1776 int result = StaticValue::fromReturnedValue(left.constant).toInt32() | rightAsInt;
1777 return Reference::fromConst(this, Encode(result));
1778 }
1779 left.loadInAccumulator();
1780 Instruction::BitOrConst bitOr;
1781 bitOr.rhs = rightAsInt;
1782 bytecodeGenerator->addInstruction(bitOr);
1783 } else {
1784 right.loadInAccumulator();
1785 Instruction::BitOr bitOr;
1786 bitOr.lhs = left.stackSlot();
1787 bytecodeGenerator->addInstruction(bitOr);
1788 }
1789 break;
1790 case QSOperator::BitXor:
1791 if (right.isConstant()) {
1792 int rightAsInt = StaticValue::fromReturnedValue(right.constant).toInt32();
1793 if (left.isConstant()) {
1794 int result = StaticValue::fromReturnedValue(left.constant).toInt32() ^ rightAsInt;
1795 return Reference::fromConst(this, Encode(result));
1796 }
1797 left.loadInAccumulator();
1798 Instruction::BitXorConst bitXor;
1799 bitXor.rhs = rightAsInt;
1800 bytecodeGenerator->addInstruction(bitXor);
1801 } else {
1802 right.loadInAccumulator();
1803 Instruction::BitXor bitXor;
1804 bitXor.lhs = left.stackSlot();
1805 bytecodeGenerator->addInstruction(bitXor);
1806 }
1807 break;
1808 case QSOperator::URShift:
1809 if (right.isConstant()) {
1810 left.loadInAccumulator();
1811 Instruction::UShrConst ushr;
1812 ushr.rhs = StaticValue::fromReturnedValue(right.constant).toInt32() & 0x1f;
1813 bytecodeGenerator->addInstruction(ushr);
1814 } else {
1815 right.loadInAccumulator();
1816 Instruction::UShr ushr;
1817 ushr.lhs = left.stackSlot();
1818 bytecodeGenerator->addInstruction(ushr);
1819 }
1820 break;
1821 case QSOperator::RShift:
1822 if (right.isConstant()) {
1823 left.loadInAccumulator();
1824 Instruction::ShrConst shr;
1825 shr.rhs = StaticValue::fromReturnedValue(right.constant).toInt32() & 0x1f;
1826 bytecodeGenerator->addInstruction(shr);
1827 } else {
1828 right.loadInAccumulator();
1829 Instruction::Shr shr;
1830 shr.lhs = left.stackSlot();
1831 bytecodeGenerator->addInstruction(shr);
1832 }
1833 break;
1834 case QSOperator::LShift:
1835 if (right.isConstant()) {
1836 left.loadInAccumulator();
1837 Instruction::ShlConst shl;
1838 shl.rhs = StaticValue::fromReturnedValue(right.constant).toInt32() & 0x1f;
1839 bytecodeGenerator->addInstruction(shl);
1840 } else {
1841 right.loadInAccumulator();
1842 Instruction::Shl shl;
1843 shl.lhs = left.stackSlot();
1844 bytecodeGenerator->addInstruction(shl);
1845 }
1846 break;
1847 case QSOperator::InstanceOf: {
1848 Instruction::CmpInstanceOf binop;
1849 left = left.storeOnStack();
1850 right.loadInAccumulator();
1851 binop.lhs = left.stackSlot();
1852 bytecodeGenerator->addInstruction(binop);
1853 break;
1854 }
1855 case QSOperator::As: {
1856 Instruction::As as;
1857 left = left.storeOnStack();
1858 right.loadInAccumulator();
1859 as.lhs = left.stackSlot();
1860 bytecodeGenerator->addInstruction(as);
1861 break;
1862 }
1863 case QSOperator::In: {
1864 Instruction::CmpIn binop;
1865 left = left.storeOnStack();
1866 right.loadInAccumulator();
1867 binop.lhs = left.stackSlot();
1868 bytecodeGenerator->addInstruction(binop);
1869 break;
1870 }
1871 case QSOperator::StrictEqual: {
1872 if (exprAccept(cx))
1873 return jumpBinop(oper, left, right);
1874
1875 Instruction::CmpStrictEqual cmp;
1876 left = left.storeOnStack();
1877 right.loadInAccumulator();
1878 cmp.lhs = left.stackSlot();
1879 bytecodeGenerator->addInstruction(cmp);
1880 break;
1881 }
1882 case QSOperator::StrictNotEqual: {
1883 if (exprAccept(cx))
1884 return jumpBinop(oper, left, right);
1885
1886 Instruction::CmpStrictNotEqual cmp;
1887 left = left.storeOnStack();
1888 right.loadInAccumulator();
1889 cmp.lhs = left.stackSlot();
1890 bytecodeGenerator->addInstruction(cmp);
1891 break;
1892 }
1893 case QSOperator::Equal: {
1894 if (exprAccept(cx))
1895 return jumpBinop(oper, left, right);
1896
1897 Instruction::CmpEq cmp;
1898 left = left.storeOnStack();
1899 right.loadInAccumulator();
1900 cmp.lhs = left.stackSlot();
1901 bytecodeGenerator->addInstruction(cmp);
1902 break;
1903 }
1904 case QSOperator::NotEqual: {
1905 if (exprAccept(cx))
1906 return jumpBinop(oper, left, right);
1907
1908 Instruction::CmpNe cmp;
1909 left = left.storeOnStack();
1910 right.loadInAccumulator();
1911 cmp.lhs = left.stackSlot();
1912 bytecodeGenerator->addInstruction(cmp);
1913 break;
1914 }
1915 case QSOperator::Gt: {
1916 if (exprAccept(cx))
1917 return jumpBinop(oper, left, right);
1918
1919 Instruction::CmpGt cmp;
1920 left = left.storeOnStack();
1921 right.loadInAccumulator();
1922 cmp.lhs = left.stackSlot();
1923 bytecodeGenerator->addInstruction(cmp);
1924 break;
1925 }
1926 case QSOperator::Ge: {
1927 if (exprAccept(cx))
1928 return jumpBinop(oper, left, right);
1929
1930 Instruction::CmpGe cmp;
1931 left = left.storeOnStack();
1932 right.loadInAccumulator();
1933 cmp.lhs = left.stackSlot();
1934 bytecodeGenerator->addInstruction(cmp);
1935 break;
1936 }
1937 case QSOperator::Lt: {
1938 if (exprAccept(cx))
1939 return jumpBinop(oper, left, right);
1940
1941 Instruction::CmpLt cmp;
1942 left = left.storeOnStack();
1943 right.loadInAccumulator();
1944 cmp.lhs = left.stackSlot();
1945 bytecodeGenerator->addInstruction(cmp);
1946 break;
1947 }
1948 case QSOperator::Le:
1949 if (exprAccept(cx))
1950 return jumpBinop(oper, left, right);
1951
1952 Instruction::CmpLe cmp;
1953 left = left.storeOnStack();
1954 right.loadInAccumulator();
1955 cmp.lhs = left.stackSlot();
1956 bytecodeGenerator->addInstruction(cmp);
1957 break;
1958 default:
1959 Q_UNREACHABLE();
1960 }
1961
1962 return Reference::fromAccumulator(this);
1963}
1964
1965Codegen::Reference Codegen::jumpBinop(QSOperator::Op oper, Reference &left, Reference &right)
1966{
1967 // See if we can generate specialized comparison instructions:
1968 if (oper == QSOperator::Equal || oper == QSOperator::NotEqual) {
1969 // Because == and != are reflexive, we can do the following:
1970 if (left.isConstant() && !right.isConstant())
1971 qSwap(left, right); // null==a -> a==null
1972
1973 if (right.isConstant()) {
1974 StaticValue c = StaticValue::fromReturnedValue(right.constant);
1975 if (c.isNull() || c.isUndefined()) {
1976 left.loadInAccumulator();
1977 if (oper == QSOperator::Equal) {
1978 Instruction::CmpEqNull cmp;
1979 bytecodeGenerator->addInstruction(cmp);
1980 addCJump();
1981 return Reference();
1982 } else if (oper == QSOperator::NotEqual) {
1983 Instruction::CmpNeNull cmp;
1984 bytecodeGenerator->addInstruction(cmp);
1985 addCJump();
1986 return Reference();
1987 }
1988 } else if (c.isInt32()) {
1989 left.loadInAccumulator();
1990 if (oper == QSOperator::Equal) {
1991 Instruction::CmpEqInt cmp;
1992 cmp.lhs = c.int_32();
1993 bytecodeGenerator->addInstruction(cmp);
1994 addCJump();
1995 return Reference();
1996 } else if (oper == QSOperator::NotEqual) {
1997 Instruction::CmpNeInt cmp;
1998 cmp.lhs = c.int_32();
1999 bytecodeGenerator->addInstruction(cmp);
2000 addCJump();
2001 return Reference();
2002 }
2003
2004 }
2005 }
2006 }
2007
2008 left = left.storeOnStack();
2009 right.loadInAccumulator();
2010
2011 switch (oper) {
2012 case QSOperator::StrictEqual: {
2013 Instruction::CmpStrictEqual cmp;
2014 cmp.lhs = left.stackSlot();
2015 bytecodeGenerator->addInstruction(cmp);
2016 addCJump();
2017 break;
2018 }
2019 case QSOperator::StrictNotEqual: {
2020 Instruction::CmpStrictNotEqual cmp;
2021 cmp.lhs = left.stackSlot();
2022 bytecodeGenerator->addInstruction(cmp);
2023 addCJump();
2024 break;
2025 }
2026 case QSOperator::Equal: {
2027 Instruction::CmpEq cmp;
2028 cmp.lhs = left.stackSlot();
2029 bytecodeGenerator->addInstruction(cmp);
2030 addCJump();
2031 break;
2032 }
2033 case QSOperator::NotEqual: {
2034 Instruction::CmpNe cmp;
2035 cmp.lhs = left.stackSlot();
2036 bytecodeGenerator->addInstruction(cmp);
2037 addCJump();
2038 break;
2039 }
2040 case QSOperator::Gt: {
2041 Instruction::CmpGt cmp;
2042 cmp.lhs = left.stackSlot();
2043 bytecodeGenerator->addInstruction(cmp);
2044 addCJump();
2045 break;
2046 }
2047 case QSOperator::Ge: {
2048 Instruction::CmpGe cmp;
2049 cmp.lhs = left.stackSlot();
2050 bytecodeGenerator->addInstruction(cmp);
2051 addCJump();
2052 break;
2053 }
2054 case QSOperator::Lt: {
2055 Instruction::CmpLt cmp;
2056 cmp.lhs = left.stackSlot();
2057 bytecodeGenerator->addInstruction(cmp);
2058 addCJump();
2059 break;
2060 }
2061 case QSOperator::Le: {
2062 Instruction::CmpLe cmp;
2063 cmp.lhs = left.stackSlot();
2064 bytecodeGenerator->addInstruction(cmp);
2065 addCJump();
2066 break;
2067 }
2068 default:
2069 Q_UNREACHABLE();
2070 }
2071 return Reference();
2072}
2073
2074Codegen::Reference Codegen::loadSubscriptForCall(const Codegen::Reference &base)
2075{
2076 // Retrieve the function to be called before generating the arguments.
2077 // Generating the arguments might change the array.
2078 base.elementSubscript.loadInAccumulator();
2079 Codegen::Instruction::LoadElement load;
2080 load.base = base.elementBase;
2081 bytecodeGenerator->addInstruction(load);
2082 return Reference::fromAccumulator(this);
2083}
2084
2085bool Codegen::visit(CallExpression *ast)
2086{
2087 if (hasError())
2088 return false;
2089
2090 const bool isTailOfChain = traverseOptionalChain(ast);
2091
2092 RegisterScope scope(this);
2093 TailCallBlocker blockTailCalls(this);
2094
2095 Reference expr = expression(ast->base);
2096 Reference base = expr;
2097
2098 if (hasError())
2099 return false;
2100 switch (base.type) {
2101 case Reference::Member:
2102 base = base.asLValue();
2103 break;
2104 case Reference::Subscript:
2105 base.element = loadSubscriptForCall(base).storeOnStack().stackSlot();
2106 base.subscriptLoadedForCall = true;
2107 break;
2108 case Reference::Name:
2109 break;
2110 case Reference::Super:
2111 handleConstruct(base, ast->arguments);
2112 return false;
2113 case Reference::SuperProperty:
2114 break;
2115 default:
2116 base = base.storeOnStack();
2117 break;
2118 }
2119
2120 if (expr.hasSavedCallBaseSlot) {
2121 // Hack to preserve `this` context in optional chain calls. See optionalChainFinalizer().
2122 base.hasSavedCallBaseSlot = true;
2123 base.savedCallBaseSlot = expr.savedCallBaseSlot;
2124 base.savedCallPropertyNameIndex = expr.savedCallPropertyNameIndex;
2125 }
2126
2127 int thisObject = bytecodeGenerator->newRegister();
2128 int functionObject = bytecodeGenerator->newRegister();
2129
2130 if (ast->isOptional || m_optionalChainsStates->top().actuallyHasOptionals) {
2131 base.loadInAccumulator();
2132 bytecodeGenerator->addInstruction(Instruction::CmpEqNull());
2133 auto jumpToUndefined = bytecodeGenerator->jumpTrue();
2134 m_optionalChainsStates->top().jumpsToPatch.emplace_back(std::move(jumpToUndefined));
2135 }
2136
2137 auto calldata = pushArgs(ast->arguments);
2138 if (hasError())
2139 return false;
2140
2141 blockTailCalls.unblock();
2142 if (calldata.hasSpread || _tailCallsAreAllowed) {
2143 Reference baseObject = base.baseObject();
2144 if (!baseObject.isStackSlot()) {
2145 baseObject.storeOnStack(thisObject);
2146 baseObject = Reference::fromStackSlot(this, thisObject);
2147 }
2148
2149 const int func = [&]() {
2150 if (base.type == Reference::Subscript)
2151 return base.element;
2152
2153 if (!base.isStackSlot()) {
2154 base.storeOnStack(functionObject);
2155 base = Reference::fromStackSlot(this, functionObject);
2156 }
2157
2158 return base.stackSlot();
2159 }();
2160
2161 if (calldata.hasSpread) {
2162 Instruction::CallWithSpread call;
2163 call.func = func;
2164 call.thisObject = baseObject.stackSlot();
2165 call.argc = calldata.argc;
2166 call.argv = calldata.argv;
2167 bytecodeGenerator->addInstruction(call);
2168 } else {
2169 Instruction::TailCall call;
2170 call.func = func;
2171 call.thisObject = baseObject.stackSlot();
2172 call.argc = calldata.argc;
2173 call.argv = calldata.argv;
2174 bytecodeGenerator->addInstruction(call);
2175 }
2176
2177 optionalChainFinalizer(Reference::fromAccumulator(this), isTailOfChain);
2178 return false;
2179 }
2180
2181 handleCall(base, calldata, functionObject, thisObject, ast->isOptional);
2182 optionalChainFinalizer(Reference::fromAccumulator(this), isTailOfChain);
2183 return false;
2184}
2185
2186void Codegen::endVisit(CallExpression *ast)
2187{
2188 m_seenOptionalChainNodes.remove(ast);
2189}
2190
2191void Codegen::handleCall(Reference &base, Arguments calldata, int slotForFunction, int slotForThisObject, bool optional)
2192{
2193 if (base.sourceLocation.isValid())
2194 bytecodeGenerator->setLocation(base.sourceLocation);
2195
2196 //### Do we really need all these call instructions? can's we load the callee in a temp?
2197 if (base.type == Reference::Member || base.hasSavedCallBaseSlot) {
2198 if (useFastLookups) {
2199 Instruction::CallPropertyLookup call;
2200 if (base.hasSavedCallBaseSlot) {
2201 call.base = base.savedCallBaseSlot;
2202 call.lookupIndex = registerGetterLookup(
2203 base.savedCallPropertyNameIndex, JSUnitGenerator::LookupForCall);
2204 } else {
2205 call.base = base.propertyBase.stackSlot();
2206 call.lookupIndex = registerGetterLookup(
2207 base.propertyNameIndex, JSUnitGenerator::LookupForCall);
2208 }
2209 call.argc = calldata.argc;
2210 call.argv = calldata.argv;
2211 bytecodeGenerator->addInstruction(call);
2212 } else {
2213 Instruction::CallProperty call;
2214 if (base.hasSavedCallBaseSlot) {
2215 call.base = base.savedCallBaseSlot;
2216 call.name = base.savedCallPropertyNameIndex;
2217 } else {
2218 call.base = base.propertyBase.stackSlot();
2219 call.name = base.propertyNameIndex;
2220 }
2221 call.argc = calldata.argc;
2222 call.argv = calldata.argv;
2223 bytecodeGenerator->addInstruction(call);
2224 }
2225 } else if (base.type == Reference::Subscript) {
2226 Instruction::CallWithReceiver call;
2227 call.thisObject = base.elementBase.stackSlot();
2228 call.name = base.element;
2229 call.argc = calldata.argc;
2230 call.argv = calldata.argv;
2231 bytecodeGenerator->addInstruction(call);
2232 } else if (base.type == Reference::Name) {
2233 if (base.name == QStringLiteral("eval") && !optional) {
2234 Instruction::CallPossiblyDirectEval call;
2235 call.argc = calldata.argc;
2236 call.argv = calldata.argv;
2237 bytecodeGenerator->addInstruction(call);
2238 } else if (useFastLookups && base.global) {
2239 if (base.qmlGlobal) {
2240 Instruction::CallQmlContextPropertyLookup call;
2241 call.index = registerQmlContextPropertyGetterLookup(
2242 base.nameAsIndex(), JSUnitGenerator::LookupForCall);
2243 call.argc = calldata.argc;
2244 call.argv = calldata.argv;
2245 bytecodeGenerator->addInstruction(call);
2246 } else {
2247 Instruction::CallGlobalLookup call;
2248 call.index = registerGlobalGetterLookup(
2249 base.nameAsIndex(), JSUnitGenerator::LookupForCall);
2250 call.argc = calldata.argc;
2251 call.argv = calldata.argv;
2252 bytecodeGenerator->addInstruction(call);
2253 }
2254 } else {
2255 Instruction::CallName call;
2256 call.name = base.nameAsIndex();
2257 call.argc = calldata.argc;
2258 call.argv = calldata.argv;
2259 bytecodeGenerator->addInstruction(call);
2260 }
2261 } else if (base.type == Reference::SuperProperty) {
2262 Reference receiver = base.baseObject();
2263 if (!base.isStackSlot()) {
2264 base.storeOnStack(slotForFunction);
2265 base = Reference::fromStackSlot(this, slotForFunction);
2266 }
2267 if (!receiver.isStackSlot()) {
2268 receiver.storeOnStack(slotForThisObject);
2269 receiver = Reference::fromStackSlot(this, slotForThisObject);
2270 }
2271 Instruction::CallWithReceiver call;
2272 call.name = base.stackSlot();
2273 call.thisObject = receiver.stackSlot();
2274 call.argc = calldata.argc;
2275 call.argv = calldata.argv;
2276 bytecodeGenerator->addInstruction(call);
2277 } else {
2278 Q_ASSERT(base.isStackSlot());
2279 Instruction::CallValue call;
2280 call.name = base.stackSlot();
2281 call.argc = calldata.argc;
2282 call.argv = calldata.argv;
2283 bytecodeGenerator->addInstruction(call);
2284 }
2285}
2286
2287Codegen::Arguments Codegen::pushArgs(ArgumentList *args)
2288{
2289 bool hasSpread = false;
2290 int argc = 0;
2291 for (ArgumentList *it = args; it; it = it->next) {
2292 if (it->spreadToken.isValid()) {
2293 hasSpread = true;
2294 ++argc;
2295 }
2296 ++argc;
2297 }
2298
2299 if (!argc)
2300 return { 0, 0, false };
2301
2302 int calldata = bytecodeGenerator->newRegisterArray(argc);
2303
2304 argc = 0;
2305 for (ArgumentList *it = args; it; it = it->next) {
2306 if (it->spreadToken.isValid()) {
2307 Reference::fromConst(
2308 this,
2309 StaticValue::emptyValue().asReturnedValue()).storeOnStack(calldata + argc);
2310 ++argc;
2311 }
2312 RegisterScope scope(this);
2313 Reference e = expression(it->expression);
2314 if (hasError())
2315 break;
2316 if (!argc && !it->next && !hasSpread) {
2317 // avoid copy for functions taking a single argument
2318 if (e.isStackSlot()) {
2319 e.tdzCheck();
2320 return { 1, e.stackSlot(), hasSpread };
2321 }
2322 }
2323 (void) e.storeOnStack(calldata + argc);
2324 ++argc;
2325 }
2326
2327 return { argc, calldata, hasSpread };
2328}
2329
2330Codegen::Arguments Codegen::pushTemplateArgs(TemplateLiteral *args)
2331{
2332 int argc = 0;
2333 for (TemplateLiteral *it = args; it; it = it->next)
2334 ++argc;
2335
2336 if (!argc)
2337 return { 0, 0, false };
2338
2339 int calldata = bytecodeGenerator->newRegisterArray(argc);
2340
2341 argc = 0;
2342 for (TemplateLiteral *it = args; it && it->expression; it = it->next) {
2343 RegisterScope scope(this);
2344 Reference e = expression(it->expression);
2345 if (hasError())
2346 break;
2347 (void) e.storeOnStack(calldata + argc);
2348 ++argc;
2349 }
2350
2351 return { argc, calldata, false };
2352}
2353
2354bool Codegen::visit(ConditionalExpression *ast)
2355{
2356 if (hasError())
2357 return false;
2358
2359 RegisterScope scope(this);
2360 TailCallBlocker blockTailCalls(this);
2361
2362 BytecodeGenerator::Label iftrue = bytecodeGenerator->newLabel();
2363 BytecodeGenerator::Label iffalse = bytecodeGenerator->newLabel();
2364 condition(ast->expression, &iftrue, &iffalse, true);
2365
2366 blockTailCalls.unblock();
2367
2368 iftrue.link();
2369 Reference ok = expression(ast->ok);
2370 if (hasError())
2371 return false;
2372 ok.loadInAccumulator();
2373 BytecodeGenerator::Jump jump_endif = bytecodeGenerator->jump();
2374
2375 iffalse.link();
2376 Reference ko = expression(ast->ko);
2377 if (hasError()) {
2378 jump_endif.link(); // dummy link, to prevent assert in Jump destructor from triggering
2379 return false;
2380 }
2381 ko.loadInAccumulator();
2382
2383 jump_endif.link();
2384 setExprResult(Reference::fromAccumulator(this));
2385
2386 return false;
2387}
2388
2389bool Codegen::visit(DeleteExpression *ast)
2390{
2391 if (hasError())
2392 return false;
2393
2394 const bool isTailOfChain = traverseOptionalChain(ast);
2395
2396 RegisterScope scope(this);
2397 TailCallBlocker blockTailCalls(this);
2398 Reference expr = expression(ast->expression);
2399 if (hasError())
2400 return false;
2401
2402 const bool chainActuallyHasOptionals = m_optionalChainsStates->top().actuallyHasOptionals;
2403 if (chainActuallyHasOptionals)
2404 Q_ASSERT(expr.type == Reference::Member || expr.type == Reference::Subscript);
2405
2406 switch (expr.type) {
2407 case Reference::SuperProperty:
2408 // ### this should throw a reference error at runtime.
2409 return false;
2410 case Reference::StackSlot:
2411 if (!expr.stackSlotIsLocalOrArgument)
2412 break;
2413 Q_FALLTHROUGH();
2414 case Reference::ScopedLocal:
2415 // Trying to delete a function argument might throw.
2416 if (_context->isStrict) {
2417 throwSyntaxError(ast->deleteToken, QStringLiteral("Delete of an unqualified identifier in strict mode."));
2418 return false;
2419 }
2420 setExprResult(Reference::fromConst(this, QV4::Encode(false)));
2421 return false;
2422 case Reference::Name: {
2423 if (_context->isStrict) {
2424 throwSyntaxError(ast->deleteToken, QStringLiteral("Delete of an unqualified identifier in strict mode."));
2425 return false;
2426 }
2427 Instruction::DeleteName del;
2428 del.name = expr.nameAsIndex();
2429 bytecodeGenerator->addInstruction(del);
2430 setExprResult(Reference::fromAccumulator(this));
2431 return false;
2432 }
2433 case Reference::Member: {
2434 //### maybe add a variant where the base can be in the accumulator?
2435 expr = expr.asLValue();
2436
2437 if (chainActuallyHasOptionals) {
2438 expr.loadInAccumulator();
2439 bytecodeGenerator->addInstruction(Instruction::CmpEqNull());
2440 auto jumpToUndefined = bytecodeGenerator->jumpTrue();
2441 m_optionalChainsStates->top().jumpsToPatch.emplace_back(std::move(jumpToUndefined));
2442 }
2443
2444 Instruction::LoadRuntimeString instr;
2445 instr.stringId = expr.propertyNameIndex;
2446 bytecodeGenerator->addInstruction(instr);
2447 Reference index = Reference::fromStackSlot(this);
2448 index.storeConsumeAccumulator();
2449 Instruction::DeleteProperty del;
2450 del.base = expr.propertyBase.stackSlot();
2451 del.index = index.stackSlot();
2452 bytecodeGenerator->addInstruction(del);
2453 auto ref = Reference::fromAccumulator(this);
2454
2455 optionalChainFinalizer(ref, isTailOfChain, true);
2456 return false;
2457 }
2458 case Reference::Subscript: {
2459 //### maybe add a variant where the index can be in the accumulator?
2460 expr = expr.asLValue();
2461
2462 if (chainActuallyHasOptionals) {
2463 expr.loadInAccumulator();
2464 bytecodeGenerator->addInstruction(Instruction::CmpEqNull());
2465 auto jumpToUndefined = bytecodeGenerator->jumpTrue();
2466 m_optionalChainsStates->top().jumpsToPatch.emplace_back(std::move(jumpToUndefined));
2467 }
2468
2469 Instruction::DeleteProperty del;
2470 del.base = expr.elementBase;
2471 del.index = expr.elementSubscript.stackSlot();
2472 bytecodeGenerator->addInstruction(del);
2473 auto ref = Reference::fromAccumulator(this);
2474
2475 optionalChainFinalizer(ref, isTailOfChain, true);
2476 return false;
2477 }
2478 default:
2479 break;
2480 }
2481 // [[11.4.1]] Return true if it's not a reference
2482 setExprResult(Reference::fromConst(this, QV4::Encode(true)));
2483 return false;
2484}
2485
2486void Codegen::endVisit(DeleteExpression *ast) {
2487 m_seenOptionalChainNodes.remove(ast);
2488}
2489
2490bool Codegen::visit(FalseLiteral *)
2491{
2492 if (hasError())
2493 return false;
2494
2495 setExprResult(Reference::fromConst(this, QV4::Encode(false)));
2496 return false;
2497}
2498
2499bool Codegen::visit(SuperLiteral *)
2500{
2501 if (hasError())
2502 return false;
2503
2504 setExprResult(Reference::fromSuper(this));
2505 return false;
2506}
2507
2508bool Codegen::traverseOptionalChain(Node *node)
2509{
2510 if (m_seenOptionalChainNodes.contains(node))
2511 return false;
2512
2513 const auto isOptionalChainableNode = [](const Node *node) {
2514 return node->kind == Node::Kind_FieldMemberExpression ||
2515 node->kind == Node::Kind_CallExpression ||
2516 node->kind == Node::Kind_ArrayMemberExpression ||
2517 node->kind == Node::Kind_DeleteExpression;
2518 };
2519 m_optionalChainsStates->emplace();
2520 while (isOptionalChainableNode(node)) {
2521 m_seenOptionalChainNodes.insert(node);
2522
2523 switch (node->kind) {
2524 case Node::Kind_FieldMemberExpression: {
2525 auto *fme = AST::cast<FieldMemberExpression *>(node);
2526 m_optionalChainsStates->top().actuallyHasOptionals |= fme->isOptional;
2527 node = fme->base;
2528 break;
2529 }
2530 case Node::Kind_CallExpression: {
2531 auto *ce = AST::cast<CallExpression *>(node);
2532 m_optionalChainsStates->top().actuallyHasOptionals |= ce->isOptional;
2533 node = ce->base;
2534 break;
2535 }
2536 case Node::Kind_ArrayMemberExpression: {
2537 auto *ame = AST::cast<ArrayMemberExpression *>(node);
2538 m_optionalChainsStates->top().actuallyHasOptionals |= ame->isOptional;
2539 node = ame->base;
2540 break;
2541 }
2542 case Node::Kind_DeleteExpression:
2543 node = AST::cast<DeleteExpression *>(node)->expression;
2544 break;
2545 default:
2546 Q_UNREACHABLE();
2547 }
2548 }
2549
2550 return true;
2551}
2552
2553void Codegen::optionalChainFinalizer(const Reference &expressionResult, bool tailOfChain,
2554 bool isDeleteExpression)
2555{
2556 auto &chainState = m_optionalChainsStates->top();
2557 if (!tailOfChain) {
2558 setExprResult(expressionResult);
2559 return;
2560 } else if (!chainState.actuallyHasOptionals) {
2561 setExprResult(expressionResult);
2562 m_optionalChainsStates->pop();
2563 return;
2564 }
2565
2566 auto savedBaseSlot = -1;
2567 if (expressionResult.type == Reference::Member)
2568 savedBaseSlot = expressionResult.propertyBase.storeOnStack().stackSlot();
2569 expressionResult.loadInAccumulator();
2570
2571 std::optional<Moth::BytecodeGenerator::Jump> jumpToDone;
2572 if (!isDeleteExpression) // Delete expressions always return true, avoid the extra jump
2573 jumpToDone.emplace(bytecodeGenerator->jump());
2574
2575 for (auto &jump : chainState.jumpsToPatch)
2576 jump.link();
2577
2578 if (isDeleteExpression)
2579 bytecodeGenerator->addInstruction(Instruction::LoadTrue());
2580 else
2581 bytecodeGenerator->addInstruction(Instruction::LoadUndefined());
2582
2583 if (jumpToDone.has_value())
2584 jumpToDone.value().link();
2585
2586 auto ref = Reference::fromAccumulator(this);
2587 if (expressionResult.type == Reference::Member) {
2588 /* Because the whole optional chain is handled at once with a chain finalizer instead of
2589 * instruction by instruction, the result of the chain (either undefined or the result of
2590 * the optional operation) is stored in the accumulator. This works fine except for one
2591 * edge case where the `this` context is required in a call
2592 * (see tst_ecmascripttests: language/expressions/optional-chaining/optional-call-preserves-this.js).
2593 *
2594 * In order to preserve the `this` context in the call, the call base and the property name
2595 * index need to be available as with a Member reference. However, since the result must be
2596 * in the accumulator the resulting reference is of type Accumulator. Therefore, the call
2597 * base and the property name index are `glued` to an accumulator reference to make it work
2598 * when deciding which call instruction to use later on.
2599 */
2600 ref.hasSavedCallBaseSlot = true;
2601 ref.savedCallBaseSlot = savedBaseSlot;
2602 ref.savedCallPropertyNameIndex = expressionResult.propertyNameIndex;
2603 }
2604 setExprResult(ref);
2605 m_optionalChainsStates->pop();
2606}
2607
2608bool Codegen::visit(FieldMemberExpression *ast)
2609{
2610 if (hasError())
2611 return false;
2612
2613 const bool isTailOfChain = traverseOptionalChain(ast);
2614
2615 TailCallBlocker blockTailCalls(this);
2616
2617 if (AST::IdentifierExpression *id = AST::cast<AST::IdentifierExpression *>(ast->base)) {
2618 if (id->name == QLatin1String("new")) {
2619 // new.target
2620 Q_ASSERT(ast->name == QLatin1String("target"));
2621
2622 if (_context->isArrowFunction || _context->contextType == ContextType::Eval) {
2623 Reference r = referenceForName(QStringLiteral("new.target"), false);
2624 r.isReadonly = true;
2625 setExprResult(r);
2626
2627 return false;
2628 }
2629
2630 auto ref = Reference::fromStackSlot(this, CallData::NewTarget);
2631 optionalChainFinalizer(ref, isTailOfChain);
2632 return false;
2633 }
2634 }
2635
2636 Reference base = expression(ast->base);
2637
2638 if (hasError())
2639 return false;
2640 if (base.isSuper()) {
2641 Instruction::LoadRuntimeString load;
2642 load.stringId = registerString(ast->name.toString());
2643 bytecodeGenerator->addInstruction(load);
2644 Reference property = Reference::fromAccumulator(this).storeOnStack();
2645
2646 optionalChainFinalizer(Reference::fromSuperProperty(property), isTailOfChain);
2647 return false;
2648 }
2649
2650 auto ref = Reference::fromMember(base, ast->name.toString(), ast->lastSourceLocation(),
2651 ast->isOptional, &m_optionalChainsStates->top().jumpsToPatch);
2652
2653 optionalChainFinalizer(ref, isTailOfChain);
2654 return false;
2655}
2656
2657void Codegen::endVisit(FieldMemberExpression *ast)
2658{
2659 m_seenOptionalChainNodes.remove(ast);
2660}
2661
2662bool Codegen::visit(TaggedTemplate *ast)
2663{
2664 if (hasError())
2665 return false;
2666
2667 RegisterScope scope(this);
2668 auto base = expression(ast->base);
2669 if (hasError())
2670 return false;
2671 return handleTaggedTemplate(std::move(base), ast);
2672}
2673
2674bool Codegen::handleTaggedTemplate(Reference base, TaggedTemplate *ast)
2675{
2676 if (hasError())
2677 return false;
2678
2679 int functionObject = -1, thisObject = -1;
2680 switch (base.type) {
2681 case Reference::Member:
2682 base = base.asLValue();
2683 break;
2684 case Reference::Subscript:
2685 base.element = loadSubscriptForCall(base).storeOnStack().stackSlot();
2686 base.subscriptLoadedForCall = true;
2687 break;
2688 case Reference::Name:
2689 break;
2690 case Reference::SuperProperty:
2691 thisObject = bytecodeGenerator->newRegister();
2692 functionObject = bytecodeGenerator->newRegister();
2693 break;
2694 default:
2695 base = base.storeOnStack();
2696 break;
2697 }
2698
2699 createTemplateObject(ast->templateLiteral);
2700 int templateObjectTemp = Reference::fromAccumulator(this).storeOnStack().stackSlot();
2701 Q_UNUSED(templateObjectTemp);
2702 auto calldata = pushTemplateArgs(ast->templateLiteral);
2703 if (hasError())
2704 return false;
2705 ++calldata.argc;
2706 Q_ASSERT(calldata.argv == templateObjectTemp + 1);
2707 --calldata.argv;
2708
2709 handleCall(base, calldata, functionObject, thisObject);
2710 setExprResult(Reference::fromAccumulator(this));
2711 return false;
2712}
2713
2714void Codegen::createTemplateObject(TemplateLiteral *t)
2715{
2716 TemplateObject obj;
2717
2718 for (TemplateLiteral *it = t; it; it = it->next) {
2719 obj.strings.append(registerString(it->value.toString()));
2720 obj.rawStrings.append(registerString(it->rawValue.toString()));
2721 }
2722
2723 int index = _module->templateObjects.size();
2724 _module->templateObjects.append(obj);
2725
2726 Instruction::GetTemplateObject getTemplateObject;
2727 getTemplateObject.index = index;
2728 bytecodeGenerator->addInstruction(getTemplateObject);
2729}
2730
2731bool Codegen::visit(FunctionExpression *ast)
2732{
2733 if (hasError())
2734 return false;
2735
2736 TailCallBlocker blockTailCalls(this);
2737
2738 RegisterScope scope(this);
2739
2740 int function = defineFunction(ast->name.toString(), ast, ast->formals, ast->body);
2741 if (hasError())
2742 return false;
2743 loadClosure(function);
2744 setExprResult(Reference::fromAccumulator(this));
2745 return false;
2746}
2747
2748Codegen::Reference Codegen::referenceForName(const QString &name, bool isLhs, const SourceLocation &accessLocation)
2749{
2750 Context::ResolvedName resolved = _context->resolveName(name, accessLocation);
2751 bool throwsReferenceError = false;
2752
2753 if (resolved.type == Context::ResolvedName::Local || resolved.type == Context::ResolvedName::Stack
2754 || resolved.type == Context::ResolvedName::Import) {
2755 if (resolved.isArgOrEval && isLhs)
2756 // ### add correct source location
2757 throwSyntaxError(SourceLocation(), QStringLiteral("Variable name may not be eval or arguments in strict mode"));
2758
2759 if (resolved.declarationLocation.isValid() && accessLocation.isValid()
2760 && resolved.declarationLocation.begin() > accessLocation.end()) {
2761 Q_ASSERT(_interface);
2762 if (resolved.memberType == Context::FunctionDefinition) {
2763 _interface->reportFunctionUsedBeforeDeclaration(
2764 name, url().toLocalFile(), resolved.declarationLocation, accessLocation);
2765 } else {
2766 _interface->reportVarUsedBeforeDeclaration(
2767 name, url().toLocalFile(), resolved.declarationLocation, accessLocation);
2768 }
2769 if (resolved.type == Context::ResolvedName::Stack && resolved.requiresTDZCheck)
2770 throwsReferenceError = true;
2771 }
2772
2773 if (resolved.isInjected && accessLocation.isValid()) {
2774 qCWarning(lcQmlInjectedParameter).nospace().noquote()
2775 << url().toString() << ":" << accessLocation.startLine
2776 << ":" << accessLocation.startColumn << " Parameter \"" << name
2777 << "\" is not declared."
2778 << " Injection of parameters into signal handlers is deprecated."
2779 << " Use JavaScript functions with formal parameters instead.";
2780 }
2781
2782 Reference r;
2783 switch (resolved.type) {
2784 case Context::ResolvedName::Local:
2785 r = Reference::fromScopedLocal(this, resolved.index, resolved.scope); break;
2786 case Context::ResolvedName::Stack:
2787 r = Reference::fromStackSlot(this, resolved.index, true /*isLocal*/); break;
2788 case Context::ResolvedName::Import:
2789 r = Reference::fromImport(this, resolved.index); break;
2790 default: Q_UNREACHABLE();
2791 }
2792 if (r.isStackSlot() && _volatileMemoryLocations.isVolatile(name))
2793 r.isVolatile = true;
2794 r.isArgOrEval = resolved.isArgOrEval;
2795 r.isReferenceToConst = resolved.isConst;
2796 r.requiresTDZCheck = resolved.requiresTDZCheck;
2797 r.name = name; // used to show correct name at run-time when TDZ check fails.
2798 r.sourceLocation = accessLocation;
2799 r.throwsReferenceError = throwsReferenceError;
2800 return r;
2801 }
2802
2803 Reference r = Reference::fromName(this, name);
2804 r.global = useFastLookups && (resolved.type == Context::ResolvedName::Global || resolved.type == Context::ResolvedName::QmlGlobal);
2805 r.qmlGlobal = resolved.type == Context::ResolvedName::QmlGlobal;
2806 r.sourceLocation = accessLocation;
2807 if (!r.global && !r.qmlGlobal
2808 && _context->contextType == ContextType::ScriptImportedByQML
2809 && Codegen::isNameGlobal(name)) {
2810 // the global object is frozen, so we know that members of it are
2811 // pointing to the global object. This is important so that references
2812 // to Math etc. do not go through the expensive path in the context wrapper
2813 // that tries to see whether we have a matching type
2814 r.global = true;
2815 }
2816 return r;
2817}
2818
2819void Codegen::loadClosure(int closureId)
2820{
2821 if (closureId >= 0) {
2822 Instruction::LoadClosure load;
2823 load.value = closureId;
2824 bytecodeGenerator->addInstruction(load);
2825 } else {
2826 Reference::fromConst(this, Encode::undefined()).loadInAccumulator();
2827 }
2828}
2829
2830bool Codegen::visit(IdentifierExpression *ast)
2831{
2832 if (hasError())
2833 return false;
2834
2835 setExprResult(referenceForName(ast->name.toString(), false, ast->firstSourceLocation()));
2836 return false;
2837}
2838
2839bool Codegen::visit(NestedExpression *ast)
2840{
2841 if (hasError())
2842 return false;
2843
2844 accept(ast->expression);
2845 return false;
2846}
2847
2848void Codegen::handleConstruct(const Reference &base, ArgumentList *arguments)
2849{
2850 Reference constructor;
2851 if (base.isSuper()) {
2852 Instruction::LoadSuperConstructor super;
2853 bytecodeGenerator->addInstruction(super);
2854 constructor = Reference::fromAccumulator(this).storeOnStack();
2855 } else {
2856 constructor = base.storeOnStack();
2857 }
2858
2859 auto calldata = pushArgs(arguments);
2860 if (hasError())
2861 return;
2862
2863 if (base.isSuper())
2864 Reference::fromStackSlot(this, CallData::NewTarget).loadInAccumulator();
2865 else
2866 constructor.loadInAccumulator();
2867
2868 if (calldata.hasSpread) {
2869 Instruction::ConstructWithSpread create;
2870 create.func = constructor.stackSlot();
2871 create.argc = calldata.argc;
2872 create.argv = calldata.argv;
2873 bytecodeGenerator->addInstruction(create);
2874 } else {
2875 Instruction::Construct create;
2876 create.func = constructor.stackSlot();
2877 create.argc = calldata.argc;
2878 create.argv = calldata.argv;
2879 bytecodeGenerator->addInstruction(create);
2880 }
2881 if (base.isSuper())
2882 // set the result up as the thisObject
2883 Reference::fromAccumulator(this).storeOnStack(CallData::This);
2884
2885 setExprResult(Reference::fromAccumulator(this));
2886}
2887
2888bool Codegen::visit(NewExpression *ast)
2889{
2890 if (hasError())
2891 return false;
2892
2893 RegisterScope scope(this);
2894 TailCallBlocker blockTailCalls(this);
2895
2896 Reference base = expression(ast->expression);
2897 if (hasError())
2898 return false;
2899 if (base.isSuper()) {
2900 throwSyntaxError(ast->expression->firstSourceLocation(), QStringLiteral("Cannot use new with super."));
2901 return false;
2902 }
2903
2904 handleConstruct(base, nullptr);
2905 return false;
2906}
2907
2908bool Codegen::visit(NewMemberExpression *ast)
2909{
2910 if (hasError())
2911 return false;
2912
2913 RegisterScope scope(this);
2914 TailCallBlocker blockTailCalls(this);
2915
2916 Reference base = expression(ast->base);
2917 if (hasError())
2918 return false;
2919 if (base.isSuper()) {
2920 throwSyntaxError(ast->base->firstSourceLocation(), QStringLiteral("Cannot use new with super."));
2921 return false;
2922 }
2923
2924 handleConstruct(base, ast->arguments);
2925 return false;
2926}
2927
2928bool Codegen::visit(NotExpression *ast)
2929{
2930 if (hasError())
2931 return false;
2932
2933 TailCallBlocker blockTailCalls(this);
2934 auto e = expression(ast->expression);
2935 if (hasError())
2936 return false;
2937 setExprResult(unop(Not, e));
2938 return false;
2939}
2940
2941bool Codegen::visit(NullExpression *)
2942{
2943 if (hasError())
2944 return false;
2945
2946 if (exprAccept(cx))
2947 bytecodeGenerator->jump().link(*currentExpr().iffalse());
2948 else
2949 setExprResult(Reference::fromConst(this, Encode::null()));
2950
2951 return false;
2952}
2953
2954bool Codegen::visit(NumericLiteral *ast)
2955{
2956 if (hasError())
2957 return false;
2958
2959 setExprResult(Reference::fromConst(this, QV4::Encode::smallestNumber(ast->value)));
2960 return false;
2961}
2962
2963bool Codegen::visit(ObjectPattern *ast)
2964{
2965 if (hasError())
2966 return false;
2967
2968 TailCallBlocker blockTailCalls(this);
2969
2970 RegisterScope scope(this);
2971
2972 QStringList members;
2973
2974 int argc = 0;
2975 int args = 0;
2976 auto push = [this, &args, &argc](const Reference &arg) {
2977 int temp = bytecodeGenerator->newRegister();
2978 if (argc == 0)
2979 args = temp;
2980 (void) arg.storeOnStack(temp);
2981 ++argc;
2982 };
2983
2984 PatternPropertyList *it = ast->properties;
2985 for (; it; it = it->next) {
2986 PatternProperty *p = it->property;
2987 AST::ComputedPropertyName *cname = AST::cast<AST::ComputedPropertyName *>(p->name);
2988 if (cname || p->type != PatternProperty::Literal)
2989 break;
2990 QString name = p->name->asString();
2991 uint arrayIndex = stringToArrayIndex(name);
2992 if (arrayIndex != UINT_MAX)
2993 break;
2994 if (members.contains(name))
2995 break;
2996 members.append(name);
2997
2998 Reference value;
2999 {
3000 RegisterScope innerScope(this);
3001 value = expression(p->initializer, name);
3002 if (hasError())
3003 return false;
3004
3005 // Locals and arguments can be moved directly. They outlive the innerScope.
3006 if (!value.isStackSlot() || !value.stackSlotIsLocalOrArgument) {
3007 value.loadInAccumulator();
3008 value = Reference::fromAccumulator(this);
3009 }
3010 }
3011 push(value);
3012 }
3013
3014 int classId = jsUnitGenerator->registerJSClass(members);
3015
3016 // handle complex property setters
3017 for (; it; it = it->next) {
3018 PatternProperty *p = it->property;
3019 AST::ComputedPropertyName *cname = AST::cast<AST::ComputedPropertyName *>(p->name);
3020 ObjectLiteralArgument argType = ObjectLiteralArgument::Value;
3021 if (p->type == PatternProperty::Method)
3022 argType = ObjectLiteralArgument::Method;
3023 else if (p->type == PatternProperty::Getter)
3024 argType = ObjectLiteralArgument::Getter;
3025 else if (p->type == PatternProperty::Setter)
3026 argType = ObjectLiteralArgument::Setter;
3027
3028 Reference::fromConst(this, Encode(int(argType))).loadInAccumulator();
3029 push(Reference::fromAccumulator(this));
3030
3031 if (cname) {
3032 RegisterScope innerScope(this);
3033 Reference name = expression(cname->expression);
3034 if (hasError())
3035 return false;
3036 name.loadInAccumulator();
3037 } else {
3038 QString name = p->name->asString();
3039#if 0
3040 uint arrayIndex = QV4::String::toArrayIndex(name);
3041 if (arrayIndex != UINT_MAX) {
3042 Reference::fromConst(this, Encode(arrayIndex)).loadInAccumulator();
3043 } else
3044#endif
3045 {
3046 Instruction::LoadRuntimeString instr;
3047 instr.stringId = registerString(name);
3048 bytecodeGenerator->addInstruction(instr);
3049 }
3050 }
3051 push(Reference::fromAccumulator(this));
3052 {
3053 RegisterScope innerScope(this);
3054 if (p->type != PatternProperty::Literal) {
3055 // need to get the closure id for the method
3056 FunctionExpression *f = p->initializer->asFunctionDefinition();
3057 Q_ASSERT(f);
3058 int function = defineFunction(f->name.toString(), f, f->formals, f->body);
3059 if (hasError())
3060 return false;
3061 Reference::fromConst(this, Encode(function)).loadInAccumulator();
3062 } else {
3063 Reference value = expression(p->initializer);
3064 if (hasError())
3065 return false;
3066 value.loadInAccumulator();
3067 }
3068 }
3069 push(Reference::fromAccumulator(this));
3070 }
3071
3072 Instruction::DefineObjectLiteral call;
3073 call.internalClassId = classId;
3074 call.argc = argc;
3075 call.args = Moth::StackSlot::createRegister(args);
3076 bytecodeGenerator->addInstruction(call);
3077 setExprResult(Reference::fromAccumulator(this));
3078 return false;
3079}
3080
3081bool Codegen::visit(PostDecrementExpression *ast)
3082{
3083 if (hasError())
3084 return false;
3085
3086 Reference expr = expression(ast->base);
3087 if (hasError())
3088 return false;
3089 if (!expr.isLValue()) {
3090 throwReferenceError(ast->base->lastSourceLocation(), QStringLiteral("Invalid left-hand side expression in postfix operation"));
3091 return false;
3092 }
3093 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(expr, ast->decrementToken))
3094 return false;
3095
3096 setExprResult(unop(PostDecrement, expr));
3097
3098 return false;
3099}
3100
3101bool Codegen::visit(PostIncrementExpression *ast)
3102{
3103 if (hasError())
3104 return false;
3105
3106 Reference expr = expression(ast->base);
3107 if (hasError())
3108 return false;
3109 if (!expr.isLValue()) {
3110 throwReferenceError(ast->base->lastSourceLocation(), QStringLiteral("Invalid left-hand side expression in postfix operation"));
3111 return false;
3112 }
3113 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(expr, ast->incrementToken))
3114 return false;
3115
3116 setExprResult(unop(PostIncrement, expr));
3117 return false;
3118}
3119
3120bool Codegen::visit(PreDecrementExpression *ast)
3121{ if (hasError())
3122 return false;
3123
3124 Reference expr = expression(ast->expression);
3125 if (hasError())
3126 return false;
3127 if (!expr.isLValue()) {
3128 throwReferenceError(ast->expression->lastSourceLocation(), QStringLiteral("Prefix -- operator applied to value that is not a reference."));
3129 return false;
3130 }
3131
3132 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(expr, ast->decrementToken))
3133 return false;
3134 setExprResult(unop(PreDecrement, expr));
3135 return false;
3136}
3137
3138bool Codegen::visit(PreIncrementExpression *ast)
3139{
3140 if (hasError())
3141 return false;
3142
3143 Reference expr = expression(ast->expression);
3144 if (hasError())
3145 return false;
3146 if (!expr.isLValue()) {
3147 throwReferenceError(ast->expression->lastSourceLocation(), QStringLiteral("Prefix ++ operator applied to value that is not a reference."));
3148 return false;
3149 }
3150
3151 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(expr, ast->incrementToken))
3152 return false;
3153 setExprResult(unop(PreIncrement, expr));
3154 return false;
3155}
3156
3157bool Codegen::visit(RegExpLiteral *ast)
3158{
3159 if (hasError())
3160 return false;
3161
3162 auto r = Reference::fromStackSlot(this);
3163 r.isReadonly = true;
3164 setExprResult(r);
3165
3166 Instruction::MoveRegExp instr;
3167 instr.regExpId = jsUnitGenerator->registerRegExp(ast);
3168 instr.destReg = r.stackSlot();
3169 bytecodeGenerator->addInstruction(instr);
3170 return false;
3171}
3172
3173bool Codegen::visit(StringLiteral *ast)
3174{
3175 if (hasError())
3176 return false;
3177
3178 auto r = Reference::fromAccumulator(this);
3179 r.isReadonly = true;
3180 setExprResult(r);
3181
3182 Instruction::LoadRuntimeString instr;
3183 instr.stringId = registerString(ast->value.toString());
3184 bytecodeGenerator->addInstruction(instr);
3185 return false;
3186}
3187
3188bool Codegen::visit(TemplateLiteral *ast)
3189{
3190 if (hasError())
3191 return false;
3192
3193 TailCallBlocker blockTailCalls(this);
3194
3195 Instruction::LoadRuntimeString instr;
3196 instr.stringId = registerString(ast->value.toString());
3197 bytecodeGenerator->addInstruction(instr);
3198
3199 if (ast->expression) {
3200 RegisterScope scope(this);
3201 int temp = bytecodeGenerator->newRegister();
3202 Instruction::StoreReg store;
3203 store.reg = temp;
3204 bytecodeGenerator->addInstruction(store);
3205
3206 Reference expr = expression(ast->expression);
3207 if (hasError())
3208 return false;
3209
3210 if (ast->next) {
3211 int temp2 = bytecodeGenerator->newRegister();
3212 expr.storeOnStack(temp2);
3213 visit(ast->next);
3214
3215 Instruction::Add instr;
3216 instr.lhs = temp2;
3217 bytecodeGenerator->addInstruction(instr);
3218 } else {
3219 expr.loadInAccumulator();
3220 }
3221
3222 Instruction::Add instr;
3223 instr.lhs = temp;
3224 bytecodeGenerator->addInstruction(instr);
3225 }
3226
3227 auto r = Reference::fromAccumulator(this);
3228 r.isReadonly = true;
3229
3230 setExprResult(r);
3231 return false;
3232
3233}
3234
3235bool Codegen::visit(ThisExpression *)
3236{
3237 if (hasError())
3238 return false;
3239
3240 for (Context *parentContext = _context; parentContext; parentContext = parentContext->parent) {
3241 if (parentContext->isArrowFunction) {
3242 Reference r = referenceForName(QStringLiteral("this"), false);
3243 r.isReadonly = true;
3244 setExprResult(r);
3245 return false;
3246 }
3247 if (parentContext->contextType != ContextType::Block)
3248 break;
3249 }
3250
3251 setExprResult(Reference::fromThis(this));
3252 return false;
3253}
3254
3255bool Codegen::visit(TildeExpression *ast)
3256{
3257 if (hasError())
3258 return false;
3259
3260 TailCallBlocker blockTailCalls(this);
3261 auto e = expression(ast->expression);
3262 if (hasError())
3263 return false;
3264
3265 setExprResult(unop(Compl, e));
3266 return false;
3267}
3268
3269bool Codegen::visit(TrueLiteral *)
3270{
3271 if (hasError())
3272 return false;
3273
3274 setExprResult(Reference::fromConst(this, QV4::Encode(true)));
3275 return false;
3276}
3277
3278bool Codegen::visit(TypeOfExpression *ast)
3279{
3280 if (hasError())
3281 return false;
3282
3283 RegisterScope scope(this);
3284 TailCallBlocker blockTailCalls(this);
3285
3286 Reference expr = expression(ast->expression);
3287 if (hasError())
3288 return false;
3289
3290 if (expr.type == Reference::Name) {
3291 // special handling as typeof doesn't throw here
3292 Instruction::TypeofName instr;
3293 instr.name = expr.nameAsIndex();
3294 bytecodeGenerator->addInstruction(instr);
3295 } else {
3296 expr.loadInAccumulator();
3297 Instruction::TypeofValue instr;
3298 bytecodeGenerator->addInstruction(instr);
3299 }
3300 setExprResult(Reference::fromAccumulator(this));
3301
3302 return false;
3303}
3304
3305bool Codegen::visit(UnaryMinusExpression *ast)
3306{
3307 if (hasError())
3308 return false;
3309
3310 TailCallBlocker blockTailCalls(this);
3311 auto e = expression(ast->expression);
3312 if (hasError())
3313 return false;
3314
3315 setExprResult(unop(UMinus, e));
3316 return false;
3317}
3318
3319bool Codegen::visit(UnaryPlusExpression *ast)
3320{
3321 if (hasError())
3322 return false;
3323
3324 TailCallBlocker blockTailCalls(this);
3325 auto e = expression(ast->expression);
3326 if (hasError())
3327 return false;
3328
3329 setExprResult(unop(UPlus, e));
3330 return false;
3331}
3332
3333bool Codegen::visit(VoidExpression *ast)
3334{
3335 if (hasError())
3336 return false;
3337
3338 RegisterScope scope(this);
3339 TailCallBlocker blockTailCalls(this);
3340
3341 statement(ast->expression);
3342 setExprResult(Reference::fromConst(this, Encode::undefined()));
3343 return false;
3344}
3345
3346bool Codegen::visit(FunctionDeclaration * ast)
3347{
3348 if (hasError())
3349 return false;
3350
3351 // no need to block tail calls: the function body isn't visited here.
3352 RegisterScope scope(this);
3353
3354 if (_functionContext->contextType == ContextType::Binding)
3355 referenceForName(ast->name.toString(), true).loadInAccumulator();
3356 exprAccept(nx);
3357 return false;
3358}
3359
3360bool Codegen::visit(YieldExpression *ast)
3361{
3362 if (inFormalParameterList) {
3363 throwSyntaxError(ast->firstSourceLocation(), QLatin1String("yield is not allowed inside parameter lists"));
3364 return false;
3365 }
3366
3367 auto innerMostCurentFunctionContext = _context;
3368 while (innerMostCurentFunctionContext && innerMostCurentFunctionContext->contextType != ContextType::Function)
3369 innerMostCurentFunctionContext = innerMostCurentFunctionContext->parent;
3370
3371 Q_ASSERT(innerMostCurentFunctionContext); // yield outside function would have been rejected by parser
3372
3373 if (!innerMostCurentFunctionContext->isGenerator) {
3374 throwSyntaxError(ast->firstSourceLocation(), u"Yield is only valid in generator functions"_s);
3375 return false;
3376 }
3377
3378 RegisterScope scope(this);
3379 TailCallBlocker blockTailCalls(this);
3380 Reference expr = ast->expression ? expression(ast->expression) : Reference::fromConst(this, Encode::undefined());
3381 if (hasError())
3382 return false;
3383
3384 Reference acc = Reference::fromAccumulator(this);
3385
3386 if (ast->isYieldStar) {
3387 Reference iterator = Reference::fromStackSlot(this);
3388 Reference lhsValue = Reference::fromConst(this, Encode::undefined()).storeOnStack();
3389
3390 expr.loadInAccumulator();
3391 Instruction::GetIterator getIterator;
3392 getIterator.iterator = static_cast<int>(AST::ForEachType::Of);
3393 bytecodeGenerator->addInstruction(getIterator);
3394 iterator.storeConsumeAccumulator();
3395 Instruction::LoadUndefined load;
3396 bytecodeGenerator->addInstruction(load);
3397
3398 // Enter the loop by fall-through, so that the code generator can tell it's reachable.
3399 BytecodeGenerator::Label in = bytecodeGenerator->label();
3400
3401 Instruction::IteratorNextForYieldStar next;
3402 next.object = lhsValue.stackSlot();
3403 next.iterator = iterator.stackSlot();
3404 BytecodeGenerator::Jump done = bytecodeGenerator->addJumpInstruction(next);
3405 BytecodeGenerator::Jump yieldValue = bytecodeGenerator->jumpNotUndefined();
3406
3407 lhsValue.loadInAccumulator();
3408 emitReturn(acc);
3409
3410 yieldValue.link();
3411 lhsValue.loadInAccumulator();
3412 Instruction::YieldStar yield;
3413 bytecodeGenerator->addInstruction(yield);
3414 bytecodeGenerator->jump().link(in);
3415
3416 done.link();
3417 bytecodeGenerator->checkException();
3418
3419 lhsValue.loadInAccumulator();
3420 setExprResult(acc);
3421 return false;
3422 }
3423
3424 expr.loadInAccumulator();
3425 Instruction::Yield yield;
3426 bytecodeGenerator->addInstruction(yield);
3427 Instruction::Resume resume;
3428 BytecodeGenerator::Jump jump = bytecodeGenerator->addJumpInstruction(resume);
3429 emitReturn(acc);
3430 jump.link();
3431 setExprResult(acc);
3432 return false;
3433}
3434
3435int Codegen::defineFunction(const QString &name, AST::Node *ast, AST::FormalParameterList *formals,
3436 AST::StatementList *body)
3437{
3438 enterContext(ast);
3439
3440 if (_context->functionIndex >= 0)
3441 // already defined
3442 return leaveContext();
3443
3444 _context->name = name.isEmpty() ? currentExpr().result().name : name;
3445 _module->functions.append(_context);
3446 _context->functionIndex = _module->functions.size() - 1;
3447
3448 Context *savedFunctionContext = _functionContext;
3449 _functionContext = _context;
3450 ControlFlow *savedControlFlow = controlFlow;
3451 controlFlow = nullptr;
3452
3453 if (_context->contextType == ContextType::Global || _context->contextType == ContextType::ScriptImportedByQML) {
3454 _module->blocks.append(_context);
3455 _context->blockIndex = _module->blocks.size() - 1;
3456 }
3457 if (_module->isDebugging()) // allow the debugger to see overwritten arguments
3458 _context->argumentsCanEscape = true;
3459
3460 // When a user writes the following QML signal binding:
3461 // onSignal: function() { doSomethingUsefull }
3462 // we will generate a binding function that just returns the closure. However, that's not useful
3463 // at all, because if the onSignal is a signal handler, the user is actually making it explicit
3464 // that the binding is a function, so we should execute that. However, we don't know that during
3465 // AOT compilation, so mark the surrounding function as only-returning-a-closure.
3466 _context->returnsClosure = body && cast<ExpressionStatement *>(body->statement)
3467 && cast<FunctionExpression *>(cast<ExpressionStatement *>(body->statement)->expression);
3468
3469 BytecodeGenerator bytecode(_context->line, _module->debugInstructionPass,
3470 storeSourceLocations);
3471 BytecodeGenerator *savedBytecodeGenerator;
3472 savedBytecodeGenerator = bytecodeGenerator;
3473 bytecodeGenerator = &bytecode;
3474 bytecodeGenerator->setLocation(ast->firstSourceLocation());
3475 BytecodeGenerator::Label *savedReturnLabel = _returnLabel;
3476 _returnLabel = nullptr;
3477
3478 OptionalChainStates optionalChainStates;
3479 OptionalChainStates *savedOptionalChainStates = m_optionalChainsStates;
3480 m_optionalChainsStates = &optionalChainStates;
3481
3482 // reserve the js stack frame (Context & js Function & accumulator)
3483 bytecodeGenerator->newRegisterArray(
3484 sizeof(CallData) / sizeof(StaticValue) - 1 + _context->arguments.size());
3485
3486 bool _inFormalParameterList = false;
3487 qSwap(_inFormalParameterList, inFormalParameterList);
3488
3489 int returnAddress = -1;
3490 bool _requiresReturnValue = _context->requiresImplicitReturnValue();
3491 qSwap(requiresReturnValue, _requiresReturnValue);
3492 returnAddress = bytecodeGenerator->newRegister();
3493 qSwap(_returnAddress, returnAddress);
3494
3495 // register the lexical scope for global code
3496 if (!_context->parent && _context->requiresExecutionContext) {
3497 _module->blocks.append(_context);
3498 _context->blockIndex = _module->blocks.size() - 1;
3499 }
3500
3501 TailCallBlocker maybeBlockTailCalls(this, _context->canHaveTailCalls());
3502
3503 RegisterScope registerScope(this);
3504 _context->emitBlockHeader(this);
3505
3506 {
3507 QScopedValueRollback<bool> inFormals(inFormalParameterList, true);
3508 TailCallBlocker blockTailCalls(this); // we're not in the FunctionBody or ConciseBody yet
3509
3510 int argc = 0;
3511 while (formals) {
3512 PatternElement *e = formals->element;
3513 if (!e) {
3514 if (!formals->next)
3515 // trailing comma
3516 break;
3517 Q_UNREACHABLE();
3518 }
3519
3520 if (e->type == PatternElement::RestElement) {
3521 Q_ASSERT(!formals->next);
3522 Reference arg = referenceForName(e->bindingIdentifier.toString(), true);
3523 Instruction::CreateRestParameter rest;
3524 rest.argIndex = argc;
3525 bytecodeGenerator->addInstruction(rest);
3526 arg.storeConsumeAccumulator();
3527 } else {
3528 // Copy the value of TDZ-promoted parameters into distinct slots to enable TDZ check
3529 const auto memberIt = _context->members.constFind(e->bindingIdentifier.toString());
3530 const bool promoted = memberIt != _context->members.constEnd()
3531 && memberIt->isFormalParameterTDZPromotion;
3532 if (e->bindingTarget || e->initializer || promoted) {
3533 Reference arg = referenceForFormalParameter(argc);
3534 initializeAndDestructureBindingElement(e, arg, /*isDefinition=*/true);
3535 if (hasError())
3536 break;
3537 }
3538 }
3539 formals = formals->next;
3540 ++argc;
3541 }
3542 }
3543
3544 if (_context->isGenerator) {
3545 Instruction::Yield yield;
3546 bytecodeGenerator->addInstruction(yield);
3547 }
3548
3549 statementList(body);
3550
3551 if (hasError()) {
3552 bytecodeGenerator->setError(true);
3553 } else {
3554 bytecodeGenerator->setLocation(ast->lastSourceLocation());
3555 _context->emitBlockFooter(this);
3556
3557 if (_returnLabel) {
3558 _returnLabel->link();
3559 bytecodeGenerator->setLocation(ast->lastSourceLocation());
3560 }
3561
3562 if (_returnLabel || requiresReturnValue) {
3563 Instruction::LoadReg load;
3564 load.reg = Moth::StackSlot::createRegister(_returnAddress);
3565 bytecodeGenerator->addInstruction(load);
3566 } else {
3567 Reference::fromConst(this, Encode::undefined()).loadInAccumulator();
3568 }
3569
3570 bytecodeGenerator->addInstruction(Instruction::Ret());
3571
3572 Q_ASSERT(_context == _functionContext);
3573 bytecodeGenerator->finalize(_context);
3574 _context->registerCountInFunction = bytecodeGenerator->registerCount();
3575 static const bool showCode = qEnvironmentVariableIsSet("QV4_SHOW_BYTECODE");
3576 if (showCode) {
3577 qDebug() << "=== Bytecode for" << _context->name << "strict mode" << _context->isStrict
3578 << "register count" << _context->registerCountInFunction << "implicit return" << requiresReturnValue;
3579 qDebug().noquote() << QV4::Moth::dumpBytecode(
3580 _context->code, _context->locals.size(), _context->arguments.size(),
3581 _context->line, _context->lineAndStatementNumberMapping);
3582 qDebug();
3583 }
3584 }
3585
3586 qSwap(_returnAddress, returnAddress);
3587 qSwap(requiresReturnValue, _requiresReturnValue);
3588 qSwap(_inFormalParameterList, inFormalParameterList);
3589 m_optionalChainsStates = savedOptionalChainStates;
3590 bytecodeGenerator = savedBytecodeGenerator;
3591 delete _returnLabel;
3592 _returnLabel = savedReturnLabel;
3593 controlFlow = savedControlFlow;
3594 _functionContext = savedFunctionContext;
3595
3596 return leaveContext();
3597}
3598
3599bool Codegen::visit(Block *ast)
3600{
3601 if (hasError())
3602 return false;
3603
3604 RegisterScope scope(this);
3605
3606 ControlFlowBlock controlFlow(this, ast);
3607 statementList(ast->statements);
3608 return false;
3609}
3610
3611bool Codegen::visit(BreakStatement *ast)
3612{
3613 if (hasError())
3614 return false;
3615
3616 // no need to block tail calls here: children aren't visited
3617 if (!controlFlow) {
3618 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral("Break outside of loop"));
3619 return false;
3620 }
3621
3622 ControlFlow::UnwindTarget target = controlFlow->unwindTarget(ControlFlow::Break, ast->label.toString());
3623 if (!target.linkLabel.isValid()) {
3624 if (ast->label.isEmpty())
3625 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral("Break outside of loop"));
3626 else
3627 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral("Undefined label '%1'").arg(ast->label.toString()));
3628 return false;
3629 }
3630
3631 controlFlow->unwind(target);
3632
3633 return false;
3634}
3635
3636bool Codegen::visit(ContinueStatement *ast)
3637{
3638 if (hasError())
3639 return false;
3640
3641 // no need to block tail calls here: children aren't visited
3642 RegisterScope scope(this);
3643
3644 if (!controlFlow) {
3645 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral("Continue outside of loop"));
3646 return false;
3647 }
3648
3649 ControlFlow::UnwindTarget target = controlFlow->unwindTarget(ControlFlow::Continue, ast->label.toString());
3650 if (!target.linkLabel.isValid()) {
3651 if (ast->label.isEmpty())
3652 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral("Undefined label '%1'").arg(ast->label.toString()));
3653 else
3654 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral("continue outside of loop"));
3655 return false;
3656 }
3657
3658 controlFlow->unwind(target);
3659
3660 return false;
3661}
3662
3663bool Codegen::visit(DebuggerStatement *)
3664{
3665 Q_UNIMPLEMENTED();
3666 return false;
3667}
3668
3669bool Codegen::visit(DoWhileStatement *ast)
3670{
3671 if (hasError())
3672 return false;
3673
3674 RegisterScope scope(this);
3675
3676 BytecodeGenerator::Label body = bytecodeGenerator->newLabel();
3677 BytecodeGenerator::Label cond = bytecodeGenerator->newLabel();
3678 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
3679
3680 ControlFlowLoop flow(this, &end, &cond);
3681
3682 // special case that is not a loop:
3683 // do {...} while (false)
3684 if (!AST::cast<FalseLiteral *>(ast->expression))
3685 bytecodeGenerator->addLoopStart(body);
3686
3687 body.link();
3688 statement(ast->statement);
3689 setJumpOutLocation(bytecodeGenerator, ast->statement, ast->semicolonToken);
3690
3691 cond.link();
3692 if (AST::cast<TrueLiteral *>(ast->expression)) {
3693 // do {} while (true) -> just jump back to the loop body, no need to generate a condition
3694 bytecodeGenerator->checkException();
3695 bytecodeGenerator->jump().link(body);
3696 } else if (AST::cast<FalseLiteral *>(ast->expression)) {
3697 // do {} while (false) -> fall through, no need to generate a condition
3698 } else {
3699 TailCallBlocker blockTailCalls(this);
3700 bytecodeGenerator->checkException();
3701 condition(ast->expression, &body, &end, false);
3702 }
3703
3704 end.link();
3705
3706 return false;
3707}
3708
3709bool Codegen::visit(EmptyStatement *)
3710{
3711 return false;
3712}
3713
3714bool Codegen::visit(ExpressionStatement *ast)
3715{
3716 if (hasError())
3717 return false;
3718
3719 RegisterScope scope(this);
3720 TailCallBlocker blockTailCalls(this);
3721
3722 if (requiresReturnValue) {
3723 Reference e = expression(ast->expression);
3724 if (hasError())
3725 return false;
3726 (void) e.storeOnStack(_returnAddress);
3727 } else {
3728 statement(ast->expression);
3729 }
3730 return false;
3731}
3732
3733bool Codegen::visit(ForEachStatement *ast)
3734{
3735 if (hasError())
3736 return false;
3737
3738 RegisterScope scope(this);
3739 TailCallBlocker blockTailCalls(this);
3740
3741 Reference iterator = Reference::fromStackSlot(this);
3742 Reference lhsValue = Reference::fromStackSlot(this);
3743
3744 // There should be a temporal block, so that variables declared in lhs shadow outside vars.
3745 // This block should define a temporal dead zone for those variables.
3746 {
3747 RegisterScope innerScope(this);
3748 ControlFlowBlock controlFlow(this, ast);
3749 Reference expr = expression(ast->expression);
3750 if (hasError())
3751 return false;
3752
3753 expr.loadInAccumulator();
3754 Instruction::GetIterator iteratorObjInstr;
3755 iteratorObjInstr.iterator = static_cast<int>(ast->type);
3756 bytecodeGenerator->addInstruction(iteratorObjInstr);
3757 iterator.storeConsumeAccumulator();
3758 }
3759
3760 BytecodeGenerator::Label in = bytecodeGenerator->newLabel();
3761 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
3762 BytecodeGenerator::Label done;
3763
3764 {
3765 std::function<void()> cleanup;
3766 if (ast->type == ForEachType::Of) {
3767 done = bytecodeGenerator->newLabel();
3768 cleanup = [iterator, this, done]() {
3769 iterator.loadInAccumulator();
3770 Instruction::IteratorClose close;
3771 bytecodeGenerator->addInstruction(close);
3772 done.link();
3773 };
3774 } else {
3775 done = end;
3776 }
3777 BytecodeGenerator::Label continueLabel = bytecodeGenerator->newLabel();
3778 ControlFlowLoop flow(this, &end, &continueLabel, std::move(cleanup));
3779 bytecodeGenerator->addLoopStart(in);
3780 in.link();
3781 iterator.loadInAccumulator();
3782 Instruction::IteratorNext next;
3783 next.value = lhsValue.stackSlot();
3784 bytecodeGenerator->addJumpInstruction(next).link(done);
3785
3786 // each iteration gets it's own context, as per spec
3787 {
3788 RegisterScope innerScope(this);
3789 ControlFlowBlock controlFlow(this, ast);
3790
3791 if (ExpressionNode *e = ast->lhs->expressionCast()) {
3792 if (AST::Pattern *p = e->patternCast()) {
3793 RegisterScope scope(this);
3794 destructurePattern(p, lhsValue);
3795 } else {
3796 Reference lhs = expression(e);
3797 if (hasError())
3798 goto error;
3799 if (!lhs.isLValue()) {
3800 throwReferenceError(e->firstSourceLocation(), QStringLiteral("Invalid left-hand side expression for 'in' expression"));
3801 goto error;
3802 }
3803 lhs = lhs.asLValue();
3804 lhsValue.loadInAccumulator();
3805 lhs.storeConsumeAccumulator();
3806 }
3807 } else if (PatternElement *p = AST::cast<PatternElement *>(ast->lhs)) {
3808 initializeAndDestructureBindingElement(p, lhsValue, /*isDefinition =*/ true);
3809 if (hasError())
3810 goto error;
3811 } else {
3812 Q_UNREACHABLE();
3813 }
3814
3815 blockTailCalls.unblock();
3816 statement(ast->statement);
3817 setJumpOutLocation(bytecodeGenerator, ast->statement, ast->forToken);
3818 }
3819
3820 continueLabel.link();
3821 bytecodeGenerator->setLocation(ast->forToken);
3822 bytecodeGenerator->checkException();
3823 bytecodeGenerator->jump().link(in);
3824
3825 error:
3826 end.link();
3827
3828 // all execution paths need to end up here (normal loop exit, break, and exceptions) in
3829 // order to reset the unwind handler, and to close the iterator in calse of an for-of loop.
3830 }
3831
3832 return false;
3833}
3834
3835bool Codegen::visit(ForStatement *ast)
3836{
3837 if (hasError())
3838 return false;
3839
3840 RegisterScope scope(this);
3841 TailCallBlocker blockTailCalls(this);
3842
3843 ControlFlowBlock controlFlow(this, ast);
3844
3845 if (ast->initialiser)
3846 statement(ast->initialiser);
3847 else if (ast->declarations)
3848 variableDeclarationList(ast->declarations);
3849
3850 BytecodeGenerator::Label cond = bytecodeGenerator->label();
3851 BytecodeGenerator::Label body = bytecodeGenerator->newLabel();
3852 BytecodeGenerator::Label step = bytecodeGenerator->newLabel();
3853 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
3854
3855 ControlFlowLoop flow(this, &end, &step);
3856 bytecodeGenerator->addLoopStart(cond);
3857 condition(ast->condition, &body, &end, true);
3858
3859 body.link();
3860 blockTailCalls.unblock();
3861 statement(ast->statement);
3862 blockTailCalls.reblock();
3863 setJumpOutLocation(bytecodeGenerator, ast->statement, ast->forToken);
3864
3865 step.link();
3866 if (_context->requiresExecutionContext) {
3867 Instruction::CloneBlockContext clone;
3868 bytecodeGenerator->addInstruction(clone);
3869 }
3870 statement(ast->expression);
3871 bytecodeGenerator->setLocation(ast->forToken);
3872 bytecodeGenerator->checkException();
3873 bytecodeGenerator->jump().link(cond);
3874
3875 end.link();
3876
3877 return false;
3878}
3879
3880bool Codegen::visit(IfStatement *ast)
3881{
3882 if (hasError())
3883 return false;
3884
3885 RegisterScope scope(this);
3886 TailCallBlocker blockTailCalls(this);
3887
3888 BytecodeGenerator::Label trueLabel = bytecodeGenerator->newLabel();
3889 BytecodeGenerator::Label falseLabel = bytecodeGenerator->newLabel();
3890 condition(ast->expression, &trueLabel, &falseLabel, true);
3891 blockTailCalls.unblock();
3892
3893 trueLabel.link();
3894 statement(ast->ok);
3895 if (ast->ko) {
3896 BytecodeGenerator::Jump jump_endif = bytecodeGenerator->jump();
3897 falseLabel.link();
3898 statement(ast->ko);
3899 jump_endif.link();
3900 } else {
3901 falseLabel.link();
3902 }
3903
3904 return false;
3905}
3906
3907bool Codegen::visit(LabelledStatement *ast)
3908{
3909 if (hasError())
3910 return false;
3911
3912 RegisterScope scope(this);
3913
3914 // check that no outer loop contains the label
3915 ControlFlow *l = controlFlow;
3916 while (l) {
3917 if (l->label() == ast->label) {
3918 QString error = QString(QStringLiteral("Label '%1' has already been declared")).arg(ast->label.toString());
3919 throwSyntaxError(ast->firstSourceLocation(), error);
3920 return false;
3921 }
3922 l = l->parent;
3923 }
3924 _labelledStatement = ast;
3925
3926 if (AST::cast<AST::SwitchStatement *>(ast->statement) ||
3927 AST::cast<AST::WhileStatement *>(ast->statement) ||
3928 AST::cast<AST::DoWhileStatement *>(ast->statement) ||
3929 AST::cast<AST::ForStatement *>(ast->statement) ||
3930 AST::cast<AST::ForEachStatement *>(ast->statement)) {
3931 statement(ast->statement); // labelledStatement will be associated with the ast->statement's loop.
3932 } else {
3933 BytecodeGenerator::Label breakLabel = bytecodeGenerator->newLabel();
3934 ControlFlowLoop flow(this, &breakLabel);
3935 statement(ast->statement);
3936 breakLabel.link();
3937 }
3938
3939 return false;
3940}
3941
3942void Codegen::emitReturn(const Reference &expr)
3943{
3944 if (controlFlow) {
3945 const ControlFlow::UnwindTarget target = controlFlow->unwindTarget(ControlFlow::Return);
3946 if (target.linkLabel.isValid() && (target.unwindLevel || target.completionRegister >= 0)) {
3947 Q_ASSERT(_returnAddress >= 0);
3948 (void) expr.storeOnStack(_returnAddress);
3949 controlFlow->unwind(target);
3950 return;
3951 }
3952 }
3953
3954 expr.loadInAccumulator();
3955 bytecodeGenerator->addInstruction(Instruction::Ret());
3956}
3957
3958bool Codegen::visit(ReturnStatement *ast)
3959{
3960 if (hasError())
3961 return false;
3962
3963 if (_functionContext->contextType != ContextType::Function && _functionContext->contextType != ContextType::Binding) {
3964 throwSyntaxError(ast->returnToken, QStringLiteral("Return statement outside of function"));
3965 return false;
3966 }
3967 Reference expr;
3968 if (ast->expression) {
3969 expr = expression(ast->expression);
3970 if (hasError())
3971 return false;
3972 } else {
3973 expr = Reference::fromConst(this, Encode::undefined());
3974 }
3975
3976 emitReturn(expr);
3977
3978 return false;
3979}
3980
3981bool Codegen::visit(SwitchStatement *ast)
3982{
3983 if (hasError())
3984 return false;
3985
3986 if (requiresReturnValue)
3987 Reference::fromConst(this, Encode::undefined()).storeOnStack(_returnAddress);
3988
3989 RegisterScope scope(this);
3990 TailCallBlocker blockTailCalls(this);
3991
3992 if (ast->block) {
3993 BytecodeGenerator::Label switchEnd = bytecodeGenerator->newLabel();
3994
3995 Reference lhs = expression(ast->expression);
3996 if (hasError())
3997 return false;
3998 lhs = lhs.storeOnStack();
3999
4000 ControlFlowBlock controlFlow(this, ast->block);
4001
4002 // set up labels for all clauses
4003 QHash<Node *, BytecodeGenerator::Label> blockMap;
4004 for (CaseClauses *it = ast->block->clauses; it; it = it->next)
4005 blockMap[it->clause] = bytecodeGenerator->newLabel();
4006 if (ast->block->defaultClause)
4007 blockMap[ast->block->defaultClause] = bytecodeGenerator->newLabel();
4008 for (CaseClauses *it = ast->block->moreClauses; it; it = it->next)
4009 blockMap[it->clause] = bytecodeGenerator->newLabel();
4010
4011 // do the switch conditions
4012 for (CaseClauses *it = ast->block->clauses; it; it = it->next) {
4013 CaseClause *clause = it->clause;
4014 Reference rhs = expression(clause->expression);
4015 if (hasError())
4016 return false;
4017 rhs.loadInAccumulator();
4018 bytecodeGenerator->jumpStrictEqual(lhs.stackSlot(), blockMap.value(clause));
4019 }
4020
4021 for (CaseClauses *it = ast->block->moreClauses; it; it = it->next) {
4022 CaseClause *clause = it->clause;
4023 Reference rhs = expression(clause->expression);
4024 if (hasError())
4025 return false;
4026 rhs.loadInAccumulator();
4027 bytecodeGenerator->jumpStrictEqual(lhs.stackSlot(), blockMap.value(clause));
4028 }
4029
4030 if (DefaultClause *defaultClause = ast->block->defaultClause)
4031 bytecodeGenerator->jump().link(blockMap.value(defaultClause));
4032 else
4033 bytecodeGenerator->jump().link(switchEnd);
4034
4035 ControlFlowLoop flow(this, &switchEnd);
4036
4037 insideSwitch = true;
4038 blockTailCalls.unblock();
4039 for (CaseClauses *it = ast->block->clauses; it; it = it->next) {
4040 CaseClause *clause = it->clause;
4041 blockMap[clause].link();
4042
4043 statementList(clause->statements);
4044 }
4045
4046 if (ast->block->defaultClause) {
4047 DefaultClause *clause = ast->block->defaultClause;
4048 blockMap[clause].link();
4049
4050 statementList(clause->statements);
4051 }
4052
4053 for (CaseClauses *it = ast->block->moreClauses; it; it = it->next) {
4054 CaseClause *clause = it->clause;
4055 blockMap[clause].link();
4056
4057 statementList(clause->statements);
4058 }
4059 insideSwitch = false;
4060
4061 switchEnd.link();
4062
4063 }
4064
4065 return false;
4066}
4067
4068bool Codegen::visit(ThrowStatement *ast)
4069{
4070 if (hasError())
4071 return false;
4072
4073 RegisterScope scope(this);
4074 TailCallBlocker blockTailCalls(this);
4075
4076 Reference expr = expression(ast->expression);
4077 if (hasError())
4078 return false;
4079
4080 expr.loadInAccumulator();
4081 Instruction::ThrowException instr;
4082 bytecodeGenerator->addInstruction(instr);
4083 return false;
4084}
4085
4086void Codegen::handleTryCatch(TryStatement *ast)
4087{
4088 Q_ASSERT(ast);
4089 RegisterScope scope(this);
4090 {
4091 ControlFlowCatch catchFlow(this, ast->catchExpression);
4092 RegisterScope scope(this);
4093 TailCallBlocker blockTailCalls(this); // IMPORTANT: destruction will unblock tail calls before catch is generated
4094 statement(ast->statement);
4095 }
4096}
4097
4098void Codegen::handleTryFinally(TryStatement *ast)
4099{
4100 RegisterScope scope(this);
4101 const bool hasCatchBlock = ast->catchExpression;
4102 ControlFlowFinally finally(this, ast->finallyExpression, hasCatchBlock);
4103 TailCallBlocker blockTailCalls(this); // IMPORTANT: destruction will unblock tail calls before finally is generated
4104
4105 if (ast->catchExpression) {
4106 handleTryCatch(ast);
4107 } else {
4108 RegisterScope scope(this);
4109 statement(ast->statement);
4110 }
4111}
4112
4113bool Codegen::visit(TryStatement *ast)
4114{
4115 if (hasError())
4116 return false;
4117
4118 RegisterScope scope(this);
4119
4120 if (ast->finallyExpression && ast->finallyExpression->statement) {
4121 handleTryFinally(ast);
4122 } else {
4123 handleTryCatch(ast);
4124 }
4125
4126 return false;
4127}
4128
4129bool Codegen::visit(VariableStatement *ast)
4130{
4131 if (hasError())
4132 return false;
4133
4134 variableDeclarationList(ast->declarations);
4135 return false;
4136}
4137
4138bool Codegen::visit(WhileStatement *ast)
4139{
4140 if (hasError())
4141 return false;
4142
4143 if (AST::cast<FalseLiteral *>(ast->expression))
4144 return false;
4145
4146 RegisterScope scope(this);
4147
4148 BytecodeGenerator::Label start = bytecodeGenerator->newLabel();
4149 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
4150 BytecodeGenerator::Label cond = bytecodeGenerator->label();
4151 ControlFlowLoop flow(this, &end, &cond);
4152 bytecodeGenerator->addLoopStart(cond);
4153
4154 bytecodeGenerator->checkException();
4155
4156 if (!AST::cast<TrueLiteral *>(ast->expression)) {
4157 TailCallBlocker blockTailCalls(this);
4158 condition(ast->expression, &start, &end, true);
4159 }
4160
4161 start.link();
4162 statement(ast->statement);
4163 setJumpOutLocation(bytecodeGenerator, ast->statement, ast->whileToken);
4164 bytecodeGenerator->jump().link(cond);
4165
4166 end.link();
4167 return false;
4168}
4169
4170bool Codegen::visit(WithStatement *ast)
4171{
4172 if (hasError())
4173 return false;
4174
4175 RegisterScope scope(this);
4176 TailCallBlocker blockTailCalls(this);
4177
4178 Reference src = expression(ast->expression);
4179 if (hasError())
4180 return false;
4181 src = src.storeOnStack(); // trigger load before we setup the exception handler, so exceptions here go to the right place
4182 src.loadInAccumulator();
4183
4184 enterContext(ast);
4185 {
4186 blockTailCalls.unblock();
4187 ControlFlowWith flow(this);
4188 statement(ast->statement);
4189 }
4190 leaveContext();
4191
4192 return false;
4193}
4194
4195bool Codegen::visit(UiArrayBinding *)
4196{
4197 Q_UNIMPLEMENTED();
4198 return false;
4199}
4200
4201bool Codegen::visit(UiObjectBinding *)
4202{
4203 Q_UNIMPLEMENTED();
4204 return false;
4205}
4206
4207bool Codegen::visit(UiObjectDefinition *)
4208{
4209 Q_UNIMPLEMENTED();
4210 return false;
4211}
4212
4213bool Codegen::visit(UiPublicMember *)
4214{
4215 Q_UNIMPLEMENTED();
4216 return false;
4217}
4218
4219bool Codegen::visit(UiScriptBinding *)
4220{
4221 Q_UNIMPLEMENTED();
4222 return false;
4223}
4224
4225bool Codegen::visit(UiSourceElement *)
4226{
4227 Q_UNIMPLEMENTED();
4228 return false;
4229}
4230
4231bool Codegen::throwSyntaxErrorOnEvalOrArgumentsInStrictMode(const Reference &r, const SourceLocation& loc)
4232{
4233 if (!_context->isStrict)
4234 return false;
4235 bool isArgOrEval = false;
4236 if (r.type == Reference::Name) {
4237 QString str = jsUnitGenerator->stringForIndex(r.nameAsIndex());
4238 if (str == QLatin1String("eval") || str == QLatin1String("arguments")) {
4239 isArgOrEval = true;
4240 }
4241 } else if (r.type == Reference::ScopedLocal || r.isRegister()) {
4242 isArgOrEval = r.isArgOrEval;
4243 }
4244 if (isArgOrEval)
4245 throwSyntaxError(loc, QStringLiteral("Variable name may not be eval or arguments in strict mode"));
4246 return isArgOrEval;
4247}
4248
4249void Codegen::throwError(ErrorType errorType, const SourceLocation &loc, const QString &detail)
4250{
4251 if (hasError())
4252 return;
4253
4254 _errorType = errorType;
4255 _error.message = detail;
4256 _error.loc = loc;
4257}
4258
4259void Codegen::throwSyntaxError(const SourceLocation &loc, const QString &detail)
4260{
4261 throwError(SyntaxError, loc, detail);
4262}
4263
4264void Codegen::throwReferenceError(const SourceLocation &loc, const QString &detail)
4265{
4266 throwError(ReferenceError, loc, detail);
4267}
4268
4269QQmlJS::DiagnosticMessage Codegen::error() const
4270{
4271 return _error;
4272}
4273
4274QQmlRefPointer<QV4::CompiledData::CompilationUnit> Codegen::generateCompilationUnit(
4275 bool generateUnitData)
4276{
4277 return QQmlRefPointer<QV4::CompiledData::CompilationUnit>(
4278 new QV4::CompiledData::CompilationUnit(
4279 generateUnitData ? jsUnitGenerator->generateUnit() : nullptr),
4280 QQmlRefPointer<QV4::CompiledData::CompilationUnit>::Adopt);
4281}
4282
4283QQmlRefPointer<QV4::CompiledData::CompilationUnit> Codegen::compileModule(
4284 Moth::DebugInstructionPass debugInstructionPass, const QString &url,
4285 const QString &sourceCode,
4286 const QDateTime &sourceTimeStamp, QList<QQmlJS::DiagnosticMessage> *diagnostics)
4287{
4288 QQmlJS::Engine ee;
4289 const QQmlJS::Parser::Result parsed =
4290 QQmlJS::Parser::parseCode(&ee, sourceCode, QQmlJS::Parser::Goal::Module);
4291
4292 if (diagnostics)
4293 *diagnostics = parsed.diagnosticMessages;
4294
4295 if (!parsed.success)
4296 return QQmlRefPointer<CompiledData::CompilationUnit>();
4297
4298 QQmlJS::AST::ESModule *moduleNode = QQmlJS::AST::cast<QQmlJS::AST::ESModule *>(parsed.rootNode);
4299 if (!moduleNode) {
4300 // if parsing was successful, and we have no module, then
4301 // the file was empty.
4302 if (diagnostics)
4303 diagnostics->clear();
4304 return nullptr;
4305 }
4306
4307 using namespace QV4::Compiler;
4308 Compiler::Module compilerModule(url, url, debugInstructionPass);
4309 compilerModule.unitFlags |= CompiledData::Unit::IsESModule;
4310 compilerModule.sourceTimeStamp = sourceTimeStamp;
4311 JSUnitGenerator jsGenerator(&compilerModule);
4312 Codegen cg(&jsGenerator, /*strictMode*/true);
4313 cg.generateFromModule(sourceCode, moduleNode, &compilerModule);
4314 if (cg.hasError()) {
4315 if (diagnostics)
4316 *diagnostics << cg.error();
4317 return QQmlRefPointer<CompiledData::CompilationUnit>();
4318 }
4319
4320 return cg.generateCompilationUnit();
4321}
4322
4323const QV4::CompiledData::Unit *Codegen::generateNativeModuleUnitData(
4324 Moth::DebugInstructionPass debugInstructionPass, const QString &url,
4325 const Value &value)
4326{
4327 using namespace QV4::Compiler;
4328 Compiler::Module compilerModule(url, url, debugInstructionPass);
4329 compilerModule.unitFlags |= CompiledData::Unit::IsESModule;
4330 JSUnitGenerator jsGenerator(&compilerModule);
4331 Codegen cg(&jsGenerator, /*strictMode*/true);
4332 cg.generateFromModule(value, &compilerModule);
4333 Q_ASSERT(!cg.hasError());
4334 return jsGenerator.generateUnit();
4335}
4336
4338{
4339 VolatileMemoryLocations locs;
4340 Codegen *parent;
4341
4342public:
4347
4349 {
4350 s->accept(this);
4351 return locs;
4352 }
4353
4354 bool visit(ArrayMemberExpression *) override
4355 {
4356 locs.setAllVolatile();
4357 return false;
4358 }
4359
4360 bool visit(FieldMemberExpression *) override
4361 {
4362 locs.setAllVolatile();
4363 return false;
4364 }
4365
4366 bool visit(PostIncrementExpression *e) override
4367 {
4368 collectIdentifiers(locs.specificLocations, e->base);
4369 return false;
4370 }
4371
4372 bool visit(PostDecrementExpression *e) override
4373 {
4374 collectIdentifiers(locs.specificLocations, e->base);
4375 return false;
4376 }
4377
4378 bool visit(PreIncrementExpression *e) override
4379 {
4380 collectIdentifiers(locs.specificLocations, e->expression);
4381 return false;
4382 }
4383
4384 bool visit(PreDecrementExpression *e) override
4385 {
4386 collectIdentifiers(locs.specificLocations, e->expression);
4387 return false;
4388 }
4389
4390 bool visit(BinaryExpression *e) override
4391 {
4392 switch (e->op) {
4393 case QSOperator::Assign:
4394 // The left side may be a destructuring pattern. All of its targets are written.
4395 collectIdentifiers(locs.specificLocations, e->left);
4396 return true;
4397
4398 case QSOperator::InplaceAnd:
4399 case QSOperator::InplaceSub:
4400 case QSOperator::InplaceDiv:
4401 case QSOperator::InplaceAdd:
4402 case QSOperator::InplaceLeftShift:
4403 case QSOperator::InplaceMod:
4404 case QSOperator::InplaceExp:
4405 case QSOperator::InplaceMul:
4406 case QSOperator::InplaceOr:
4407 case QSOperator::InplaceRightShift:
4408 case QSOperator::InplaceURightShift:
4409 case QSOperator::InplaceXor:
4410 collectIdentifiers(locs.specificLocations, e);
4411 return false;
4412
4413 default:
4414 return true;
4415 }
4416 }
4417
4422
4423private:
4424 void collectIdentifiers(QList<QStringView> &ids, AST::Node *node) {
4425 class Collector: public QQmlJS::AST::Visitor {
4426 private:
4427 QList<QStringView> &ids;
4428 VolatileMemoryLocationScanner *parent;
4429
4430 public:
4431 Collector(QList<QStringView> &ids, VolatileMemoryLocationScanner *parent) :
4432 QQmlJS::AST::Visitor(parent->recursionDepth()), ids(ids), parent(parent)
4433 {}
4434
4435 bool visit(IdentifierExpression *ie) final {
4436 ids.append(ie->name);
4437 return false;
4438 }
4439
4440 bool visit(PatternElement *pe) final {
4441 if (!pe->bindingIdentifier.isEmpty())
4442 ids.append(pe->bindingIdentifier);
4443 return true;
4444 }
4445
4446 bool visit(PatternProperty *pp) final {
4447 if (!pp->bindingIdentifier.isEmpty())
4448 ids.append(pp->bindingIdentifier);
4449 return true;
4450 }
4451
4452 void throwRecursionDepthError() final
4453 {
4454 parent->throwRecursionDepthError();
4455 }
4456 };
4457 Collector collector(ids, this);
4458 node->accept(&collector);
4459 }
4460};
4461
4462Codegen::VolatileMemoryLocations Codegen::scanVolatileMemoryLocations(AST::Node *ast)
4463{
4464 VolatileMemoryLocationScanner scanner(this);
4465 return scanner.scan(ast);
4466}
4467
4468QUrl Codegen::url() const
4469{
4470 return QUrl(_fileNameIsUrl ? QUrl(_module->fileName) : QUrl::fromLocalFile(_module->fileName));
4471}
4472
4473bool Codegen::RValue::operator==(const RValue &other) const
4474{
4475 switch (type) {
4476 case Accumulator:
4477 return other.isAccumulator();
4478 case StackSlot:
4479 return other.isStackSlot() && theStackSlot == other.theStackSlot;
4480 case Const:
4481 return other.isConst() && constant == other.constant;
4482 default:
4483 return false;
4484 }
4485}
4486
4487Codegen::RValue Codegen::RValue::storeOnStack() const
4488{
4489 switch (type) {
4490 case Accumulator:
4491 return RValue::fromStackSlot(codegen, Reference::fromAccumulator(codegen).storeOnStack().stackSlot());
4492 case StackSlot:
4493 return *this;
4494 case Const:
4495 return RValue::fromStackSlot(codegen, Reference::storeConstOnStack(codegen, constant).stackSlot());
4496 default:
4497 Q_UNREACHABLE();
4498 }
4499}
4500
4501void Codegen::RValue::loadInAccumulator() const
4502{
4503 switch (type) {
4504 case Accumulator:
4505 // nothing to do
4506 return;
4507 case StackSlot:
4508 return Reference::fromStackSlot(codegen, theStackSlot).loadInAccumulator();
4509 case Const:
4510 return Reference::fromConst(codegen, constant).loadInAccumulator();
4511 default:
4512 Q_UNREACHABLE();
4513 }
4514
4515}
4516
4517bool Codegen::Reference::operator==(const Codegen::Reference &other) const
4518{
4519 if (type != other.type)
4520 return false;
4521 switch (type) {
4522 case Invalid:
4523 case Accumulator:
4524 break;
4525 case Super:
4526 return true;
4527 case SuperProperty:
4528 return property == other.property;
4529 case StackSlot:
4530 return theStackSlot == other.theStackSlot;
4531 case ScopedLocal:
4532 return index == other.index && scope == other.scope;
4533 case Name:
4534 return nameAsIndex() == other.nameAsIndex();
4535 case Member:
4536 return propertyBase == other.propertyBase && propertyNameIndex == other.propertyNameIndex;
4537 case Subscript:
4538 return elementBase == other.elementBase && other.subscriptLoadedForCall
4539 ? (subscriptLoadedForCall && element == other.element)
4540 : (!subscriptLoadedForCall && elementSubscript == other.elementSubscript);
4541 case Import:
4542 return index == other.index;
4543 case Const:
4544 return constant == other.constant;
4545 }
4546 return true;
4547}
4548
4549Codegen::RValue Codegen::Reference::asRValue() const
4550{
4551 switch (type) {
4552 case Invalid:
4553 Q_UNREACHABLE();
4554 case Accumulator:
4555 return RValue::fromAccumulator(codegen);
4556 case StackSlot:
4557 return RValue::fromStackSlot(codegen, stackSlot());
4558 case Const:
4559 return RValue::fromConst(codegen, constant);
4560 default:
4561 loadInAccumulator();
4562 return RValue::fromAccumulator(codegen);
4563 }
4564}
4565
4566Codegen::Reference Codegen::Reference::asLValue() const
4567{
4568 switch (type) {
4569 case Invalid:
4570 case Accumulator:
4571 Q_UNREACHABLE();
4572 case Super:
4573 codegen->throwSyntaxError(SourceLocation(), QStringLiteral("Super lvalues not implemented."));
4574 return *this;
4575 case Member:
4576 if (!propertyBase.isStackSlot()) {
4577 Reference r = *this;
4578 r.propertyBase = propertyBase.storeOnStack();
4579 return r;
4580 }
4581 return *this;
4582 case Subscript:
4583 if (!elementSubscript.isStackSlot()) {
4584 Reference r = *this;
4585 r.elementSubscript = elementSubscript.storeOnStack();
4586 return r;
4587 }
4588 return *this;
4589 default:
4590 return *this;
4591 }
4592}
4593
4594Codegen::Reference Codegen::Reference::storeConsumeAccumulator() const
4595{
4596 storeAccumulator(); // it doesn't matter what happens here, just do it.
4597 return Reference();
4598}
4599
4600Codegen::Reference Codegen::Reference::baseObject() const
4601{
4602 if (type == Reference::Member) {
4603 RValue rval = propertyBase;
4604 if (!rval.isValid())
4605 return Reference::fromConst(codegen, Encode::undefined());
4606 if (rval.isAccumulator())
4607 return Reference::fromAccumulator(codegen);
4608 if (rval.isStackSlot())
4609 return Reference::fromStackSlot(codegen, rval.stackSlot());
4610 if (rval.isConst())
4611 return Reference::fromConst(codegen, rval.constantValue());
4612 Q_UNREACHABLE();
4613 } else if (type == Reference::Subscript) {
4614 return Reference::fromStackSlot(codegen, elementBase.stackSlot());
4615 } else if (type == Reference::SuperProperty) {
4616 return Reference::fromStackSlot(codegen, CallData::This);
4617 } else {
4618 return Reference::fromConst(codegen, Encode::undefined());
4619 }
4620}
4621
4622Codegen::Reference Codegen::Reference::storeOnStack() const
4623{ return doStoreOnStack(-1); }
4624
4625void Codegen::Reference::storeOnStack(int slotIndex) const
4626{ doStoreOnStack(slotIndex); }
4627
4628Codegen::Reference Codegen::Reference::doStoreOnStack(int slotIndex) const
4629{
4630 Q_ASSERT(isValid());
4631
4632 if (isStackSlot() && slotIndex == -1 && !(stackSlotIsLocalOrArgument && isVolatile) && !requiresTDZCheck)
4633 return *this;
4634
4635 if (isStackSlot() && !requiresTDZCheck) { // temp-to-temp move
4636 Reference dest = Reference::fromStackSlot(codegen, slotIndex);
4637 Instruction::MoveReg move;
4638 move.srcReg = stackSlot();
4639 move.destReg = dest.stackSlot();
4640 codegen->bytecodeGenerator->addInstruction(move);
4641 return dest;
4642 }
4643
4644 Reference slot = Reference::fromStackSlot(codegen, slotIndex);
4645 if (isConstant()) {
4646 Instruction::MoveConst move;
4647 move.constIndex = codegen->registerConstant(constant);
4648 move.destTemp = slot.stackSlot();
4649 codegen->bytecodeGenerator->addInstruction(move);
4650 } else {
4651 loadInAccumulator();
4652 slot.storeConsumeAccumulator();
4653 }
4654 return slot;
4655}
4656
4657void Codegen::Reference::tdzCheck(bool requiresCheck, bool throwsReferenceError) const {
4658 if (throwsReferenceError) {
4659 codegen->generateThrowException(QStringLiteral("ReferenceError"),
4660 name + QStringLiteral(" is not defined"));
4661 return;
4662 }
4663 if (!requiresCheck)
4664 return;
4665 Instruction::DeadTemporalZoneCheck check;
4666 check.name = codegen->registerString(name);
4667 codegen->bytecodeGenerator->addInstruction(check);
4668}
4669
4670void Codegen::Reference::tdzCheckStackSlot(Moth::StackSlot slot, bool requiresCheck, bool throwsReferenceError) const {
4671 if (!requiresCheck)
4672 return;
4673 Instruction::LoadReg load;
4674 load.reg = slot;
4675 codegen->bytecodeGenerator->addInstruction(load);
4676 tdzCheck(true, throwsReferenceError);
4677}
4678
4679// Verifies, at run-time, that this reference is not currently in its temporal dead zone.
4680// Only call this for references being *assigned to*, never for the store that performs a
4681// binding's own initialization (that store is what ends the TDZ). Clobbers the accumulator.
4682void Codegen::Reference::checkTDZBeforeAssignment() const
4683{
4684 if (!requiresTDZCheck)
4685 return;
4686
4687 if (type != StackSlot && type != ScopedLocal)
4688 return;
4689
4690 loadInAccumulator();
4691}
4692
4693Codegen::Reference Codegen::Reference::storeRetainAccumulator() const
4694{
4695 if (storeWipesAccumulator()) {
4696 // a store will
4697 auto tmp = Reference::fromStackSlot(codegen);
4698 tmp.storeAccumulator(); // this is safe, and won't destory the accumulator
4699 tmp.isReadonly = isReadonly;
4700 storeAccumulator();
4701 return tmp;
4702 } else {
4703 // ok, this is safe, just do the store.
4704 storeAccumulator();
4705 return *this;
4706 }
4707}
4708
4709bool Codegen::Reference::storeWipesAccumulator() const
4710{
4711 switch (type) {
4712 default:
4713 case Invalid:
4714 case Const:
4715 case Accumulator:
4716 Q_UNREACHABLE();
4717 return false;
4718 case StackSlot:
4719 case ScopedLocal:
4720 return false;
4721 case Name:
4722 case Member:
4723 case Subscript:
4724 return true;
4725 }
4726}
4727
4728void Codegen::Reference::storeAccumulator() const
4729{
4730 if (throwsReferenceError) {
4731 codegen->generateThrowException(QStringLiteral("ReferenceError"),
4732 name + QStringLiteral(" is not defined"));
4733 return;
4734 }
4735
4736 if (isReferenceToConst) {
4737 // throw a type error
4738 codegen->generateThrowException(QStringLiteral("TypeError"));
4739 return;
4740 }
4741
4742 switch (type) {
4743 case Super:
4744 Q_UNREACHABLE_RETURN();
4745 case SuperProperty:
4746 Instruction::StoreSuperProperty store;
4747 store.property = property.stackSlot();
4748 codegen->bytecodeGenerator->addInstruction(store);
4749 return;
4750 case StackSlot: {
4751 Instruction::StoreReg store;
4752 store.reg = theStackSlot;
4753 codegen->bytecodeGenerator->addInstruction(store);
4754 return;
4755 }
4756 case ScopedLocal: {
4757 if (scope == 0) {
4758 Instruction::StoreLocal store;
4759 store.index = index;
4760 codegen->bytecodeGenerator->addInstruction(store);
4761 } else {
4762 Instruction::StoreScopedLocal store;
4763 store.index = index;
4764 store.scope = scope;
4765 codegen->bytecodeGenerator->addInstruction(store);
4766 }
4767 return;
4768 }
4769 case Name: {
4770 Context *c = codegen->currentContext();
4771 if (c->isStrict) {
4772 Instruction::StoreNameStrict store;
4773 store.name = nameAsIndex();
4774 codegen->bytecodeGenerator->addInstruction(store);
4775 } else {
4776 Instruction::StoreNameSloppy store;
4777 store.name = nameAsIndex();
4778 codegen->bytecodeGenerator->addInstruction(store);
4779 }
4780 } return;
4781 case Member:
4782 if (codegen->useFastLookups) {
4783 Instruction::SetLookup store;
4784 store.base = propertyBase.stackSlot();
4785 store.index = codegen->registerSetterLookup(propertyNameIndex);
4786 codegen->bytecodeGenerator->addInstruction(store);
4787 } else {
4788 Instruction::StoreProperty store;
4789 store.base = propertyBase.stackSlot();
4790 store.name = propertyNameIndex;
4791 codegen->bytecodeGenerator->addInstruction(store);
4792 }
4793 return;
4794 case Subscript: {
4795 Instruction::StoreElement store;
4796 store.base = elementBase;
4797 store.index = elementSubscript.stackSlot();
4798 codegen->bytecodeGenerator->addInstruction(store);
4799 } return;
4800 case Invalid:
4801 case Accumulator:
4802 case Const:
4803 case Import:
4804 break;
4805 }
4806
4807 Q_UNREACHABLE();
4808}
4809
4810void Codegen::Reference::loadInAccumulator() const
4811{
4812 switch (type) {
4813 case Accumulator:
4814 return;
4815 case Super:
4816 Q_UNREACHABLE_RETURN();
4817 case SuperProperty:
4818 tdzCheckStackSlot(property, subscriptRequiresTDZCheck, false);
4819 Instruction::LoadSuperProperty load;
4820 load.property = property.stackSlot();
4821 codegen->bytecodeGenerator->addInstruction(load);
4822 return;
4823 case Const: {
4824 if (constant == Encode::null()) {
4825 Instruction::LoadNull load;
4826 codegen->bytecodeGenerator->addInstruction(load);
4827 } else if (constant == Encode(true)) {
4828 Instruction::LoadTrue load;
4829 codegen->bytecodeGenerator->addInstruction(load);
4830 } else if (constant == Encode(false)) {
4831 Instruction::LoadFalse load;
4832 codegen->bytecodeGenerator->addInstruction(load);
4833 } else if (constant == Encode::undefined()) {
4834 Instruction::LoadUndefined load;
4835 codegen->bytecodeGenerator->addInstruction(load);
4836 } else {
4837 StaticValue p = StaticValue::fromReturnedValue(constant);
4838 if (p.isNumber()) {
4839 double d = p.asDouble();
4840 int i = QJSNumberCoercion::toInteger(d);
4841 if (d == i && (d != 0 || !std::signbit(d))) {
4842 if (!i) {
4843 Instruction::LoadZero load;
4844 codegen->bytecodeGenerator->addInstruction(load);
4845 return;
4846 }
4847 Instruction::LoadInt load;
4848 load.value = StaticValue::fromReturnedValue(constant).toInt32();
4849 codegen->bytecodeGenerator->addInstruction(load);
4850 return;
4851 }
4852 }
4853 Instruction::LoadConst load;
4854 load.index = codegen->registerConstant(constant);
4855 codegen->bytecodeGenerator->addInstruction(load);
4856 }
4857 } return;
4858 case StackSlot: {
4859 Instruction::LoadReg load;
4860 load.reg = stackSlot();
4861 codegen->bytecodeGenerator->addInstruction(load);
4862 tdzCheck(requiresTDZCheck, throwsReferenceError);
4863 } return;
4864 case ScopedLocal: {
4865 if (!scope) {
4866 Instruction::LoadLocal load;
4867 load.index = index;
4868 codegen->bytecodeGenerator->addInstruction(load);
4869 } else {
4870 Instruction::LoadScopedLocal load;
4871 load.index = index;
4872 load.scope = scope;
4873 codegen->bytecodeGenerator->addInstruction(load);
4874 }
4875 tdzCheck(requiresTDZCheck, throwsReferenceError);
4876 return;
4877 }
4878 case Name:
4879 if (global) {
4880 // these value properties of the global object are immutable, we we can directly convert them
4881 // to their numeric value here
4882 if (name == QStringLiteral("undefined")) {
4883 Reference::fromConst(codegen, Encode::undefined()).loadInAccumulator();
4884 return;
4885 } else if (name == QStringLiteral("Infinity")) {
4886 Reference::fromConst(codegen, Encode(qInf())).loadInAccumulator();
4887 return;
4888 } else if (name == QStringLiteral("Nan")) {
4889 Reference::fromConst(codegen, Encode(qQNaN())).loadInAccumulator();
4890 return;
4891 }
4892 }
4893
4894 if (sourceLocation.isValid())
4895 codegen->bytecodeGenerator->setLocation(sourceLocation);
4896
4897 if (global) {
4898 if (qmlGlobal) {
4899 Instruction::LoadQmlContextPropertyLookup load;
4900 load.index = codegen->registerQmlContextPropertyGetterLookup(
4901 nameAsIndex(), JSUnitGenerator::LookupForStorage);
4902 codegen->bytecodeGenerator->addInstruction(load);
4903 } else {
4904 Instruction::LoadGlobalLookup load;
4905 load.index = codegen->registerGlobalGetterLookup(
4906 nameAsIndex(), JSUnitGenerator::LookupForStorage);
4907 codegen->bytecodeGenerator->addInstruction(load);
4908 }
4909 } else {
4910 Instruction::LoadName load;
4911 load.name = nameAsIndex();
4912 codegen->bytecodeGenerator->addInstruction(load);
4913 }
4914 return;
4915 case Member:
4916 propertyBase.loadInAccumulator();
4917 tdzCheck(requiresTDZCheck, throwsReferenceError);
4918
4919 if (sourceLocation.isValid())
4920 codegen->bytecodeGenerator->setLocation(sourceLocation);
4921
4922 if (codegen->useFastLookups) {
4923 if (optionalChainJumpsToPatch && isOptional) {
4924 auto jump = codegen->bytecodeGenerator->jumpOptionalLookup(
4925 codegen->registerGetterLookup(
4926 propertyNameIndex, JSUnitGenerator::LookupForStorage));
4927 optionalChainJumpsToPatch->emplace_back(std::move(jump));
4928 } else {
4929 Instruction::GetLookup load;
4930 load.index = codegen->registerGetterLookup(
4931 propertyNameIndex, JSUnitGenerator::LookupForStorage);
4932 codegen->bytecodeGenerator->addInstruction(load);
4933 }
4934 } else {
4935 if (optionalChainJumpsToPatch && isOptional) {
4936 auto jump = codegen->bytecodeGenerator->jumpOptionalProperty(propertyNameIndex);
4937 optionalChainJumpsToPatch->emplace_back(std::move(jump));
4938 } else {
4939 Instruction::LoadProperty load;
4940 load.name = propertyNameIndex;
4941 codegen->bytecodeGenerator->addInstruction(load);
4942 }
4943 }
4944 return;
4945 case Import: {
4946 Instruction::LoadImport load;
4947 load.index = index;
4948 codegen->bytecodeGenerator->addInstruction(load);
4949 tdzCheck(requiresTDZCheck, throwsReferenceError);
4950 } return;
4951 case Subscript: {
4952 tdzCheckStackSlot(elementBase, requiresTDZCheck, throwsReferenceError);
4953 elementSubscript.loadInAccumulator();
4954 tdzCheck(subscriptRequiresTDZCheck, false);
4955 Instruction::LoadElement load;
4956 load.base = elementBase;
4957 codegen->bytecodeGenerator->addInstruction(load);
4958 } return;
4959 case Invalid:
4960 break;
4961 }
4962 Q_UNREACHABLE();
4963}
4964
4965QT_END_NAMESPACE
Codegen::VolatileMemoryLocations scan(AST::Node *s)
bool visit(ArrayMemberExpression *) override
Definition qjsvalue.h:24
QT_BEGIN_NAMESPACE Q_STATIC_LOGGING_CATEGORY(lcSynthesizedIterableAccess, "qt.iterable.synthesized", QtWarningMsg)
static Node * completionStatement(StatementList *list)
static CompletionState completionState(StatementList *list)
static QSOperator::Op baseOp(int op)
CompletionState
static void setJumpOutLocation(QV4::Moth::BytecodeGenerator *bytecodeGenerator, const Statement *body, const SourceLocation &fallback)
static constexpr const QLatin1StringView s_globalNames[]