summaryrefslogtreecommitdiff
path: root/src/qdoc/qdoc/utilities.cpp
blob: d0f18338b59cdec49a5b48cea19712a2a3db0017 (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
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include <QtCore/qprocess.h>
#include "utilities.h"

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(lcQdoc, "qt.qdoc")
Q_LOGGING_CATEGORY(lcQdocClang, "qt.qdoc.clang")

/*!
    \namespace Utilities
    \internal
    \brief This namespace holds QDoc-internal utility methods.
 */
namespace Utilities {
static inline void setDebugEnabled(bool value)
{
    const_cast<QLoggingCategory &>(lcQdoc()).setEnabled(QtDebugMsg, value);
    const_cast<QLoggingCategory &>(lcQdocClang()).setEnabled(QtDebugMsg, value);
}

void startDebugging(const QString &message)
{
    setDebugEnabled(true);
    qCDebug(lcQdoc, "START DEBUGGING: %ls", qUtf16Printable(message));
}

void stopDebugging(const QString &message)
{
    qCDebug(lcQdoc, "STOP DEBUGGING: %ls", qUtf16Printable(message));
    setDebugEnabled(false);
}

bool debugging()
{
    return lcQdoc().isEnabled(QtDebugMsg);
}

/*!
    \internal
    Convenience method that's used to get the correct punctuation character for
    the words at \a wordPosition in a list of \a numberOfWords length.
    For the last position in the list, returns "." (full stop). For any other
    word, this method calls comma().

    \sa comma()
 */
QString separator(qsizetype wordPosition, qsizetype numberOfWords)
{
    static QString terminator = QStringLiteral(".");
    if (wordPosition == numberOfWords - 1)
        return terminator;
    else
        return comma(wordPosition, numberOfWords);
}

/*!
    \internal
    Convenience method that's used to get the correct punctuation character for
    the words at \a wordPosition in a list of \a numberOfWords length.

    For a list of length one, returns an empty QString. For a list of length
    two, returns the string " and ". For any length beyond two, returns the
    string ", " until the last element, which returns ", and ".

    \sa comma()
 */
QString comma(qsizetype wordPosition, qsizetype numberOfWords)
{
    if (wordPosition == numberOfWords - 1)
        return QString();
    if (numberOfWords == 2)
        return QStringLiteral(" and ");
    if (wordPosition == 0 || wordPosition < numberOfWords - 2)
        return QStringLiteral(", ");
    return QStringLiteral(", and ");
}

/*!
  \internal
  Replace non-alphanum characters in \a str with hyphens
  and convert all characters to lowercase. Returns the
  result of the conversion with leading, trailing, and
  consecutive hyphens removed.

  The implementation is equivalent to:

  \code
      name.replace(QRegularExpression("[^A-Za-z0-9]+"), " ");
      name = name.simplified();
      name.replace(QLatin1Char(' '), QLatin1Char('-'));
      name = name.toLower();
  \endcode
*/
QString canonicalizeFileName(const QString &name)
{
    QString result;
    bool begun = false;
    const auto *data{name.constData()};
    for (qsizetype i = 0; i < name.size(); ++i) {
        char16_t u{data[i].unicode()};
        if (u >= 'A' && u <= 'Z')
            u += 'a' - 'A';
        if ((u >= 'a' && u <= 'z') || (u >= '0' && u <= '9')) {
            result += QLatin1Char(u);
            begun = true;
        } else if (begun) {
            result += QLatin1Char('-');
            begun = false;
        }
    }
    if (result.endsWith(QLatin1Char('-')))
        result.chop(1);

    return result;
}

/*!
    \internal
*/
static bool runProcess(const QString &program, const QStringList &arguments,
                       QByteArray *stdOutIn, QByteArray *stdErrIn)
{
    QProcess process;
    process.start(program, arguments, QProcess::ReadWrite);
    if (!process.waitForStarted()) {
        qCDebug(lcQdoc).nospace() << "Unable to start " << process.program()
                                  << ": " << process.errorString();
        return false;
    }
    process.closeWriteChannel();
    const bool finished = process.waitForFinished();
    const QByteArray stdErr = process.readAllStandardError();
    if (stdErrIn)
        *stdErrIn = stdErr;
    if (stdOutIn)
        *stdOutIn = process.readAllStandardOutput();

    if (!finished) {
        qCDebug(lcQdoc).nospace() << process.program() << " timed out: " << stdErr;
        process.kill();
        return false;
    }

    if (process.exitStatus() != QProcess::NormalExit) {
        qCDebug(lcQdoc).nospace() << process.program() << " crashed: " << stdErr;
        return false;
    }

    if (process.exitCode() != 0) {
        qCDebug(lcQdoc).nospace() <<  process.program() << " exited with "
            << process.exitCode() << ": " << stdErr;
        return false;
    }

    return true;
}

/*!
    \internal
*/
static QByteArray frameworkSuffix() {
    return QByteArrayLiteral(" (framework directory)");
}

/*!
    \internal
    Determine the compiler's internal include paths from the output of

    \badcode
    [clang++|g++] -E -x c++ - -v </dev/null
    \endcode

    Output looks like:

    \badcode
    #include <...> search starts here:
    /usr/local/include
    /System/Library/Frameworks (framework directory)
    End of search list.
    \endcode
*/
QStringList getInternalIncludePaths(const QString &compiler)
{
    QStringList result;
    QStringList arguments;
    arguments << QStringLiteral("-E") << QStringLiteral("-x") << QStringLiteral("c++")
              << QStringLiteral("-") << QStringLiteral("-v");
    QByteArray stdOut;
    QByteArray stdErr;
    if (!runProcess(compiler, arguments, &stdOut, &stdErr))
        return result;
    const QByteArrayList stdErrLines = stdErr.split('\n');
    bool isIncludeDir = false;
    for (const QByteArray &line : stdErrLines) {
        if (isIncludeDir) {
            if (line.startsWith(QByteArrayLiteral("End of search list"))) {
                isIncludeDir = false;
            } else {
                QByteArray prefix("-I");
                QByteArray headerPath{line.trimmed()};
                if (headerPath.endsWith(frameworkSuffix())) {
                    headerPath.truncate(headerPath.size() - frameworkSuffix().size());
                    prefix = QByteArrayLiteral("-F");
                }
                result.append(QString::fromLocal8Bit(prefix + headerPath));
            }
        } else if (line.startsWith(QByteArrayLiteral("#include <...> search starts here"))) {
            isIncludeDir = true;
        }
    }

    return result;
}

} // namespace Utilities

QT_END_NAMESPACE