Reduce memory consumption of source coordinates
[profile/ivi/qtdeclarative.git] / tools / qmlmin / main.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtQml module of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
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>
50 #include <iostream>
51 #include <cstdlib>
52
53 QT_BEGIN_NAMESPACE
54
55 //
56 // QML/JS minifier
57 //
58 namespace QQmlJS {
59
60 enum RegExpFlag {
61     Global     = 0x01,
62     IgnoreCase = 0x02,
63     Multiline  = 0x04
64 };
65
66
67 class QmlminLexer: protected Lexer, public Directives
68 {
69     QQmlJS::Engine _engine;
70     QString _fileName;
71     QString _directives;
72
73 public:
74     QmlminLexer(): Lexer(&_engine) {}
75     virtual ~QmlminLexer() {}
76
77     QString fileName() const { return _fileName; }
78
79     bool operator()(const QString &fileName, const QString &code)
80     {
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);
86         _fileName = fileName;
87         _directives.clear();
88         return parse(startToken);
89     }
90
91     QString directives()
92     {
93         return _directives;
94     }
95
96     //
97     // Handle the .pragma/.import directives
98     //
99     virtual void pragmaLibrary()
100     {
101         _directives += QLatin1String(".pragma library\n");
102     }
103
104     virtual void importFile(const QString &jsfile, const QString &module)
105     {
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');
113     }
114
115     virtual void importModule(const QString &uri, const QString &version, const QString &module)
116     {
117         _directives += QLatin1String(".import ");
118         _directives += uri;
119         _directives += QLatin1Char(' ');
120         _directives += version;
121         _directives += QLatin1String(" as ");
122         _directives += module;
123         _directives += QLatin1Char('\n');
124     }
125
126 protected:
127     virtual bool parse(int startToken) = 0;
128
129     static QString quote(const QString &string)
130     {
131         QString quotedString;
132         foreach (const QChar &ch, string) {
133             if (ch == QLatin1Char('"'))
134                 quotedString += QLatin1String("\\\"");
135             else {
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;
146             }
147         }
148         return quotedString;
149     }
150
151     bool isIdentChar(const QChar &ch) const
152     {
153         if (ch.isLetterOrNumber())
154             return true;
155         else if (ch == QLatin1Char('_') || ch == QLatin1Char('$'))
156             return true;
157         return false;
158     }
159
160     bool isRegExpRule(int ruleno) const
161     {
162         return ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ||
163                 ruleno == J_SCRIPT_REGEXPLITERAL_RULE2;
164     }
165
166     bool scanRestOfRegExp(int ruleno, QString *restOfRegExp)
167     {
168         if (! scanRegExp(ruleno == J_SCRIPT_REGEXPLITERAL_RULE1 ? Lexer::NoPrefix : Lexer::EqualPrefix))
169             return false;
170
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
176         }
177         *restOfRegExp += QLatin1Char('/');
178         const RegExpFlag flags = (RegExpFlag) regExpFlags();
179         if (flags & Global)
180             *restOfRegExp += QLatin1Char('g');
181         if (flags & IgnoreCase)
182             *restOfRegExp += QLatin1Char('i');
183         if (flags & Multiline)
184             *restOfRegExp += QLatin1Char('m');
185
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(' ');
191         }
192         return true;
193     }
194 };
195
196
197 class Minify: public QmlminLexer
198 {
199     QVector<int> _stateStack;
200     QList<int> _tokens;
201     QList<QString> _tokenStrings;
202     QString _minifiedCode;
203     int _maxWidth;
204     int _width;
205
206 public:
207     Minify(int maxWidth);
208
209     QString minifiedCode() const;
210
211 protected:
212     void append(const QString &s);
213     bool parse(int startToken);
214     void escape(const QChar &ch, QString *out);
215 };
216
217 Minify::Minify(int maxWidth)
218     : _stateStack(128), _maxWidth(maxWidth), _width(0)
219 {
220 }
221
222 QString Minify::minifiedCode() const
223 {
224     return _minifiedCode;
225 }
226
227 void Minify::append(const QString &s)
228 {
229     if (!s.isEmpty()) {
230         if (_maxWidth) {
231             // Prefer not to exceed the maximum chars per line (but don't break up segments)
232             int segmentLength = s.count();
233             if (_width && ((_width + segmentLength) > _maxWidth)) {
234                 _minifiedCode.append(QLatin1Char('\n'));
235                 _width = 0;
236             }
237
238             _width += segmentLength;
239         }
240
241         _minifiedCode.append(s);
242     }
243 }
244
245 void Minify::escape(const QChar &ch, QString *out)
246 {
247     out->append(QLatin1String("\\u"));
248     const QString hx = QString::number(ch.unicode(), 16);
249     switch (hx.length()) {
250     case 1: out->append(QLatin1String("000")); break;
251     case 2: out->append(QLatin1String("00")); break;
252     case 3: out->append(QLatin1String("0")); break;
253     case 4: break;
254     default: Q_ASSERT(!"unreachable");
255     }
256     out->append(hx);
257 }
258
259 bool Minify::parse(int startToken)
260 {
261     int yyaction = 0;
262     int yytoken = -1;
263     int yytos = -1;
264     QString yytokentext;
265     QString assembled;
266
267     _minifiedCode.clear();
268     _tokens.append(startToken);
269     _tokenStrings.append(QString());
270
271     if (startToken == T_FEED_JS_PROGRAM) {
272         // parse optional pragma directive
273         if (scanDirectives(this)) {
274             // append the scanned directives to the minifier code.
275             append(directives());
276
277             _tokens.append(tokenKind());
278             _tokenStrings.append(tokenText());
279         } else {
280             std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
281             return false;
282         }
283     }
284
285     do {
286         if (++yytos == _stateStack.size())
287             _stateStack.resize(_stateStack.size() * 2);
288
289         _stateStack[yytos] = yyaction;
290
291     again:
292         if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
293             if (_tokens.isEmpty()) {
294                 _tokens.append(lex());
295                 _tokenStrings.append(tokenText());
296             }
297
298             yytoken = _tokens.takeFirst();
299             yytokentext = _tokenStrings.takeFirst();
300         }
301
302         yyaction = t_action(yyaction, yytoken);
303         if (yyaction > 0) {
304             if (yyaction == ACCEPT_STATE) {
305                 --yytos;
306                 if (!assembled.isEmpty())
307                     append(assembled);
308                 return true;
309             }
310
311             const QChar lastChar = assembled.isEmpty() ? (_minifiedCode.isEmpty() ? QChar()
312                                                                                   : _minifiedCode.at(_minifiedCode.length() - 1))
313                                                        : assembled.at(assembled.length() - 1);
314
315             if (yytoken == T_SEMICOLON) {
316                 assembled += QLatin1Char(';');
317
318                 append(assembled);
319                 assembled.clear();
320
321             } else if (yytoken == T_PLUS || yytoken == T_MINUS || yytoken == T_PLUS_PLUS || yytoken == T_MINUS_MINUS) {
322                 if (lastChar == QLatin1Char(spell[yytoken][0])) {
323                     // don't merge unary signs, additive expressions and postfix/prefix increments.
324                     assembled += QLatin1Char(' ');
325                 }
326
327                 assembled += QLatin1String(spell[yytoken]);
328
329             } else if (yytoken == T_NUMERIC_LITERAL) {
330                 if (isIdentChar(lastChar))
331                     assembled += QLatin1Char(' ');
332
333                 if (yytokentext.startsWith('.'))
334                     assembled += QLatin1Char('0');
335
336                 assembled += yytokentext;
337
338                 if (assembled.endsWith(QLatin1Char('.')))
339                     assembled += QLatin1Char('0');
340
341             } else if (yytoken == T_IDENTIFIER) {
342                 QString identifier = yytokentext;
343
344                 if (classify(identifier.constData(), identifier.size(), qmlMode()) != T_IDENTIFIER) {
345                     // the unescaped identifier is a keyword. In this case just replace
346                     // the last character of the identifier with it escape sequence.
347                     const QChar ch = identifier.at(identifier.length() - 1);
348                     identifier.chop(1);
349                     escape(ch, &identifier);
350                 }
351
352                 if (isIdentChar(lastChar))
353                     assembled += QLatin1Char(' ');
354
355                 foreach (const QChar &ch, identifier) {
356                     if (isIdentChar(ch))
357                         assembled += ch;
358                     else {
359                         escape(ch, &assembled);
360                     }
361                 }
362
363             } else if (yytoken == T_STRING_LITERAL || yytoken == T_MULTILINE_STRING_LITERAL) {
364                 assembled += QLatin1Char('"');
365                 assembled += quote(yytokentext);
366                 assembled += QLatin1Char('"');
367             } else {
368                 if (isIdentChar(lastChar)) {
369                     if (! yytokentext.isEmpty()) {
370                         const QChar ch = yytokentext.at(0);
371                         if (isIdentChar(ch))
372                             assembled += QLatin1Char(' ');
373                     }
374                 }
375                 assembled += yytokentext;
376             }
377             yytoken = -1;
378         } else if (yyaction < 0) {
379             const int ruleno = -yyaction - 1;
380             yytos -= rhs[ruleno];
381
382             if (isRegExpRule(ruleno)) {
383                 QString restOfRegExp;
384
385                 if (! scanRestOfRegExp(ruleno, &restOfRegExp))
386                     break; // break the loop, it wil report a syntax error
387
388                 assembled += restOfRegExp;
389             }
390             yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
391         }
392     } while (yyaction);
393
394     const int yyerrorstate = _stateStack[yytos];
395
396     // automatic insertion of `;'
397     if (yytoken != -1 && t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
398         _tokens.prepend(yytoken);
399         _tokenStrings.prepend(yytokentext);
400         yyaction = yyerrorstate;
401         yytoken = T_SEMICOLON;
402         goto again;
403     }
404
405     std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
406     return false;
407 }
408
409
410 class Tokenize: public QmlminLexer
411 {
412     QVector<int> _stateStack;
413     QList<int> _tokens;
414     QList<QString> _tokenStrings;
415     QStringList _minifiedCode;
416
417 public:
418     Tokenize();
419
420     QStringList tokenStream() const;
421
422 protected:
423     virtual bool parse(int startToken);
424 };
425
426 Tokenize::Tokenize()
427     : _stateStack(128)
428 {
429 }
430
431 QStringList Tokenize::tokenStream() const
432 {
433     return _minifiedCode;
434 }
435
436 bool Tokenize::parse(int startToken)
437 {
438     int yyaction = 0;
439     int yytoken = -1;
440     int yytos = -1;
441     QString yytokentext;
442
443     _minifiedCode.clear();
444     _tokens.append(startToken);
445     _tokenStrings.append(QString());
446
447     if (startToken == T_FEED_JS_PROGRAM) {
448         // parse optional pragma directive
449         if (scanDirectives(this)) {
450             // append the scanned directives as one token to
451             // the token stream.
452             _minifiedCode.append(directives());
453
454             _tokens.append(tokenKind());
455             _tokenStrings.append(tokenText());
456         } else {
457             std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
458             return false;
459         }
460     }
461
462     do {
463         if (++yytos == _stateStack.size())
464             _stateStack.resize(_stateStack.size() * 2);
465
466         _stateStack[yytos] = yyaction;
467
468     again:
469         if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
470             if (_tokens.isEmpty()) {
471                 _tokens.append(lex());
472                 _tokenStrings.append(tokenText());
473             }
474
475             yytoken = _tokens.takeFirst();
476             yytokentext = _tokenStrings.takeFirst();
477         }
478
479         yyaction = t_action(yyaction, yytoken);
480         if (yyaction > 0) {
481             if (yyaction == ACCEPT_STATE) {
482                 --yytos;
483                 return true;
484             }
485
486             if (yytoken == T_SEMICOLON)
487                 _minifiedCode += QLatin1String(";");
488             else
489                 _minifiedCode += yytokentext;
490
491             yytoken = -1;
492         } else if (yyaction < 0) {
493             const int ruleno = -yyaction - 1;
494             yytos -= rhs[ruleno];
495
496             if (isRegExpRule(ruleno)) {
497                 QString restOfRegExp;
498
499                 if (! scanRestOfRegExp(ruleno, &restOfRegExp))
500                     break; // break the loop, it wil report a syntax error
501
502                 _minifiedCode.last().append(restOfRegExp);
503             }
504
505             yyaction = nt_action(_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
506         }
507     } while (yyaction);
508
509     const int yyerrorstate = _stateStack[yytos];
510
511     // automatic insertion of `;'
512     if (yytoken != -1 && t_action(yyerrorstate, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
513         _tokens.prepend(yytoken);
514         _tokenStrings.prepend(yytokentext);
515         yyaction = yyerrorstate;
516         yytoken = T_SEMICOLON;
517         goto again;
518     }
519
520     std::cerr << qPrintable(fileName()) << ":" << tokenStartLine() << ":" << tokenStartColumn() << ": syntax error" << std::endl;
521     return false;
522 }
523
524 } // end of QQmlJS namespace
525
526 static void usage(bool showHelp = false)
527 {
528     std::cerr << "Usage: qmlmin [options] file" << std::endl;
529
530     if (showHelp) {
531         std::cerr << " Removes comments and layout characters" << std::endl
532                   << " The options are:" << std::endl
533                   << "  -o<file>                write output to file rather than stdout" << std::endl
534                   << "  -v --verify-only        just run the verifier, no output" << std::endl
535                   << "  -w<width>               restrict line characters to width" << std::endl
536                   << "  -h                      display this output" << std::endl;
537     }
538 }
539
540 int runQmlmin(int argc, char *argv[])
541 {
542     QCoreApplication app(argc, argv);
543
544     const QStringList args = app.arguments();
545
546     QString fileName;
547     QString outputFile;
548     bool verifyOnly = false;
549
550     // By default ensure the output character width is less than 16-bits (pass 0 to disable)
551     int width = USHRT_MAX;
552
553     int index = 1;
554     while (index < args.size()) {
555         const QString arg = args.at(index++);
556         const QString next = index < args.size() ? args.at(index) : QString();
557
558         if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) {
559             usage(/*showHelp*/ true);
560             return 0;
561         } else if (arg == QLatin1String("-v") || arg == QLatin1String("--verify-only")) {
562             verifyOnly = true;
563         } else if (arg == QLatin1String("-o")) {
564             if (next.isEmpty()) {
565                 std::cerr << "qmlmin: argument to '-o' is missing" << std::endl;
566                 return EXIT_FAILURE;
567             } else {
568                 outputFile = next;
569                 ++index; // consume the next argument
570             }
571         } else if (arg.startsWith(QLatin1String("-o"))) {
572             outputFile = arg.mid(2);
573
574             if (outputFile.isEmpty()) {
575                 std::cerr << "qmlmin: argument to '-o' is missing" << std::endl;
576                 return EXIT_FAILURE;
577             }
578         } else if (arg == QLatin1String("-w")) {
579             if (next.isEmpty()) {
580                 std::cerr << "qmlmin: argument to '-w' is missing" << std::endl;
581                 return EXIT_FAILURE;
582             } else {
583                 bool ok;
584                 width = next.toInt(&ok);
585
586                 if (!ok) {
587                     std::cerr << "qmlmin: argument to '-w' is invalid" << std::endl;
588                     return EXIT_FAILURE;
589                 }
590
591                 ++index; // consume the next argument
592             }
593         } else if (arg.startsWith(QLatin1String("-w"))) {
594             bool ok;
595             width = arg.mid(2).toInt(&ok);
596
597             if (!ok) {
598                 std::cerr << "qmlmin: argument to '-w' is invalid" << std::endl;
599                 return EXIT_FAILURE;
600             }
601         } else {
602             const bool isInvalidOpt = arg.startsWith(QLatin1Char('-'));
603             if (! isInvalidOpt && fileName.isEmpty())
604                 fileName = arg;
605             else {
606                 usage(/*show help*/ isInvalidOpt);
607                 if (isInvalidOpt)
608                     std::cerr << "qmlmin: invalid option '" << qPrintable(arg) << "'" << std::endl;
609                 else
610                     std::cerr << "qmlmin: too many input files specified" << std::endl;
611                 return EXIT_FAILURE;
612             }
613         }
614     }
615
616     if (fileName.isEmpty()) {
617         usage();
618         return 0;
619     }
620
621     QFile file(fileName);
622     if (! file.open(QFile::ReadOnly)) {
623         std::cerr << "qmlmin: '" << qPrintable(fileName) << "' no such file or directory" << std::endl;
624         return EXIT_FAILURE;
625     }
626
627     const QString code = QString::fromUtf8(file.readAll()); // QML files are UTF-8 encoded.
628     file.close();
629
630     QQmlJS::Minify minify(width);
631     if (! minify(fileName, code)) {
632         std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (not a valid QML/JS file)" << std::endl;
633         return EXIT_FAILURE;
634     }
635
636     //
637     // verify the output
638     //
639     QQmlJS::Minify secondMinify(width);
640     if (! secondMinify(fileName, minify.minifiedCode()) || secondMinify.minifiedCode() != minify.minifiedCode()) {
641         std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "'" << std::endl;
642         return EXIT_FAILURE;
643     }
644
645     QQmlJS::Tokenize originalTokens, minimizedTokens;
646     originalTokens(fileName, code);
647     minimizedTokens(fileName, minify.minifiedCode());
648
649     if (originalTokens.tokenStream().size() != minimizedTokens.tokenStream().size()) {
650         std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "'" << std::endl;
651         return EXIT_FAILURE;
652     }
653
654     if (! verifyOnly) {
655         if (outputFile.isEmpty()) {
656             const QByteArray chars = minify.minifiedCode().toUtf8();
657             std::cout << chars.constData();
658         } else {
659             QFile file(outputFile);
660             if (! file.open(QFile::WriteOnly)) {
661                 std::cerr << "qmlmin: cannot minify '" << qPrintable(fileName) << "' (permission denied)" << std::endl;
662                 return EXIT_FAILURE;
663             }
664
665             file.write(minify.minifiedCode().toUtf8());
666             file.close();
667         }
668     }
669
670     return 0;
671 }
672
673 QT_END_NAMESPACE
674
675 int main(int argc, char **argv)
676 {
677     return QT_PREPEND_NAMESPACE(runQmlmin(argc, argv));
678 }