1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtQml module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include <private/qqmljsengine_p.h>
43 #include <private/qqmljslexer_p.h>
44 #include <private/qqmljsparser_p.h>
45 #include <QtCore/QCoreApplication>
46 #include <QtCore/QStringList>
47 #include <QtCore/QFile>
48 #include <QtCore/QFileInfo>
49 #include <QtCore/QDir>
67 class QmlminLexer: protected Lexer, public Directives
69 QQmlJS::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 if (ch == QLatin1Char('\0')) quotedString += QLatin1String("\\0");
145 else quotedString += ch;
151 bool isIdentChar(const QChar &ch) const
153 if (ch.isLetterOrNumber())
155 else if (ch == QLatin1Char('_') || ch == QLatin1Char('$'))
160 bool isRegExpRule(int ruleno) const
162 return ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ||
163 ruleno == J_SCRIPT_REGEXPLITERAL_RULE2;
166 bool scanRestOfRegExp(int ruleno, QString *restOfRegExp)
168 if (! scanRegExp(ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ? Lexer::NoPrefix : Lexer::EqualPrefix))
171 *restOfRegExp = regExpPattern();
172 if (ruleno == J_SCRIPT_REGEXPLITERAL_RULE2) {
173 Q_ASSERT(! restOfRegExp->isEmpty());
174 Q_ASSERT(restOfRegExp->at(0) == QLatin1Char('='));
175 *restOfRegExp = restOfRegExp->mid(1); // strip the prefix
177 *restOfRegExp += QLatin1Char('/');
178 const RegExpFlag flags = (RegExpFlag) regExpFlags();
180 *restOfRegExp += QLatin1Char('g');
181 if (flags & IgnoreCase)
182 *restOfRegExp += QLatin1Char('i');
183 if (flags & Multiline)
184 *restOfRegExp += QLatin1Char('m');
186 if (regExpFlags() == 0) {
187 // Add an extra space after the regexp literal delimiter (aka '/').
188 // This will avoid possible problems when pasting tokens like `instanceof'
189 // after the regexp literal.
190 *restOfRegExp += QLatin1Char(' ');
197 class Minify: public QmlminLexer
199 QVector<int> _stateStack;
201 QList<QString> _tokenStrings;
202 QString _minifiedCode;
207 QString minifiedCode() const;
210 bool parse(int startToken);
211 void escape(const QChar &ch, QString *out);
219 QString Minify::minifiedCode() const
221 return _minifiedCode;
224 void Minify::escape(const QChar &ch, QString *out)
226 out->append(QLatin1String("\\u"));
227 const QString hx = QString::number(ch.unicode(), 16);
228 switch (hx.length()) {
229 case 1: out->append(QLatin1String("000")); break;
230 case 2: out->append(QLatin1String("00")); break;
231 case 3: out->append(QLatin1String("0")); break;
233 default: Q_ASSERT(!"unreachable");
238 bool Minify::parse(int startToken)
245 _minifiedCode.clear();
246 _tokens.append(startToken);
247 _tokenStrings.append(QString());
249 if (startToken == T_FEED_JS_PROGRAM) {
250 // parse optional pragma directive
251 if (scanDirectives(this)) {
252 // append the scanned directives to the minifier code.
253 _minifiedCode += directives();
255 _tokens.append(tokenKind());
256 _tokenStrings.append(tokenText());
258 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
264 if (++yytos == _stateStack.size())
265 _stateStack.resize(_stateStack.size() * 2);
267 _stateStack[yytos] = yyaction;
270 if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
271 if (_tokens.isEmpty()) {
272 _tokens.append(lex());
273 _tokenStrings.append(tokenText());
276 yytoken = _tokens.takeFirst();
277 yytokentext = _tokenStrings.takeFirst();
280 yyaction = t_action(yyaction, yytoken);
282 if (yyaction == ACCEPT_STATE) {
287 const QChar lastChar = _minifiedCode.isEmpty() ? QChar() : _minifiedCode.at(_minifiedCode.length() - 1);
289 if (yytoken == T_SEMICOLON) {
290 _minifiedCode += QLatin1Char(';');
292 } else if (yytoken == T_PLUS || yytoken == T_MINUS || yytoken == T_PLUS_PLUS || yytoken == T_MINUS_MINUS) {
293 if (lastChar == QLatin1Char(spell[yytoken][0])) {
294 // don't merge unary signs, additive expressions and postfix/prefix increments.
295 _minifiedCode += QLatin1Char(' ');
298 _minifiedCode += QLatin1String(spell[yytoken]);
300 } else if (yytoken == T_NUMERIC_LITERAL) {
301 if (isIdentChar(lastChar))
302 _minifiedCode += QLatin1Char(' ');
304 if (yytokentext.startsWith('.'))
305 _minifiedCode += QLatin1Char('0');
307 _minifiedCode += yytokentext;
309 if (_minifiedCode.endsWith(QLatin1Char('.')))
310 _minifiedCode += QLatin1Char('0');
312 } else if (yytoken == T_IDENTIFIER) {
313 QString identifier = yytokentext;
315 if (classify(identifier.constData(), identifier.size(), qmlMode()) != T_IDENTIFIER) {
316 // the unescaped identifier is a keyword. In this case just replace
317 // the last character of the identifier with it escape sequence.
318 const QChar ch = identifier.at(identifier.length() - 1);
320 escape(ch, &identifier);
323 if (isIdentChar(lastChar))
324 _minifiedCode += QLatin1Char(' ');
326 foreach (const QChar &ch, identifier) {
330 escape(ch, &_minifiedCode);
334 } else if (yytoken == T_STRING_LITERAL || yytoken == T_MULTILINE_STRING_LITERAL) {
335 _minifiedCode += QLatin1Char('"');
336 _minifiedCode += quote(yytokentext);
337 _minifiedCode += QLatin1Char('"');
339 if (isIdentChar(lastChar)) {
340 if (! yytokentext.isEmpty()) {
341 const QChar ch = yytokentext.at(0);
343 _minifiedCode += QLatin1Char(' ');
346 _minifiedCode += yytokentext;
349 } else if (yyaction < 0) {
350 const int ruleno = -yyaction - 1;
351 yytos -= rhs[ruleno];
353 if (isRegExpRule(ruleno)) {
354 QString restOfRegExp;
356 if (! scanRestOfRegExp(ruleno, &restOfRegExp))
357 break; // break the loop, it wil report a syntax error
359 _minifiedCode += restOfRegExp;
361 yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
365 const int yyerrorstate = _stateStack[yytos];
367 // automatic insertion of `;'
368 if (yytoken != -1 && t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
369 _tokens.prepend(yytoken);
370 _tokenStrings.prepend(yytokentext);
371 yyaction = yyerrorstate;
372 yytoken = T_SEMICOLON;
376 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
381 class Tokenize: public QmlminLexer
383 QVector<int> _stateStack;
385 QList<QString> _tokenStrings;
386 QStringList _minifiedCode;
391 QStringList tokenStream() const;
394 virtual bool parse(int startToken);
402 QStringList Tokenize::tokenStream() const
404 return _minifiedCode;
407 bool Tokenize::parse(int startToken)
414 _minifiedCode.clear();
415 _tokens.append(startToken);
416 _tokenStrings.append(QString());
418 if (startToken == T_FEED_JS_PROGRAM) {
419 // parse optional pragma directive
420 if (scanDirectives(this)) {
421 // append the scanned directives as one token to
423 _minifiedCode.append(directives());
425 _tokens.append(tokenKind());
426 _tokenStrings.append(tokenText());
428 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
434 if (++yytos == _stateStack.size())
435 _stateStack.resize(_stateStack.size() * 2);
437 _stateStack[yytos] = yyaction;
440 if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
441 if (_tokens.isEmpty()) {
442 _tokens.append(lex());
443 _tokenStrings.append(tokenText());
446 yytoken = _tokens.takeFirst();
447 yytokentext = _tokenStrings.takeFirst();
450 yyaction = t_action(yyaction, yytoken);
452 if (yyaction == ACCEPT_STATE) {
457 if (yytoken == T_SEMICOLON)
458 _minifiedCode += QLatin1String(";");
460 _minifiedCode += yytokentext;
463 } else if (yyaction < 0) {
464 const int ruleno = -yyaction - 1;
465 yytos -= rhs[ruleno];
467 if (isRegExpRule(ruleno)) {
468 QString restOfRegExp;
470 if (! scanRestOfRegExp(ruleno, &restOfRegExp))
471 break; // break the loop, it wil report a syntax error
473 _minifiedCode.last().append(restOfRegExp);
476 yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
480 const int yyerrorstate = _stateStack[yytos];
482 // automatic insertion of `;'
483 if (yytoken != -1 && t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
484 _tokens.prepend(yytoken);
485 _tokenStrings.prepend(yytokentext);
486 yyaction = yyerrorstate;
487 yytoken = T_SEMICOLON;
491 std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
495 } // end of QQmlJS namespace
497 static void usage(bool showHelp = false)
499 std::cerr << "Usage: qmlmin [options] file" << std::endl;
502 std::cerr << " Removes comments and layout characters" << std::endl
503 << " The options are:" << std::endl
504 << " -o<file> write output to file rather than stdout" << std::endl
505 << " -v --verify-only just run the verifier, no output" << std::endl
506 << " -h display this output" << std::endl;
510 int runQmlmin(int argc, char *argv[])
512 QCoreApplication app(argc, argv);
514 const QStringList args = app.arguments();
518 bool verifyOnly = false;
521 while (index < args.size()) {
522 const QString arg = args.at(index++);
523 const QString next = index < args.size() ? args.at(index) : QString();
525 if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) {
526 usage(/*showHelp*/ true);
528 } else if (arg == QLatin1String("-v") || arg == QLatin1String("--verify-only")) {
530 } else if (arg == QLatin1String("-o")) {
531 if (next.isEmpty()) {
532 std::cerr << "qmlmin: argument to '-o' is missing" << std::endl;
536 ++index; // consume the next argument
538 } else if (arg.startsWith(QLatin1String("-o"))) {
539 outputFile = arg.mid(2);
541 if (outputFile.isEmpty()) {
542 std::cerr << "qmlmin: argument to '-o' is missing" << std::endl;
546 const bool isInvalidOpt = arg.startsWith(QLatin1Char('-'));
547 if (! isInvalidOpt && fileName.isEmpty())
550 usage(/*show help*/ isInvalidOpt);
552 std::cerr << "qmlmin: invalid option '" << qPrintable(arg) << "'" << std::endl;
554 std::cerr << "qmlmin: too many input files specified" << std::endl;
560 if (fileName.isEmpty()) {
565 QFile file(fileName);
566 if (! file.open(QFile::ReadOnly)) {
567 std::cerr << "qmlmin: '" << qPrintable(fileName) << "' no such file or directory" << std::endl;
571 const QString code = QString::fromUtf8(file.readAll()); // QML files are UTF-8 encoded.
574 QQmlJS::Minify minify;
575 if (! minify(fileName, code)) {
576 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (not a valid QML/JS file)" << std::endl;
583 QQmlJS::Minify secondMinify;
584 if (! secondMinify(fileName, minify.minifiedCode()) || secondMinify.minifiedCode() != minify.minifiedCode()) {
585 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "'" << std::endl;
589 QQmlJS::Tokenize originalTokens, minimizedTokens;
590 originalTokens(fileName, code);
591 minimizedTokens(fileName, minify.minifiedCode());
593 if (originalTokens.tokenStream().size() != minimizedTokens.tokenStream().size()) {
594 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "'" << std::endl;
599 if (outputFile.isEmpty()) {
600 const QByteArray chars = minify.minifiedCode().toUtf8();
601 std::cout << chars.constData();
603 QFile file(outputFile);
604 if (! file.open(QFile::WriteOnly)) {
605 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (permission denied)" << std::endl;
609 file.write(minify.minifiedCode().toUtf8());
619 int main(int argc, char **argv)
621 return QT_PREPEND_NAMESPACE(runQmlmin(argc, argv));