summaryrefslogtreecommitdiffstats
path: root/src/linguist/lupdate/cpp_clang.h
blob: 88e25facda1771a428fea6db5d4f915b3af4aa0b (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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#ifndef CLANG_CPP_H
#define CLANG_CPP_H

#include "lupdate.h"
#include "synchronized.h"

#include <QtCore/qloggingcategory.h>
#include <QtCore/qregularexpression.h>
#include <QtCore/qstring.h>

QT_WARNING_PUSH
QT_WARNING_DISABLE_MSVC(4100)
QT_WARNING_DISABLE_MSVC(4146)
QT_WARNING_DISABLE_MSVC(4267)
QT_WARNING_DISABLE_MSVC(4624)
QT_WARNING_DISABLE_GCC("-Wnonnull")

#include <llvm/ADT/StringRef.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Basic/FileManager.h>

QT_WARNING_POP

#include <vector>
#include <iostream>
#include <sstream>

QT_BEGIN_NAMESPACE

Q_DECLARE_LOGGING_CATEGORY(lcClang)

inline QString toQt(llvm::StringRef str)
{
    return QString::fromUtf8(str.data(), str.size());
}

#define LUPDATE_CLANG_VERSION_CHECK(major, minor, patch) ((major<<16)|(minor<<8)|(patch))
#define LUPDATE_CLANG_VERSION LUPDATE_CLANG_VERSION_CHECK(LUPDATE_CLANG_VERSION_MAJOR, \
    LUPDATE_CLANG_VERSION_MINOR, LUPDATE_CLANG_VERSION_PATCH)

// Local storage of translation information (information from the AST and linguist side)
struct TranslationRelatedStore
{
    QString callType;
    QString rawCode;
    QString funcName;
    qint64 locationCol = -1;
    QString contextArg;
    QString contextRetrieved;
    QString lupdateSource;
    QString lupdateLocationFile;
    QString lupdateInputFile; // file associated to the running of the tool
    qint64 lupdateLocationLine = -1;
    QString lupdateId;
    QString lupdateSourceWhenId;
    QString lupdateIdMetaData;
    QString lupdateMagicMetaData;
    QHash<QString, QString> lupdateAllMagicMetaData;
    QString lupdateComment;
    QString lupdateExtraComment;
    QString lupdatePlural;
    QString lupdateWarning;
    clang::SourceLocation sourceLocation;

