aboutsummaryrefslogtreecommitdiffstats
path: root/tools/qmltc/main.cpp
blob: 49e218f4fe918088816083d8cf694274b25af19c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmltccommandlineutils.h"
#include "prototype/codegenerator.h"
#include "qmltcvisitor.h"
#include "qmltctyperesolver.h"

#include "qmltccompiler.h"

#include <QtQml/private/qqmlirbuilder_p.h>
#include <private/qqmljscompiler_p.h>
#include <private/qqmljsresourcefilemapper_p.h>

#include <QtCore/qcoreapplication.h>
#include <QtCore/qurl.h>
#include <QtCore/qhashfunctions.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qlibraryinfo.h>
#include <QtCore/qcommandlineparser.h>

#include <cstdlib> // EXIT_SUCCESS, EXIT_FAILURE

void setupLogger(QQmlJSLogger &logger) // prepare logger to work with compiler
{
    const QSet<QQmlJSLoggerCategory> exceptions {
        Log_ControlsSanity, // this category is just weird
        Log_UnusedImport, // not critical
    };

    for (int i = 0; i <= static_cast<int>(QQmlJSLoggerCategory_Last); ++i) {
        const auto c = static_cast<QQmlJSLoggerCategory>(i);
        if (exceptions.contains(c))
            continue;
        logger.setCategoryLevel(c, QtCriticalMsg);
        logger.setCategoryIgnored(c, false);
    }
}

int main(int argc, char **argv)
{
    // Produce reliably the same output for the same input by disabling QHash's
    // random seeding.
    qSetGlobalQHashSeed(0);
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(u"qmltc"_qs);
    QCoreApplication::setApplicationVersion(QStringLiteral(QT_VERSION_STR));

    // command-line parsing:
    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption importPathOption {
        u"I"_qs, QCoreApplication::translate("main", "Look for QML modules in specified directory"),
        QCoreApplication::translate("main", "import directory")
    };
    parser.addOption(importPathOption);
    QCommandLineOption qmldirOption {
        u"i"_qs, QCoreApplication::translate("main", "Include extra qmldir files"),
        QCoreApplication::translate("main", "qmldir file")
    };
    parser.addOption(qmldirOption);
    QCommandLineOption outputCppOption {
        u"impl"_qs, QCoreApplication::translate("main", "Generated C++ source file path"),
        QCoreApplication::translate("main", "cpp path")
    };
    parser.addOption(outputCppOption);
    QCommandLineOption outputHOption {
        u"header"_qs, QCoreApplication::translate("main", "Generated C++ header file path"),
        QCoreApplication::translate("main", "h path")
    };
    parser.addOption(outputHOption);
    QCommandLineOption resourceOption {
        u"resource"_qs,
        QCoreApplication::translate(
                "main", "Qt resource file that might later contain one of the compiled files"),
        QCoreApplication::translate("main", "resource file name")
    };
    parser.addOption(resourceOption);
    QCommandLineOption namespaceOption {
        u"namespace"_qs, QCoreApplication::translate("main", "Namespace of the generated C++ code"),
        QCoreApplication::translate("main", "namespace")
    };
    parser.addOption(namespaceOption);

    parser.process(app);

    const QStringList sources = parser.positionalArguments();
    if (sources.size() != 1) {
        if (sources.isEmpty()) {
            parser.showHelp();
        } else {
            fprintf(stderr, "%s\n",
                    qPrintable(u"Too many input files specified: '"_qs + sources.join(u"' '"_qs)
                               + u'\''));
        }
        return EXIT_FAILURE;
    }
    const QString inputFile = sources.first();

    QString url = parseUrlArgument(inputFile);
    if (url.isNull())
        return EXIT_FAILURE;
    if (!url.endsWith(u".qml")) {
        fprintf(stderr, "Non-QML file passed as input\n");
        return EXIT_FAILURE;
    }

    QString sourceCode = loadUrl(url);
    if (sourceCode.isEmpty())
        return EXIT_FAILURE;

    QString implicitImportDirectory = getImplicitImportDirectory(url);
    if (implicitImportDirectory.isEmpty())
        return EXIT_FAILURE;

    QStringList importPaths = parser.values(importPathOption);
    importPaths.append(QLibraryInfo::path(QLibraryInfo::QmlImportsPath));
    QStringList qmldirFiles = parser.values(qmldirOption);

    QString outputCppFile;
    if (!parser.isSet(outputCppOption)) {
        outputCppFile = url.first(url.size() - 3) + u"cpp"_qs;
    } else {
        outputCppFile = parser.value(outputCppOption);
    }

    QString outputHFile;
    if (!parser.isSet(outputHOption)) {
        outputHFile = url.first(url.size() - 3) + u"h"_qs;
    } else {
        outputHFile = parser.value(outputHOption);
    }

    if (!parser.isSet(resourceOption)) {
        fprintf(stderr, "No resource paths for file: %s\n", qPrintable(inputFile));
        return EXIT_FAILURE;
    }

    // main logic:
    QmlIR::Document document(false); // used by QmltcTypeResolver/QQmlJSTypeResolver
    // NB: JS unit generated here is ignored, so use noop function
    QQmlJSSaveFunction noop([](auto &&...) { return true; });
    QQmlJSCompileError error;
    if (!qCompileQmlFile(document, url, noop, nullptr, &error)) {
        error.augment(u"Error compiling qml file: "_qs).print();
        return EXIT_FAILURE;
    }

    const QStringList resourceFiles = parser.values(resourceOption);
    QQmlJSResourceFileMapper mapper(resourceFiles);

    // verify that we can map current file to qrc (then use the qrc path later)
    const QStringList paths = mapper.resourcePaths(QQmlJSResourceFileMapper::localFileFilter(url));
    if (paths.isEmpty()) {
        fprintf(stderr, "Failed to find a resource path for file: %s\n", qPrintable(inputFile));
        return EXIT_FAILURE;
    } else if (paths.size() > 1) {
        fprintf(stderr, "Too many (expected 1) resource paths for file: %s\n",
                qPrintable(inputFile));
        return EXIT_FAILURE;
    }

    QmltcCompilerInfo info;
    info.outputCppFile = parser.value(outputCppOption);
    info.outputHFile = parser.value(outputHOption);
    info.resourcePath = paths.first();
    info.outputNamespace = parser.value(namespaceOption);

    QQmlJSImporter importer { importPaths, &mapper };
    QQmlJSLogger logger;
    logger.setFileName(url);
    logger.setCode(sourceCode);
    setupLogger(logger);

    QmltcVisitor visitor(&importer, &logger,
                         QQmlJSImportVisitor::implicitImportDirectory(url, &mapper), qmldirFiles);
    QmltcTypeResolver typeResolver { &importer };
    typeResolver.init(visitor, document.program);

    if (logger.hasErrors())
        return EXIT_FAILURE;

    QList<QQmlJS::DiagnosticMessage> warnings = importer.takeGlobalWarnings();
    if (!warnings.isEmpty()) {
        logger.log(QStringLiteral("Type warnings occurred while compiling file:"), Log_Import,
                   QQmlJS::SourceLocation());
        logger.processMessages(warnings, Log_Import);
        // Log_Import is critical for the compiler
        return EXIT_FAILURE;
    }

    CodeGenerator generator(url, &logger, &document, &typeResolver, &info);
    generator.generate();

    if (logger.hasErrors())
        return EXIT_FAILURE;

    return EXIT_SUCCESS;
}