aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/clangformat/clangformatutils.cpp
blob: 6732524f41e52fdd687c8b0a4dd56a95a79a6f0b (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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "clangformatutils.h"

#include "clangformatconstants.h"

#include <coreplugin/icore.h>

#include <cppeditor/cppcodestylepreferences.h>
#include <cppeditor/cppcodestylesettings.h>

#include <texteditor/icodestylepreferences.h>
#include <texteditor/tabsettings.h>
#include <texteditor/texteditorsettings.h>

#include <projectexplorer/editorconfiguration.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectmanager.h>

#include <utils/qtcassert.h>
#include <utils/expected.h>

#include <QCryptographicHash>
#include <QLoggingCategory>

using namespace clang;
using namespace format;
using namespace llvm;
using namespace CppEditor;
using namespace ProjectExplorer;
using namespace TextEditor;
using namespace Utils;

namespace ClangFormat {

clang::format::FormatStyle calculateQtcStyle()
{
    clang::format::FormatStyle style = getLLVMStyle();
    style.Language = FormatStyle::LK_Cpp;
    style.AccessModifierOffset = -4;
    style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
#if LLVM_VERSION_MAJOR >= 15
    style.AlignConsecutiveAssignments = {false, false, false, false, false};
    style.AlignConsecutiveDeclarations = {false, false, false, false, false};
#else
    style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
    style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
#endif
    style.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
    style.AlignOperands = FormatStyle::OAS_Align;
#if LLVM_VERSION_MAJOR >= 16
    style.AlignTrailingComments = {FormatStyle::TCAS_Always, 0};
#else
    style.AlignTrailingComments = true;
#endif
    style.AllowAllParametersOfDeclarationOnNextLine = true;
    style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
    style.AllowShortCaseLabelsOnASingleLine = false;
    style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
    style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
    style.AllowShortLoopsOnASingleLine = false;
    style.AlwaysBreakBeforeMultilineStrings = false;
#if LLVM_VERSION_MAJOR >= 19
    style.BreakAfterReturnType = FormatStyle::RTBS_None;
    style.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
#else
    style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
    style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
#endif
    style.BinPackArguments = false;
    style.BinPackParameters = false;
    style.BraceWrapping.AfterClass = true;
    style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
    style.BraceWrapping.AfterEnum = false;
    style.BraceWrapping.AfterFunction = true;
    style.BraceWrapping.AfterNamespace = false;
    style.BraceWrapping.AfterObjCDeclaration = false;
    style.BraceWrapping.AfterStruct = true;
    style.BraceWrapping.AfterUnion = false;
    style.BraceWrapping.BeforeCatch = false;
    style.BraceWrapping.BeforeElse = false;
    style.BraceWrapping.IndentBraces = false;
    style.BraceWrapping.SplitEmptyFunction = false;
    style.BraceWrapping.SplitEmptyRecord = false;
    style.BraceWrapping.SplitEmptyNamespace = false;
    style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
    style.BreakBeforeBraces = FormatStyle::BS_Custom;
    style.BreakBeforeTernaryOperators = true;
    style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
    style.BreakAfterJavaFieldAnnotations = false;
    style.BreakStringLiterals = true;
    style.ColumnLimit = 100;
    style.CommentPragmas = "^ IWYU pragma:";
    style.CompactNamespaces = false;
#if LLVM_VERSION_MAJOR >= 15
    style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
#else
    style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
#endif
    style.ConstructorInitializerIndentWidth = 4;
    style.ContinuationIndentWidth = 4;
    style.Cpp11BracedListStyle = true;
    style.DerivePointerAlignment = false;
    style.DisableFormat = false;
    style.ExperimentalAutoDetectBinPacking = false;
    style.FixNamespaceComments = true;
    style.ForEachMacros = {"forever", "foreach", "Q_FOREACH", "BOOST_FOREACH"};
    style.IncludeStyle.IncludeCategories = {{"^<Q.*", 200, 200, true}};
    style.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
    style.IndentCaseLabels = false;
    style.IndentWidth = 4;
    style.IndentWrappedFunctionNames = false;
    style.JavaScriptQuotes = FormatStyle::JSQS_Leave;
    style.JavaScriptWrapImports = true;
    style.KeepEmptyLinesAtTheStartOfBlocks = false;
    // Do not add QT_BEGIN_NAMESPACE/QT_END_NAMESPACE as this will indent lines in between.
    style.MacroBlockBegin = "";
    style.MacroBlockEnd = "";
    style.MaxEmptyLinesToKeep = 1;
    style.NamespaceIndentation = FormatStyle::NI_None;
    style.ObjCBlockIndentWidth = 4;
    style.ObjCSpaceAfterProperty = false;
    style.ObjCSpaceBeforeProtocolList = true;
    style.PenaltyBreakAssignment = 150;
    style.PenaltyBreakBeforeFirstCallParameter = 300;
    style.PenaltyBreakComment = 500;
    style.PenaltyBreakFirstLessLess = 400;
    style.PenaltyBreakString = 600;
    style.PenaltyExcessCharacter = 50;
    style.PenaltyReturnTypeOnItsOwnLine = 300;
    style.PointerAlignment = FormatStyle::PAS_Right;
    style.ReflowComments = false;
    style.SortIncludes = FormatStyle::SI_CaseSensitive;
#if LLVM_VERSION_MAJOR >= 16
    style.SortUsingDeclarations = FormatStyle::SUD_Lexicographic;
#else
    style.SortUsingDeclarations = true;
#endif
    style.SpaceAfterCStyleCast = true;
    style.SpaceAfterTemplateKeyword = false;
    style.SpaceBeforeAssignmentOperators = true;
    style.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
#if LLVM_VERSION_MAJOR < 17
    style.SpaceInEmptyParentheses = false;
#endif
    style.SpacesBeforeTrailingComments = 1;
    style.SpacesInAngles = FormatStyle::SIAS_Never;
    style.SpacesInContainerLiterals = false;
#if LLVM_VERSION_MAJOR >= 17
    style.SpacesInParens = FormatStyle::SIPO_Never;
#else
    style.SpacesInCStyleCastParentheses = false;
    style.SpacesInParentheses = false;
#endif
    style.SpacesInSquareBrackets = false;
    addQtcStatementMacros(style);
    style.TabWidth = 4;
    style.UseTab = FormatStyle::UT_Never;
    style.Standard = FormatStyle::LS_Auto;
    return style;
}

clang::format::FormatStyle qtcStyle()
{
    static clang::format::FormatStyle style = calculateQtcStyle();
    return style;
}

clang::format::FormatStyle currentQtStyle(const TextEditor::ICodeStylePreferences *preferences)
{
    clang::format::FormatStyle style = qtcStyle();
    if (!preferences)
        return style;

    fromTabSettings(style, preferences->tabSettings());
    if (auto ccpPreferences = dynamic_cast<const CppEditor::CppCodeStylePreferences *>(preferences))
        fromCppCodeStyleSettings(style, ccpPreferences->codeStyleSettings());
    return style;
}

void fromCppCodeStyleSettings(clang::format::FormatStyle &style,
                              const CppEditor::CppCodeStyleSettings &settings)
{
    using namespace clang::format;
    if (settings.indentAccessSpecifiers)
        style.AccessModifierOffset = 0;
    else
        style.AccessModifierOffset = -1 * style.IndentWidth;

    if (settings.indentNamespaceBody && settings.indentNamespaceBraces)
        style.NamespaceIndentation = FormatStyle::NamespaceIndentationKind::NI_All;
    else
        style.NamespaceIndentation = FormatStyle::NamespaceIndentationKind::NI_None;

    if (settings.indentClassBraces && settings.indentEnumBraces && settings.indentBlockBraces
        && settings.indentFunctionBraces)
        style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
    else
        style.BreakBeforeBraces = FormatStyle::BS_Custom;

    style.IndentCaseLabels = settings.indentSwitchLabels;
    style.IndentCaseBlocks = settings.indentBlocksRelativeToSwitchLabels;

    if (settings.extraPaddingForConditionsIfConfusingAlign)
        style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
    else if (settings.alignAssignments)
        style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
    else
        style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;

    style.DerivePointerAlignment = settings.bindStarToIdentifier || settings.bindStarToTypeName
                                   || settings.bindStarToLeftSpecifier
                                   || settings.bindStarToRightSpecifier;

    if ((settings.bindStarToIdentifier || settings.bindStarToRightSpecifier)
        && ClangFormatSettings::instance().mode() == ClangFormatSettings::Mode::Formatting)
        style.PointerAlignment = FormatStyle::PAS_Right;

    if ((settings.bindStarToTypeName || settings.bindStarToLeftSpecifier)
        && ClangFormatSettings::instance().mode() == ClangFormatSettings::Mode::Formatting)
        style.PointerAlignment = FormatStyle::PAS_Left;
}

void fromTabSettings(clang::format::FormatStyle &style, const TextEditor::TabSettings &settings)
{
    using namespace clang::format;

    style.IndentWidth = settings.m_indentSize;
    style.TabWidth = settings.m_tabSize;

    switch (settings.m_tabPolicy) {
    case TextEditor::TabSettings::TabPolicy::MixedTabPolicy:
        style.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
        break;
    case TextEditor::TabSettings::TabPolicy::SpacesOnlyTabPolicy:
        style.UseTab = FormatStyle::UT_Never;
        break;
    case TextEditor::TabSettings::TabPolicy::TabsOnlyTabPolicy:
        style.UseTab = FormatStyle::UT_Always;
        break;
    }
}

QString projectUniqueId(ProjectExplorer::Project *project)
{
    if (!project)
        return QString();

    return QString::fromUtf8(QCryptographicHash::hash(project->projectFilePath().toString().toUtf8(),
                                                      QCryptographicHash::Md5)
                                 .toHex(0));
}

bool getProjectUseGlobalSettings(const ProjectExplorer::Project *project)
{
    const QVariant projectUseGlobalSettings = project ? project->namedSettings(
                                                  Constants::USE_GLOBAL_SETTINGS)
                                                      : QVariant();

    return projectUseGlobalSettings.isValid() ? projectUseGlobalSettings.toBool() : true;
}

bool getProjectCustomSettings(const ProjectExplorer::Project *project)
{
    const QVariant projectCustomSettings = project ? project->namedSettings(
                                               Constants::USE_CUSTOM_SETTINGS_ID)
                                                   : QVariant();

    return projectCustomSettings.isValid()
               ? projectCustomSettings.toBool()
               : ClangFormatSettings::instance().useCustomSettings();
}

bool getCurrentCustomSettings(const Utils::FilePath &filePath)
{
    const ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::projectForFile(
        filePath);

    return getProjectUseGlobalSettings(project)
               ? ClangFormatSettings::instance().useCustomSettings()
               : getProjectCustomSettings(project);
}

ClangFormatSettings::Mode getProjectIndentationOrFormattingSettings(
    const ProjectExplorer::Project *project)
{
    const QVariant projectIndentationOrFormatting = project
                                                        ? project->namedSettings(Constants::MODE_ID)
                                                        : QVariant();

    return projectIndentationOrFormatting.isValid()
               ? static_cast<ClangFormatSettings::Mode>(projectIndentationOrFormatting.toInt())
               : ClangFormatSettings::instance().mode();
}

ClangFormatSettings::Mode getCurrentIndentationOrFormattingSettings(const Utils::FilePath &filePath)
{
    const ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::projectForFile(
        filePath);

    return getProjectUseGlobalSettings(project)
               ? ClangFormatSettings::instance().mode()
               : getProjectIndentationOrFormattingSettings(project);
}

Utils::FilePath findConfig(const Utils::FilePath &fileName)
{
    Utils::FilePath parentDirectory = fileName.parentDir();
    while (parentDirectory.exists()) {
        Utils::FilePath settingsFilePath = parentDirectory / Constants::SETTINGS_FILE_NAME;
        if (settingsFilePath.exists())
            return settingsFilePath;

        Utils::FilePath settingsAltFilePath = parentDirectory / Constants::SETTINGS_FILE_ALT_NAME;
        if (settingsAltFilePath.exists())
            return settingsAltFilePath;

        parentDirectory = parentDirectory.parentDir();
    }
    return {};
}

Utils::FilePath configForFile(const Utils::FilePath &fileName)
{
    if (!getCurrentCustomSettings(fileName))
        return findConfig(fileName);

    const ProjectExplorer::Project *projectForFile
        = ProjectExplorer::ProjectManager::projectForFile(fileName);

    const TextEditor::ICodeStylePreferences *preferences
        = projectForFile
              ? projectForFile->editorConfiguration()->codeStyle("Cpp")->currentPreferences()
              : TextEditor::TextEditorSettings::codeStyle("Cpp")->currentPreferences();

    return filePathToCurrentSettings(preferences);
}

void addQtcStatementMacros(clang::format::FormatStyle &style)
{
    static const std::vector<std::string> macros = {"Q_CLASSINFO",
                                                    "Q_ENUM",
                                                    "Q_ENUM_NS",
                                                    "Q_FLAG",
                                                    "Q_FLAG_NS",
                                                    "Q_GADGET",
                                                    "Q_GADGET_EXPORT",
                                                    "Q_INTERFACES",
                                                    "Q_LOGGING_CATEGORY",
                                                    "Q_MOC_INCLUDE",
                                                    "Q_NAMESPACE",
                                                    "Q_NAMESPACE_EXPORT",
                                                    "Q_OBJECT",
                                                    "Q_PROPERTY",
                                                    "Q_REVISION",
                                                    "Q_DISABLE_COPY",
                                                    "Q_SET_OBJECT_NAME",
                                                    "QT_BEGIN_NAMESPACE",
                                                    "QT_END_NAMESPACE",

                                                    "QML_ADDED_IN_MINOR_VERSION",
                                                    "QML_ANONYMOUS",
                                                    "QML_ATTACHED",
                                                    "QML_DECLARE_TYPE",
                                                    "QML_DECLARE_TYPEINFO",
                                                    "QML_ELEMENT",
                                                    "QML_EXTENDED",
                                                    "QML_EXTENDED_NAMESPACE",
                                                    "QML_EXTRA_VERSION",
                                                    "QML_FOREIGN",
                                                    "QML_FOREIGN_NAMESPACE",
                                                    "QML_IMPLEMENTS_INTERFACES",
                                                    "QML_INTERFACE",
                                                    "QML_NAMED_ELEMENT",
                                                    "QML_REMOVED_IN_MINOR_VERSION",
                                                    "QML_SINGLETON",
                                                    "QML_UNAVAILABLE",
                                                    "QML_UNCREATABLE",
                                                    "QML_VALUE_TYPE"};
    for (const std::string &macro : macros) {
        if (std::find(style.StatementMacros.begin(), style.StatementMacros.end(), macro)
            == style.StatementMacros.end())
            style.StatementMacros.emplace_back(macro);
    }
}

Utils::FilePath filePathToCurrentSettings(const TextEditor::ICodeStylePreferences *codeStyle)
{
    return Core::ICore::userResourcePath() / "clang-format/"
           / Utils::FileUtils::fileSystemFriendlyName(codeStyle->displayName())
           / QLatin1String(Constants::SETTINGS_FILE_NAME);
}

static QString s_errorMessage;
Utils::expected_str<void> parseConfigurationContent(const std::string &fileContent,
                                                    clang::format::FormatStyle &style)
{
    auto diagHandler = [](const llvm::SMDiagnostic &diag, void * /*context*/) {
        s_errorMessage = QString::fromStdString(diag.getMessage().str()) + " "
                         + QString::number(diag.getLineNo()) + ":"
                         + QString::number(diag.getColumnNo());
    };

    style.Language = clang::format::FormatStyle::LK_Cpp;
    const std::error_code error = parseConfiguration(llvm::MemoryBufferRef(fileContent, "YAML"),
                                                     &style,
                                                     false,
                                                     diagHandler,
                                                     nullptr);

    if (error)
        return make_unexpected(s_errorMessage);
    return {};
}

Utils::expected_str<void> parseConfigurationFile(const Utils::FilePath &filePath,
                                                 clang::format::FormatStyle &style)
{
    return parseConfigurationContent(filePath.fileContents().value_or(QByteArray()).toStdString(),
                                     style);
}

} // namespace ClangFormat