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>
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>
35using namespace Qt::StringLiterals;
42using namespace QQmlJS;
43using namespace QQmlJS::AST;
45void CodegenWarningInterface::reportVarUsedBeforeDeclaration(
46 const QString &name,
const QString &fileName, QQmlJS::SourceLocation declarationLocation,
47 QQmlJS::SourceLocation accessLocation)
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 <<
".";
55void CodegenWarningInterface::reportFunctionUsedBeforeDeclaration(
const QString &,
const QString &,
56 QQmlJS::SourceLocation,
57 QQmlJS::SourceLocation)
63 const Statement *body,
const SourceLocation &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);
76 bytecodeGenerator->setLocation(body->lastSourceLocation());
81void Codegen::generateThrowException(
const QString &type,
const QString &text)
83 RegisterScope scope(
this);
84 Instruction::Construct construct;
90 Instruction::LoadRuntimeString load;
91 load.stringId = registerString(text);
92 bytecodeGenerator->addInstruction(load);
93 construct.argv = Reference::fromAccumulator(
this).storeOnStack().stackSlot();
95 Reference r = referenceForName(type,
false);
97 construct.func = r.stackSlot();
98 bytecodeGenerator->addInstruction(construct);
99 Instruction::ThrowException throwException;
100 bytecodeGenerator->addInstruction(throwException);
103Codegen::Codegen(QV4::Compiler::JSUnitGenerator *jsUnitGenerator,
bool strict,
104 CodegenWarningInterface *iface,
bool storeSourceLocations)
108 _labelledStatement(
nullptr),
109 jsUnitGenerator(jsUnitGenerator),
111 storeSourceLocations(storeSourceLocations),
112 _fileNameIsUrl(
false),
115 jsUnitGenerator->codeGeneratorName = QStringLiteral(
"moth");
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"),
189bool Codegen::isNameGlobal(QAnyStringView name)
191 return std::binary_search(std::begin(s_globalNames), std::end(s_globalNames), name);
195
196
197
198
199bool Codegen::isNameKeyword(QAnyStringView name)
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"),
212 return std::binary_search(std::begin(s_keywordNames), std::end(s_keywordNames), name);
215void Codegen::forEachGlobalName(qxp::function_ref<
void (QLatin1StringView)> &&handler)
217 for (QLatin1StringView name : s_globalNames)
221void Codegen::generateFromProgram(
222 const QString &sourceCode, Program *node, Module *module, ContextType contextType)
229 ScanFunctions scan(
this, sourceCode, contextType);
235 defineFunction(QStringLiteral(
"%entry"), node,
nullptr, node->statements);
238void Codegen::generateFromModule(
const QString &sourceCode, ESModule *node, Module *module)
245 ScanFunctions scan(
this, sourceCode, ContextType::ESModule);
252 Compiler::Context *moduleContext = _module->contextMap.value(node);
253 for (
const auto &entry: std::as_const(moduleContext->exportEntries)) {
254 if (entry.moduleRequest.isEmpty()) {
256 _module->localExportEntries << entry;
257 }
else if (entry.importName == QLatin1Char(
'*')) {
258 _module->starExportEntries << entry;
260 _module->indirectExportEntries << entry;
263 _module->importEntries = moduleContext->importEntries;
265 _module->moduleRequests = std::move(moduleContext->moduleRequests);
266 _module->moduleRequests.removeDuplicates();
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);
273 defineFunction(QStringLiteral(
"%entry"), node,
nullptr, node->body);
276void Codegen::generateFromModule(
const Value &value, Module *module)
281 _module->newContext(
nullptr,
nullptr, ContextType::ESModule);
282 enterContext(
nullptr);
284 _context->name = QStringLiteral(
"%entry");
285 _module->functions.append(_context);
286 _context->functionIndex = _module->functions.size() - 1;
289 entry.localName = entry.exportName = QLatin1String(
"default");
290 _module->localExportEntries << entry;
292 if (Object *o = value.objectValue()) {
294 QV4::ObjectIterator it(scope, o, QV4::ObjectIterator::EnumerableOnly);
295 QV4::PropertyAttributes attrs;
296 QV4::ScopedPropertyKey name(scope);
298 name = it.next(
nullptr, &attrs);
299 if (!name->isValid())
303 entry.localName = entry.exportName = name->toQString();
304 _module->localExportEntries << entry;
308 std::sort(_module->localExportEntries.begin(), _module->localExportEntries.end(),
309 ExportEntry::lessThan);
311 for (
auto it = _module->localExportEntries.cbegin(), end = _module->localExportEntries.cend();
313 Context::Member member;
314 member.index = _context->locals.size();
315 _context->locals.append(it->exportName);
316 _context->members.insert(it->exportName, member);
322void Codegen::enterContext(Node *node)
324 _context = _module->contextMap.value(node);
328int Codegen::leaveContext()
331 int functionIndex = _context->functionIndex;
332 _context = _context->parent;
333 return functionIndex;
336Context *Codegen::enterBlock(Node *node)
342Codegen::Reference Codegen::unop(UnaryOperation op,
const Reference &expr)
347 if (expr.isConstant()) {
348 auto v = StaticValue::fromReturnedValue(expr.constant);
352 return Reference::fromConst(
this, Encode(!v.toBoolean()));
357 int intVal = v.integerValue();
358 if (intVal && intVal != std::numeric_limits<
int>::min())
359 r = QV4::Encode(-intVal);
361 r = QV4::Encode(-
double(intVal));
362 }
else if (v.isDouble()) {
363 r = QV4::Encode(-v.doubleValue());
365 r = QV4::Encode(-v.int_32());
367 return Reference::fromConst(
this, r);
371 return Reference::fromConst(
this, Encode((
int)~v.toInt32()));
380 expr.loadInAccumulator();
381 Instruction::UMinus uminus = {};
382 bytecodeGenerator->addInstruction(uminus);
383 return Reference::fromAccumulator(
this);
386 expr.loadInAccumulator();
387 Instruction::UPlus uplus = {};
388 bytecodeGenerator->addInstruction(uplus);
389 return Reference::fromAccumulator(
this);
392 expr.loadInAccumulator();
393 Instruction::UNot unot;
394 bytecodeGenerator->addInstruction(unot);
395 return Reference::fromAccumulator(
this);
398 expr.loadInAccumulator();
399 Instruction::UCompl ucompl;
400 bytecodeGenerator->addInstruction(ucompl);
401 return Reference::fromAccumulator(
this);
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;
420 Reference e = expr.asLValue();
421 e.loadInAccumulator();
423 Instruction::Increment inc = {};
424 bytecodeGenerator->addInstruction(inc);
426 return e.storeConsumeAccumulator();
428 return e.storeRetainAccumulator();
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;
447 Reference e = expr.asLValue();
448 e.loadInAccumulator();
450 Instruction::Decrement dec = {};
451 bytecodeGenerator->addInstruction(dec);
453 return e.storeConsumeAccumulator();
455 return e.storeRetainAccumulator();
462void Codegen::addCJump()
464 const Result &expression = currentExpr();
465 bytecodeGenerator->addCJumpInstruction(expression.trueBlockFollowsCondition(),
466 expression.iftrue(), expression.iffalse());
469void Codegen::statement(Statement *ast)
471 RegisterScope scope(
this);
473 bytecodeGenerator->incrementStatement();
474 bytecodeGenerator->setLocation(ast->firstSourceLocation());
476 VolatileMemoryLocations vLocs = scanVolatileMemoryLocations(ast);
477 qSwap(_volatileMemoryLocations, vLocs);
479 qSwap(_volatileMemoryLocations, vLocs);
482void Codegen::statement(ExpressionNode *ast)
487 RegisterScope scope(
this);
489 bytecodeGenerator->incrementStatement();
490 pushExpr(Result(nx));
491 VolatileMemoryLocations vLocs = scanVolatileMemoryLocations(ast);
492 qSwap(_volatileMemoryLocations, vLocs);
496 qSwap(_volatileMemoryLocations, vLocs);
497 Reference result = popResult();
501 if (result.loadTriggersSideEffect())
502 result.loadInAccumulator();
506void Codegen::condition(ExpressionNode *ast,
const BytecodeGenerator::Label *iftrue,
507 const BytecodeGenerator::Label *iffalse,
bool trueBlockFollowsCondition)
515 pushExpr(Result(iftrue, iffalse, trueBlockFollowsCondition));
517 Result r = popExpr();
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());
531 bytecodeGenerator->jumpTrue().link(*r.iftrue());
535void Codegen::program(Program *ast)
538 statementList(ast->statements);
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)
558 if (it->statement->kind == Statement::Kind_Block) {
559 CompletionState subState = completionState(
static_cast<Block *>(it->statement)->statements);
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)
583 if (it->statement->kind == Statement::Kind_Block) {
584 CompletionState state = completionState(
static_cast<Block *>(it->statement)->statements);
589 return it->statement;
594 completionStatement = it->statement;
596 return completionStatement;
599void Codegen::statementList(StatementList *ast)
604 bool _requiresReturnValue = requiresReturnValue;
607 if (!controlFlow || !controlFlow->hasLoop())
608 requiresReturnValue =
false;
610 Node *needsCompletion =
nullptr;
612 if (_requiresReturnValue && !requiresReturnValue)
613 needsCompletion = completionStatement(ast);
615 if (requiresReturnValue && !needsCompletion && !insideSwitch) {
617 Reference::fromConst(
this, Encode::undefined()).storeOnStack(_returnAddress);
620 bool _insideSwitch = insideSwitch;
621 insideSwitch =
false;
623 for (StatementList *it = ast; it; it = it->next) {
624 if (it->statement == needsCompletion)
625 requiresReturnValue =
true;
626 if (Statement *s = it->statement->statementCast())
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) {
637 if (Visitor *visitor = _interface->unreachableVisitor())
638 Node::accept(it->next, visitor);
642 requiresReturnValue = _requiresReturnValue;
643 insideSwitch = _insideSwitch;
646void Codegen::variableDeclaration(PatternElement *ast)
648 TailCallBlocker blockTailCalls(
this);
649 RegisterScope scope(
this);
651 if (!ast->initializer) {
652 if (ast->isLexicallyScoped()) {
653 Reference::fromConst(
this, Encode::undefined()).loadInAccumulator();
654 Reference varToStore = targetForPatternElement(ast);
655 varToStore.storeConsumeAccumulator();
659 initializeAndDestructureBindingElement(ast, Reference(),
true);
662void Codegen::variableDeclarationList(VariableDeclarationList *ast)
664 for (VariableDeclarationList *it = ast; it; it = it->next) {
665 variableDeclaration(it->declaration);
669Codegen::Reference Codegen::targetForPatternElement(AST::PatternElement *p)
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);
678 if (!lhs.isLValue()) {
679 throwReferenceError(p->bindingTarget->firstSourceLocation(), QStringLiteral(
"Binding target is not a reference."));
682 lhs = lhs.asLValue();
690Codegen::Reference Codegen::referenceForFormalParameter(
int argIndex)
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);
698void Codegen::initializeAndDestructureBindingElement(AST::PatternElement *e,
const Reference &base,
bool isDefinition)
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);
705 varToStore.isReferenceToConst =
false;
709 if (e->typeAnnotation) {
710 throwSyntaxError(e->firstSourceLocation(),
711 QLatin1String(
"Type annotations on default parameters are not supported."));
714 const auto loadValueForStore = [&](
const Reference &value) {
715 if (isDefinition || !varToStore.requiresTDZCheck) {
716 value.loadInAccumulator();
719 Reference stashed = value.storeOnStack();
720 varToStore.checkTDZBeforeAssignment();
721 stashed.loadInAccumulator();
724 if (e->initializer) {
725 if (!baseRef.isValid()) {
727 Reference expr = expression(e->initializer);
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);
740 loadValueForStore(expr);
741 varToStore.storeConsumeAccumulator();
744 baseRef.loadInAccumulator();
745 BytecodeGenerator::Jump jump = bytecodeGenerator->jumpNotUndefined();
746 Reference expr = expression(e->initializer);
751 expr.loadInAccumulator();
753 loadValueForStore(Reference::fromAccumulator(
this));
754 varToStore.storeConsumeAccumulator();
756 }
else if (baseRef != varToStore && baseRef.isValid()) {
757 loadValueForStore(baseRef);
758 varToStore.storeConsumeAccumulator();
760 Pattern *p = e->destructuringPattern();
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) {
772 varToStore.loadInAccumulator();
773 Instruction::ToObject toObject;
774 bytecodeGenerator->addInstruction(toObject);
779Codegen::Reference Codegen::referenceForPropertyName(
const Codegen::Reference &object, AST::PropertyName *name)
781 AST::ComputedPropertyName *cname = AST::cast<AST::ComputedPropertyName *>(name);
784 Reference computedName = expression(cname->expression);
787 computedName = computedName.storeOnStack();
788 property = Reference::fromSubscript(object, computedName).asLValue();
790 QString propertyName = name->asString();
791 property = Reference::fromMember(object, propertyName);
796void Codegen::destructurePropertyList(
const Codegen::Reference &object, PatternPropertyList *bindingList,
bool isDefinition)
798 RegisterScope scope(
this);
800 object.loadInAccumulator();
801 Instruction::ThrowOnNullOrUndefined t;
802 bytecodeGenerator->addInstruction(t);
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);
810 initializeAndDestructureBindingElement(p, property, isDefinition);
816void Codegen::destructureElementList(
const Codegen::Reference &array, PatternElementList *bindingList,
bool isDefinition)
818 RegisterScope scope(
this);
820 Reference iterator = Reference::fromStackSlot(
this);
821 QVarLengthArray<Reference, 32> iteratorValues;
824 array.loadInAccumulator();
825 Instruction::GetIterator iteratorObjInstr;
826 iteratorObjInstr.iterator =
static_cast<
int>(AST::ForEachType::Of);
827 bytecodeGenerator->addInstruction(iteratorObjInstr);
828 iterator.storeConsumeAccumulator();
830 BytecodeGenerator::Label done = bytecodeGenerator->newLabel();
831 Reference needsClose = Reference::storeConstOnStack(
this, Encode(
false));
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);
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);
860 Reference::fromConst(
this, Encode(
true)).storeOnStack(needsClose.stackSlot());
863 bytecodeGenerator->checkException();
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);
876 auto it = iteratorValues.constBegin();
877 for (PatternElementList *p = bindingList; p; p = p->next) {
878 PatternElement *e = p->element;
883 if (e->type == PatternElement::RestElement) {
884 Q_ASSERT(it == iteratorValues.constEnd());
887 Reference::fromConst(
this, Encode(
false)).storeOnStack(needsClose.stackSlot());
889 iterator.loadInAccumulator();
890 bytecodeGenerator->addInstruction(Instruction::DestructureRestElement());
891 initializeAndDestructureBindingElement(
892 e, Reference::fromAccumulator(
this), isDefinition);
894 Q_ASSERT(it != iteratorValues.constEnd());
895 initializeAndDestructureBindingElement(e, *it++, isDefinition);
904void Codegen::destructurePattern(Pattern *p,
const Reference &rhs)
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);
916bool Codegen::visit(ArgumentList *)
918 Q_UNREACHABLE_RETURN(
false);
921bool Codegen::visit(CaseBlock *)
923 Q_UNREACHABLE_RETURN(
false);
926bool Codegen::visit(CaseClause *)
928 Q_UNREACHABLE_RETURN(
false);
931bool Codegen::visit(CaseClauses *)
933 Q_UNREACHABLE_RETURN(
false);
936bool Codegen::visit(Catch *)
938 Q_UNREACHABLE_RETURN(
false);
941bool Codegen::visit(DefaultClause *)
943 Q_UNREACHABLE_RETURN(
false);
946bool Codegen::visit(Elision *)
948 Q_UNREACHABLE_RETURN(
false);
951bool Codegen::visit(Finally *)
953 Q_UNREACHABLE_RETURN(
false);
956bool Codegen::visit(FormalParameterList *)
958 Q_UNREACHABLE_RETURN(
false);
961bool Codegen::visit(Program *)
963 Q_UNREACHABLE_RETURN(
false);
966bool Codegen::visit(PatternElement *)
968 Q_UNREACHABLE_RETURN(
false);
971bool Codegen::visit(PatternElementList *)
973 Q_UNREACHABLE_RETURN(
false);
976bool Codegen::visit(PatternProperty *)
978 Q_UNREACHABLE_RETURN(
false);
981bool Codegen::visit(PatternPropertyList *)
983 Q_UNREACHABLE_RETURN(
false);
986bool Codegen::visit(ExportDeclaration *ast)
988 if (!ast->exportDefault)
991 TailCallBlocker blockTailCalls(
this);
992 Reference exportedValue;
994 if (
auto *fdecl = AST::cast<FunctionDeclaration*>(ast->variableStatementOrDeclaration)) {
996 visit(
static_cast<FunctionExpression*>(fdecl));
997 exportedValue = popResult();
998 }
else if (
auto *classDecl = AST::cast<ClassDeclaration*>(ast->variableStatementOrDeclaration)) {
1000 visit(
static_cast<ClassExpression*>(classDecl));
1001 exportedValue = popResult();
1002 }
else if (ExpressionNode *expr = ast->variableStatementOrDeclaration->expressionCast()) {
1003 exportedValue = expression(expr);
1008 exportedValue.loadInAccumulator();
1010 const int defaultExportIndex = _context->locals.indexOf(_context->localNameForDefaultExport);
1011 Q_ASSERT(defaultExportIndex != -1);
1012 Reference defaultExportSlot = Reference::fromScopedLocal(
this, defaultExportIndex, 0);
1013 defaultExportSlot.storeConsumeAccumulator();
1018bool Codegen::visit(TypeAnnotation *ast)
1020 throwSyntaxError(ast->firstSourceLocation(), QLatin1String(
"Type annotations are not supported (yet)."));
1024bool Codegen::visit(StatementList *)
1026 Q_UNREACHABLE_RETURN(
false);
1029bool Codegen::visit(UiArrayMemberList *)
1031 Q_UNREACHABLE_RETURN(
false);
1034bool Codegen::visit(UiImport *)
1036 Q_UNREACHABLE_RETURN(
false);
1039bool Codegen::visit(UiHeaderItemList *)
1041 Q_UNREACHABLE_RETURN(
false);
1044bool Codegen::visit(UiPragmaValueList *)
1046 Q_UNREACHABLE_RETURN(
false);
1049bool Codegen::visit(UiPragma *)
1051 Q_UNREACHABLE_RETURN(
false);
1054bool Codegen::visit(UiObjectInitializer *)
1056 Q_UNREACHABLE_RETURN(
false);
1059bool Codegen::visit(UiObjectMemberList *)
1061 Q_UNREACHABLE_RETURN(
false);
1064bool Codegen::visit(UiParameterList *)
1066 Q_UNREACHABLE_RETURN(
false);
1069bool Codegen::visit(UiProgram *)
1071 Q_UNREACHABLE_RETURN(
false);
1074bool Codegen::visit(UiQualifiedId *)
1076 Q_UNREACHABLE_RETURN(
false);
1079bool Codegen::visit(VariableDeclarationList *)
1081 Q_UNREACHABLE_RETURN(
false);
1084bool Codegen::visit(ClassExpression *ast)
1086 TailCallBlocker blockTailCalls(
this);
1088 Compiler::Class jsClass;
1089 jsClass.nameIndex = registerString(ast->name.toString());
1091 ClassElementList *constructor =
nullptr;
1092 int nComputedNames = 0;
1093 int nStaticComputedNames = 0;
1095 RegisterScope scope(
this);
1096 ControlFlowBlock controlFlow(
this, ast);
1098 for (
auto *member = ast->elements; member; member = member->next) {
1099 PatternProperty *p = member->property;
1100 FunctionExpression *f = p->initializer->asFunctionDefinition();
1102 AST::ComputedPropertyName *cname = AST::cast<ComputedPropertyName *>(p->name);
1105 if (member->isStatic)
1106 ++nStaticComputedNames;
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)) };
1117 if (member->isStatic) {
1118 if (name == QStringLiteral(
"prototype")) {
1119 throwSyntaxError(ast->firstSourceLocation(), QLatin1String(
"Cannot declare a static method named 'prototype'."));
1122 jsClass.staticMethods << m;
1124 if (name == QStringLiteral(
"constructor")) {
1126 throwSyntaxError(ast->firstSourceLocation(), QLatin1String(
"Cannot declare a multiple constructors in a class."));
1129 if (m.type != Compiler::Class::Method::Regular) {
1130 throwSyntaxError(ast->firstSourceLocation(), QLatin1String(
"Cannot declare a getter or setter named 'constructor'."));
1133 constructor = member;
1134 jsClass.constructorIndex = m.functionIndex;
1138 jsClass.methods << m;
1142 int classIndex = _module->classes.size();
1143 _module->classes.append(jsClass);
1145 Reference heritage = Reference::fromStackSlot(
this);
1146 if (ast->heritage) {
1147 bytecodeGenerator->setLocation(ast->heritage->firstSourceLocation());
1148 Reference r = expression(ast->heritage);
1151 r.storeOnStack(heritage.stackSlot());
1153 Reference::fromConst(
this, StaticValue::emptyValue().asReturnedValue()).loadInAccumulator();
1154 heritage.storeConsumeAccumulator();
1157 int computedNames = nComputedNames ? bytecodeGenerator->newRegisterArray(nComputedNames) : 0;
1158 int currentStaticName = computedNames;
1159 int currentNonStaticName = computedNames + nStaticComputedNames;
1161 for (
auto *member = ast->elements; member; member = member->next) {
1162 AST::ComputedPropertyName *cname = AST::cast<AST::ComputedPropertyName *>(member->property->name);
1165 RegisterScope scope(
this);
1166 bytecodeGenerator->setLocation(cname->firstSourceLocation());
1167 Reference computedName = expression(cname->expression);
1170 computedName.storeOnStack(member->isStatic ? currentStaticName++ : currentNonStaticName++);
1173 Instruction::CreateClass createClass;
1174 createClass.classIndex = classIndex;
1175 createClass.heritage = heritage.stackSlot();
1176 createClass.computedNames = computedNames;
1178 bytecodeGenerator->addInstruction(createClass);
1180 if (!ast->name.isEmpty()) {
1181 Reference ctor = referenceForName(ast->name.toString(),
true);
1182 ctor.isReferenceToConst =
false;
1183 (
void) ctor.storeRetainAccumulator();
1186 setExprResult(Reference::fromAccumulator(
this));
1190bool Codegen::visit(ClassDeclaration *ast)
1192 TailCallBlocker blockTailCalls(
this);
1193 Reference outerVar = referenceForName(ast->name.toString(),
true);
1194 visit(
static_cast<ClassExpression *>(ast));
1195 (
void) outerVar.storeRetainAccumulator();
1199bool Codegen::visit(CommaExpression *ast)
1204 TailCallBlocker blockTailCalls(
this);
1205 statement(ast->left);
1206 blockTailCalls.unblock();
1207 clearExprResultName();
1212bool Codegen::visit(ArrayPattern *ast)
1217 TailCallBlocker blockTailCalls(
this);
1219 PatternElementList *it = ast->elements;
1223 RegisterScope scope(
this);
1226 auto push = [
this, &argc, &args](AST::ExpressionNode *arg) {
1227 int temp = bytecodeGenerator->newRegister();
1231 auto c = Reference::fromConst(
this, StaticValue::emptyValue().asReturnedValue());
1232 (
void) c.storeOnStack(temp);
1234 RegisterScope scope(
this);
1235 Reference r = expression(arg);
1238 (
void) r.storeOnStack(temp);
1243 for (; it; it = it->next) {
1244 PatternElement *e = it->element;
1245 if (e && e->type == PatternElement::SpreadElement)
1247 for (Elision *elision = it->elision; elision; elision = elision->next)
1253 push(e->initializer);
1259 Q_ASSERT(argc == 0);
1263 Instruction::DefineArray call;
1265 call.args = Moth::StackSlot::createRegister(args);
1266 bytecodeGenerator->addInstruction(call);
1270 setExprResult(Reference::fromAccumulator(
this));
1273 Q_ASSERT(it->element && it->element->type == PatternElement::SpreadElement);
1275 RegisterScope scope(
this);
1276 Reference array = Reference::fromStackSlot(
this);
1277 array.storeConsumeAccumulator();
1278 Reference index = Reference::storeConstOnStack(
this, Encode(argc));
1280 auto pushAccumulator = [&]() {
1281 Reference slot = Reference::fromSubscript(array, index);
1282 slot.storeConsumeAccumulator();
1284 index.loadInAccumulator();
1285 Instruction::Increment inc = {};
1286 bytecodeGenerator->addInstruction(inc);
1287 index.storeConsumeAccumulator();
1291 for (Elision *elision = it->elision; elision; elision = elision->next) {
1292 Reference::fromConst(
1293 this, StaticValue::emptyValue().asReturnedValue()).loadInAccumulator();
1303 if (it->element->type == PatternElement::SpreadElement) {
1304 RegisterScope scope(
this);
1306 Reference iterator = Reference::fromStackSlot(
this);
1307 Reference lhsValue = Reference::fromStackSlot(
this);
1312 RegisterScope innerScope(
this);
1313 Reference expr = expression(it->element->initializer);
1317 expr.loadInAccumulator();
1318 Instruction::GetIterator iteratorObjInstr;
1319 iteratorObjInstr.iterator =
static_cast<
int>(AST::ForEachType::Of);
1320 bytecodeGenerator->addInstruction(iteratorObjInstr);
1321 iterator.storeConsumeAccumulator();
1324 BytecodeGenerator::Label in = bytecodeGenerator->newLabel();
1325 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
1326 BytecodeGenerator::Label done = bytecodeGenerator->newLabel();
1329 auto cleanup = [
this, iterator, done]() {
1330 iterator.loadInAccumulator();
1331 Instruction::IteratorClose close;
1332 bytecodeGenerator->addInstruction(close);
1335 ControlFlowLoop flow(
this, &end, &in, std::move(cleanup));
1338 bytecodeGenerator->addLoopStart(in);
1339 iterator.loadInAccumulator();
1340 Instruction::IteratorNext next;
1341 next.value = lhsValue.stackSlot();
1342 bytecodeGenerator->addJumpInstruction(next).link(done);
1344 lhsValue.loadInAccumulator();
1347 bytecodeGenerator->checkException();
1348 bytecodeGenerator->jump().link(in);
1352 RegisterScope innerScope(
this);
1353 Reference expr = expression(it->element->initializer);
1357 expr.loadInAccumulator();
1364 array.loadInAccumulator();
1365 setExprResult(Reference::fromAccumulator(
this));
1370bool Codegen::visit(ArrayMemberExpression *ast)
1375 const bool isTailOfChain = traverseOptionalChain(ast);
1377 TailCallBlocker blockTailCalls(
this);
1378 Reference base = expression(ast->base);
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));
1389 if (base.isSuper()) {
1390 auto e = expression(ast->expression);
1393 Reference index = e.storeOnStack();
1394 optionalChainFinalizer(Reference::fromSuperProperty(index), isTailOfChain);
1397 base = base.storeOnStack();
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(),
1406 &m_optionalChainsStates->top().jumpsToPatch);
1408 optionalChainFinalizer(ref, isTailOfChain);
1412 if (ast->isOptional)
1415 Reference index = Reference::fromConst(
this, QV4::Encode(arrayIndex));
1416 optionalChainFinalizer(Reference::fromSubscript(base, index), isTailOfChain);
1421 if (ast->isOptional)
1424 Reference index = expression(ast->expression);
1429 optionalChainFinalizer(Reference::fromSubscript(base, index), isTailOfChain);
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;
1452bool Codegen::visit(BinaryExpression *ast)
1457 TailCallBlocker blockTailCalls(
this);
1459 if (ast->op == QSOperator::And) {
1460 if (exprAccept(cx)) {
1461 auto iftrue = bytecodeGenerator->newLabel();
1462 condition(ast->left, &iftrue, currentExpr().iffalse(),
true);
1464 blockTailCalls.unblock();
1465 const Result &expr = currentExpr();
1466 condition(ast->right, expr.iftrue(), expr.iffalse(), expr.trueBlockFollowsCondition());
1468 auto iftrue = bytecodeGenerator->newLabel();
1469 auto endif = bytecodeGenerator->newLabel();
1471 Reference left = expression(ast->left);
1474 left.loadInAccumulator();
1476 bytecodeGenerator->setLocation(ast->operatorToken);
1477 bytecodeGenerator->jumpFalse().link(endif);
1480 blockTailCalls.unblock();
1481 Reference right = expression(ast->right);
1484 right.loadInAccumulator();
1488 setExprResult(Reference::fromAccumulator(
this));
1491 }
else if (ast->op == QSOperator::Or) {
1492 if (exprAccept(cx)) {
1493 auto iffalse = bytecodeGenerator->newLabel();
1494 condition(ast->left, currentExpr().iftrue(), &iffalse,
false);
1496 const Result &expr = currentExpr();
1497 condition(ast->right, expr.iftrue(), expr.iffalse(), expr.trueBlockFollowsCondition());
1499 auto iffalse = bytecodeGenerator->newLabel();
1500 auto endif = bytecodeGenerator->newLabel();
1502 Reference left = expression(ast->left);
1505 left.loadInAccumulator();
1507 bytecodeGenerator->setLocation(ast->operatorToken);
1508 bytecodeGenerator->jumpTrue().link(endif);
1511 blockTailCalls.unblock();
1512 Reference right = expression(ast->right);
1515 right.loadInAccumulator();
1519 setExprResult(Reference::fromAccumulator(
this));
1522 }
else if (ast->op == QSOperator::Coalesce) {
1524 Reference left = expression(ast->left);
1528 BytecodeGenerator::Label iftrue = bytecodeGenerator->newLabel();
1530 Instruction::CmpEqNull cmp;
1532 left = left.storeOnStack();
1533 left.loadInAccumulator();
1534 bytecodeGenerator->addInstruction(cmp);
1536 bytecodeGenerator->jumpTrue().link(iftrue);
1538 blockTailCalls.unblock();
1540 left.loadInAccumulator();
1541 BytecodeGenerator::Jump jump_endif = bytecodeGenerator->jump();
1544 Reference right = expression(ast->right);
1550 right.loadInAccumulator();
1552 setExprResult(Reference::fromAccumulator(
this));
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);
1562 right = right.storeOnStack();
1563 destructurePattern(p, right);
1564 if (!exprAccept(nx)) {
1565 right.loadInAccumulator();
1566 setExprResult(Reference::fromAccumulator(
this));
1570 Reference left = expression(ast->left);
1574 if (!left.isLValue()) {
1575 throwReferenceError(ast->operatorToken, QStringLiteral(
"left-hand side of assignment operator is not an lvalue"));
1578 left = left.asLValue();
1579 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(left, ast->left->lastSourceLocation()))
1581 blockTailCalls.unblock();
1582 Reference r = expression(ast->right);
1585 if (left.requiresTDZCheck) {
1586 r = r.storeOnStack();
1587 left.checkTDZBeforeAssignment();
1589 r.loadInAccumulator();
1591 bytecodeGenerator->setLocation(ast->left->firstSourceLocation());
1593 setExprResult(left.storeConsumeAccumulator());
1595 setExprResult(left.storeRetainAccumulator());
1599 Reference left = expression(ast->left);
1604 case QSOperator::Or:
1605 case QSOperator::And:
1606 case QSOperator::Assign:
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()))
1625 if (!left.isLValue()) {
1626 throwSyntaxError(ast->operatorToken, QStringLiteral(
"left-hand side of inplace operator is not an lvalue"));
1629 left = left.asLValue();
1631 Reference tempLeft = left.storeOnStack();
1632 Reference right = expression(ast->right);
1637 binopHelper(ast, baseOp(ast->op), tempLeft, right).loadInAccumulator();
1638 setExprResult(left.storeRetainAccumulator());
1643 case QSOperator::BitAnd:
1644 case QSOperator::BitOr:
1645 case QSOperator::BitXor:
1646 if (left.isConstant()) {
1647 Reference right = expression(ast->right);
1650 setExprResult(binopHelper(ast,
static_cast<QSOperator::Op>(ast->op), right, left));
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: {
1675 if (AST::NumericLiteral *rhs = AST::cast<AST::NumericLiteral *>(ast->right)) {
1677 right = exprResult();
1679 left = left.storeOnStack();
1680 right = expression(ast->right);
1685 setExprResult(binopHelper(ast,
static_cast<QSOperator::Op>(ast->op), left, right));
1694Codegen::Reference Codegen::binopHelper(BinaryExpression *ast, QSOperator::Op oper, Reference &left,
1697 auto loc = combine(ast->left->firstSourceLocation(), ast->right->lastSourceLocation());
1698 bytecodeGenerator->setLocation(loc);
1700 case QSOperator::Add: {
1701 left = left.storeOnStack();
1702 right.loadInAccumulator();
1703 Instruction::Add add;
1704 add.lhs = left.stackSlot();
1705 bytecodeGenerator->addInstruction(add);
1708 case QSOperator::Sub: {
1709 if (right.isConstant() && right.constant == Encode(
int(1))) {
1710 left.loadInAccumulator();
1711 Instruction::Decrement dec = {};
1712 bytecodeGenerator->addInstruction(dec);
1714 left = left.storeOnStack();
1715 right.loadInAccumulator();
1716 Instruction::Sub sub;
1717 sub.lhs = left.stackSlot();
1718 bytecodeGenerator->addInstruction(sub);
1722 case QSOperator::Exp: {
1723 left = left.storeOnStack();
1724 right.loadInAccumulator();
1725 Instruction::Exp exp;
1726 exp.lhs = left.stackSlot();
1727 bytecodeGenerator->addInstruction(exp);
1730 case QSOperator::Mul: {
1731 left = left.storeOnStack();
1732 right.loadInAccumulator();
1733 Instruction::Mul mul;
1734 mul.lhs = left.stackSlot();
1735 bytecodeGenerator->addInstruction(mul);
1738 case QSOperator::Div: {
1739 left = left.storeOnStack();
1740 right.loadInAccumulator();
1741 Instruction::Div div;
1742 div.lhs = left.stackSlot();
1743 bytecodeGenerator->addInstruction(div);
1746 case QSOperator::Mod: {
1747 left = left.storeOnStack();
1748 right.loadInAccumulator();
1749 Instruction::Mod mod;
1750 mod.lhs = left.stackSlot();
1751 bytecodeGenerator->addInstruction(mod);
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));
1761 left.loadInAccumulator();
1762 Instruction::BitAndConst bitAnd;
1763 bitAnd.rhs = rightAsInt;
1764 bytecodeGenerator->addInstruction(bitAnd);
1766 right.loadInAccumulator();
1767 Instruction::BitAnd bitAnd;
1768 bitAnd.lhs = left.stackSlot();
1769 bytecodeGenerator->addInstruction(bitAnd);
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));
1779 left.loadInAccumulator();
1780 Instruction::BitOrConst bitOr;
1781 bitOr.rhs = rightAsInt;
1782 bytecodeGenerator->addInstruction(bitOr);
1784 right.loadInAccumulator();
1785 Instruction::BitOr bitOr;
1786 bitOr.lhs = left.stackSlot();
1787 bytecodeGenerator->addInstruction(bitOr);
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));
1797 left.loadInAccumulator();
1798 Instruction::BitXorConst bitXor;
1799 bitXor.rhs = rightAsInt;
1800 bytecodeGenerator->addInstruction(bitXor);
1802 right.loadInAccumulator();
1803 Instruction::BitXor bitXor;
1804 bitXor.lhs = left.stackSlot();
1805 bytecodeGenerator->addInstruction(bitXor);
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);
1815 right.loadInAccumulator();
1816 Instruction::UShr ushr;
1817 ushr.lhs = left.stackSlot();
1818 bytecodeGenerator->addInstruction(ushr);
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);
1828 right.loadInAccumulator();
1829 Instruction::Shr shr;
1830 shr.lhs = left.stackSlot();
1831 bytecodeGenerator->addInstruction(shr);
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);
1841 right.loadInAccumulator();
1842 Instruction::Shl shl;
1843 shl.lhs = left.stackSlot();
1844 bytecodeGenerator->addInstruction(shl);
1847 case QSOperator::InstanceOf: {
1848 Instruction::CmpInstanceOf binop;
1849 left = left.storeOnStack();
1850 right.loadInAccumulator();
1851 binop.lhs = left.stackSlot();
1852 bytecodeGenerator->addInstruction(binop);
1855 case QSOperator::As: {
1857 left = left.storeOnStack();
1858 right.loadInAccumulator();
1859 as.lhs = left.stackSlot();
1860 bytecodeGenerator->addInstruction(as);
1863 case QSOperator::In: {
1864 Instruction::CmpIn binop;
1865 left = left.storeOnStack();
1866 right.loadInAccumulator();
1867 binop.lhs = left.stackSlot();
1868 bytecodeGenerator->addInstruction(binop);
1871 case QSOperator::StrictEqual: {
1873 return jumpBinop(oper, left, right);
1875 Instruction::CmpStrictEqual cmp;
1876 left = left.storeOnStack();
1877 right.loadInAccumulator();
1878 cmp.lhs = left.stackSlot();
1879 bytecodeGenerator->addInstruction(cmp);
1882 case QSOperator::StrictNotEqual: {
1884 return jumpBinop(oper, left, right);
1886 Instruction::CmpStrictNotEqual cmp;
1887 left = left.storeOnStack();
1888 right.loadInAccumulator();
1889 cmp.lhs = left.stackSlot();
1890 bytecodeGenerator->addInstruction(cmp);
1893 case QSOperator::Equal: {
1895 return jumpBinop(oper, left, right);
1897 Instruction::CmpEq cmp;
1898 left = left.storeOnStack();
1899 right.loadInAccumulator();
1900 cmp.lhs = left.stackSlot();
1901 bytecodeGenerator->addInstruction(cmp);
1904 case QSOperator::NotEqual: {
1906 return jumpBinop(oper, left, right);
1908 Instruction::CmpNe cmp;
1909 left = left.storeOnStack();
1910 right.loadInAccumulator();
1911 cmp.lhs = left.stackSlot();
1912 bytecodeGenerator->addInstruction(cmp);
1915 case QSOperator::Gt: {
1917 return jumpBinop(oper, left, right);
1919 Instruction::CmpGt cmp;
1920 left = left.storeOnStack();
1921 right.loadInAccumulator();
1922 cmp.lhs = left.stackSlot();
1923 bytecodeGenerator->addInstruction(cmp);
1926 case QSOperator::Ge: {
1928 return jumpBinop(oper, left, right);
1930 Instruction::CmpGe cmp;
1931 left = left.storeOnStack();
1932 right.loadInAccumulator();
1933 cmp.lhs = left.stackSlot();
1934 bytecodeGenerator->addInstruction(cmp);
1937 case QSOperator::Lt: {
1939 return jumpBinop(oper, left, right);
1941 Instruction::CmpLt cmp;
1942 left = left.storeOnStack();
1943 right.loadInAccumulator();
1944 cmp.lhs = left.stackSlot();
1945 bytecodeGenerator->addInstruction(cmp);
1948 case QSOperator::Le:
1950 return jumpBinop(oper, left, right);
1952 Instruction::CmpLe cmp;
1953 left = left.storeOnStack();
1954 right.loadInAccumulator();
1955 cmp.lhs = left.stackSlot();
1956 bytecodeGenerator->addInstruction(cmp);
1962 return Reference::fromAccumulator(
this);
1965Codegen::Reference Codegen::jumpBinop(QSOperator::Op oper, Reference &left, Reference &right)
1968 if (oper == QSOperator::Equal || oper == QSOperator::NotEqual) {
1970 if (left.isConstant() && !right.isConstant())
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);
1982 }
else if (oper == QSOperator::NotEqual) {
1983 Instruction::CmpNeNull cmp;
1984 bytecodeGenerator->addInstruction(cmp);
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);
1996 }
else if (oper == QSOperator::NotEqual) {
1997 Instruction::CmpNeInt cmp;
1998 cmp.lhs = c.int_32();
1999 bytecodeGenerator->addInstruction(cmp);
2008 left = left.storeOnStack();
2009 right.loadInAccumulator();
2012 case QSOperator::StrictEqual: {
2013 Instruction::CmpStrictEqual cmp;
2014 cmp.lhs = left.stackSlot();
2015 bytecodeGenerator->addInstruction(cmp);
2019 case QSOperator::StrictNotEqual: {
2020 Instruction::CmpStrictNotEqual cmp;
2021 cmp.lhs = left.stackSlot();
2022 bytecodeGenerator->addInstruction(cmp);
2026 case QSOperator::Equal: {
2027 Instruction::CmpEq cmp;
2028 cmp.lhs = left.stackSlot();
2029 bytecodeGenerator->addInstruction(cmp);
2033 case QSOperator::NotEqual: {
2034 Instruction::CmpNe cmp;
2035 cmp.lhs = left.stackSlot();
2036 bytecodeGenerator->addInstruction(cmp);
2040 case QSOperator::Gt: {
2041 Instruction::CmpGt cmp;
2042 cmp.lhs = left.stackSlot();
2043 bytecodeGenerator->addInstruction(cmp);
2047 case QSOperator::Ge: {
2048 Instruction::CmpGe cmp;
2049 cmp.lhs = left.stackSlot();
2050 bytecodeGenerator->addInstruction(cmp);
2054 case QSOperator::Lt: {
2055 Instruction::CmpLt cmp;
2056 cmp.lhs = left.stackSlot();
2057 bytecodeGenerator->addInstruction(cmp);
2061 case QSOperator::Le: {
2062 Instruction::CmpLe cmp;
2063 cmp.lhs = left.stackSlot();
2064 bytecodeGenerator->addInstruction(cmp);
2074Codegen::Reference Codegen::loadSubscriptForCall(
const Codegen::Reference &base)
2078 base.elementSubscript.loadInAccumulator();
2079 Codegen::Instruction::LoadElement load;
2080 load.base = base.elementBase;
2081 bytecodeGenerator->addInstruction(load);
2082 return Reference::fromAccumulator(
this);
2085bool Codegen::visit(CallExpression *ast)
2090 const bool isTailOfChain = traverseOptionalChain(ast);
2092 RegisterScope scope(
this);
2093 TailCallBlocker blockTailCalls(
this);
2095 Reference expr = expression(ast->base);
2096 Reference base = expr;
2100 switch (base.type) {
2101 case Reference::Member:
2102 base = base.asLValue();
2104 case Reference::Subscript:
2105 base.element = loadSubscriptForCall(base).storeOnStack().stackSlot();
2106 base.subscriptLoadedForCall =
true;
2108 case Reference::Name:
2110 case Reference::Super:
2111 handleConstruct(base, ast->arguments);
2113 case Reference::SuperProperty:
2116 base = base.storeOnStack();
2120 if (expr.hasSavedCallBaseSlot) {
2122 base.hasSavedCallBaseSlot =
true;
2123 base.savedCallBaseSlot = expr.savedCallBaseSlot;
2124 base.savedCallPropertyNameIndex = expr.savedCallPropertyNameIndex;
2127 int thisObject = bytecodeGenerator->newRegister();
2128 int functionObject = bytecodeGenerator->newRegister();
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));
2137 auto calldata = pushArgs(ast->arguments);
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);
2149 const int func = [&]() {
2150 if (base.type == Reference::Subscript)
2151 return base.element;
2153 if (!base.isStackSlot()) {
2154 base.storeOnStack(functionObject);
2155 base = Reference::fromStackSlot(
this, functionObject);
2158 return base.stackSlot();
2161 if (calldata.hasSpread) {
2162 Instruction::CallWithSpread call;
2164 call.thisObject = baseObject.stackSlot();
2165 call.argc = calldata.argc;
2166 call.argv = calldata.argv;
2167 bytecodeGenerator->addInstruction(call);
2169 Instruction::TailCall call;
2171 call.thisObject = baseObject.stackSlot();
2172 call.argc = calldata.argc;
2173 call.argv = calldata.argv;
2174 bytecodeGenerator->addInstruction(call);
2177 optionalChainFinalizer(Reference::fromAccumulator(
this), isTailOfChain);
2181 handleCall(base, calldata, functionObject, thisObject, ast->isOptional);
2182 optionalChainFinalizer(Reference::fromAccumulator(
this), isTailOfChain);
2186void Codegen::endVisit(CallExpression *ast)
2188 m_seenOptionalChainNodes.remove(ast);
2191void Codegen::handleCall(Reference &base, Arguments calldata,
int slotForFunction,
int slotForThisObject,
bool optional)
2193 if (base.sourceLocation.isValid())
2194 bytecodeGenerator->setLocation(base.sourceLocation);
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);
2205 call.base = base.propertyBase.stackSlot();
2206 call.lookupIndex = registerGetterLookup(
2207 base.propertyNameIndex, JSUnitGenerator::LookupForCall);
2209 call.argc = calldata.argc;
2210 call.argv = calldata.argv;
2211 bytecodeGenerator->addInstruction(call);
2213 Instruction::CallProperty call;
2214 if (base.hasSavedCallBaseSlot) {
2215 call.base = base.savedCallBaseSlot;
2216 call.name = base.savedCallPropertyNameIndex;
2218 call.base = base.propertyBase.stackSlot();
2219 call.name = base.propertyNameIndex;
2221 call.argc = calldata.argc;
2222 call.argv = calldata.argv;
2223 bytecodeGenerator->addInstruction(call);
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);
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);
2255 Instruction::CallName call;
2256 call.name = base.nameAsIndex();
2257 call.argc = calldata.argc;
2258 call.argv = calldata.argv;
2259 bytecodeGenerator->addInstruction(call);
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);
2267 if (!receiver.isStackSlot()) {
2268 receiver.storeOnStack(slotForThisObject);
2269 receiver = Reference::fromStackSlot(
this, slotForThisObject);
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);
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);
2287Codegen::Arguments Codegen::pushArgs(ArgumentList *args)
2289 bool hasSpread =
false;
2291 for (ArgumentList *it = args; it; it = it->next) {
2292 if (it->spreadToken.isValid()) {
2300 return { 0, 0,
false };
2302 int calldata = bytecodeGenerator->newRegisterArray(argc);
2305 for (ArgumentList *it = args; it; it = it->next) {
2306 if (it->spreadToken.isValid()) {
2307 Reference::fromConst(
2309 StaticValue::emptyValue().asReturnedValue()).storeOnStack(calldata + argc);
2312 RegisterScope scope(
this);
2313 Reference e = expression(it->expression);
2316 if (!argc && !it->next && !hasSpread) {
2318 if (e.isStackSlot()) {
2320 return { 1, e.stackSlot(), hasSpread };
2323 (
void) e.storeOnStack(calldata + argc);
2327 return { argc, calldata, hasSpread };
2330Codegen::Arguments Codegen::pushTemplateArgs(TemplateLiteral *args)
2333 for (TemplateLiteral *it = args; it; it = it->next)
2337 return { 0, 0,
false };
2339 int calldata = bytecodeGenerator->newRegisterArray(argc);
2342 for (TemplateLiteral *it = args; it && it->expression; it = it->next) {
2343 RegisterScope scope(
this);
2344 Reference e = expression(it->expression);
2347 (
void) e.storeOnStack(calldata + argc);
2351 return { argc, calldata,
false };
2354bool Codegen::visit(ConditionalExpression *ast)
2359 RegisterScope scope(
this);
2360 TailCallBlocker blockTailCalls(
this);
2362 BytecodeGenerator::Label iftrue = bytecodeGenerator->newLabel();
2363 BytecodeGenerator::Label iffalse = bytecodeGenerator->newLabel();
2364 condition(ast->expression, &iftrue, &iffalse,
true);
2366 blockTailCalls.unblock();
2369 Reference ok = expression(ast->ok);
2372 ok.loadInAccumulator();
2373 BytecodeGenerator::Jump jump_endif = bytecodeGenerator->jump();
2376 Reference ko = expression(ast->ko);
2381 ko.loadInAccumulator();
2384 setExprResult(Reference::fromAccumulator(
this));
2389bool Codegen::visit(DeleteExpression *ast)
2394 const bool isTailOfChain = traverseOptionalChain(ast);
2396 RegisterScope scope(
this);
2397 TailCallBlocker blockTailCalls(
this);
2398 Reference expr = expression(ast->expression);
2402 const bool chainActuallyHasOptionals = m_optionalChainsStates->top().actuallyHasOptionals;
2403 if (chainActuallyHasOptionals)
2404 Q_ASSERT(expr.type == Reference::Member || expr.type == Reference::Subscript);
2406 switch (expr.type) {
2407 case Reference::SuperProperty:
2410 case Reference::StackSlot:
2411 if (!expr.stackSlotIsLocalOrArgument)
2414 case Reference::ScopedLocal:
2416 if (_context->isStrict) {
2417 throwSyntaxError(ast->deleteToken, QStringLiteral(
"Delete of an unqualified identifier in strict mode."));
2420 setExprResult(Reference::fromConst(
this, QV4::Encode(
false)));
2422 case Reference::Name: {
2423 if (_context->isStrict) {
2424 throwSyntaxError(ast->deleteToken, QStringLiteral(
"Delete of an unqualified identifier in strict mode."));
2427 Instruction::DeleteName del;
2428 del.name = expr.nameAsIndex();
2429 bytecodeGenerator->addInstruction(del);
2430 setExprResult(Reference::fromAccumulator(
this));
2433 case Reference::Member: {
2435 expr = expr.asLValue();
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));
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);
2455 optionalChainFinalizer(ref, isTailOfChain,
true);
2458 case Reference::Subscript: {
2460 expr = expr.asLValue();
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));
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);
2475 optionalChainFinalizer(ref, isTailOfChain,
true);
2482 setExprResult(Reference::fromConst(
this, QV4::Encode(
true)));
2486void Codegen::endVisit(DeleteExpression *ast) {
2487 m_seenOptionalChainNodes.remove(ast);
2490bool Codegen::visit(FalseLiteral *)
2495 setExprResult(Reference::fromConst(
this, QV4::Encode(
false)));
2499bool Codegen::visit(SuperLiteral *)
2504 setExprResult(Reference::fromSuper(
this));
2508bool Codegen::traverseOptionalChain(Node *node)
2510 if (m_seenOptionalChainNodes.contains(node))
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;
2519 m_optionalChainsStates->emplace();
2520 while (isOptionalChainableNode(node)) {
2521 m_seenOptionalChainNodes.insert(node);
2523 switch (node->kind) {
2524 case Node::Kind_FieldMemberExpression: {
2525 auto *fme = AST::cast<FieldMemberExpression *>(node);
2526 m_optionalChainsStates->top().actuallyHasOptionals |= fme->isOptional;
2530 case Node::Kind_CallExpression: {
2531 auto *ce = AST::cast<CallExpression *>(node);
2532 m_optionalChainsStates->top().actuallyHasOptionals |= ce->isOptional;
2536 case Node::Kind_ArrayMemberExpression: {
2537 auto *ame = AST::cast<ArrayMemberExpression *>(node);
2538 m_optionalChainsStates->top().actuallyHasOptionals |= ame->isOptional;
2542 case Node::Kind_DeleteExpression:
2543 node = AST::cast<DeleteExpression *>(node)->expression;
2553void Codegen::optionalChainFinalizer(
const Reference &expressionResult,
bool tailOfChain,
2554 bool isDeleteExpression)
2556 auto &chainState = m_optionalChainsStates->top();
2558 setExprResult(expressionResult);
2560 }
else if (!chainState.actuallyHasOptionals) {
2561 setExprResult(expressionResult);
2562 m_optionalChainsStates->pop();
2566 auto savedBaseSlot = -1;
2567 if (expressionResult.type == Reference::Member)
2568 savedBaseSlot = expressionResult.propertyBase.storeOnStack().stackSlot();
2569 expressionResult.loadInAccumulator();
2571 std::optional<Moth::BytecodeGenerator::Jump> jumpToDone;
2572 if (!isDeleteExpression)
2573 jumpToDone.emplace(bytecodeGenerator->jump());
2575 for (
auto &jump : chainState.jumpsToPatch)
2578 if (isDeleteExpression)
2579 bytecodeGenerator->addInstruction(Instruction::LoadTrue());
2581 bytecodeGenerator->addInstruction(Instruction::LoadUndefined());
2583 if (jumpToDone.has_value())
2584 jumpToDone.value().link();
2586 auto ref = Reference::fromAccumulator(
this);
2587 if (expressionResult.type == Reference::Member) {
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600 ref.hasSavedCallBaseSlot =
true;
2601 ref.savedCallBaseSlot = savedBaseSlot;
2602 ref.savedCallPropertyNameIndex = expressionResult.propertyNameIndex;
2605 m_optionalChainsStates->pop();
2608bool Codegen::visit(FieldMemberExpression *ast)
2613 const bool isTailOfChain = traverseOptionalChain(ast);
2615 TailCallBlocker blockTailCalls(
this);
2617 if (AST::IdentifierExpression *id = AST::cast<AST::IdentifierExpression *>(ast->base)) {
2618 if (id->name == QLatin1String(
"new")) {
2620 Q_ASSERT(ast->name == QLatin1String(
"target"));
2622 if (_context->isArrowFunction || _context->contextType == ContextType::Eval) {
2623 Reference r = referenceForName(QStringLiteral(
"new.target"),
false);
2624 r.isReadonly =
true;
2630 auto ref = Reference::fromStackSlot(
this, CallData::NewTarget);
2631 optionalChainFinalizer(ref, isTailOfChain);
2636 Reference base = expression(ast->base);
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();
2646 optionalChainFinalizer(Reference::fromSuperProperty(property), isTailOfChain);
2650 auto ref = Reference::fromMember(base, ast->name.toString(), ast->lastSourceLocation(),
2651 ast->isOptional, &m_optionalChainsStates->top().jumpsToPatch);
2653 optionalChainFinalizer(ref, isTailOfChain);
2657void Codegen::endVisit(FieldMemberExpression *ast)
2659 m_seenOptionalChainNodes.remove(ast);
2662bool Codegen::visit(TaggedTemplate *ast)
2667 RegisterScope scope(
this);
2668 auto base = expression(ast->base);
2671 return handleTaggedTemplate(std::move(base), ast);
2674bool Codegen::handleTaggedTemplate(Reference base, TaggedTemplate *ast)
2679 int functionObject = -1, thisObject = -1;
2680 switch (base.type) {
2681 case Reference::Member:
2682 base = base.asLValue();
2684 case Reference::Subscript:
2685 base.element = loadSubscriptForCall(base).storeOnStack().stackSlot();
2686 base.subscriptLoadedForCall =
true;
2688 case Reference::Name:
2690 case Reference::SuperProperty:
2691 thisObject = bytecodeGenerator->newRegister();
2692 functionObject = bytecodeGenerator->newRegister();
2695 base = base.storeOnStack();
2699 createTemplateObject(ast->templateLiteral);
2700 int templateObjectTemp = Reference::fromAccumulator(
this).storeOnStack().stackSlot();
2701 Q_UNUSED(templateObjectTemp);
2702 auto calldata = pushTemplateArgs(ast->templateLiteral);
2706 Q_ASSERT(calldata.argv == templateObjectTemp + 1);
2709 handleCall(base, calldata, functionObject, thisObject);
2710 setExprResult(Reference::fromAccumulator(
this));
2714void Codegen::createTemplateObject(TemplateLiteral *t)
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()));
2723 int index = _module->templateObjects.size();
2724 _module->templateObjects.append(obj);
2726 Instruction::GetTemplateObject getTemplateObject;
2727 getTemplateObject.index = index;
2728 bytecodeGenerator->addInstruction(getTemplateObject);
2731bool Codegen::visit(FunctionExpression *ast)
2736 TailCallBlocker blockTailCalls(
this);
2738 RegisterScope scope(
this);
2740 int function = defineFunction(ast->name.toString(), ast, ast->formals, ast->body);
2743 loadClosure(function);
2744 setExprResult(Reference::fromAccumulator(
this));
2748Codegen::Reference Codegen::referenceForName(
const QString &name,
bool isLhs,
const SourceLocation &accessLocation)
2750 Context::ResolvedName resolved = _context->resolveName(name, accessLocation);
2751 bool throwsReferenceError =
false;
2753 if (resolved.type == Context::ResolvedName::Local || resolved.type == Context::ResolvedName::Stack
2754 || resolved.type == Context::ResolvedName::Import) {
2755 if (resolved.isArgOrEval && isLhs)
2757 throwSyntaxError(SourceLocation(), QStringLiteral(
"Variable name may not be eval or arguments in strict mode"));
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);
2766 _interface->reportVarUsedBeforeDeclaration(
2767 name, url().toLocalFile(), resolved.declarationLocation, accessLocation);
2769 if (resolved.type == Context::ResolvedName::Stack && resolved.requiresTDZCheck)
2770 throwsReferenceError =
true;
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.";
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 );
break;
2788 case Context::ResolvedName::Import:
2789 r = Reference::fromImport(
this, resolved.index);
break;
2790 default: Q_UNREACHABLE();
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;
2798 r.sourceLocation = accessLocation;
2799 r.throwsReferenceError = throwsReferenceError;
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)) {
2819void Codegen::loadClosure(
int closureId)
2821 if (closureId >= 0) {
2822 Instruction::LoadClosure load;
2823 load.value = closureId;
2824 bytecodeGenerator->addInstruction(load);
2826 Reference::fromConst(
this, Encode::undefined()).loadInAccumulator();
2830bool Codegen::visit(IdentifierExpression *ast)
2835 setExprResult(referenceForName(ast->name.toString(),
false, ast->firstSourceLocation()));
2839bool Codegen::visit(NestedExpression *ast)
2844 accept(ast->expression);
2848void Codegen::handleConstruct(
const Reference &base, ArgumentList *arguments)
2850 Reference constructor;
2851 if (base.isSuper()) {
2852 Instruction::LoadSuperConstructor super;
2853 bytecodeGenerator->addInstruction(super);
2854 constructor = Reference::fromAccumulator(
this).storeOnStack();
2856 constructor = base.storeOnStack();
2859 auto calldata = pushArgs(arguments);
2864 Reference::fromStackSlot(
this, CallData::NewTarget).loadInAccumulator();
2866 constructor.loadInAccumulator();
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);
2875 Instruction::Construct create;
2876 create.func = constructor.stackSlot();
2877 create.argc = calldata.argc;
2878 create.argv = calldata.argv;
2879 bytecodeGenerator->addInstruction(create);
2883 Reference::fromAccumulator(
this).storeOnStack(CallData::This);
2885 setExprResult(Reference::fromAccumulator(
this));
2888bool Codegen::visit(NewExpression *ast)
2893 RegisterScope scope(
this);
2894 TailCallBlocker blockTailCalls(
this);
2896 Reference base = expression(ast->expression);
2899 if (base.isSuper()) {
2900 throwSyntaxError(ast->expression->firstSourceLocation(), QStringLiteral(
"Cannot use new with super."));
2904 handleConstruct(base,
nullptr);
2908bool Codegen::visit(NewMemberExpression *ast)
2913 RegisterScope scope(
this);
2914 TailCallBlocker blockTailCalls(
this);
2916 Reference base = expression(ast->base);
2919 if (base.isSuper()) {
2920 throwSyntaxError(ast->base->firstSourceLocation(), QStringLiteral(
"Cannot use new with super."));
2924 handleConstruct(base, ast->arguments);
2928bool Codegen::visit(NotExpression *ast)
2933 TailCallBlocker blockTailCalls(
this);
2934 auto e = expression(ast->expression);
2937 setExprResult(unop(Not, e));
2941bool Codegen::visit(NullExpression *)
2947 bytecodeGenerator->jump().link(*currentExpr().iffalse());
2949 setExprResult(Reference::fromConst(
this, Encode::null()));
2954bool Codegen::visit(NumericLiteral *ast)
2959 setExprResult(Reference::fromConst(
this, QV4::Encode::smallestNumber(ast->value)));
2963bool Codegen::visit(ObjectPattern *ast)
2968 TailCallBlocker blockTailCalls(
this);
2970 RegisterScope scope(
this);
2972 QStringList members;
2976 auto push = [
this, &args, &argc](
const Reference &arg) {
2977 int temp = bytecodeGenerator->newRegister();
2980 (
void) arg.storeOnStack(temp);
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)
2990 QString name = p->name->asString();
2991 uint arrayIndex = stringToArrayIndex(name);
2992 if (arrayIndex != UINT_MAX)
2994 if (members.contains(name))
2996 members.append(name);
3000 RegisterScope innerScope(
this);
3001 value = expression(p->initializer, name);
3006 if (!value.isStackSlot() || !value.stackSlotIsLocalOrArgument) {
3007 value.loadInAccumulator();
3008 value = Reference::fromAccumulator(
this);
3014 int classId = jsUnitGenerator->registerJSClass(members);
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;
3028 Reference::fromConst(
this, Encode(
int(argType))).loadInAccumulator();
3029 push(Reference::fromAccumulator(
this));
3032 RegisterScope innerScope(
this);
3033 Reference name = expression(cname->expression);
3036 name.loadInAccumulator();
3038 QString name = p->name->asString();
3040 uint arrayIndex = QV4::String::toArrayIndex(name);
3041 if (arrayIndex != UINT_MAX) {
3042 Reference::fromConst(
this, Encode(arrayIndex)).loadInAccumulator();
3046 Instruction::LoadRuntimeString instr;
3047 instr.stringId = registerString(name);
3048 bytecodeGenerator->addInstruction(instr);
3051 push(Reference::fromAccumulator(
this));
3053 RegisterScope innerScope(
this);
3054 if (p->type != PatternProperty::Literal) {
3056 FunctionExpression *f = p->initializer->asFunctionDefinition();
3058 int function = defineFunction(f->name.toString(), f, f->formals, f->body);
3061 Reference::fromConst(
this, Encode(function)).loadInAccumulator();
3063 Reference value = expression(p->initializer);
3066 value.loadInAccumulator();
3069 push(Reference::fromAccumulator(
this));
3072 Instruction::DefineObjectLiteral call;
3073 call.internalClassId = classId;
3075 call.args = Moth::StackSlot::createRegister(args);
3076 bytecodeGenerator->addInstruction(call);
3077 setExprResult(Reference::fromAccumulator(
this));
3081bool Codegen::visit(PostDecrementExpression *ast)
3086 Reference expr = expression(ast->base);
3089 if (!expr.isLValue()) {
3090 throwReferenceError(ast->base->lastSourceLocation(), QStringLiteral(
"Invalid left-hand side expression in postfix operation"));
3093 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(expr, ast->decrementToken))
3096 setExprResult(unop(PostDecrement, expr));
3101bool Codegen::visit(PostIncrementExpression *ast)
3106 Reference expr = expression(ast->base);
3109 if (!expr.isLValue()) {
3110 throwReferenceError(ast->base->lastSourceLocation(), QStringLiteral(
"Invalid left-hand side expression in postfix operation"));
3113 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(expr, ast->incrementToken))
3116 setExprResult(unop(PostIncrement, expr));
3120bool Codegen::visit(PreDecrementExpression *ast)
3124 Reference expr = expression(ast->expression);
3127 if (!expr.isLValue()) {
3128 throwReferenceError(ast->expression->lastSourceLocation(), QStringLiteral(
"Prefix -- operator applied to value that is not a reference."));
3132 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(expr, ast->decrementToken))
3134 setExprResult(unop(PreDecrement, expr));
3138bool Codegen::visit(PreIncrementExpression *ast)
3143 Reference expr = expression(ast->expression);
3146 if (!expr.isLValue()) {
3147 throwReferenceError(ast->expression->lastSourceLocation(), QStringLiteral(
"Prefix ++ operator applied to value that is not a reference."));
3151 if (throwSyntaxErrorOnEvalOrArgumentsInStrictMode(expr, ast->incrementToken))
3153 setExprResult(unop(PreIncrement, expr));
3157bool Codegen::visit(RegExpLiteral *ast)
3162 auto r = Reference::fromStackSlot(
this);
3163 r.isReadonly =
true;
3166 Instruction::MoveRegExp instr;
3167 instr.regExpId = jsUnitGenerator->registerRegExp(ast);
3168 instr.destReg = r.stackSlot();
3169 bytecodeGenerator->addInstruction(instr);
3173bool Codegen::visit(StringLiteral *ast)
3178 auto r = Reference::fromAccumulator(
this);
3179 r.isReadonly =
true;
3182 Instruction::LoadRuntimeString instr;
3183 instr.stringId = registerString(ast->value.toString());
3184 bytecodeGenerator->addInstruction(instr);
3188bool Codegen::visit(TemplateLiteral *ast)
3193 TailCallBlocker blockTailCalls(
this);
3195 Instruction::LoadRuntimeString instr;
3196 instr.stringId = registerString(ast->value.toString());
3197 bytecodeGenerator->addInstruction(instr);
3199 if (ast->expression) {
3200 RegisterScope scope(
this);
3201 int temp = bytecodeGenerator->newRegister();
3202 Instruction::StoreReg store;
3204 bytecodeGenerator->addInstruction(store);
3206 Reference expr = expression(ast->expression);
3211 int temp2 = bytecodeGenerator->newRegister();
3212 expr.storeOnStack(temp2);
3215 Instruction::Add instr;
3217 bytecodeGenerator->addInstruction(instr);
3219 expr.loadInAccumulator();
3222 Instruction::Add instr;
3224 bytecodeGenerator->addInstruction(instr);
3227 auto r = Reference::fromAccumulator(
this);
3228 r.isReadonly =
true;
3235bool Codegen::visit(ThisExpression *)
3240 for (Context *parentContext = _context; parentContext; parentContext = parentContext->parent) {
3241 if (parentContext->isArrowFunction) {
3242 Reference r = referenceForName(QStringLiteral(
"this"),
false);
3243 r.isReadonly =
true;
3247 if (parentContext->contextType != ContextType::Block)
3251 setExprResult(Reference::fromThis(
this));
3255bool Codegen::visit(TildeExpression *ast)
3260 TailCallBlocker blockTailCalls(
this);
3261 auto e = expression(ast->expression);
3265 setExprResult(unop(Compl, e));
3269bool Codegen::visit(TrueLiteral *)
3274 setExprResult(Reference::fromConst(
this, QV4::Encode(
true)));
3278bool Codegen::visit(TypeOfExpression *ast)
3283 RegisterScope scope(
this);
3284 TailCallBlocker blockTailCalls(
this);
3286 Reference expr = expression(ast->expression);
3290 if (expr.type == Reference::Name) {
3292 Instruction::TypeofName instr;
3293 instr.name = expr.nameAsIndex();
3294 bytecodeGenerator->addInstruction(instr);
3296 expr.loadInAccumulator();
3297 Instruction::TypeofValue instr;
3298 bytecodeGenerator->addInstruction(instr);
3300 setExprResult(Reference::fromAccumulator(
this));
3305bool Codegen::visit(UnaryMinusExpression *ast)
3310 TailCallBlocker blockTailCalls(
this);
3311 auto e = expression(ast->expression);
3315 setExprResult(unop(UMinus, e));
3319bool Codegen::visit(UnaryPlusExpression *ast)
3324 TailCallBlocker blockTailCalls(
this);
3325 auto e = expression(ast->expression);
3329 setExprResult(unop(UPlus, e));
3333bool Codegen::visit(VoidExpression *ast)
3338 RegisterScope scope(
this);
3339 TailCallBlocker blockTailCalls(
this);
3341 statement(ast->expression);
3342 setExprResult(Reference::fromConst(
this, Encode::undefined()));
3346bool Codegen::visit(FunctionDeclaration * ast)
3352 RegisterScope scope(
this);
3354 if (_functionContext->contextType == ContextType::Binding)
3355 referenceForName(ast->name.toString(),
true).loadInAccumulator();
3360bool Codegen::visit(YieldExpression *ast)
3362 if (inFormalParameterList) {
3363 throwSyntaxError(ast->firstSourceLocation(), QLatin1String(
"yield is not allowed inside parameter lists"));
3367 auto innerMostCurentFunctionContext = _context;
3368 while (innerMostCurentFunctionContext && innerMostCurentFunctionContext->contextType != ContextType::Function)
3369 innerMostCurentFunctionContext = innerMostCurentFunctionContext->parent;
3371 Q_ASSERT(innerMostCurentFunctionContext);
3373 if (!innerMostCurentFunctionContext->isGenerator) {
3374 throwSyntaxError(ast->firstSourceLocation(), u"Yield is only valid in generator functions"_s);
3378 RegisterScope scope(
this);
3379 TailCallBlocker blockTailCalls(
this);
3380 Reference expr = ast->expression ? expression(ast->expression) : Reference::fromConst(
this, Encode::undefined());
3384 Reference acc = Reference::fromAccumulator(
this);
3386 if (ast->isYieldStar) {
3387 Reference iterator = Reference::fromStackSlot(
this);
3388 Reference lhsValue = Reference::fromConst(
this, Encode::undefined()).storeOnStack();
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);
3399 BytecodeGenerator::Label in = bytecodeGenerator->label();
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();
3407 lhsValue.loadInAccumulator();
3411 lhsValue.loadInAccumulator();
3412 Instruction::YieldStar yield;
3413 bytecodeGenerator->addInstruction(yield);
3414 bytecodeGenerator->jump().link(in);
3417 bytecodeGenerator->checkException();
3419 lhsValue.loadInAccumulator();
3424 expr.loadInAccumulator();
3425 Instruction::Yield yield;
3426 bytecodeGenerator->addInstruction(yield);
3427 Instruction::Resume resume;
3428 BytecodeGenerator::Jump jump = bytecodeGenerator->addJumpInstruction(resume);
3435int Codegen::defineFunction(
const QString &name, AST::Node *ast, AST::FormalParameterList *formals,
3436 AST::StatementList *body)
3440 if (_context->functionIndex >= 0)
3442 return leaveContext();
3444 _context->name = name.isEmpty() ? currentExpr().result().name : name;
3445 _module->functions.append(_context);
3446 _context->functionIndex = _module->functions.size() - 1;
3448 Context *savedFunctionContext = _functionContext;
3449 _functionContext = _context;
3450 ControlFlow *savedControlFlow = controlFlow;
3451 controlFlow =
nullptr;
3453 if (_context->contextType == ContextType::Global || _context->contextType == ContextType::ScriptImportedByQML) {
3454 _module->blocks.append(_context);
3455 _context->blockIndex = _module->blocks.size() - 1;
3457 if (_module->isDebugging())
3458 _context->argumentsCanEscape =
true;
3466 _context->returnsClosure = body && cast<ExpressionStatement *>(body->statement)
3467 && cast<FunctionExpression *>(cast<ExpressionStatement *>(body->statement)->expression);
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;
3478 OptionalChainStates optionalChainStates;
3479 OptionalChainStates *savedOptionalChainStates = m_optionalChainsStates;
3480 m_optionalChainsStates = &optionalChainStates;
3483 bytecodeGenerator->newRegisterArray(
3484 sizeof(CallData) /
sizeof(StaticValue) - 1 + _context->arguments.size());
3486 bool _inFormalParameterList =
false;
3487 qSwap(_inFormalParameterList, inFormalParameterList);
3489 int returnAddress = -1;
3490 bool _requiresReturnValue = _context->requiresImplicitReturnValue();
3491 qSwap(requiresReturnValue, _requiresReturnValue);
3492 returnAddress = bytecodeGenerator->newRegister();
3493 qSwap(_returnAddress, returnAddress);
3496 if (!_context->parent && _context->requiresExecutionContext) {
3497 _module->blocks.append(_context);
3498 _context->blockIndex = _module->blocks.size() - 1;
3501 TailCallBlocker maybeBlockTailCalls(
this, _context->canHaveTailCalls());
3503 RegisterScope registerScope(
this);
3504 _context->emitBlockHeader(
this);
3507 QScopedValueRollback<
bool> inFormals(inFormalParameterList,
true);
3508 TailCallBlocker blockTailCalls(
this);
3512 PatternElement *e = formals->element;
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();
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,
true);
3539 formals = formals->next;
3544 if (_context->isGenerator) {
3545 Instruction::Yield yield;
3546 bytecodeGenerator->addInstruction(yield);
3549 statementList(body);
3552 bytecodeGenerator->setError(
true);
3554 bytecodeGenerator->setLocation(ast->lastSourceLocation());
3555 _context->emitBlockFooter(
this);
3558 _returnLabel->link();
3559 bytecodeGenerator->setLocation(ast->lastSourceLocation());
3562 if (_returnLabel || requiresReturnValue) {
3563 Instruction::LoadReg load;
3564 load.reg = Moth::StackSlot::createRegister(_returnAddress);
3565 bytecodeGenerator->addInstruction(load);
3567 Reference::fromConst(
this, Encode::undefined()).loadInAccumulator();
3570 bytecodeGenerator->addInstruction(Instruction::Ret());
3572 Q_ASSERT(_context == _functionContext);
3573 bytecodeGenerator->finalize(_context);
3574 _context->registerCountInFunction = bytecodeGenerator->registerCount();
3575 static const bool showCode = qEnvironmentVariableIsSet(
"QV4_SHOW_BYTECODE");
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);
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;
3596 return leaveContext();
3599bool Codegen::visit(Block *ast)
3604 RegisterScope scope(
this);
3606 ControlFlowBlock controlFlow(
this, ast);
3607 statementList(ast->statements);
3611bool Codegen::visit(BreakStatement *ast)
3618 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral(
"Break outside of loop"));
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"));
3627 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral(
"Undefined label '%1'").arg(ast->label.toString()));
3631 controlFlow->unwind(target);
3636bool Codegen::visit(ContinueStatement *ast)
3642 RegisterScope scope(
this);
3645 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral(
"Continue outside of loop"));
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()));
3654 throwSyntaxError(ast->lastSourceLocation(), QStringLiteral(
"continue outside of loop"));
3658 controlFlow->unwind(target);
3663bool Codegen::visit(DebuggerStatement *)
3669bool Codegen::visit(DoWhileStatement *ast)
3674 RegisterScope scope(
this);
3676 BytecodeGenerator::Label body = bytecodeGenerator->newLabel();
3677 BytecodeGenerator::Label cond = bytecodeGenerator->newLabel();
3678 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
3680 ControlFlowLoop flow(
this, &end, &cond);
3684 if (!AST::cast<FalseLiteral *>(ast->expression))
3685 bytecodeGenerator->addLoopStart(body);
3688 statement(ast->statement);
3689 setJumpOutLocation(bytecodeGenerator, ast->statement, ast->semicolonToken);
3692 if (AST::cast<TrueLiteral *>(ast->expression)) {
3694 bytecodeGenerator->checkException();
3695 bytecodeGenerator->jump().link(body);
3696 }
else if (AST::cast<FalseLiteral *>(ast->expression)) {
3699 TailCallBlocker blockTailCalls(
this);
3700 bytecodeGenerator->checkException();
3701 condition(ast->expression, &body, &end,
false);
3709bool Codegen::visit(EmptyStatement *)
3714bool Codegen::visit(ExpressionStatement *ast)
3719 RegisterScope scope(
this);
3720 TailCallBlocker blockTailCalls(
this);
3722 if (requiresReturnValue) {
3723 Reference e = expression(ast->expression);
3726 (
void) e.storeOnStack(_returnAddress);
3728 statement(ast->expression);
3733bool Codegen::visit(ForEachStatement *ast)
3738 RegisterScope scope(
this);
3739 TailCallBlocker blockTailCalls(
this);
3741 Reference iterator = Reference::fromStackSlot(
this);
3742 Reference lhsValue = Reference::fromStackSlot(
this);
3747 RegisterScope innerScope(
this);
3748 ControlFlowBlock controlFlow(
this, ast);
3749 Reference expr = expression(ast->expression);
3753 expr.loadInAccumulator();
3754 Instruction::GetIterator iteratorObjInstr;
3755 iteratorObjInstr.iterator =
static_cast<
int>(ast->type);
3756 bytecodeGenerator->addInstruction(iteratorObjInstr);
3757 iterator.storeConsumeAccumulator();
3760 BytecodeGenerator::Label in = bytecodeGenerator->newLabel();
3761 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
3762 BytecodeGenerator::Label done;
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);
3777 BytecodeGenerator::Label continueLabel = bytecodeGenerator->newLabel();
3778 ControlFlowLoop flow(
this, &end, &continueLabel, std::move(cleanup));
3779 bytecodeGenerator->addLoopStart(in);
3781 iterator.loadInAccumulator();
3782 Instruction::IteratorNext next;
3783 next.value = lhsValue.stackSlot();
3784 bytecodeGenerator->addJumpInstruction(next).link(done);
3788 RegisterScope innerScope(
this);
3789 ControlFlowBlock controlFlow(
this, ast);
3791 if (ExpressionNode *e = ast->lhs->expressionCast()) {
3792 if (AST::Pattern *p = e->patternCast()) {
3793 RegisterScope scope(
this);
3794 destructurePattern(p, lhsValue);
3796 Reference lhs = expression(e);
3799 if (!lhs.isLValue()) {
3800 throwReferenceError(e->firstSourceLocation(), QStringLiteral(
"Invalid left-hand side expression for 'in' expression"));
3803 lhs = lhs.asLValue();
3804 lhsValue.loadInAccumulator();
3805 lhs.storeConsumeAccumulator();
3807 }
else if (PatternElement *p = AST::cast<PatternElement *>(ast->lhs)) {
3808 initializeAndDestructureBindingElement(p, lhsValue,
true);
3815 blockTailCalls.unblock();
3816 statement(ast->statement);
3817 setJumpOutLocation(bytecodeGenerator, ast->statement, ast->forToken);
3820 continueLabel.link();
3821 bytecodeGenerator->setLocation(ast->forToken);
3822 bytecodeGenerator->checkException();
3823 bytecodeGenerator->jump().link(in);
3835bool Codegen::visit(ForStatement *ast)
3840 RegisterScope scope(
this);
3841 TailCallBlocker blockTailCalls(
this);
3843 ControlFlowBlock controlFlow(
this, ast);
3845 if (ast->initialiser)
3846 statement(ast->initialiser);
3847 else if (ast->declarations)
3848 variableDeclarationList(ast->declarations);
3850 BytecodeGenerator::Label cond = bytecodeGenerator->label();
3851 BytecodeGenerator::Label body = bytecodeGenerator->newLabel();
3852 BytecodeGenerator::Label step = bytecodeGenerator->newLabel();
3853 BytecodeGenerator::Label end = bytecodeGenerator->newLabel();
3855 ControlFlowLoop flow(
this, &end, &step);
3856 bytecodeGenerator->addLoopStart(cond);
3857 condition(ast->condition, &body, &end,
true);
3860 blockTailCalls.unblock();
3861 statement(ast->statement);
3862 blockTailCalls.reblock();
3863 setJumpOutLocation(bytecodeGenerator, ast->statement, ast->forToken);
3866 if (_context->requiresExecutionContext) {
3867 Instruction::CloneBlockContext clone;
3868 bytecodeGenerator->addInstruction(clone);
3870 statement(ast->expression);
3871 bytecodeGenerator->setLocation(ast->forToken);
3872 bytecodeGenerator->checkException();
3873 bytecodeGenerator->jump().link(cond);
3880bool Codegen::visit(IfStatement *ast)
3885 RegisterScope scope(
this);
3886 TailCallBlocker blockTailCalls(
this);
3888 BytecodeGenerator::Label trueLabel = bytecodeGenerator->newLabel();
3889 BytecodeGenerator::Label falseLabel = bytecodeGenerator->newLabel();
3890 condition(ast->expression, &trueLabel, &falseLabel,
true);
3891 blockTailCalls.unblock();
3896 BytecodeGenerator::Jump jump_endif = bytecodeGenerator->jump();
3907bool Codegen::visit(LabelledStatement *ast)
3912 RegisterScope scope(
this);
3915 ControlFlow *l = controlFlow;
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);
3924 _labelledStatement = ast;
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);
3933 BytecodeGenerator::Label breakLabel = bytecodeGenerator->newLabel();
3934 ControlFlowLoop flow(
this, &breakLabel);
3935 statement(ast->statement);
3942void Codegen::emitReturn(
const Reference &expr)
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);
3954 expr.loadInAccumulator();
3955 bytecodeGenerator->addInstruction(Instruction::Ret());
3958bool Codegen::visit(ReturnStatement *ast)
3963 if (_functionContext->contextType != ContextType::Function && _functionContext->contextType != ContextType::Binding) {
3964 throwSyntaxError(ast->returnToken, QStringLiteral(
"Return statement outside of function"));
3968 if (ast->expression) {
3969 expr = expression(ast->expression);
3973 expr = Reference::fromConst(
this, Encode::undefined());
3981bool Codegen::visit(SwitchStatement *ast)
3986 if (requiresReturnValue)
3987 Reference::fromConst(
this, Encode::undefined()).storeOnStack(_returnAddress);
3989 RegisterScope scope(
this);
3990 TailCallBlocker blockTailCalls(
this);
3993 BytecodeGenerator::Label switchEnd = bytecodeGenerator->newLabel();
3995 Reference lhs = expression(ast->expression);
3998 lhs = lhs.storeOnStack();
4000 ControlFlowBlock controlFlow(
this, ast->block);
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();
4012 for (CaseClauses *it = ast->block->clauses; it; it = it->next) {
4013 CaseClause *clause = it->clause;
4014 Reference rhs = expression(clause->expression);
4017 rhs.loadInAccumulator();
4018 bytecodeGenerator->jumpStrictEqual(lhs.stackSlot(), blockMap.value(clause));
4021 for (CaseClauses *it = ast->block->moreClauses; it; it = it->next) {
4022 CaseClause *clause = it->clause;
4023 Reference rhs = expression(clause->expression);
4026 rhs.loadInAccumulator();
4027 bytecodeGenerator->jumpStrictEqual(lhs.stackSlot(), blockMap.value(clause));
4030 if (DefaultClause *defaultClause = ast->block->defaultClause)
4031 bytecodeGenerator->jump().link(blockMap.value(defaultClause));
4033 bytecodeGenerator->jump().link(switchEnd);
4035 ControlFlowLoop flow(
this, &switchEnd);
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();
4043 statementList(clause->statements);
4046 if (ast->block->defaultClause) {
4047 DefaultClause *clause = ast->block->defaultClause;
4048 blockMap[clause].link();
4050 statementList(clause->statements);
4053 for (CaseClauses *it = ast->block->moreClauses; it; it = it->next) {
4054 CaseClause *clause = it->clause;
4055 blockMap[clause].link();
4057 statementList(clause->statements);
4059 insideSwitch =
false;
4068bool Codegen::visit(ThrowStatement *ast)
4073 RegisterScope scope(
this);
4074 TailCallBlocker blockTailCalls(
this);
4076 Reference expr = expression(ast->expression);
4080 expr.loadInAccumulator();
4081 Instruction::ThrowException instr;
4082 bytecodeGenerator->addInstruction(instr);
4086void Codegen::handleTryCatch(TryStatement *ast)
4089 RegisterScope scope(
this);
4091 ControlFlowCatch catchFlow(
this, ast->catchExpression);
4092 RegisterScope scope(
this);
4093 TailCallBlocker blockTailCalls(
this);
4094 statement(ast->statement);
4098void Codegen::handleTryFinally(TryStatement *ast)
4100 RegisterScope scope(
this);
4101 const bool hasCatchBlock = ast->catchExpression;
4102 ControlFlowFinally finally(
this, ast->finallyExpression, hasCatchBlock);
4103 TailCallBlocker blockTailCalls(
this);
4105 if (ast->catchExpression) {
4106 handleTryCatch(ast);
4108 RegisterScope scope(
this);
4109 statement(ast->statement);
4113bool Codegen::visit(TryStatement *ast)
4118 RegisterScope scope(
this);
4120 if (ast->finallyExpression && ast->finallyExpression->statement) {
4121 handleTryFinally(ast);
4123 handleTryCatch(ast);
4129bool Codegen::visit(VariableStatement *ast)
4134 variableDeclarationList(ast->declarations);
4138bool Codegen::visit(WhileStatement *ast)
4143 if (AST::cast<FalseLiteral *>(ast->expression))
4146 RegisterScope scope(
this);
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);
4154 bytecodeGenerator->checkException();
4156 if (!AST::cast<TrueLiteral *>(ast->expression)) {
4157 TailCallBlocker blockTailCalls(
this);
4158 condition(ast->expression, &start, &end,
true);
4162 statement(ast->statement);
4163 setJumpOutLocation(bytecodeGenerator, ast->statement, ast->whileToken);
4164 bytecodeGenerator->jump().link(cond);
4170bool Codegen::visit(WithStatement *ast)
4175 RegisterScope scope(
this);
4176 TailCallBlocker blockTailCalls(
this);
4178 Reference src = expression(ast->expression);
4181 src = src.storeOnStack();
4182 src.loadInAccumulator();
4186 blockTailCalls.unblock();
4187 ControlFlowWith flow(
this);
4188 statement(ast->statement);
4195bool Codegen::visit(UiArrayBinding *)
4201bool Codegen::visit(UiObjectBinding *)
4207bool Codegen::visit(UiObjectDefinition *)
4213bool Codegen::visit(UiPublicMember *)
4219bool Codegen::visit(UiScriptBinding *)
4225bool Codegen::visit(UiSourceElement *)
4231bool Codegen::throwSyntaxErrorOnEvalOrArgumentsInStrictMode(
const Reference &r,
const SourceLocation& loc)
4233 if (!_context->isStrict)
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")) {
4241 }
else if (r.type == Reference::ScopedLocal || r.isRegister()) {
4242 isArgOrEval = r.isArgOrEval;
4245 throwSyntaxError(loc, QStringLiteral(
"Variable name may not be eval or arguments in strict mode"));
4249void Codegen::throwError(ErrorType errorType,
const SourceLocation &loc,
const QString &detail)
4254 _errorType = errorType;
4255 _error.message = detail;
4259void Codegen::throwSyntaxError(
const SourceLocation &loc,
const QString &detail)
4261 throwError(SyntaxError, loc, detail);
4264void Codegen::throwReferenceError(
const SourceLocation &loc,
const QString &detail)
4266 throwError(ReferenceError, loc, detail);
4269QQmlJS::DiagnosticMessage Codegen::error()
const
4274QQmlRefPointer<QV4::CompiledData::CompilationUnit> Codegen::generateCompilationUnit(
4275 bool generateUnitData)
4277 return QQmlRefPointer<QV4::CompiledData::CompilationUnit>(
4278 new QV4::CompiledData::CompilationUnit(
4279 generateUnitData ? jsUnitGenerator->generateUnit() :
nullptr),
4280 QQmlRefPointer<QV4::CompiledData::CompilationUnit>::Adopt);
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)
4289 const QQmlJS::Parser::Result parsed =
4290 QQmlJS::Parser::parseCode(&ee, sourceCode, QQmlJS::Parser::Goal::Module);
4293 *diagnostics = parsed.diagnosticMessages;
4295 if (!parsed.success)
4296 return QQmlRefPointer<CompiledData::CompilationUnit>();
4298 QQmlJS::AST::ESModule *moduleNode = QQmlJS::AST::cast<QQmlJS::AST::ESModule *>(parsed.rootNode);
4303 diagnostics->clear();
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,
true);
4313 cg.generateFromModule(sourceCode, moduleNode, &compilerModule);
4314 if (cg.hasError()) {
4316 *diagnostics << cg.error();
4317 return QQmlRefPointer<CompiledData::CompilationUnit>();
4320 return cg.generateCompilationUnit();
4323const QV4::CompiledData::Unit *Codegen::generateNativeModuleUnitData(
4324 Moth::DebugInstructionPass debugInstructionPass,
const QString &url,
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,
true);
4332 cg.generateFromModule(value, &compilerModule);
4333 Q_ASSERT(!cg.hasError());
4334 return jsGenerator.generateUnit();
4339 VolatileMemoryLocations locs;
4354 bool visit(ArrayMemberExpression *)
override
4356 locs.setAllVolatile();
4360 bool visit(FieldMemberExpression *)
override
4362 locs.setAllVolatile();
4366 bool visit(PostIncrementExpression *e)
override
4368 collectIdentifiers(locs.specificLocations, e->base);
4372 bool visit(PostDecrementExpression *e)
override
4374 collectIdentifiers(locs.specificLocations, e->base);
4378 bool visit(PreIncrementExpression *e)
override
4380 collectIdentifiers(locs.specificLocations, e->expression);
4384 bool visit(PreDecrementExpression *e)
override
4386 collectIdentifiers(locs.specificLocations, e->expression);
4390 bool visit(BinaryExpression *e)
override
4393 case QSOperator::Assign:
4395 collectIdentifiers(locs.specificLocations, e->left);
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);
4424 void collectIdentifiers(QList<QStringView> &ids, AST::Node *node) {
4425 class Collector:
public QQmlJS::AST::Visitor {
4427 QList<QStringView> &ids;
4428 VolatileMemoryLocationScanner *parent;
4431 Collector(QList<QStringView> &ids, VolatileMemoryLocationScanner *parent) :
4432 QQmlJS::AST::Visitor(parent->recursionDepth()), ids(ids), parent(parent)
4435 bool visit(IdentifierExpression *ie)
final {
4436 ids.append(ie->name);
4440 bool visit(PatternElement *pe)
final {
4441 if (!pe->bindingIdentifier.isEmpty())
4442 ids.append(pe->bindingIdentifier);
4446 bool visit(PatternProperty *pp)
final {
4447 if (!pp->bindingIdentifier.isEmpty())
4448 ids.append(pp->bindingIdentifier);
4452 void throwRecursionDepthError() final
4454 parent->throwRecursionDepthError();
4457 Collector collector(ids,
this);
4458 node->accept(&collector);
4462Codegen::VolatileMemoryLocations
Codegen::scanVolatileMemoryLocations(AST::Node *ast)
4464 VolatileMemoryLocationScanner scanner(
this);
4465 return scanner.scan(ast);
4470 return QUrl(_fileNameIsUrl ? QUrl(_module->fileName) : QUrl::fromLocalFile(_module->fileName));
4473bool Codegen::RValue::operator==(
const RValue &other)
const
4477 return other.isAccumulator();
4479 return other.isStackSlot() && theStackSlot == other.theStackSlot;
4481 return other.isConst() && constant == other.constant;
4487Codegen::RValue Codegen::RValue::storeOnStack()
const
4491 return RValue::fromStackSlot(codegen, Reference::fromAccumulator(codegen).storeOnStack().stackSlot());
4495 return RValue::fromStackSlot(codegen, Reference::storeConstOnStack(codegen, constant).stackSlot());
4501void Codegen::RValue::loadInAccumulator()
const
4508 return Reference::fromStackSlot(codegen, theStackSlot).loadInAccumulator();
4510 return Reference::fromConst(codegen, constant).loadInAccumulator();
4517bool Codegen::Reference::operator==(
const Codegen::Reference &other)
const
4519 if (type != other.type)
4528 return property == other.property;
4530 return theStackSlot == other.theStackSlot;
4532 return index == other.index && scope == other.scope;
4534 return nameAsIndex() == other.nameAsIndex();
4536 return propertyBase == other.propertyBase && propertyNameIndex == other.propertyNameIndex;
4538 return elementBase == other.elementBase && other.subscriptLoadedForCall
4539 ? (subscriptLoadedForCall && element == other.element)
4540 : (!subscriptLoadedForCall && elementSubscript == other.elementSubscript);
4542 return index == other.index;
4544 return constant == other.constant;
4549Codegen::RValue Codegen::Reference::asRValue()
const
4555 return RValue::fromAccumulator(codegen);
4557 return RValue::fromStackSlot(codegen, stackSlot());
4559 return RValue::fromConst(codegen, constant);
4561 loadInAccumulator();
4562 return RValue::fromAccumulator(codegen);
4566Codegen::Reference Codegen::Reference::asLValue()
const
4573 codegen->throwSyntaxError(SourceLocation(), QStringLiteral(
"Super lvalues not implemented."));
4576 if (!propertyBase.isStackSlot()) {
4577 Reference r = *
this;
4578 r.propertyBase = propertyBase.storeOnStack();
4583 if (!elementSubscript.isStackSlot()) {
4584 Reference r = *
this;
4585 r.elementSubscript = elementSubscript.storeOnStack();
4594Codegen::Reference Codegen::Reference::storeConsumeAccumulator()
const
4600Codegen::Reference Codegen::Reference::baseObject()
const
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());
4611 return Reference::fromConst(codegen, rval.constantValue());
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);
4618 return Reference::fromConst(codegen, Encode::undefined());
4622Codegen::Reference Codegen::Reference::storeOnStack()
const
4623{
return doStoreOnStack(-1); }
4625void Codegen::Reference::storeOnStack(
int slotIndex)
const
4626{ doStoreOnStack(slotIndex); }
4628Codegen::Reference Codegen::Reference::doStoreOnStack(
int slotIndex)
const
4630 Q_ASSERT(isValid());
4632 if (isStackSlot() && slotIndex == -1 && !(stackSlotIsLocalOrArgument && isVolatile) && !requiresTDZCheck)
4635 if (isStackSlot() && !requiresTDZCheck) {
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);
4644 Reference slot = Reference::fromStackSlot(codegen, slotIndex);
4646 Instruction::MoveConst move;
4647 move.constIndex = codegen->registerConstant(constant);
4648 move.destTemp = slot.stackSlot();
4649 codegen->bytecodeGenerator->addInstruction(move);
4651 loadInAccumulator();
4652 slot.storeConsumeAccumulator();
4657void Codegen::Reference::tdzCheck(
bool requiresCheck,
bool throwsReferenceError)
const {
4658 if (throwsReferenceError) {
4659 codegen->generateThrowException(QStringLiteral(
"ReferenceError"),
4660 name + QStringLiteral(
" is not defined"));
4665 Instruction::DeadTemporalZoneCheck check;
4666 check.name = codegen->registerString(name);
4667 codegen->bytecodeGenerator->addInstruction(check);
4670void Codegen::Reference::tdzCheckStackSlot(Moth::StackSlot slot,
bool requiresCheck,
bool throwsReferenceError)
const {
4673 Instruction::LoadReg load;
4675 codegen->bytecodeGenerator->addInstruction(load);
4676 tdzCheck(
true, throwsReferenceError);
4682void Codegen::Reference::checkTDZBeforeAssignment()
const
4684 if (!requiresTDZCheck)
4687 if (type != StackSlot && type != ScopedLocal)
4690 loadInAccumulator();
4693Codegen::Reference Codegen::Reference::storeRetainAccumulator()
const
4695 if (storeWipesAccumulator()) {
4697 auto tmp = Reference::fromStackSlot(codegen);
4698 tmp.storeAccumulator();
4699 tmp.isReadonly = isReadonly;
4709bool Codegen::Reference::storeWipesAccumulator()
const
4728void Codegen::Reference::storeAccumulator()
const
4730 if (throwsReferenceError) {
4731 codegen->generateThrowException(QStringLiteral(
"ReferenceError"),
4732 name + QStringLiteral(
" is not defined"));
4736 if (isReferenceToConst) {
4738 codegen->generateThrowException(QStringLiteral(
"TypeError"));
4744 Q_UNREACHABLE_RETURN();
4746 Instruction::StoreSuperProperty store;
4747 store.property = property.stackSlot();
4748 codegen->bytecodeGenerator->addInstruction(store);
4751 Instruction::StoreReg store;
4752 store.reg = theStackSlot;
4753 codegen->bytecodeGenerator->addInstruction(store);
4758 Instruction::StoreLocal store;
4759 store.index = index;
4760 codegen->bytecodeGenerator->addInstruction(store);
4762 Instruction::StoreScopedLocal store;
4763 store.index = index;
4764 store.scope = scope;
4765 codegen->bytecodeGenerator->addInstruction(store);
4770 Context *c = codegen->currentContext();
4772 Instruction::StoreNameStrict store;
4773 store.name = nameAsIndex();
4774 codegen->bytecodeGenerator->addInstruction(store);
4776 Instruction::StoreNameSloppy store;
4777 store.name = nameAsIndex();
4778 codegen->bytecodeGenerator->addInstruction(store);
4782 if (codegen->useFastLookups) {
4783 Instruction::SetLookup store;
4784 store.base = propertyBase.stackSlot();
4785 store.index = codegen->registerSetterLookup(propertyNameIndex);
4786 codegen->bytecodeGenerator->addInstruction(store);
4788 Instruction::StoreProperty store;
4789 store.base = propertyBase.stackSlot();
4790 store.name = propertyNameIndex;
4791 codegen->bytecodeGenerator->addInstruction(store);
4795 Instruction::StoreElement store;
4796 store.base = elementBase;
4797 store.index = elementSubscript.stackSlot();
4798 codegen->bytecodeGenerator->addInstruction(store);
4810void Codegen::Reference::loadInAccumulator()
const
4816 Q_UNREACHABLE_RETURN();
4818 tdzCheckStackSlot(property, subscriptRequiresTDZCheck,
false);
4819 Instruction::LoadSuperProperty load;
4820 load.property = property.stackSlot();
4821 codegen->bytecodeGenerator->addInstruction(load);
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);
4837 StaticValue p = StaticValue::fromReturnedValue(constant);
4839 double d = p.asDouble();
4840 int i = QJSNumberCoercion::toInteger(d);
4841 if (d == i && (d != 0 || !std::signbit(d))) {
4843 Instruction::LoadZero load;
4844 codegen->bytecodeGenerator->addInstruction(load);
4847 Instruction::LoadInt load;
4848 load.value = StaticValue::fromReturnedValue(constant).toInt32();
4849 codegen->bytecodeGenerator->addInstruction(load);
4853 Instruction::LoadConst load;
4854 load.index = codegen->registerConstant(constant);
4855 codegen->bytecodeGenerator->addInstruction(load);
4859 Instruction::LoadReg load;
4860 load.reg = stackSlot();
4861 codegen->bytecodeGenerator->addInstruction(load);
4862 tdzCheck(requiresTDZCheck, throwsReferenceError);
4866 Instruction::LoadLocal load;
4868 codegen->bytecodeGenerator->addInstruction(load);
4870 Instruction::LoadScopedLocal load;
4873 codegen->bytecodeGenerator->addInstruction(load);
4875 tdzCheck(requiresTDZCheck, throwsReferenceError);
4882 if (name == QStringLiteral(
"undefined")) {
4883 Reference::fromConst(codegen, Encode::undefined()).loadInAccumulator();
4885 }
else if (name == QStringLiteral(
"Infinity")) {
4886 Reference::fromConst(codegen, Encode(qInf())).loadInAccumulator();
4888 }
else if (name == QStringLiteral(
"Nan")) {
4889 Reference::fromConst(codegen, Encode(qQNaN())).loadInAccumulator();
4894 if (sourceLocation.isValid())
4895 codegen->bytecodeGenerator->setLocation(sourceLocation);
4899 Instruction::LoadQmlContextPropertyLookup load;
4900 load.index = codegen->registerQmlContextPropertyGetterLookup(
4901 nameAsIndex(), JSUnitGenerator::LookupForStorage);
4902 codegen->bytecodeGenerator->addInstruction(load);
4904 Instruction::LoadGlobalLookup load;
4905 load.index = codegen->registerGlobalGetterLookup(
4906 nameAsIndex(), JSUnitGenerator::LookupForStorage);
4907 codegen->bytecodeGenerator->addInstruction(load);
4910 Instruction::LoadName load;
4911 load.name = nameAsIndex();
4912 codegen->bytecodeGenerator->addInstruction(load);
4916 propertyBase.loadInAccumulator();
4917 tdzCheck(requiresTDZCheck, throwsReferenceError);
4919 if (sourceLocation.isValid())
4920 codegen->bytecodeGenerator->setLocation(sourceLocation);
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));
4929 Instruction::GetLookup load;
4930 load.index = codegen->registerGetterLookup(
4931 propertyNameIndex, JSUnitGenerator::LookupForStorage);
4932 codegen->bytecodeGenerator->addInstruction(load);
4935 if (optionalChainJumpsToPatch && isOptional) {
4936 auto jump = codegen->bytecodeGenerator->jumpOptionalProperty(propertyNameIndex);
4937 optionalChainJumpsToPatch->emplace_back(std::move(jump));
4939 Instruction::LoadProperty load;
4940 load.name = propertyNameIndex;
4941 codegen->bytecodeGenerator->addInstruction(load);
4946 Instruction::LoadImport load;
4948 codegen->bytecodeGenerator->addInstruction(load);
4949 tdzCheck(requiresTDZCheck, throwsReferenceError);
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);
void throwRecursionDepthError() override
VolatileMemoryLocationScanner(Codegen *parent)
Codegen::VolatileMemoryLocations scan(AST::Node *s)
bool visit(ArrayMemberExpression *) override
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)
static void setJumpOutLocation(QV4::Moth::BytecodeGenerator *bytecodeGenerator, const Statement *body, const SourceLocation &fallback)
static constexpr const QLatin1StringView s_globalNames[]