1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtDeclarative module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qdeclarativejsengine_p.h"
43 #include "qdeclarativejslexer_p.h"
44 #include "qdeclarativejsparser_p.h"
45 #include <QtCore/QCoreApplication>
46 #include <QtCore/QStringList>
47 #include <QtCore/QFile>
48 #include <QtCore/QFileInfo>
49 #include <QtCore/QDir>
58 namespace QDeclarativeJS {
67 class QmlminLexer: protected Lexer, public Directives
69 QDeclarativeJS::Engine _engine;
74 QmlminLexer(): Lexer(&_engine) {}
75 virtual ~QmlminLexer() {}
77 QString fileName() const { return _fileName; }
79 bool operator()(const QString &fileName, const QString &code)
81 int startToken = T_FEED_JS_PROGRAM;
82 const QFileInfo fileInfo(fileName);
83 if (fileInfo.suffix().toLower() == QLatin1String("qml"))
84 startToken = T_FEED_UI_PROGRAM;
85 setCode(code, /*line = */ 1, /*qmlMode = */ startToken == T_FEED_UI_PROGRAM);
88 return parse(startToken);
97 // Handle the .pragma/.import directives
99 virtual void pragmaLibrary()
101 _directives += QLatin1String(".pragma library\n");
104 virtual void importFile(const QString &jsfile, const QString &module)
106 _directives += QLatin1String(".import");
107 _directives += QLatin1Char('"');
108 _directives += quote(jsfile);
109 _directives += QLatin1Char('"');
110 _directives += QLatin1String("as ");
111 _directives += module;
112 _directives += QLatin1Char('\n');
115 virtual void importModule(const QString &uri, const QString &version, const QString &module)
117 _directives += QLatin1String(".import ");
119 _directives += QLatin1Char(' ');
120 _directives += version;
121 _directives += QLatin1String(" as ");
122 _directives += module;
123 _directives += QLatin1Char('\n');
127 virtual bool parse(int startToken) = 0;
129 static QString quote(const QString &string)
131 QString quotedString;
132 foreach (const QChar &ch, string) {
133 if (ch == QLatin1Char('"'))
134 quotedString += QLatin1String("\\\"");
136 if (ch == QLatin1Char('\\')) quotedString += QLatin1String("\\\\");
137 else if (ch == QLatin1Char('\"')) quotedString += QLatin1String("\\\"");
138 else if (ch == QLatin1Char('\b')) quotedString += QLatin1String("\\b");
139 else if (ch == QLatin1Char('\f')) quotedString += QLatin1String("\\f");
140 else if (ch == QLatin1Char('\n')) quotedString += QLatin1String("\\n");
141 else if (ch == QLatin1Char('\r')) quotedString += QLatin1String("\\r");
142 else if (ch == QLatin1Char('\t')) quotedString += QLatin1String("\\t");
143 else if (ch == QLatin1Char('\v')) quotedString += QLatin1String("\\v");
144 else quotedString += ch;
150 bool isIdentChar(const QChar &ch) const
152 if (ch.isLetterOrNumber())
154 else if (ch == QLatin1Char('_') || ch == QLatin1Char('$'))
159 bool isRegExpRule(int ruleno) const
161 return ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ||
162 ruleno == J_SCRIPT_REGEXPLITERAL_RULE2;
165 bool scanRestOfRegExp(int ruleno, QString *restOfRegExp)
167 if (! scanRegExp(ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ? Lexer::NoPrefix : Lexer::EqualPrefix))
170 *restOfRegExp = regExpPattern();
171 if (ruleno == J_SCRIPT_REGEXPLITERAL_RULE2) {
172 Q_ASSERT(! restOfRegExp->isEmpty());
173 Q_ASSERT(restOfRegExp->at(0) == QLatin1Char('='));
174 *restOfRegExp = restOfRegExp->mid(1); // strip the prefix
176 *restOfRegExp += QLatin1Char('/');
177 const RegExpFlag flags = (RegExpFlag) regExpFlags();
179 *restOfRegExp += QLatin1Char('g');
180 if (flags & IgnoreCase)
181 *restOfRegExp += QLatin1Char('i');
182 if (flags & Multiline)
183 *restOfRegExp += QLatin1Char('m');
189 class Minify: public QmlminLexer
191 QVector<int> _stateStack;
193 QList<QString> _tokenStrings;
194 QString _minifiedCode;
199 QString minifiedCode() const;
202 bool parse(int startToken);
210 QString Minify::minifiedCode() const
212 return _minifiedCode;
215 bool Minify::parse(int startToken)
222 _minifiedCode.clear();
223 _tokens.append(startToken);
224 _tokenStrings.append(QString());
226 if (startToken == T_FEED_JS_PROGRAM) {
227 // parse optional pragma directive
228 if (scanDirectives(this)) {
229 // append the scanned directives to the minifier code.
230 _minifiedCode += directives();
232 _tokens.append(tokenKind());
233 _tokenStrings.append(tokenText());
235 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
241 if (++yytos == _stateStack.size())
242 _stateStack.resize(_stateStack.size() * 2);
244 _stateStack[yytos] = yyaction;
247 if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
248 if (_tokens.isEmpty()) {
249 _tokens.append(lex());
250 _tokenStrings.append(tokenText());
253 yytoken = _tokens.takeFirst();
254 yytokentext = _tokenStrings.takeFirst();
257 yyaction = t_action(yyaction, yytoken);
259 if (yyaction == ACCEPT_STATE) {
264 const QChar lastChar = _minifiedCode.isEmpty() ? QChar() : _minifiedCode.at(_minifiedCode.length() - 1);
266 if (yytoken == T_SEMICOLON) {
267 _minifiedCode += QLatin1Char(';');
269 } else if (yytoken == T_PLUS || yytoken == T_MINUS || yytoken == T_PLUS_PLUS || yytoken == T_MINUS_MINUS) {
270 if (lastChar == QLatin1Char(spell[yytoken][0])) {
271 // don't merge unary signs, additive expressions and postfix/prefix increments.
272 _minifiedCode += QLatin1Char(' ');
275 _minifiedCode += QLatin1String(spell[yytoken]);
277 } else if (yytoken == T_NUMERIC_LITERAL) {
278 if (isIdentChar(lastChar))
279 _minifiedCode += QLatin1Char(' ');
281 if (yytokentext.startsWith('.'))
282 _minifiedCode += QLatin1Char('0');
284 _minifiedCode += yytokentext;
286 if (_minifiedCode.endsWith(QLatin1Char('.')))
287 _minifiedCode += QLatin1Char('0');
289 } else if (yytoken == T_IDENTIFIER) {
290 if (isIdentChar(lastChar))
291 _minifiedCode += QLatin1Char(' ');
293 foreach (const QChar &ch, yytokentext) {
297 _minifiedCode += QLatin1String("\\u");
298 const QString hx = QString::number(ch.unicode(), 16);
299 switch (hx.length()) {
300 case 1: _minifiedCode += QLatin1String("000"); break;
301 case 2: _minifiedCode += QLatin1String("00"); break;
302 case 3: _minifiedCode += QLatin1String("0"); break;
305 std::cerr << "qmlmin: invalid unicode sequence" << std::endl;
312 } else if (yytoken == T_STRING_LITERAL || yytoken == T_MULTILINE_STRING_LITERAL) {
313 _minifiedCode += QLatin1Char('"');
314 _minifiedCode += quote(yytokentext);
315 _minifiedCode += QLatin1Char('"');
317 if (isIdentChar(lastChar)) {
318 if (! yytokentext.isEmpty()) {
319 const QChar ch = yytokentext.at(0);
321 _minifiedCode += QLatin1Char(' ');
324 _minifiedCode += yytokentext;
327 } else if (yyaction < 0) {
328 const int ruleno = -yyaction - 1;
329 yytos -= rhs[ruleno];
331 if (isRegExpRule(ruleno)) {
332 QString restOfRegExp;
334 if (! scanRestOfRegExp(ruleno, &restOfRegExp))
335 break; // break the loop, it wil report a syntax error
337 _minifiedCode += restOfRegExp;
339 yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
343 const int yyerrorstate = _stateStack[yytos];
345 // automatic insertion of `;'
346 if (yytoken != -1 && t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
347 _tokens.prepend(yytoken);
348 _tokenStrings.prepend(yytokentext);
349 yyaction = yyerrorstate;
350 yytoken = T_SEMICOLON;
354 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
359 class Tokenize: public QmlminLexer
361 QVector<int> _stateStack;
363 QList<QString> _tokenStrings;
364 QStringList _minifiedCode;
369 QStringList tokenStream() const;
372 virtual bool parse(int startToken);
380 QStringList Tokenize::tokenStream() const
382 return _minifiedCode;
385 bool Tokenize::parse(int startToken)
392 _minifiedCode.clear();
393 _tokens.append(startToken);
394 _tokenStrings.append(QString());
396 if (startToken == T_FEED_JS_PROGRAM) {
397 // parse optional pragma directive
398 if (scanDirectives(this)) {
399 // append the scanned directives as one token to
401 _minifiedCode.append(directives());
403 _tokens.append(tokenKind());
404 _tokenStrings.append(tokenText());
406 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
412 if (++yytos == _stateStack.size())
413 _stateStack.resize(_stateStack.size() * 2);
415 _stateStack[yytos] = yyaction;
418 if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
419 if (_tokens.isEmpty()) {
420 _tokens.append(lex());
421 _tokenStrings.append(tokenText());
424 yytoken = _tokens.takeFirst();
425 yytokentext = _tokenStrings.takeFirst();
428 yyaction = t_action(yyaction, yytoken);
430 if (yyaction == ACCEPT_STATE) {
435 if (yytoken == T_SEMICOLON)
436 _minifiedCode += QLatin1String(";");
438 _minifiedCode += yytokentext;
441 } else if (yyaction < 0) {
442 const int ruleno = -yyaction - 1;
443 yytos -= rhs[ruleno];
445 if (isRegExpRule(ruleno)) {
446 QString restOfRegExp;
448 if (! scanRestOfRegExp(ruleno, &restOfRegExp))
449 break; // break the loop, it wil report a syntax error
451 _minifiedCode.last().append(restOfRegExp);
454 yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
458 const int yyerrorstate = _stateStack[yytos];
460 // automatic insertion of `;'
461 if (yytoken != -1 && t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
462 _tokens.prepend(yytoken);
463 _tokenStrings.prepend(yytokentext);
464 yyaction = yyerrorstate;
465 yytoken = T_SEMICOLON;
469 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
473 } // end of QDeclarativeJS namespace
475 static void usage(bool showHelp = false)
477 std::cerr << "Usage: qmlmin [options] file" << std::endl;
480 std::cerr << " Removes comments and layout characters" << std::endl
481 << " The options are:" << std::endl
482 << " -o<file> write output to file rather than stdout" << std::endl
483 << " -v --verify-only just run the verifier, no output" << std::endl
484 << " -h display this output" << std::endl;
488 int runQmlmin(int argc, char *argv[])
490 QCoreApplication app(argc, argv);
492 const QStringList args = app.arguments();
496 bool verifyOnly = false;
499 while (index < args.size()) {
500 const QString arg = args.at(index++);
501 const QString next = index < args.size() ? args.at(index) : QString();
503 if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) {
504 usage(/*showHelp*/ true);
506 } else if (arg == QLatin1String("-v") || arg == QLatin1String("--verify-only")) {
508 } else if (arg == QLatin1String("-o")) {
509 if (next.isEmpty()) {
510 std::cerr << "qmlmin: argument to '-o' is missing" << std::endl;
514 ++index; // consume the next argument
516 } else if (arg.startsWith(QLatin1String("-o"))) {
517 outputFile = arg.mid(2);
519 if (outputFile.isEmpty()) {
520 std::cerr << "qmlmin: argument to '-o' is missing" << std::endl;
524 const bool isInvalidOpt = arg.startsWith(QLatin1Char('-'));
525 if (! isInvalidOpt && fileName.isEmpty())
528 usage(/*show help*/ isInvalidOpt);
530 std::cerr << "qmlmin: invalid option '" << qPrintable(arg) << "'" << std::endl;
532 std::cerr << "qmlmin: too many input files specified" << std::endl;
538 if (fileName.isEmpty()) {
543 QFile file(fileName);
544 if (! file.open(QFile::ReadOnly)) {
545 std::cerr << "qmlmin: '" << qPrintable(fileName) << "' no such file or directory" << std::endl;
549 const QString code = QString::fromUtf8(file.readAll()); // QML files are UTF-8 encoded.
552 QDeclarativeJS::Minify minify;
553 if (! minify(fileName, code)) {
554 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (not a valid QML/JS file)" << std::endl;
561 QDeclarativeJS::Minify secondMinify;
562 if (! secondMinify(fileName, minify.minifiedCode()) || secondMinify.minifiedCode() != minify.minifiedCode()) {
563 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "'" << std::endl;
567 QDeclarativeJS::Tokenize originalTokens, minimizedTokens;
568 originalTokens(fileName, code);
569 minimizedTokens(fileName, minify.minifiedCode());
571 if (originalTokens.tokenStream().size() != minimizedTokens.tokenStream().size()) {
572 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "'" << std::endl;
577 if (outputFile.isEmpty()) {
578 const QByteArray chars = minify.minifiedCode().toUtf8();
579 std::cout << chars.constData();
581 QFile file(outputFile);
582 if (! file.open(QFile::WriteOnly)) {
583 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (permission denied)" << std::endl;
587 file.write(minify.minifiedCode().toUtf8());
597 int main(int argc, char **argv)
599 return QT_PREPEND_NAMESPACE(runQmlmin(argc, argv));