Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qv4compilerscanfunctions.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant
4
6
7#include <QtCore/QCoreApplication>
8#include <QtCore/QStringList>
9#include <QtCore/QSet>
10#include <QtCore/QBuffer>
11#include <QtCore/QBitArray>
12#include <QtCore/QStack>
13#include <private/qqmljsast_p.h>
14#include <private/qv4compilercontext_p.h>
15#include <private/qv4codegen_p.h>
16
17QT_USE_NAMESPACE
18using namespace QV4;
19using namespace QV4::Compiler;
20using namespace QQmlJS;
21using namespace QQmlJS::AST;
22
23static CompiledData::Location location(const QQmlJS::SourceLocation &astLocation)
24{
25 return CompiledData::Location(astLocation.startLine, astLocation.startColumn);
26}
27
28
29ScanFunctions::ScanFunctions(Codegen *cg, const QString &sourceCode, ContextType defaultProgramType)
31 , _cg(cg)
33 , _context(nullptr)
34 , _allowFuncDecls(true)
36{
37}
38
39void ScanFunctions::enterGlobalEnvironment(ContextType compilationMode)
40{
41 enterEnvironment(astNodeForGlobalEnvironment, compilationMode, QStringLiteral("%GlobalCode"));
42}
43
44void ScanFunctions::enterEnvironment(Node *node, ContextType compilationMode, const QString &name)
45{
46 Context *c = _cg->_module->contextMap.value(node);
47 if (!c)
48 c = _cg->_module->newContext(node, _context, compilationMode);
49 if (!c->isStrict)
50 c->isStrict = _cg->_strictMode;
51 c->name = name;
52 _contextStack.append(c);
53 _context = c;
54}
55
57{
58 _contextStack.pop();
59 _context = _contextStack.isEmpty() ? nullptr : _contextStack.top();
60}
61
62void ScanFunctions::checkDirectivePrologue(StatementList *ast)
63{
64 Q_ASSERT(_context);
65 for (StatementList *it = ast; it; it = it->next) {
66 if (ExpressionStatement *expr = cast<ExpressionStatement *>(it->statement)) {
67 if (StringLiteral *strLit = cast<StringLiteral *>(expr->expression)) {
68 // Use the source code, because the StringLiteral's
69 // value might have escape sequences in it, which is not
70 // allowed.
71 if (strLit->literalToken.length < 2)
72 continue;
73 QStringView str = QStringView{_sourceCode}.mid(strLit->literalToken.offset + 1, strLit->literalToken.length - 2);
74 if (str == QLatin1String("use strict")) {
75 _context->isStrict = true;
76 } else {
77 // TODO: give a warning.
78 }
79 continue;
80 }
81 }
82
83 break;
84 }
85}
86
87void ScanFunctions::checkName(QStringView name, const QQmlJS::SourceLocation &loc)
88{
89 Q_ASSERT(_context);
90 if (_context->isStrict) {
91 if (name == QLatin1String("implements")
92 || name == QLatin1String("interface")
93 || name == QLatin1String("let")
94 || name == QLatin1String("package")
95 || name == QLatin1String("private")
96 || name == QLatin1String("protected")
97 || name == QLatin1String("public")
98 || name == QLatin1String("static")
99 || name == QLatin1String("yield")) {
100 _cg->throwSyntaxError(loc, QStringLiteral("Unexpected strict mode reserved word"));
101 }
102 }
103}
104
105bool ScanFunctions::visit(Program *ast)
106{
107 enterEnvironment(ast, defaultProgramType, QStringLiteral("%ProgramCode"));
108 checkDirectivePrologue(ast->statements);
109 return true;
110}
111
112void ScanFunctions::endVisit(Program *)
113{
115}
116
117bool ScanFunctions::visit(ESModule *ast)
118{
119 enterEnvironment(ast, defaultProgramType, QStringLiteral("%ModuleCode"));
120 Q_ASSERT(_context);
121 _context->isStrict = true;
122 return true;
123}
124
125void ScanFunctions::endVisit(ESModule *)
126{
128}
129
130bool ScanFunctions::visit(ExportDeclaration *declaration)
131{
132 Q_ASSERT(_context);
133 QString module;
134 if (declaration->fromClause) {
135 module = declaration->fromClause->moduleSpecifier.toString();
136 if (!module.isEmpty())
137 _context->moduleRequests << module;
138 }
139
140 QString localNameForDefaultExport = QStringLiteral("*default*");
141
142 if (declaration->exportsAll()) {
143 Q_ASSERT_X(declaration->fromClause, "ScanFunctions",
144 "ExportDeclaration with exportAll always have a fromClause");
145 Compiler::ExportEntry entry;
146 entry.moduleRequest = declaration->fromClause->moduleSpecifier.toString();
147 entry.importName = QStringLiteral("*");
148 entry.location = location(declaration->firstSourceLocation());
149 _context->exportEntries << entry;
150 } else if (declaration->exportClause) {
151 for (ExportsList *it = declaration->exportClause->exportsList; it; it = it->next) {
152 ExportSpecifier *spec = it->exportSpecifier;
153 Compiler::ExportEntry entry;
154 if (module.isEmpty())
155 entry.localName = spec->identifier.toString();
156 else
157 entry.importName = spec->identifier.toString();
158
159 entry.moduleRequest = module;
160 entry.exportName = spec->exportedIdentifier.toString();
161 entry.location = location(it->firstSourceLocation());
162
163 _context->exportEntries << entry;
164 }
165 } else if (auto *vstmt = AST::cast<AST::VariableStatement*>(declaration->variableStatementOrDeclaration)) {
166 BoundNames boundNames;
167 for (VariableDeclarationList *it = vstmt->declarations; it; it = it->next) {
168 if (!it->declaration)
169 continue;
170 it->declaration->boundNames(&boundNames);
171 }
172 for (const auto &name: boundNames) {
173 Compiler::ExportEntry entry;
174 entry.localName = name.id;
175 entry.exportName = name.id;
176 entry.location = location(vstmt->firstSourceLocation());
177 _context->exportEntries << entry;
178 }
179 } else if (auto *classDecl = AST::cast<AST::ClassDeclaration*>(declaration->variableStatementOrDeclaration)) {
180 QString name = classDecl->name.toString();
181 if (!name.isEmpty()) {
182 Compiler::ExportEntry entry;
183 entry.localName = name;
184 entry.exportName = name;
185 entry.location = location(classDecl->firstSourceLocation());
186 _context->exportEntries << entry;
187 if (declaration->exportDefault)
188 localNameForDefaultExport = entry.localName;
189 }
190 } else if (auto *fdef = declaration->variableStatementOrDeclaration->asFunctionDefinition()) {
191 QString functionName;
192
193 // Only function definitions for which we enter their name into the local environment
194 // can result in exports. Nested expressions such as (function foo() {}) are not accessible
195 // as locals and can only be exported as default exports (further down).
196 auto ast = declaration->variableStatementOrDeclaration;
197 if (AST::cast<AST::ExpressionStatement*>(ast) || AST::cast<AST::FunctionDeclaration*>(ast))
198 functionName = fdef->name.toString();
199
200 if (!functionName.isEmpty()) {
201 Compiler::ExportEntry entry;
202 entry.localName = functionName;
203 entry.exportName = functionName;
204 entry.location = location(fdef->firstSourceLocation());
205 _context->exportEntries << entry;
206 if (declaration->exportDefault)
207 localNameForDefaultExport = entry.localName;
208 }
209 }
210
211 if (declaration->exportDefault) {
212 Compiler::ExportEntry entry;
213 entry.localName = localNameForDefaultExport;
214 _context->localNameForDefaultExport = localNameForDefaultExport;
215 entry.exportName = QStringLiteral("default");
216 entry.location = location(declaration->firstSourceLocation());
217 _context->exportEntries << entry;
218 }
219
220 return true; // scan through potential assignment expression code, etc.
221}
222
223bool ScanFunctions::visit(ImportDeclaration *declaration)
224{
225 Q_ASSERT(_context);
226 QString module;
227 if (declaration->fromClause) {
228 module = declaration->fromClause->moduleSpecifier.toString();
229 if (!module.isEmpty())
230 _context->moduleRequests << module;
231 }
232
233 if (!declaration->moduleSpecifier.isEmpty())
234 _context->moduleRequests << declaration->moduleSpecifier.toString();
235
236 if (ImportClause *import = declaration->importClause) {
237 if (!import->importedDefaultBinding.isEmpty()) {
238 Compiler::ImportEntry entry;
239 entry.moduleRequest = module;
240 entry.importName = QStringLiteral("default");
241 entry.localName = import->importedDefaultBinding.toString();
242 entry.location = location(declaration->firstSourceLocation());
243 _context->importEntries << entry;
244 }
245
246 if (import->nameSpaceImport) {
247 Compiler::ImportEntry entry;
248 entry.moduleRequest = module;
249 entry.importName = QStringLiteral("*");
250 entry.localName = import->nameSpaceImport->importedBinding.toString();
251 entry.location = location(declaration->firstSourceLocation());
252 _context->importEntries << entry;
253 }
254
255 if (import->namedImports) {
256 for (ImportsList *it = import->namedImports->importsList; it; it = it->next) {
257 Compiler::ImportEntry entry;
258 entry.moduleRequest = module;
259 entry.localName = it->importSpecifier->importedBinding.toString();
260 if (!it->importSpecifier->identifier.isEmpty())
261 entry.importName = it->importSpecifier->identifier.toString();
262 else
263 entry.importName = entry.localName;
264 entry.location = location(declaration->firstSourceLocation());
265 _context->importEntries << entry;
266 }
267 }
268 }
269 return false;
270}
271
272bool ScanFunctions::visit(CallExpression *ast)
273{
274 Q_ASSERT(_context);
275 if (!_context->hasDirectEval) {
276 if (IdentifierExpression *id = cast<IdentifierExpression *>(ast->base)) {
277 if (id->name == QLatin1String("eval")) {
278 if (_context->usesArgumentsObject == Context::UsesArgumentsObject::Unknown)
279 _context->usesArgumentsObject = Context::UsesArgumentsObject::Used;
280 _context->hasDirectEval = true;
281 }
282 }
283 }
284 return true;
285}
286
287bool ScanFunctions::visit(PatternElement *ast)
288{
289 Q_ASSERT(_context);
290 if (!ast->isVariableDeclaration())
291 return true;
292
293 BoundNames names;
294 ast->boundNames(&names);
295
296 QQmlJS::SourceLocation declarationLocation = ast->firstSourceLocation();
297 if (_context->lastBlockInitializerLocation.isValid()) {
298 declarationLocation.length = _context->lastBlockInitializerLocation.end()
299 - declarationLocation.offset;
300 } else {
301 declarationLocation.length = ast->lastSourceLocation().end() - declarationLocation.offset;
302 }
303
304 for (const auto &name : std::as_const(names)) {
305 if (_context->isStrict && (name.id == QLatin1String("eval") || name.id == QLatin1String("arguments")))
306 _cg->throwSyntaxError(ast->identifierToken, QStringLiteral("Variable name may not be eval or arguments in strict mode"));
307 checkName(QStringView(name.id), ast->identifierToken);
308 if (name.id == QLatin1String("arguments"))
309 _context->usesArgumentsObject = Context::UsesArgumentsObject::NotUsed;
310 if (ast->scope == VariableScope::Const && !ast->initializer && !ast->isForDeclaration && !ast->destructuringPattern()) {
311 _cg->throwSyntaxError(ast->identifierToken, QStringLiteral("Missing initializer in const declaration"));
312 return false;
313 }
314 if (!_context->addLocalVar(name.id, ast->initializer ? Context::VariableDefinition : Context::VariableDeclaration, ast->scope,
315 /*function*/nullptr, declarationLocation)) {
316 _cg->throwSyntaxError(ast->identifierToken, QStringLiteral("Identifier %1 has already been declared").arg(name.id));
317 return false;
318 }
319 }
320 return true;
321}
322
323bool ScanFunctions::visit(IdentifierExpression *ast)
324{
325 Q_ASSERT(_context);
326 checkName(ast->name, ast->identifierToken);
327 if (_context->usesArgumentsObject == Context::UsesArgumentsObject::Unknown && ast->name == QLatin1String("arguments"))
328 _context->usesArgumentsObject = Context::UsesArgumentsObject::Used;
329 _context->addUsedVariable(ast->name.toString());
330 return true;
331}
332
333bool ScanFunctions::visit(ExpressionStatement *ast)
334{
335 if (FunctionExpression* expr = AST::cast<AST::FunctionExpression*>(ast->expression)) {
336 if (!_allowFuncDecls)
337 _cg->throwSyntaxError(expr->functionToken, QStringLiteral("conditional function or closure declaration"));
338
339 if (!enterFunction(expr, expr->identifierToken.length > 0
340 ? FunctionNameContext::Inner
341 : FunctionNameContext::None)) {
342 return false;
343 }
344 Node::accept(expr->formals, this);
345 Node::accept(expr->body, this);
347 return false;
348 } else {
349 SourceLocation firstToken = ast->firstSourceLocation();
350 if (QStringView{_sourceCode}.mid(firstToken.offset, firstToken.length) == QLatin1String("function")) {
351 _cg->throwSyntaxError(firstToken, QStringLiteral("unexpected token"));
352 }
353 }
354 return true;
355}
356
357bool ScanFunctions::visit(FunctionExpression *ast)
358{
359 return enterFunction(ast, ast->identifierToken.length > 0
360 ? FunctionNameContext::Inner
361 : FunctionNameContext::None);
362}
363
364bool ScanFunctions::visit(ClassExpression *ast)
365{
366 enterEnvironment(ast, ContextType::Block, QStringLiteral("%Class"));
367 Q_ASSERT(_context);
368 _context->isStrict = true;
369 _context->hasNestedFunctions = true;
370 if (!ast->name.isEmpty())
371 _context->addLocalVar(ast->name.toString(), Context::VariableDefinition, AST::VariableScope::Const);
372 return true;
373}
374
375void ScanFunctions::endVisit(ClassExpression *)
376{
378}
379
380bool ScanFunctions::visit(ClassDeclaration *ast)
381{
382 Q_ASSERT(_context);
383 if (!ast->name.isEmpty())
384 _context->addLocalVar(ast->name.toString(), Context::VariableDeclaration, AST::VariableScope::Let);
385
386 enterEnvironment(ast, ContextType::Block, QStringLiteral("%Class"));
387 _context->isStrict = true;
388 _context->hasNestedFunctions = true;
389 if (!ast->name.isEmpty())
390 _context->addLocalVar(ast->name.toString(), Context::VariableDefinition, AST::VariableScope::Const);
391 return true;
392}
393
394void ScanFunctions::endVisit(ClassDeclaration *)
395{
397}
398
399bool ScanFunctions::visit(SuperLiteral *)
400{
401 Q_ASSERT(_context);
402 Context *c = _context;
403 bool needContext = false;
404 while (c->contextType == ContextType::Block || c->isArrowFunction) {
405 needContext |= c->isArrowFunction;
406 c = c->parent;
407 }
408
409 c->requiresExecutionContext |= needContext;
410
411 return false;
412}
413
414bool ScanFunctions::visit(FieldMemberExpression *ast)
415{
416 if (AST::IdentifierExpression *id = AST::cast<AST::IdentifierExpression *>(ast->base)) {
417 if (id->name == QLatin1String("new")) {
418 // new.target
419 if (ast->name != QLatin1String("target")) {
420 _cg->throwSyntaxError(ast->identifierToken, QLatin1String("Expected 'target' after 'new.'."));
421 return false;
422 }
423 Q_ASSERT(_context);
424 Context *c = _context;
425 bool needContext = false;
426 while (c->contextType == ContextType::Block || c->isArrowFunction) {
427 needContext |= c->isArrowFunction;
428 c = c->parent;
429 }
430 c->requiresExecutionContext |= needContext;
431 c->innerFunctionAccessesNewTarget |= needContext;
432
433 return false;
434 }
435 }
436
437 return true;
438}
439
440bool ScanFunctions::visit(ArrayPattern *ast)
441{
442 for (PatternElementList *it = ast->elements; it; it = it->next)
443 Node::accept(it->element, this);
444
445 return false;
446}
447
448bool ScanFunctions::enterFunction(FunctionExpression *ast, FunctionNameContext nameContext)
449{
450 Q_ASSERT(_context);
451 if (_context->isStrict && (ast->name == QLatin1String("eval") || ast->name == QLatin1String("arguments")))
452 _cg->throwSyntaxError(ast->identifierToken, QStringLiteral("Function name may not be eval or arguments in strict mode"));
453 return enterFunction(ast, ast->name.toString(), ast->formals, ast->body, nameContext);
454}
455
456void ScanFunctions::endVisit(FunctionExpression *)
457{
459}
460
461bool ScanFunctions::visit(ObjectPattern *ast)
462{
463 TemporaryBoolAssignment allowFuncDecls(_allowFuncDecls, true);
464 Node::accept(ast->properties, this);
465 return false;
466}
467
468bool ScanFunctions::visit(PatternProperty *ast)
469{
470 Q_UNUSED(ast);
471 // ### Shouldn't be required anymore
472// if (ast->type == PatternProperty::Getter || ast->type == PatternProperty::Setter) {
473// TemporaryBoolAssignment allowFuncDecls(_allowFuncDecls, true);
474// return enterFunction(ast, QString(), ast->formals, ast->functionBody, /*enterName */ false);
475// }
476 return true;
477}
478
479void ScanFunctions::endVisit(PatternProperty *)
480{
481 // ###
482// if (ast->type == PatternProperty::Getter || ast->type == PatternProperty::Setter)
483// leaveEnvironment();
484}
485
486bool ScanFunctions::visit(FunctionDeclaration *ast)
487{
488 return enterFunction(ast, FunctionNameContext::Outer);
489}
490
491void ScanFunctions::endVisit(FunctionDeclaration *)
492{
494}
495
496bool ScanFunctions::visit(DoWhileStatement *ast) {
497 {
498 TemporaryBoolAssignment allowFuncDecls(_allowFuncDecls, !_context->isStrict);
499 Node::accept(ast->statement, this);
500 }
501 Node::accept(ast->expression, this);
502 return false;
503}
504
505bool ScanFunctions::visit(ForStatement *ast) {
506 enterEnvironment(ast, ContextType::Block, QStringLiteral("%For"));
507 Node::accept(ast->initialiser, this);
508 Node::accept(ast->declarations, this);
509 Node::accept(ast->condition, this);
510 Node::accept(ast->expression, this);
511
512 TemporaryBoolAssignment allowFuncDecls(_allowFuncDecls, !_context->isStrict);
513 Node::accept(ast->statement, this);
514
515 return false;
516}
517
518void ScanFunctions::endVisit(ForStatement *)
519{
521}
522
523bool ScanFunctions::visit(ForEachStatement *ast)
524{
525 enterEnvironment(ast, ContextType::Block, QStringLiteral("%Foreach"));
526 if (ast->expression) {
527 Q_ASSERT(_context);
528 _context->lastBlockInitializerLocation = ast->expression->lastSourceLocation();
529 }
530 Node::accept(ast->lhs, this);
531 Node::accept(ast->expression, this);
532
533 TemporaryBoolAssignment allowFuncDecls(_allowFuncDecls, !_context->isStrict);
534 Node::accept(ast->statement, this);
535
536 return false;
537}
538
539void ScanFunctions::endVisit(ForEachStatement *)
540{
542}
543
544bool ScanFunctions::visit(ThisExpression *)
545{
546 Q_ASSERT(_context);
547 _context->usesThis = true;
548 return false;
549}
550
551bool ScanFunctions::visit(Block *ast)
552{
553 TemporaryBoolAssignment allowFuncDecls(_allowFuncDecls, _context->isStrict ? false : _allowFuncDecls);
554 enterEnvironment(ast, ContextType::Block, QStringLiteral("%Block"));
555 Node::accept(ast->statements, this);
556 return false;
557}
558
560{
562}
563
564bool ScanFunctions::visit(CaseBlock *ast)
565{
566 enterEnvironment(ast, ContextType::Block, QStringLiteral("%CaseBlock"));
567 return true;
568}
569
570void ScanFunctions::endVisit(CaseBlock *)
571{
573}
574
575bool ScanFunctions::visit(Catch *ast)
576{
577 Q_ASSERT(_context);
578 TemporaryBoolAssignment allowFuncDecls(_allowFuncDecls, _context->isStrict ? false : _allowFuncDecls);
579 enterEnvironment(ast, ContextType::Block, QStringLiteral("%CatchBlock"));
580 _context->isCatchBlock = true;
581 QString caughtVar = ast->patternElement->bindingIdentifier.toString();
582 if (caughtVar.isEmpty())
583 caughtVar = QStringLiteral("@caught");
584 _context->addLocalVar(caughtVar, Context::MemberType::VariableDefinition, VariableScope::Let);
585
586 _context->caughtVariable = caughtVar;
587 if (_context->isStrict &&
588 (caughtVar == QLatin1String("eval") || caughtVar == QLatin1String("arguments"))) {
589 _cg->throwSyntaxError(ast->identifierToken, QStringLiteral("Catch variable name may not be eval or arguments in strict mode"));
590 return false;
591 }
592 Node::accept(ast->patternElement, this);
593 // skip the block statement
594 Node::accept(ast->statement->statements, this);
595 return false;
596}
597
599{
601}
602
603bool ScanFunctions::visit(WithStatement *ast)
604{
605 Q_ASSERT(_context);
606 Node::accept(ast->expression, this);
607
608 TemporaryBoolAssignment allowFuncDecls(_allowFuncDecls, _context->isStrict ? false : _allowFuncDecls);
609 enterEnvironment(ast, ContextType::Block, QStringLiteral("%WithBlock"));
610 _context->isWithBlock = true;
611
612 if (_context->isStrict) {
613 _cg->throwSyntaxError(ast->withToken, QStringLiteral("'with' statement is not allowed in strict mode"));
614 return false;
615 }
616 Node::accept(ast->statement, this);
617
618 return false;
619}
620
621void ScanFunctions::endVisit(WithStatement *)
622{
624}
625
626// Collects the names referenced anywhere within a formal parameter's default
627// value initializer. See Context::promoteFormalParameterForTDZ.
629{
630 bool visit(QQmlJS::AST::IdentifierExpression *ast) override
631 {
632 referencedNames.insert(ast->name.toString());
633 return true;
634 }
635
637
639};
640
642 Node *ast, const QString &name, FormalParameterList *formals, StatementList *body,
643 FunctionNameContext nameContext)
644{
645 Context *outerContext = _context;
646 enterEnvironment(ast, ContextType::Function, name);
647
648 FunctionExpression *expr = AST::cast<FunctionExpression *>(ast);
649 if (!expr)
650 expr = AST::cast<FunctionDeclaration *>(ast);
651 if (outerContext) {
652 outerContext->hasNestedFunctions = true;
653 // The identifier of a function expression cannot be referenced from the enclosing environment.
654 if (nameContext == FunctionNameContext::Outer) {
655 if (!outerContext->addLocalVar(name, Context::FunctionDefinition, VariableScope::Var,
656 expr, expr->identifierToken)) {
657 _cg->throwSyntaxError(ast->firstSourceLocation(), QStringLiteral("Identifier %1 has already been declared").arg(name));
658 return false;
659 }
660 outerContext->addLocalVar(name, Context::FunctionDefinition, VariableScope::Var, expr);
661 }
662 if (name == QLatin1String("arguments"))
663 outerContext->usesArgumentsObject = Context::UsesArgumentsObject::NotUsed;
664 }
665
666 Q_ASSERT(_context);
667 _context->name = name;
668 if (formals && formals->containsName(QStringLiteral("arguments")))
669 _context->usesArgumentsObject = Context::UsesArgumentsObject::NotUsed;
670 if (expr) {
671 if (expr->isArrowFunction)
672 _context->isArrowFunction = true;
673 else if (expr->isGenerator)
674 _context->isGenerator = true;
675
676 if (expr->typeAnnotation)
677 _context->returnType = expr->typeAnnotation->type;
678 }
679
680
681 if (nameContext == FunctionNameContext::Inner
682 && (!name.isEmpty() && (!formals || !formals->containsName(name)))) {
683 _context->addLocalVar(name, Context::ThisFunctionName, VariableScope::Var);
684 }
685 _context->formals = formals;
686
687 if (body && !_context->isStrict)
688 checkDirectivePrologue(body);
689
690 bool isSimpleParameterList = formals && formals->isSimpleParameterList();
691
692 _context->arguments = formals ? formals->formals() : BoundNames();
693
694 const BoundNames boundNames = formals ? formals->boundNames() : BoundNames();
695 for (int i = 0; i < boundNames.size(); ++i) {
696 const auto &arg = boundNames.at(i);
697 if (_context->isStrict || !isSimpleParameterList) {
698 bool duplicate = (boundNames.indexOf(arg.id, i + 1) != -1);
699 if (duplicate) {
700 _cg->throwSyntaxError(formals->firstSourceLocation(), QStringLiteral("Duplicate parameter name '%1' is not allowed.").arg(arg.id));
701 return false;
702 }
703 }
704 if (_context->isStrict) {
705 if (arg.id == QLatin1String("eval") || arg.id == QLatin1String("arguments")) {
706 _cg->throwSyntaxError(formals->firstSourceLocation(), QStringLiteral("'%1' cannot be used as parameter name in strict mode").arg(arg.id));
707 return false;
708 }
709 }
710 if (!_context->arguments.contains(arg.id)) {
711 _context->addLocalVar(arg.id, Context::VariableDefinition, VariableScope::Var, nullptr,
712 QQmlJS::SourceLocation(), arg.isInjected());
713 }
714 }
715
716 if (formals) {
718 for (FormalParameterList *it = formals; it; it = it->next) {
719 if (it->element && it->element->initializer)
720 it->element->initializer->accept(&collector);
721 }
722 if (!collector.referencedNames.isEmpty()) {
723 for (FormalParameterList *it = formals; it; it = it->next) {
724 PatternElement *e = it->element;
725 if (!e || e->bindingIdentifier.isEmpty())
726 continue;
727 const QString name = e->bindingIdentifier.toString();
728 if (!collector.referencedNames.contains(name))
729 continue;
730 const auto declLoc = combine(e->firstSourceLocation(), e->lastSourceLocation());
731 _context->promoteFormalParameterForTDZ(name, declLoc);
732 }
733 }
734 }
735
736 return true;
737}
738
739enum class Iteration { Continue, Break };
740
742{
744#ifdef QT_NO_DEBUG
746 void operator++() {}
747 void dismiss() {}
748#else
749 ContextCounter(Module *m) : module(m) {}
751
752 void operator++() { numContexts++; }
754
755private:
756 Module *module = nullptr;
757 qsizetype numContexts = 0;
758#endif
759};
760
761
762template<typename Action>
763void forEachContext(Module *m, Action &&action)
764{
765 ContextCounter counter(m);
766
767 if (!m->rootContext)
768 return;
769
770 QVarLengthArray<Context *> stack {m->rootContext};
771 do {
772 Context *current = stack.back();
773 stack.pop_back();
774
775 for (Context *child : std::as_const(current->nestedContexts))
776 stack.push_back(child);
777
778 if (action(current) == Iteration::Break) {
779 counter.dismiss();
780 return;
781 }
782
783 ++counter;
784 } while (!stack.empty());
785}
786
787template<typename ForEach>
788static void calcEscapingVariablesImpl(Module *m, ForEach &&forEach);
789
790void ScanFunctions::operator()(Node *node)
791{
792 if (node)
793 node->accept(this);
794
795 Module *m = _cg->_module;
796 calcEscapingVariablesImpl(m, [m](auto &&action) { forEachContext(m, action); });
797}
798
799// New contexts can only affect their ancestors, so visit those and the new ones.
801{
802 Module *m = _cg->_module;
803
804 QVarLengthArray<Context *, 8> ancestors;
805 for (Context *c = _context; c; c = c->parent)
806 ancestors.append(c);
807
808 QVarLengthArray<Context *, 32> contexts;
809 QVarLengthArray<Context *, 32> stack;
810 for (qsizetype i = ancestors.size() - 1; i >= 0; --i) {
811 contexts.append(ancestors[i]);
812 Context *next = i ? ancestors[i - 1] : nullptr;
813 for (Context *child : std::as_const(ancestors[i]->nestedContexts)) {
814 if (child != next && !child->escapingVariablesCalculated)
815 stack.append(child);
816 }
817 }
818 while (!stack.empty()) {
819 Context *current = stack.back();
820 stack.pop_back();
821 for (Context *child : std::as_const(current->nestedContexts))
822 stack.append(child);
823 contexts.append(current);
824 }
825
826 auto forEach = [&contexts](auto &&action) {
827 for (Context *c : std::as_const(contexts)) {
828 if (action(c) == Iteration::Break)
829 return;
830 }
831 };
832 // Run twice for code like function f() { if (c) { eval(s) } }
833 // The block marks f as using eval, but f was visited before the block
834 // (parents come first), so f's own eval handling needs a second pass.
835 calcEscapingVariablesImpl(m, forEach);
836 calcEscapingVariablesImpl(m, forEach);
837
838 for (Context *c : std::as_const(contexts))
839 c->escapingVariablesCalculated = true;
840}
841
842template<typename ForEach>
843static void calcEscapingVariablesImpl(Module *m, ForEach &&forEach)
844{
845 forEach([](Context *inner) {
846 if (inner->usesArgumentsObject != Context::UsesArgumentsObject::Used)
847 return Iteration::Continue;
848 if (inner->contextType != ContextType::Block && !inner->isArrowFunction)
849 return Iteration::Continue;
850 Context *c = inner->parent;
851 while (c && (c->contextType == ContextType::Block || c->isArrowFunction))
852 c = c->parent;
853 if (c)
854 c->usesArgumentsObject = Context::UsesArgumentsObject::Used;
855 inner->usesArgumentsObject = Context::UsesArgumentsObject::NotUsed;
856 return Iteration::Continue;
857 });
858
859 forEach([](Context *inner) {
860 if (!inner->parent || inner->usesArgumentsObject == Context::UsesArgumentsObject::Unknown)
861 inner->usesArgumentsObject = Context::UsesArgumentsObject::NotUsed;
862 if (inner->usesArgumentsObject == Context::UsesArgumentsObject::Used) {
863 QString arguments = QStringLiteral("arguments");
864 inner->addLocalVar(arguments, Context::VariableDeclaration, AST::VariableScope::Var);
865 if (!inner->isStrict) {
866 inner->argumentsCanEscape = true;
867 inner->requiresExecutionContext = true;
868 }
869 }
870 return Iteration::Continue;
871 });
872
873 forEach([](Context *c) {
874 if (c->contextType != ContextType::ESModule)
875 return Iteration::Continue;
876 for (const auto &entry: std::as_const(c->exportEntries)) {
877 auto mIt = c->members.constFind(entry.localName);
878 if (mIt != c->members.constEnd())
879 mIt->canEscape = true;
880 }
881 return Iteration::Break;
882 });
883
884 forEach([](Context *inner) {
885 for (const QString &var : std::as_const(inner->usedVariables)) {
886 Context *c = inner;
887 while (c) {
888 Context *current = c;
889 c = c->parent;
890 if (current->isWithBlock || current->contextType != ContextType::Block)
891 break;
892 }
893 Q_ASSERT(c != inner);
894 while (c) {
895 Context::MemberMap::const_iterator it = c->members.constFind(var);
896 if (it != c->members.constEnd()) {
897 if (c->parent || it->isLexicallyScoped()) {
898 it->canEscape = true;
899 c->requiresExecutionContext = true;
900 } else if (c->contextType == ContextType::ESModule) {
901 // Module instantiation provides a context, but vars used from inner
902 // scopes need to be stored in its locals[].
903 it->canEscape = true;
904 }
905 break;
906 }
907 if (c->hasArgument(var)) {
908 c->argumentsCanEscape = true;
909 c->requiresExecutionContext = true;
910 break;
911 }
912 c = c->parent;
913 }
914 }
915 if (inner->hasDirectEval) {
916 inner->hasDirectEval = false;
917 inner->innerFunctionAccessesNewTarget = true;
918 if (!inner->isStrict) {
919 Context *c = inner;
920 while (c->contextType == ContextType::Block) {
921 c = c->parent;
922 }
923 Q_ASSERT(c);
924 c->hasDirectEval = true;
925 c->innerFunctionAccessesThis = true;
926 }
927 Context *c = inner;
928 while (c) {
929 c->allVarsEscape = true;
930 c = c->parent;
931 }
932 }
933 if (inner->usesThis) {
934 inner->usesThis = false;
935 bool innerFunctionAccessesThis = false;
936 Context *c = inner;
937 while (c->contextType == ContextType::Block || c->isArrowFunction) {
938 innerFunctionAccessesThis |= c->isArrowFunction;
939 c = c->parent;
940 }
941 Q_ASSERT(c);
942 if (!inner->isStrict)
943 c->usesThis = true;
944 c->innerFunctionAccessesThis |= innerFunctionAccessesThis;
945 }
946
947 return Iteration::Continue;
948 });
949
950 forEach([m](Context *c) {
951 if (c->innerFunctionAccessesThis) {
952 // add an escaping 'this' variable
953 c->addLocalVar(QStringLiteral("this"), Context::VariableDefinition, VariableScope::Let);
954 c->requiresExecutionContext = true;
955 auto mIt = c->members.constFind(QStringLiteral("this"));
956 Q_ASSERT(mIt != c->members.constEnd());
957 mIt->canEscape = true;
958 }
959 if (c->innerFunctionAccessesNewTarget) {
960 // add an escaping 'new.target' variable
961 c->addLocalVar(QStringLiteral("new.target"), Context::VariableDefinition, VariableScope::Let);
962 c->requiresExecutionContext = true;
963 auto mIt = c->members.constFind(QStringLiteral("new.target"));
964 Q_ASSERT(mIt != c->members.constEnd());
965 mIt->canEscape = true;
966 }
967 if (c->allVarsEscape && c->contextType == ContextType::Block && c->members.isEmpty())
968 c->allVarsEscape = false;
969 if (c->contextType == ContextType::Global || c->contextType == ContextType::ScriptImportedByQML || (!c->isStrict && c->contextType == ContextType::Eval) || m->isDebugging())
970 c->allVarsEscape = true;
971 if (c->allVarsEscape) {
972 if (c->parent) {
973 c->requiresExecutionContext = true;
974 c->argumentsCanEscape = true;
975 } else {
976 for (const auto &m : std::as_const(c->members)) {
977 if (m.isLexicallyScoped()) {
978 c->requiresExecutionContext = true;
979 break;
980 }
981 }
982 }
983 }
984 if (c->contextType == ContextType::Block && c->isCatchBlock) {
985 c->requiresExecutionContext = true;
986 auto mIt = c->members.constFind(c->caughtVariable);
987 Q_ASSERT(mIt != c->members.constEnd());
988 mIt->canEscape = true;
989 }
990 const QLatin1String exprForOn("expression for on");
991 if (c->contextType == ContextType::Binding && c->name.size() > exprForOn.size() &&
992 c->name.startsWith(exprForOn) && c->name.at(exprForOn.size()).isUpper())
993 // we don't really need this for bindings, but we do for signal handlers, and in this case,
994 // we don't know if the code is a signal handler or not.
995 c->requiresExecutionContext = true;
996 if (c->allVarsEscape) {
997 for (const auto &m : std::as_const(c->members))
998 m.canEscape = true;
999 }
1000
1001 return Iteration::Continue;
1002 });
1003
1004 static const bool showEscapingVars = qEnvironmentVariableIsSet("QV4_SHOW_ESCAPING_VARS");
1005 if (showEscapingVars) {
1006 qDebug() << "==== escaping variables ====";
1007 for (Context *c : std::as_const(m->contextMap)) {
1008 qDebug() << "Context" << c << c->name << "requiresExecutionContext" << c->requiresExecutionContext << "isStrict" << c->isStrict;
1009 qDebug() << " isArrowFunction" << c->isArrowFunction << "innerFunctionAccessesThis" << c->innerFunctionAccessesThis;
1010 qDebug() << " parent:" << c->parent;
1011 if (c->argumentsCanEscape)
1012 qDebug() << " Arguments escape";
1013 for (auto it = c->members.constBegin(); it != c->members.constEnd(); ++it) {
1014 qDebug() << " " << it.key() << it.value().index << it.value().canEscape << "isLexicallyScoped:" << it.value().isLexicallyScoped();
1015 }
1016 }
1017 }
1018}
1019
1021{
1022 _cg->throwRecursionDepthError();
1023}
bool visit(QQmlJS::AST::Program *ast) override
bool enterFunction(QQmlJS::AST::FunctionExpression *ast, FunctionNameContext nameContext)
bool enterFunction(QQmlJS::AST::Node *ast, const QString &name, QQmlJS::AST::FormalParameterList *formals, QQmlJS::AST::StatementList *body, FunctionNameContext nameContext)
ScanFunctions(Codegen *cg, const QString &sourceCode, ContextType defaultProgramType)
void checkName(QStringView name, const QQmlJS::SourceLocation &loc)
void checkDirectivePrologue(QQmlJS::AST::StatementList *ast)
void endVisit(QQmlJS::AST::Program *) override
void enterEnvironment(QQmlJS::AST::Node *node, ContextType compilationMode, const QString &name)
void enterGlobalEnvironment(ContextType compilationMode)
void operator()(QQmlJS::AST::Node *node)
Definition qjsvalue.h:24
static void calcEscapingVariablesImpl(Module *m, ForEach &&forEach)
void forEachContext(Module *m, Action &&action)
static CompiledData::Location location(const QQmlJS::SourceLocation &astLocation)
bool visit(QQmlJS::AST::IdentifierExpression *ast) override