    bool isValid(bool printwarning = false)
    {
        switch (trFunctionAliasManager.trFunctionByName(funcName)) {
        // only one argument: the source
        case TrFunctionAliasManager::Function_Q_DECLARE_TR_FUNCTIONS:
            if (contextArg.isEmpty()) {
                if (printwarning) {
                    std::stringstream warning;
                    warning << qPrintable(lupdateLocationFile) << ":"
                        << lupdateLocationLine << ":"
                        << locationCol << ": "
                        << " \'" << qPrintable(funcName)
                        << "\' cannot be called without context."
                        << " The call is ignored." <<std::endl;
                    lupdateWarning.append(QString::fromStdString(warning.str()));
                }
                return false;
            }
            break;
        case TrFunctionAliasManager::Function_tr:
        case TrFunctionAliasManager::Function_trUtf8:
            if (lupdateSource.isEmpty()) {
                if (printwarning) {
                    std::stringstream warning;
                    warning << qPrintable(lupdateLocationFile) << ":"
                        << lupdateLocationLine << ":"
                        << locationCol << ": "
                        << " \'" << qPrintable(funcName)
                        << "\' cannot be called without source."
                        << " The call is ignored." << std::endl;
                    lupdateWarning.append(QString::fromStdString(warning.str()));
                }
                return false;
            }
            break;
        // two arguments: the context and the source
        case TrFunctionAliasManager::Function_QT_TRANSLATE_N_NOOP:
        case TrFunctionAliasManager::Function_QT_TRANSLATE_N_NOOP3:
        case TrFunctionAliasManager::Function_translate:
        case TrFunctionAliasManager::Function_QT_TRANSLATE_NOOP:
        case TrFunctionAliasManager::Function_QT_TRANSLATE_NOOP_UTF8:
        case TrFunctionAliasManager::Function_QT_TRANSLATE_NOOP3:
        case TrFunctionAliasManager::Function_QT_TRANSLATE_NOOP3_UTF8:
            if (contextArg.isEmpty() || lupdateSource.isEmpty()) {
                if (printwarning) {
                    std::stringstream warning;
                    warning << qPrintable(lupdateLocationFile) << ":"
                        << lupdateLocationLine << ":"
                        << locationCol << ": "
                        << " \'" << qPrintable(funcName)
                        << "\' cannot be called without context or source."
                        << " The call is ignored." << std::endl;
                    lupdateWarning.append(QString::fromStdString(warning.str()));
                }
                return false;
            }
            // not sure if the third argument is compulsory
            break;
        // only one argument (?) the message Id
        case TrFunctionAliasManager::Function_QT_TRID_N_NOOP:
        case TrFunctionAliasManager::Function_qtTrId:
        case TrFunctionAliasManager::Function_QT_TRID_NOOP:
            if (lupdateId.isEmpty()) {
                if (printwarning) {
                    std::stringstream warning;
                    warning << qPrintable(lupdateLocationFile) << ":"
                        << lupdateLocationLine << ":"
                        << locationCol << ": "
                        << " \'" << qPrintable(funcName)
                        << "\' cannot be called without Id."
                        << " The call is ignored." << std::endl;
                    lupdateWarning.append(QString::fromStdString(warning.str()));
                }
                return false;
            }
            break;
        default:
            if (funcName == QStringLiteral("TRANSLATOR") && lupdateComment.isEmpty()) {
                if (printwarning) {
                    std::stringstream warning;
                    warning << qPrintable(lupdateLocationFile) << ":"
                        << lupdateLocationLine << ":"
                        << locationCol << ": "
                        << qPrintable(funcName)
                        << " cannot be called without comment."
                        << " The call is ignored." << std::endl;
                    lupdateWarning.append(QString::fromStdString(warning.str()));
                }
                return false;
            }
        }
        return !lupdateLocationFile.isEmpty() && (lupdateLocationLine > -1) && (locationCol > -1);
    }

    clang::SourceLocation callLocation(const clang::SourceManager &sourceManager)
    {
        if (sourceLocation.isInvalid()) {
            auto sourceFile = sourceManager.getFileManager()
                .getFile(lupdateLocationFile.toStdString());
#if (LUPDATE_CLANG_VERSION >= LUPDATE_CLANG_VERSION_CHECK(10,0,0))
            sourceLocation = sourceManager.translateFileLineCol(sourceFile.get(),
                lupdateLocationLine, locationCol);
#else
            sourceLocation = sourceManager.translateFileLineCol(sourceFile, lupdateLocationLine,
                locationCol);
#endif
        }
        return sourceLocation;
    }

    void printStore() const
    {
        qCDebug(lcClang) << "------------------ Printing Store----------------------------------\n";
        qCDebug(lcClang)
            << "callType            : " << callType << "\n"
            << "rawCode             : \n" << rawCode << "\n"
            << "funcName            : " << funcName << "\n"
            << "LocationCol         : " << locationCol << "\n"
            << "contextArg          : " << contextArg << "\n"
            << "contextRetrieved    : " << contextRetrieved << "\n"
            << "lupdateSource       : " << lupdateSource << "\n"
            << "lupdateLocationFile : " << lupdateLocationFile << "\n"
            << "lupdateLocationLine : " << lupdateLocationLine << "\n"
            << "lupdateId           : " << lupdateId << "\n"
            << "lupdateIdMetaData   : " << lupdateIdMetaData << "\n"
            << "lupdateMagicMetaData: " << lupdateMagicMetaData << "\n"
            << "lupdateComment      : " << lupdateComment << "\n"
            << "lupdateExtraComment : " << lupdateExtraComment << "\n"
            << "lupdatePlural       : " << lupdatePlural;
        qCDebug(lcClang) << "-------------------------------------------------------------------\n";
    }
};
using TranslationStores = std::vector<TranslationRelatedStore>;

