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>
56 namespace QDeclarativeJS {
65 class QmlminLexer: protected Lexer, public Directives
67 QDeclarativeJS::Engine _engine;
72 QmlminLexer(): Lexer(&_engine) {}
73 virtual ~QmlminLexer() {}
75 QString fileName() const { return _fileName; }
77 bool operator()(const QString &fileName, const QString &code)
79 int startToken = T_FEED_JS_PROGRAM;
80 const QFileInfo fileInfo(fileName);
81 if (fileInfo.suffix().toLower() == QLatin1String("qml"))
82 startToken = T_FEED_UI_PROGRAM;
83 setCode(code, /*line = */ 1, /*qmlMode = */ startToken == T_FEED_UI_PROGRAM);
86 return parse(startToken);
95 // Handle the .pragma/.import directives
97 virtual void pragmaLibrary()
99 _directives += QLatin1String(".pragma library\n");
102 virtual void importFile(const QString &jsfile, const QString &module)
104 _directives += QLatin1String(".import");
105 _directives += QLatin1Char('"');
106 _directives += quote(jsfile);
107 _directives += QLatin1Char('"');
108 _directives += QLatin1String("as ");
109 _directives += module;
110 _directives += QLatin1Char('\n');
113 virtual void importModule(const QString &uri, const QString &version, const QString &module)
115 _directives += QLatin1String(".import ");
117 _directives += QLatin1Char(' ');
118 _directives += version;
119 _directives += QLatin1String(" as ");
120 _directives += module;
121 _directives += QLatin1Char('\n');
125 virtual bool parse(int startToken) = 0;
127 static QString quote(const QString &string)
129 QString quotedString;
130 foreach (const QChar &ch, string) {
131 if (ch == QLatin1Char('"'))
132 quotedString += QLatin1String("\\\"");
134 if (ch == QLatin1Char('\\')) quotedString += QLatin1String("\\\\");
135 else if (ch == QLatin1Char('\"')) quotedString += QLatin1String("\\\"");
136 else if (ch == QLatin1Char('\b')) quotedString += QLatin1String("\\b");
137 else if (ch == QLatin1Char('\f')) quotedString += QLatin1String("\\f");
138 else if (ch == QLatin1Char('\n')) quotedString += QLatin1String("\\n");
139 else if (ch == QLatin1Char('\r')) quotedString += QLatin1String("\\r");
140 else if (ch == QLatin1Char('\t')) quotedString += QLatin1String("\\t");
141 else if (ch == QLatin1Char('\v')) quotedString += QLatin1String("\\v");
142 else quotedString += ch;
148 bool isIdentChar(const QChar &ch) const
150 if (ch.isLetterOrNumber())
152 else if (ch == QLatin1Char('_') || ch == QLatin1Char('$'))
157 bool isRegExpRule(int ruleno) const
159 return ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ||
160 ruleno == J_SCRIPT_REGEXPLITERAL_RULE2;
163 bool scanRestOfRegExp(int ruleno, QString *restOfRegExp)
165 if (! scanRegExp(ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ? Lexer::NoPrefix : Lexer::EqualPrefix))
168 *restOfRegExp = regExpPattern();
169 if (ruleno == J_SCRIPT_REGEXPLITERAL_RULE2) {
170 Q_ASSERT(! restOfRegExp->isEmpty());
171 Q_ASSERT(restOfRegExp->at(0) == QLatin1Char('='));
172 *restOfRegExp = restOfRegExp->mid(1); // strip the prefix
174 *restOfRegExp += QLatin1Char('/');
175 const RegExpFlag flags = (RegExpFlag) regExpFlags();
177 *restOfRegExp += QLatin1Char('g');
178 if (flags & IgnoreCase)
179 *restOfRegExp += QLatin1Char('i');
180 if (flags & Multiline)
181 *restOfRegExp += QLatin1Char('m');
187 class Minify: public QmlminLexer
189 QVector<int> _stateStack;
191 QList<QString> _tokenStrings;
192 QString _minifiedCode;
197 QString minifiedCode() const;
200 bool parse(int startToken);
208 QString Minify::minifiedCode() const
210 return _minifiedCode;
213 bool Minify::parse(int startToken)
220 _minifiedCode.clear();
221 _tokens.append(startToken);
222 _tokenStrings.append(QString());
224 if (startToken == T_FEED_JS_PROGRAM) {
225 // parse optional pragma directive
226 if (scanDirectives(this)) {
227 // append the scanned directives to the minifier code.
228 _minifiedCode += directives();
230 _tokens.append(tokenKind());
231 _tokenStrings.append(tokenText());
233 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
239 if (++yytos == _stateStack.size())
240 _stateStack.resize(_stateStack.size() * 2);
242 _stateStack[yytos] = yyaction;
245 if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
246 if (_tokens.isEmpty()) {
247 _tokens.append(lex());
248 _tokenStrings.append(tokenText());
251 yytoken = _tokens.takeFirst();
252 yytokentext = _tokenStrings.takeFirst();
255 yyaction = t_action(yyaction, yytoken);
257 if (yyaction == ACCEPT_STATE) {
262 const QChar lastChar = _minifiedCode.isEmpty() ? QChar() : _minifiedCode.at(_minifiedCode.length() - 1);
264 if (yytoken == T_SEMICOLON) {
265 _minifiedCode += QLatin1Char(';');
267 } else if (yytoken == T_PLUS || yytoken == T_MINUS || yytoken == T_PLUS_PLUS || yytoken == T_MINUS_MINUS) {
268 if (lastChar == QLatin1Char(spell[yytoken][0])) {
269 // don't merge unary signs, additive expressions and postfix/prefix increments.
270 _minifiedCode += QLatin1Char(' ');
273 _minifiedCode += QLatin1String(spell[yytoken]);
275 } else if (yytoken == T_NUMERIC_LITERAL) {
276 if (isIdentChar(lastChar))
277 _minifiedCode += QLatin1Char(' ');
279 if (yytokentext.startsWith('.'))
280 _minifiedCode += QLatin1Char('0');
282 _minifiedCode += yytokentext;
284 if (_minifiedCode.endsWith(QLatin1Char('.')))
285 _minifiedCode += QLatin1Char('0');
287 } else if (yytoken == T_IDENTIFIER) {
288 if (isIdentChar(lastChar))
289 _minifiedCode += QLatin1Char(' ');
291 foreach (const QChar &ch, yytokentext) {
295 _minifiedCode += QLatin1String("\\u");
296 const QString hx = QString::number(ch.unicode(), 16);
297 switch (hx.length()) {
298 case 1: _minifiedCode += QLatin1String("000"); break;
299 case 2: _minifiedCode += QLatin1String("00"); break;
300 case 3: _minifiedCode += QLatin1String("0"); break;
303 std::cerr << "qmlmin: invalid unicode sequence" << std::endl;
310 } else if (yytoken == T_STRING_LITERAL || yytoken == T_MULTILINE_STRING_LITERAL) {
311 _minifiedCode += QLatin1Char('"');
312 _minifiedCode += quote(yytokentext);
313 _minifiedCode += QLatin1Char('"');
315 if (isIdentChar(lastChar)) {
316 if (! yytokentext.isEmpty()) {
317 const QChar ch = yytokentext.at(0);
319 _minifiedCode += QLatin1Char(' ');
322 _minifiedCode += yytokentext;
325 } else if (yyaction < 0) {
326 const int ruleno = -yyaction - 1;
327 yytos -= rhs[ruleno];
329 if (isRegExpRule(ruleno)) {
330 QString restOfRegExp;
332 if (! scanRestOfRegExp(ruleno, &restOfRegExp))
333 break; // break the loop, it wil report a syntax error
335 _minifiedCode += restOfRegExp;
337 yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
341 const int yyerrorstate = _stateStack[yytos];
343 // automatic insertion of `;'
344 if (yytoken != -1 && t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
345 _tokens.prepend(yytoken);
346 _tokenStrings.prepend(yytokentext);
347 yyaction = yyerrorstate;
348 yytoken = T_SEMICOLON;
352 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
357 class Tokenize: public QmlminLexer
359 QVector<int> _stateStack;
361 QList<QString> _tokenStrings;
362 QStringList _minifiedCode;
367 QStringList tokenStream() const;
370 virtual bool parse(int startToken);
378 QStringList Tokenize::tokenStream() const
380 return _minifiedCode;
383 bool Tokenize::parse(int startToken)
390 _minifiedCode.clear();
391 _tokens.append(startToken);
392 _tokenStrings.append(QString());
394 if (startToken == T_FEED_JS_PROGRAM) {
395 // parse optional pragma directive
396 if (scanDirectives(this)) {
397 // append the scanned directives as one token to
399 _minifiedCode.append(directives());
401 _tokens.append(tokenKind());
402 _tokenStrings.append(tokenText());
404 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
410 if (++yytos == _stateStack.size())
411 _stateStack.resize(_stateStack.size() * 2);
413 _stateStack[yytos] = yyaction;
416 if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
417 if (_tokens.isEmpty()) {
418 _tokens.append(lex());
419 _tokenStrings.append(tokenText());
422 yytoken = _tokens.takeFirst();
423 yytokentext = _tokenStrings.takeFirst();
426 yyaction = t_action(yyaction, yytoken);
428 if (yyaction == ACCEPT_STATE) {
433 if (yytoken == T_SEMICOLON)
434 _minifiedCode += QLatin1String(";");
436 _minifiedCode += yytokentext;
439 } else if (yyaction < 0) {
440 const int ruleno = -yyaction - 1;
441 yytos -= rhs[ruleno];
443 if (isRegExpRule(ruleno)) {
444 QString restOfRegExp;
446 if (! scanRestOfRegExp(ruleno, &restOfRegExp))
447 break; // break the loop, it wil report a syntax error
449 _minifiedCode.last().append(restOfRegExp);
452 yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
456 const int yyerrorstate = _stateStack[yytos];
458 // automatic insertion of `;'
459 if (yytoken != -1 && t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
460 _tokens.prepend(yytoken);
461 _tokenStrings.prepend(yytokentext);
462 yyaction = yyerrorstate;
463 yytoken = T_SEMICOLON;
467 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
471 } // end of QDeclarativeJS namespace
473 static void usage(bool showHelp = false)
475 std::cerr << "Usage: qmlmin [options] file" << std::endl;
478 std::cerr << " Removes comments and layout characters" << std::endl
479 << " The options are:" << std::endl
480 << " -o<file> write output to file rather than stdout" << std::endl
481 << " -v --verify-only just run the verifier, no output" << std::endl
482 << " -h display this output" << std::endl;
486 int main(int argc, char *argv[])
488 QCoreApplication app(argc, argv);
490 const QStringList args = app.arguments();
494 bool verifyOnly = false;
497 while (index < args.size()) {
498 const QString arg = args.at(index++);
499 const QString next = index < args.size() ? args.at(index) : QString();
501 if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) {
502 usage(/*showHelp*/ true);
504 } else if (arg == QLatin1String("-v") || arg == QLatin1String("--verify-only")) {
506 } else if (arg == QLatin1String("-o")) {
507 if (next.isEmpty()) {
508 std::cerr << "qmlmin: argument to '-o' is missing" << std::endl;
512 ++index; // consume the next argument
514 } else if (arg.startsWith(QLatin1String("-o"))) {
515 outputFile = arg.mid(2);
517 if (outputFile.isEmpty()) {
518 std::cerr << "qmlmin: argument to '-o' is missing" << std::endl;
522 const bool isInvalidOpt = arg.startsWith(QLatin1Char('-'));
523 if (! isInvalidOpt && fileName.isEmpty())
526 usage(/*show help*/ isInvalidOpt);
528 std::cerr << "qmlmin: invalid option '" << qPrintable(arg) << "'" << std::endl;
530 std::cerr << "qmlmin: too many input files specified" << std::endl;
536 if (fileName.isEmpty()) {
541 QFile file(fileName);
542 if (! file.open(QFile::ReadOnly)) {
543 std::cerr << "qmlmin: '" << qPrintable(fileName) << "' no such file or directory" << std::endl;
547 const QString code = QString::fromUtf8(file.readAll()); // QML files are UTF-8 encoded.
550 QDeclarativeJS::Minify minify;
551 if (! minify(fileName, code)) {
552 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (not a valid QML/JS file)" << std::endl;
559 QDeclarativeJS::Minify secondMinify;
560 if (! secondMinify(fileName, minify.minifiedCode()) || secondMinify.minifiedCode() != minify.minifiedCode()) {
561 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "'" << std::endl;
565 QDeclarativeJS::Tokenize originalTokens, minimizedTokens;
566 originalTokens(fileName, code);
567 minimizedTokens(fileName, minify.minifiedCode());
569 if (originalTokens.tokenStream().size() != minimizedTokens.tokenStream().size()) {
570 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "'" << std::endl;
575 if (outputFile.isEmpty()) {
576 const QByteArray chars = minify.minifiedCode().toUtf8();
577 std::cout << chars.constData();
579 QFile file(outputFile);
580 if (! file.open(QFile::WriteOnly)) {
581 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (permission denied)" << std::endl;
585 file.write(minify.minifiedCode().toUtf8());