File: gcclikecompiler.cpp

package info (click to toggle)
kdevelop 4%3A24.12.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 71,888 kB
  • sloc: cpp: 290,869; python: 3,626; javascript: 3,518; sh: 1,316; ansic: 703; xml: 401; php: 95; lisp: 66; makefile: 31; sed: 12
file content (256 lines) | stat: -rw-r--r-- 8,759 bytes parent folder | download | duplicates (2)
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
/*
    SPDX-FileCopyrightText: 2014 Sergey Kalinichev <kalinichev.so.0@gmail.com>

    SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/

#include "gcclikecompiler.h"

#include <debug.h>

#include <interfaces/iruntime.h>
#include <interfaces/iruntimecontroller.h>

#include <QFileInfo>
#include <QProcess>
#include <QRegExp>
#include <QRegularExpression>
#include <QScopeGuard>

using namespace KDevelop;

namespace
{

QString languageOption(Utils::LanguageType type)
{
    switch (type) {
        case Utils::C:
            return QStringLiteral("-xc");
        case Utils::Cpp:
            return QStringLiteral("-xc++");
        case Utils::OpenCl:
            return QStringLiteral("-xcl");
        case Utils::Cuda:
            return QStringLiteral("-xcuda");
        case Utils::ObjC:
            return QStringLiteral("-xobjective-c");
        case Utils::ObjCpp:
            return QStringLiteral("-xobjective-c++");
        default:
            Q_UNREACHABLE();
    }
}

QString languageStandard(const QString& arguments, Utils::LanguageType type)
{
    // TODO: handle -ansi flag: In C mode, this is equivalent to -std=c90. In C++ mode, it is equivalent to -std=c++98.
    // NOTE: we put the greedy .* in front to find the last occurrence
    const QRegularExpression regexp(QStringLiteral(".*(-std=\\S+)"));
    auto result = regexp.match(arguments);
    if (result.hasMatch()) {
        return result.captured(1);
    }

    switch (type) {
        case Utils::C:
        case Utils::ObjC:
            return QStringLiteral("-std=c99");
        case Utils::Cpp:
        case Utils::ObjCpp:
        case Utils::Cuda:
            return QStringLiteral("-std=c++11");
        case Utils::OpenCl:
            return QStringLiteral("-cl-std=CL1.1");
        default:
            Q_UNREACHABLE();
    }
}

}

Defines GccLikeCompiler::defines(Utils::LanguageType type, const QString& arguments) const
{
    // first do a lookup by type and arguments
    auto& data = m_definesIncludes[type][arguments];
    if (data.definedMacros.wasCached) {
        return data.definedMacros.data;
    }

    // TODO: what about -mXXX or -target= flags, some of these change search paths/defines
    const QStringList compilerArguments{
        languageOption(type),
        languageStandard(arguments, type),
        QStringLiteral("-dM"),
        QStringLiteral("-E"),
        QStringLiteral("-"),
    };

    // if that fails, do a lookup based on the actual compiler arguments
    // often these are much less variable than the arguments passed per TU
    // so here we can better exploit the cache by doing this two-phase lookup
    auto& cachedData = m_defines[compilerArguments];
    auto updateDataOnExit = qScopeGuard([&] {
        // we don't want to run the below code more than once
        // even if it errors out
        cachedData.wasCached = true;
        data.definedMacros = cachedData;
    });

    if (cachedData.wasCached) {
        return cachedData.data;
    }

    const auto rt = ICore::self()->runtimeController()->currentRuntime();
    QProcess proc;
    proc.setProcessChannelMode(QProcess::MergedChannels);
    proc.setStandardInputFile(QProcess::nullDevice());
    proc.setProgram(path());
    proc.setArguments(compilerArguments);
    rt->startProcess(&proc);

    if ( !proc.waitForStarted( 2000 ) || !proc.waitForFinished( 2000 ) ) {
        qCDebug(DEFINESANDINCLUDES) <<  "Unable to read standard macro definitions from "<< path() << compilerArguments;
        return {};
    }

    if (proc.exitCode() != 0) {
        qCWarning(DEFINESANDINCLUDES) <<  "error while fetching defines for the compiler:" << path() << compilerArguments << proc.readAll();
        return {};
    }

    // #define a 1
    // #define a
    QRegExp defineExpression(QStringLiteral("#define\\s+(\\S+)(?:\\s+(.*)\\s*)?"));

    while ( proc.canReadLine() ) {
        auto line = proc.readLine();

        if ( defineExpression.indexIn(QString::fromUtf8(line)) != -1 ) {
            cachedData.data[defineExpression.cap(1)] = defineExpression.cap(2).trimmed();
        }
    }

    return cachedData.data;
}

Path::List GccLikeCompiler::includes(Utils::LanguageType type, const QString& arguments) const
{
    // first do a lookup by type and arguments
    auto& data = m_definesIncludes[type][arguments];
    if (data.includePaths.wasCached) {
        return data.includePaths.data;
    }

    const QStringList compilerArguments {
        languageOption(type), languageStandard(arguments, type), QStringLiteral("-E"), QStringLiteral("-v"),
        QStringLiteral("-"),
    };

    // if that fails, do a lookup based on the actual compiler arguments
    // often these are much less variable than the arguments passed per TU
    // so here we can better exploit the cache by doing this two-phase lookup
    auto& cachedData = m_includes[compilerArguments];
    auto updateDataOnExit = qScopeGuard([&] {
        // we don't want to run the below code more than once
        // even if it errors out
        cachedData.wasCached = true;
        data.includePaths = cachedData;
    });

    if (cachedData.wasCached) {
        return cachedData.data;
    }

    const auto rt = ICore::self()->runtimeController()->currentRuntime();
    QProcess proc;
    proc.setProcessChannelMode( QProcess::MergedChannels );

    // The following command will spit out a bunch of information we don't care
    // about before spitting out the include paths.  The parts we care about
    // look like this:
    // #include "..." search starts here:
    // #include <...> search starts here:
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/i486-linux-gnu
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/backward
    //  /usr/local/include
    //  /usr/lib/gcc/i486-linux-gnu/4.1.2/include
    //  /usr/include
    // End of search list.

    proc.setStandardInputFile(QProcess::nullDevice());
    proc.setProgram(path());
    proc.setArguments(compilerArguments);
    rt->startProcess(&proc);

    if ( !proc.waitForStarted( 2000 ) || !proc.waitForFinished( 2000 ) ) {
        qCDebug(DEFINESANDINCLUDES) <<  "Unable to read standard include paths from " << path();
        return {};
    }

    if (proc.exitCode() != 0) {
        qCWarning(DEFINESANDINCLUDES) <<  "error while fetching includes for the compiler:" << path() << proc.readAll();
        return {};
    }

    // We'll use the following constants to know what we're currently parsing.
    enum Status {
        Initial,
        FirstSearch,
        Includes,
        Finished
    };
    Status mode = Initial;

    const auto output = QString::fromLocal8Bit( proc.readAllStandardOutput() );
    const auto lines = QStringView{output}.split(QLatin1Char('\n'));
    for (const auto line : lines) {
        switch ( mode ) {
            case Initial:
                if ( line.indexOf( QLatin1String("#include \"...\"") ) != -1 ) {
                    mode = FirstSearch;
                }
                break;
            case FirstSearch:
                if ( line.indexOf( QLatin1String("#include <...>") ) != -1 ) {
                    mode = Includes;
                }
                break;
            case Includes:
                //Detect the include-paths by the first space that is prepended. Reason: The list may contain relative paths like "."
                if (!line.startsWith(QLatin1Char(' '))) {
                    // We've reached the end of the list.
                    mode = Finished;
                } else {
                    // This is an include path, add it to the list.
                    auto hostPath = rt->pathInHost(Path(QFileInfo(line.trimmed().toString()).canonicalFilePath()));
                    // but skip folders with compiler builtins, we cannot parse these with clang
                    if (!QFile::exists(hostPath.toLocalFile() + QLatin1String("/cpuid.h"))) {
                        cachedData.data << Path(QFileInfo(hostPath.toLocalFile()).canonicalFilePath());
                    }
                }
                break;
            default:
                break;
        }
        if ( mode == Finished ) {
            break;
        }
    }

    return cachedData.data;
}

void GccLikeCompiler::invalidateCache()
{
    m_definesIncludes.clear();
}

GccLikeCompiler::GccLikeCompiler(const QString& name, const QString& path, bool editable, const QString& factoryName):
    ICompiler(name, path, factoryName, editable)
{
    connect(ICore::self()->runtimeController(), &IRuntimeController::currentRuntimeChanged, this, &GccLikeCompiler::invalidateCache);
}

#include "moc_gcclikecompiler.cpp"