struct Stores
{
    Stores(TranslationStores &a, TranslationStores &qd, TranslationStores &qn)
        : AST(a)
        , QDeclareTrWithContext(qd)
        , QNoopTranlsationWithContext(qn)
    {}

    TranslationStores Preprocessor;
    WriteSynchronizedRef<TranslationRelatedStore> AST;
    WriteSynchronizedRef<TranslationRelatedStore> QDeclareTrWithContext;
    WriteSynchronizedRef<TranslationRelatedStore> QNoopTranlsationWithContext; // or with warnings that need to be
                                                                               //displayed in the same order, always
};

namespace LupdatePrivate
{
    inline QString fixedLineEndings(const QString &s)
    {
#ifdef Q_OS_WIN
        QString result = s;
        result.replace(QLatin1String("\r\n"), QLatin1String("\n"));
        return result;
#else
        return s;
#endif
    }

    enum QuoteCompulsary
    {
        None = 0x01,
        Left = 0x02,                // Left quote is mandatory
        Right = 0x04,               // Right quote is mandatory
        LeftAndRight = Left | Right // Both quotes are mandatory
    };

    /*
        Removes the quotes around the lupdate extra, ID meta data, magic and
        ID prefix comments and source string literals.
        Depending on the given compulsory option, quotes can be unbalanced and
        still some text is returned. This is to mimic the old lupdate behavior.
    */
    inline QString cleanQuote(llvm::StringRef s, QuoteCompulsary quote)
    {
        if (s.empty())
            return {};
        s = s.trim();
        if (!s.consume_front("\"") && ((quote & Left) != 0))
            return {};
        if (!s.consume_back("\"") && ((quote & Right) != 0))
            return {};
        return fixedLineEndings(toQt(s));
    }

    /*
        Removes the quotes and a possible existing string literal prefix
        for a given string literal coming from the source code. Do not use
        to clean the quotes around the lupdate translator specific comments.
    */
    inline QString cleanQuote(const std::string &token)
    {
        if (token.empty())
            return {};

        const QString string = fixedLineEndings(QString::fromStdString(token).trimmed());
        const int index = string.indexOf(QLatin1Char('"'));
        if (index <= 0)
            return LupdatePrivate::cleanQuote(token, QuoteCompulsary::LeftAndRight);

        QRegularExpressionMatch result;
        if (string.at(index - 1) == QLatin1Char('R')) {
            static const QRegularExpression rawStringLiteral {
                QStringLiteral(
                    "(?:\\bu8|\\b[LuU])??R\\\"([^\\(\\)\\\\ ]{0,16})\\((?<characters>.*)\\)\\1\\\""
                ), QRegularExpression::DotMatchesEverythingOption };
            result = rawStringLiteral.match(string);
        } else {
            static const QRegularExpression stringLiteral {
                QStringLiteral(
                    "(?:\\bu8|\\b[LuU])+?\\\"(?<characters>[^\\\"\\\\]*(?:\\\\.[^\\\"\\\\]*)*)\\\""
                )
            };
            result = stringLiteral.match(string);
        }
        if (result.hasMatch())
            return result.captured(QStringLiteral("characters"));
        return string;
    }
}

namespace ClangCppParser
{
    void loadCPP(Translator &translator, const QStringList &filenames, ConversionData &cd,
                 bool *fail);

    using TranslatorMessageVector = std::vector<TranslatorMessage>;
    void collectMessages(TranslatorMessageVector &result, TranslationRelatedStore &store);
    TranslatorMessage translatorMessage(const TranslationRelatedStore &store,
        const QString &id, bool plural, bool isID, bool isWarningOnly = false);

    void correctAstTranslationContext(ReadSynchronizedRef<TranslationRelatedStore> &ast,
        WriteSynchronizedRef<TranslationRelatedStore> &newAst, const TranslationStores &qDecl);
    void finalize(ReadSynchronizedRef<TranslationRelatedStore> &ast,
        WriteSynchronizedRef<TranslationRelatedStore> &newAst);

    bool stringContainsTranslationInformation(llvm::StringRef ba);
    bool hasAliases();
    std::vector<std::string> getAliasFunctionDefinition();

}

QT_END_NAMESPACE

#endif