1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtQml module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #include "qqmlrewrite_p.h"
44 #include <private/qqmlglobal_p.h>
46 #include <QtCore/qdebug.h>
50 DEFINE_BOOL_CONFIG_OPTION(rewriteDump, QML_REWRITE_DUMP)
52 namespace QQmlRewrite {
54 static void rewriteStringLiteral(AST::StringLiteral *ast, const QString *code, int startPosition, TextWriter *writer)
56 const unsigned position = ast->firstSourceLocation().begin() - startPosition + 1;
57 const unsigned length = ast->literalToken.length - 2;
58 const QStringRef spell = code->midRef(position, length);
59 const int end = spell.size();
63 const QChar ch = spell.at(index++);
65 if (index < end && ch == QLatin1Char('\\')) {
68 // skip a possibly empty sequence of \r characters
69 while (pos < end && spell.at(pos) == QLatin1Char('\r'))
72 if (pos < end && spell.at(pos) == QLatin1Char('\n')) {
73 // This is a `\' followed by a newline terminator.
74 // In this case there's nothing to replace. We keep the code
75 // as it is and we resume the searching.
76 index = pos + 1; // refresh the index
78 } else if (ch == QLatin1Char('\r') || ch == QLatin1Char('\n')) {
79 const QString sep = ch == QLatin1Char('\r') ? QLatin1String("\\r") : QLatin1String("\\n");
80 const int pos = index - 1;
83 while (index < end && spell.at(index) == ch) {
88 writer->replace(position + pos, index - pos, s);
93 SharedBindingTester::SharedBindingTester()
94 : _sharable(false), _safe(false)
98 void SharedBindingTester::parse(const QString &code)
100 _sharable = _safe = false;
103 Lexer lexer(&engine);
104 Parser parser(&engine);
105 lexer.setCode(code, 0);
106 parser.parseStatement();
107 if (!parser.statement())
110 return parse(parser.statement());
113 void SharedBindingTester::parse(AST::Node *node)
118 AST::Node::acceptChild(node, this);
121 bool SharedBindingTester::visit(AST::FunctionDeclaration *)
127 bool SharedBindingTester::visit(AST::FunctionExpression *)
133 bool SharedBindingTester::visit(AST::CallExpression *e)
135 static const QString mathString = QStringLiteral("Math");
137 if (AST::IdentifierExpression *ie = AST::cast<AST::IdentifierExpression *>(e->base)) {
138 if (ie->name == mathString)
146 bool SharedBindingTester::visit(AST::IdentifierExpression *e)
148 static const QString evalString = QStringLiteral("eval");
149 if (e->name == evalString)
152 return false; // IdentifierExpression is a leaf node anyway
155 bool SharedBindingTester::visit(AST::PostDecrementExpression *)
161 bool SharedBindingTester::visit(AST::PostIncrementExpression *)
167 bool SharedBindingTester::visit(AST::PreDecrementExpression *)
173 bool SharedBindingTester::visit(AST::PreIncrementExpression *)
179 bool SharedBindingTester::visit(AST::BinaryExpression *e)
181 if (e->op == QSOperator::InplaceAnd ||
182 e->op == QSOperator::Assign ||
183 e->op == QSOperator::InplaceSub ||
184 e->op == QSOperator::InplaceDiv ||
185 e->op == QSOperator::InplaceAdd ||
186 e->op == QSOperator::InplaceLeftShift ||
187 e->op == QSOperator::InplaceMod ||
188 e->op == QSOperator::InplaceMul ||
189 e->op == QSOperator::InplaceOr ||
190 e->op == QSOperator::InplaceRightShift ||
191 e->op == QSOperator::InplaceURightShift ||
192 e->op == QSOperator::InplaceXor)
198 QString RewriteBinding::operator()(const QString &code, bool *ok, bool *sharable, bool *safe)
201 Lexer lexer(&engine);
202 Parser parser(&engine);
203 lexer.setCode(code, 0);
204 parser.parseStatement();
205 if (!parser.statement()) {
210 if (sharable || safe) {
211 SharedBindingTester tester;
212 tester.parse(parser.statement());
213 if (sharable) *sharable = tester.isSharable();
214 if (safe) *safe = tester.isSafe();
217 return rewrite(code, 0, parser.statement());
220 QString RewriteBinding::operator()(QQmlJS::AST::Node *node, const QString &code, bool *sharable, bool *safe)
225 if (sharable || safe) {
226 SharedBindingTester tester;
228 if (sharable) *sharable = tester.isSharable();
229 if (safe) *safe = tester.isSafe();
232 QQmlJS::AST::ExpressionNode *expression = node->expressionCast();
233 QQmlJS::AST::Statement *statement = node->statementCast();
234 if(!expression && !statement)
239 _position = expression ? expression->firstSourceLocation().begin() : statement->firstSourceLocation().begin();
245 unsigned startOfStatement = 0;
246 unsigned endOfStatement = (expression ? expression->lastSourceLocation().end() : statement->lastSourceLocation().end()) - _position;
248 QString startString = QLatin1String("(function ") + _name + QLatin1String("() { ");
250 startString += QLatin1String("return ");
251 _writer->replace(startOfStatement, 0, startString);
252 _writer->replace(endOfStatement, 0, QLatin1String(" })"));
255 qWarning() << "=============================================================";
256 qWarning() << "Rewrote:";
257 qWarning() << qPrintable(code);
260 QString codeCopy = code;
265 qWarning() << qPrintable(codeCopy);
266 qWarning() << "=============================================================";
272 void RewriteBinding::accept(AST::Node *node)
274 AST::Node::acceptChild(node, this);
277 QString RewriteBinding::rewrite(QString code, unsigned position,
278 AST::Statement *node)
282 _position = position;
288 unsigned startOfStatement = node->firstSourceLocation().begin() - _position;
289 unsigned endOfStatement = node->lastSourceLocation().end() - _position;
291 _writer->replace(startOfStatement, 0, QLatin1String("(function ") + _name + QLatin1String("() { "));
292 _writer->replace(endOfStatement, 0, QLatin1String(" })"));
295 qWarning() << "=============================================================";
296 qWarning() << "Rewrote:";
297 qWarning() << qPrintable(code);
304 qWarning() << qPrintable(code);
305 qWarning() << "=============================================================";
311 bool RewriteBinding::visit(AST::Block *ast)
313 for (AST::StatementList *it = ast->statements; it; it = it->next) {
315 // we need to rewrite only the last statement of a block.
316 accept(it->statement);
323 bool RewriteBinding::visit(AST::ExpressionStatement *ast)
326 unsigned startOfExpressionStatement = ast->firstSourceLocation().begin() - _position;
327 _writer->replace(startOfExpressionStatement, 0, QLatin1String("return "));
333 bool RewriteBinding::visit(AST::StringLiteral *ast)
335 rewriteStringLiteral(ast, _code, _position, _writer);
339 bool RewriteBinding::visit(AST::DoWhileStatement *)
345 void RewriteBinding::endVisit(AST::DoWhileStatement *)
350 bool RewriteBinding::visit(AST::WhileStatement *)
356 void RewriteBinding::endVisit(AST::WhileStatement *)
361 bool RewriteBinding::visit(AST::ForStatement *)
367 void RewriteBinding::endVisit(AST::ForStatement *)
372 bool RewriteBinding::visit(AST::LocalForStatement *)
378 void RewriteBinding::endVisit(AST::LocalForStatement *)
383 bool RewriteBinding::visit(AST::ForEachStatement *)
389 void RewriteBinding::endVisit(AST::ForEachStatement *)
394 bool RewriteBinding::visit(AST::LocalForEachStatement *)
400 void RewriteBinding::endVisit(AST::LocalForEachStatement *)
405 bool RewriteBinding::visit(AST::FunctionExpression *)
410 bool RewriteBinding::visit(AST::FunctionDeclaration *)
415 bool RewriteBinding::visit(AST::CaseBlock *ast)
417 // Process the initial sequence of the case clauses.
418 for (AST::CaseClauses *it = ast->clauses; it; it = it->next) {
419 // Return the value of the last statement in the block, if this is the last `case clause'
420 // of the switch statement.
421 bool returnTheValueOfLastStatement = (it->next == 0) && (ast->defaultClause == 0) && (ast->moreClauses == 0);
423 if (AST::CaseClause *clause = it->clause) {
424 accept(clause->expression);
425 rewriteCaseStatements(clause->statements, returnTheValueOfLastStatement);
429 // Process the default case clause
430 if (ast->defaultClause) {
431 // Return the value of the last statement in the block, if this is the last `case clause'
432 // of the switch statement.
433 bool rewriteTheLastStatement = (ast->moreClauses == 0);
435 rewriteCaseStatements(ast->defaultClause->statements, rewriteTheLastStatement);
438 // Process trailing `case clauses'
439 for (AST::CaseClauses *it = ast->moreClauses; it; it = it->next) {
440 // Return the value of the last statement in the block, if this is the last `case clause'
441 // of the switch statement.
442 bool returnTheValueOfLastStatement = (it->next == 0);
444 if (AST::CaseClause *clause = it->clause) {
445 accept(clause->expression);
446 rewriteCaseStatements(clause->statements, returnTheValueOfLastStatement);
453 void RewriteBinding::rewriteCaseStatements(AST::StatementList *statements, bool rewriteTheLastStatement)
455 for (AST::StatementList *it = statements; it; it = it->next) {
456 if (it->next && AST::cast<AST::BreakStatement *>(it->next->statement) != 0) {
457 // The value of the first statement followed by a `break'.
458 accept(it->statement);
460 } else if (!it->next) {
461 if (rewriteTheLastStatement)
462 accept(it->statement);
463 else if (AST::Block *block = AST::cast<AST::Block *>(it->statement))
464 rewriteCaseStatements(block->statements, rewriteTheLastStatement);
471 RewriteSignalHandler performs two different types of rewrites, depending on what information
474 When the target object is known, the rewriter can be provided a list of parameter names (and an
475 optional preconstructed parameter string), which allows us to:
476 1. Check whether the parameters are used
477 2. Rewrite with the parameters included in the rewrite
478 When this information is not available, we do a more generic rewrite, and rely on the expression
479 to perform a second rewrite with the parameter information (using createParameterString)
480 once the target object is known.
482 RewriteSignalHandler::RewriteSignalHandler()
486 , _parameterAccess(UnknownAccess)
487 , _parameterCountForJS(0)
491 void RewriteSignalHandler::accept(AST::Node *node)
493 AST::Node::acceptChild(node, this);
496 bool RewriteSignalHandler::visit(AST::StringLiteral *ast)
498 rewriteStringLiteral(ast, _code, _position, _writer);
502 //if we never make use of the signal parameters in our expression,
503 //there is no need to provide them
504 bool RewriteSignalHandler::visit(AST::IdentifierExpression *e)
506 //optimization: don't need to compare strings if a parameter has already been marked as used.
507 if (_parameterAccess == ParametersAccessed)
510 static const QString argumentsString = QStringLiteral("arguments");
511 if (_parameterNames.contains(e->name) || e->name == argumentsString)
512 _parameterAccess = ParametersAccessed;
516 static QString unnamed_error_string(QLatin1String(QT_TR_NOOP("Signal uses unnamed parameter followed by named parameter.")));
517 static QString global_error_string(QLatin1String(QT_TR_NOOP("Signal parameter \"%1\" hides global variable.")));
519 #define EXIT_ON_ERROR(error) \
525 //create a parameter string which can be inserted into a generic rewrite
526 QString RewriteSignalHandler::createParameterString(const QList<QByteArray> ¶meterNameList,
527 const QStringHash<bool> &illegalNames)
529 QList<QHashedString> hashedParameterNameList;
530 for (int i = 0; i < parameterNameList.count(); ++i)
531 hashedParameterNameList.append(QString::fromUtf8(parameterNameList.at(i).constData()));
533 return createParameterString(hashedParameterNameList, illegalNames);
536 QString RewriteSignalHandler::createParameterString(const QList<QHashedString> ¶meterNameList,
537 const QStringHash<bool> &illegalNames)
540 bool unnamedParam = false;
541 for (int i = 0; i < parameterNameList.count(); ++i) {
542 const QHashedString ¶m = parameterNameList.at(i);
545 else if (unnamedParam)
546 EXIT_ON_ERROR(unnamed_error_string)
547 else if (illegalNames.contains(param))
548 EXIT_ON_ERROR(global_error_string.arg(param))
549 ++_parameterCountForJS;
551 if (i < parameterNameList.count()-1)
552 parameters += QStringLiteral(",");
554 if (parameters.endsWith(QLatin1Char(',')))
555 parameters.resize(parameters.length() - 1);
560 If \a parameterString is provided, use \a parameterNameList to test whether the
561 parameters are used in the body of the function
562 * if unused, the rewrite will not include parameters, else
563 * if used, the rewrite will use \a parameterString
564 If \a parameterString is not provided, it is constructed from \a parameterNameList
567 QString RewriteSignalHandler::operator()(QQmlJS::AST::Node *node, const QString &code, const QString &name,
568 const QString ¶meterString,
569 const QList<QByteArray> ¶meterNameList,
570 const QStringHash<bool> &illegalNames)
573 qWarning() << "=============================================================";
574 qWarning() << "Rewrote:";
575 qWarning() << qPrintable(code);
578 bool hasParameterString = !parameterString.isEmpty();
580 QQmlJS::AST::ExpressionNode *expression = node->expressionCast();
581 QQmlJS::AST::Statement *statement = node->statementCast();
582 if (!expression && !statement)
585 if (!parameterNameList.isEmpty()) {
586 for (int i = 0; i < parameterNameList.count(); ++i) {
587 QHashedString param(QString::fromUtf8(parameterNameList.at(i).constData()));
588 _parameterNames.insert(param, i);
589 if (!hasParameterString)
590 _parameterNameList.append(param);
593 //this is set to Unaccessed here, and will be set to Accessed
594 //if we detect that a parameter has been used
595 _parameterAccess = ParametersUnaccessed;
602 _position = expression ? expression->firstSourceLocation().begin() : statement->firstSourceLocation().begin();
605 QString rewritten = code;
608 QString parameters = (_parameterAccess == ParametersUnaccessed) ? QString()
609 : hasParameterString ? parameterString
610 : createParameterString(_parameterNameList, illegalNames);
611 rewritten = QStringLiteral("(function ") + name + QStringLiteral("(") + parameters + QStringLiteral(") { ") + rewritten + QStringLiteral(" })");
615 qWarning() << qPrintable(rewritten);
616 qWarning() << "=============================================================";
622 QString RewriteSignalHandler::operator()(const QString &code, const QString &name, bool *ok,
623 const QList<QByteArray> ¶meterNameList,
624 const QStringHash<bool> &illegalNames)
627 Lexer lexer(&engine);
628 Parser parser(&engine);
629 lexer.setCode(code, 0);
630 parser.parseStatement();
631 if (!parser.statement()) {
636 return operator()(parser.statement(), code, name, QString(), parameterNameList, illegalNames);
639 } // namespace QQmlRewrite